answer
stringlengths 17
10.2M
|
|---|
package org.jbehave.threaded.swing;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import org.jbehave.core.exception.PendingException;
import org.jbehave.core.threaded.QueuedObjectHolder;
import org.jbehave.core.threaded.TimeoutException;
/**
* Used for pressing or typing all keys which have valid characters associated with them.
*/
class CharacterTyper {
private static final String ACTION_KEY = "CharacterTyper.action";
private static final String TEXT_TYPING_UNSUPPORTED = "Text typing not supported for your Swing library.";
private EventQueue sysQueue;
private Idler idler;
CharacterTyper() {
sysQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
idler = new Idler();
}
public void typeIntoComponent(Component component, String text) {
QueueingKeyAdapter queuer = new QueueingKeyAdapter(component);
try {
for (int i = 0; i < text.length(); i++) {
postKeyEvent(component, text.charAt(i));
queuer.waitForEvent();
}
} finally {
queuer.removeSelf();
}
}
/**
* Use this for any key which has a valid character associated with it, when it is being pressed
* (eg: as a game control key) rather than being typed into a text component.
*/
public void pressKeychar(Window window, char key) throws TimeoutException {
QueueingKeyAdapter queuer = null;
if(window instanceof JFrame) {
Container contentPane = ((JFrame)window).getContentPane();
if (contentPane instanceof JComponent) {
queuer = new QueueingKeyAdapter(contentPane);
}
} else {
queuer = new QueueingKeyAdapter(window.getFocusOwner());
}
postKeyEvent(window, key);
try {
queuer.waitForEvent();
} finally {
queuer.removeSelf();
}
}
private void postKeyEvent(final Component component, final char key) {
sysQueue.postEvent(createKeyPressEvent(component, key, KeyEvent.KEY_PRESSED));
sysQueue.postEvent(createKeyPressEvent(component, key, KeyEvent.KEY_RELEASED));
sysQueue.postEvent(createKeyPressEvent(component, key, KeyEvent.KEY_TYPED));
idler.waitForIdle();
}
private AWTEvent createKeyPressEvent(Component component, char c, int id) {
return new KeyEvent(component,
id,
System.currentTimeMillis(),
0,
KeyEvent.VK_UNDEFINED,
c);
}
private class QueueingKeyAdapter extends KeyAdapter {
private QueuedObjectHolder holder = new QueuedObjectHolder();
private final Component component;
public QueueingKeyAdapter(Component component) {
this.component = component;
component.requestFocus();
component.addKeyListener(this);
}
public void keyTyped(KeyEvent e) {
holder.set(e);
}
public void waitForEvent() {
try {
holder.get(1000);
} catch (TimeoutException e) {
throw new PendingException(TEXT_TYPING_UNSUPPORTED);
}
idler.waitForIdle();
}
public void removeSelf() {
component.removeKeyListener(this);
}
}
}
|
package alda;
import alda.error.UnsuccessfulException;
import alda.error.SystemException;
import alda.error.ExitCode;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.jcabi.manifests.Manifests;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
import org.apache.commons.lang3.SystemUtils;
public class AldaClient {
public static String version() {
if (Manifests.exists("alda-version")) {
return Manifests.read("alda-version");
} else {
return "unknown / development version";
}
}
public static void updateAlda()
throws SystemException, UnsuccessfulException {
// The path to the current alda executable
String programPath;
try {
programPath = Util.getProgramPath();
} catch (URISyntaxException e) {
throw new SystemException(
"Could not determine the path to the current `alda` executable.", e
);
}
String clientVersion = version();
// Make a call to the Github API to get the latest version number/download URL
String latestApiStr = "https://api.github.com/repos/alda-lang/alda/releases/latest";
String apiResult = Util.makeApiCall(latestApiStr);
// Turn api result into version numbers and links
Gson gson = new Gson();
JsonObject job = gson.fromJson(apiResult, JsonObject.class);
// Gets the download URL. This may have ...alda or ...alda.exe
String downloadURL = null;
String dlRegex = SystemUtils.IS_OS_WINDOWS ? ".*alda\\.exe$" : ".*.alda$";
String latestTag = job.getAsJsonObject().get("tag_name").toString().replaceAll("\"", "");
// Check to see if we currently have the version determined by latestTag
if (clientVersion.equals(latestTag)) {
System.out.println("Your version of alda (" + clientVersion +") is up to date!");
return;
}
for (JsonElement i : job.getAsJsonArray("assets")) {
String candidate = i.getAsJsonObject().get("browser_download_url").toString().replaceAll("\"", "");
if (candidate.matches(dlRegex)) {
downloadURL = candidate;
break;
}
}
if (downloadURL == null) {
throw new UnsuccessfulException(
"Alda download link not found for your platform. Please file an " +
"issue at: https://github.com/alda-lang/alda-client-java/issues/new"
);
}
// Workaround for windows. See #24 #25
if (SystemUtils.IS_OS_WINDOWS) {
System.out.println(
"Automated updates to alda.exe are not possible due to limitations of the Windows OS.\n" +
"For more information, see: https://github.com/alda-lang/alda-client-java/issues/24\n" +
"\n" +
"To update alda.exe, first, make sure that the server is not up by running:\n" +
"\n" +
" alda down\n" +
"\n" +
"Then, run the following command in your Powershell (you can find Powershell in your Start menu) to download the latest alda.exe:\n" +
"\n" +
" powershell -Command {[Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Ssl3 -bor [System.Net.SecurityProtocolType]::Tls -bor [System.Net.SecurityProtocolType]::Tls12 ; Invoke-WebRequest -Uri \"" + downloadURL + "\" -OutFile \"" + programPath + "\"}\n" +
"\n" +
"Or, if you'd prefer, you can install the latest alda.exe yourself from:\n" +
"https://github.com/alda-lang/alda/releases\n"
);
return;
}
// Request confirmation from user:
System.out.print("Install alda '" + latestTag + "' over '" + clientVersion + "' ? [yN]: ");
System.out.flush();
String name = (new Scanner(System.in)).nextLine();
if (!(name.equalsIgnoreCase("y") || name.equalsIgnoreCase("yes"))) {
System.out.println("Quitting...");
return;
}
System.out.println("Downloading " + downloadURL + "...");
// Download file from downloadURL to programPath
Util.downloadFile(downloadURL, programPath);
// set as executable if on UNIX
if (SystemUtils.IS_OS_UNIX) {
new File(programPath).setExecutable(true);
}
System.out.println();
System.out.println("Updated alda " + clientVersion + " => " + latestTag + ".");
System.out.println("If you have any currently running servers, you may want to restart them so that they are running the latest version.");
}
public static void listProcesses(AldaServerOptions serverOpts)
throws SystemException {
IAldaProcessReader processReader = getProcessReader();
List<AldaProcess> processes = processReader.getProcesses();
for (AldaProcess process : processes) {
if (process.type == "server") {
if (process.port == -1) {
System.out.printf("[???] Mysterious server running on unknown " +
"port (pid: %d)\n", process.pid);
System.out.flush();
} else {
serverOpts.host = "localhost";
serverOpts.port = process.port;
serverOpts.quiet = false;
AldaServer server = new AldaServer(serverOpts);
server.status();
}
} else if (process.type == "worker") {
if (process.port == -1) {
System.out.printf("[???] Mysterious worker running on unknown " +
"port (pid: %d)\n", process.pid);
System.out.flush();
} else {
System.out.printf("[%d] Worker (pid: %d)\n", process.port, process.pid);
System.out.flush();
}
} else {
if (process.port == -1) {
System.out.printf("[???] Mysterious Alda process running on " +
"unknown port (pid: %d)\n", process.pid);
System.out.flush();
} else {
System.out.printf("[%d] Mysterious Alda process (pid: %d)\n",
process.port, process.pid);
System.out.flush();
}
}
}
}
private static IAldaProcessReader getProcessReader() {
if (SystemUtils.IS_OS_WINDOWS) {
return new AldaProcessReaderWindows();
} else {
return new AldaProcessReaderUnix();
}
}
public static boolean checkForExistingServer(int port)
throws SystemException {
IAldaProcessReader processReader = getProcessReader();
List<AldaProcess> processes = processReader.getProcesses();
for (AldaProcess process : processes) {
if (process.port == port) {
return true;
}
}
return false;
}
}
|
package org.verapdf.pdfa.qa;
import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import org.verapdf.core.ProfileException;
import org.verapdf.pdfa.flavours.PDFAFlavour;
import org.verapdf.pdfa.results.ValidationResults;
import org.verapdf.pdfa.validation.ProfileDirectory;
import org.verapdf.pdfa.validation.Profiles;
import org.verapdf.pdfa.validation.ValidationProfile;
import org.verapdf.validation.profile.parser.LegacyProfileConverter;
/**
* @author <a href="mailto:carl@openpreservation.org">Carl Wilson</a>
*
*/
public enum GitHubBackedProfileDirectory implements ProfileDirectory {
/**
* Integration branch profiles
*/
INTEGRATION("integration");
/**
* This would work for Master branch profiles
*
* MASTER("master");
*/
private static final String GITHUB_ROOT = "https://raw.githubusercontent.com/veraPDF/veraPDF-validation-profiles/";
private static final String PROFILE_PATH_PART = "/PDF_A/";
private static final String PROFILE_PREFIX = "PDFA-";
private static final String XML_SUFFIX = ".xml";
private final String branchName;
private final ProfileDirectory profiles;
GitHubBackedProfileDirectory(final String branchName) {
this.branchName = branchName;
this.profiles = Profiles
.directoryFromProfiles(fromGitHubBranch(this.branchName));
}
/**
* @return the GitHub branch name that the instance is populated from
*/
public String getBranchName() {
return this.branchName;
}
/**
* { @inheritDoc }
*/
@Override
public Set<String> getValidationProfileIds() {
return this.profiles.getValidationProfileIds();
}
/**
* { @inheritDoc }
*/
@Override
public Set<PDFAFlavour> getPDFAFlavours() {
return this.profiles.getPDFAFlavours();
}
/**
* { @inheritDoc }
*/
@Override
public ValidationProfile getValidationProfileById(final String profileID) {
return this.profiles.getValidationProfileById(profileID);
}
/**
* { @inheritDoc }
*/
@Override
public ValidationProfile getValidationProfileByFlavour(
final PDFAFlavour flavour) {
return this.profiles.getValidationProfileByFlavour(flavour);
}
/**
* { @inheritDoc }
*/
@Override
public Set<ValidationProfile> getValidationProfiles() {
return this.profiles.getValidationProfiles();
}
private static Set<ValidationProfile> fromGitHubBranch(
final String branchName) {
String pathPrefix = GITHUB_ROOT + branchName + PROFILE_PATH_PART
+ PROFILE_PREFIX;
Set<ValidationProfile> profileSet = new HashSet<>();
for (PDFAFlavour flavour : PDFAFlavour.values()) {
String profileURLString = pathPrefix
+ flavour.getId().toUpperCase() + XML_SUFFIX;
try {
URL profileURL = new URL(profileURLString);
ValidationProfile profile = Profiles.profileFromXml(profileURL.openStream());
profileSet.add(profile);
} catch (IOException e) {
// Do nothing
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return profileSet;
}
/**
* Simple main that simply outputs all loaded from INTEGRATION to
* System.out.
*
* @param args
* main args, NOT processed.
* @throws JAXBException
* when converting the profile to XML goes wrong. It shouldn't.
* @throws IOException
*/
public static void main(final String[] args) throws JAXBException,
IOException {
System.out.println("XSD Schema for Validation Profile:");
System.out.println(Profiles.getValidationProfileSchema());
System.out.println("XSD Schema for Validation Result:");
System.out.println(ValidationResults.getValidationResultSchema());
for (ValidationProfile profile : INTEGRATION.getValidationProfiles()) {
System.out
.println("\n\nValidation Profile:"
+ profile.getPDFAFlavour().getId()
+ " XML representation.");
Profiles.profileToXml(profile, System.out, Boolean.TRUE);
}
}
}
|
package structures.linear;
import java.util.NoSuchElementException;
/**
* A linked list is a linear structure consisting of nodes.
* Each node has a data part that holds the client-supplied information,
* and a link that refers to the next node in the linked list. A circular linked list
* is a linked list in which the last node refers back to the first.
*/
public class CircularLinkedList<T>
{
Node<T> tail; // Refers to the last node in list
int count; // Size of the linked list
/**
* Constructor: Creates an empty linked list
*/
public CircularLinkedList()
{
this.tail = null;
this.count = 0;
}
/**
* Adds specified item to the end of this linked list.
* O(1)
* @param item
*/
public void add(T item)
{
// Create new node object with item set as the data
Node<T> newNode = new Node<T>(item);
// Empty linked list
if(this.count == 0)
{
// Point new node's next field to itself
newNode.next = newNode;
}
// Linked list with at least one node
else
{
// Point the new node's next field to the first node in the linked list
newNode.next = this.tail.next;
// Point the last node's next field to the new node
this.tail.next = newNode;
}
// Set the new node as the tail of the linked list
this.tail = newNode;
// Increment linked list's size counter
count++;
}
/**
* Adds specified item to this linked list at specified index. Index must
* refer to an existing position in the list; the existing entry will be moved over.
* Does not add to the end of the list or on an empty list.
* O(n)
* @param item Data of Node
* @param index Position to add node in linked list; 0 being the front of the list
* @throws IndexOutOfBoundsException if the index is < 0 or >= number of entries
*/
public void insertAt(T item, int index)
{
// Validate supplied index is valid
if(index < 0 || index >= this.count)
{
throw new IndexOutOfBoundsException(index + " < 0 or >= " + this.count);
}
// Find predecessor
Node<T> pred = this.tail;
for(int i = 0; i < index; i++)
{
pred = pred.next;
}
// Insert after predecessor
Node<T> newNode = new Node<T>(item);
newNode.next = pred.next;
pred.next = newNode;
count++;
}
/**
* Deletes all occurrences of specified item from this linked list.
* @param item Data to be removed from list
* @throws NoSuchElementException if the item is not in this linked list
*/
public void removeAll(T item)
{
// Empty linked list
if(this.count == 0)
{
throw new NoSuchElementException();
}
// Step through all entries
Node<T> prev = this.tail;
Node<T> curr = this.tail.next;
int oldcount = count;
for(int i = 0; i < oldcount; i++)
{
// Delete matching item
if(item.equals(curr.data))
{
prev.next = curr.next;
curr.data = null;
curr.next = null;
count
}
else
{
prev = curr; // move previous pointer forward
}
curr = prev.next; // move current pointer forward
}
// No change in linked list
if(this.count == oldcount)
{
// no match
throw new NoSuchElementException();
}
// Handles emptying list if all entries are deleted
if(count == 0)
{
tail = null;
}
// Set tail to point to last item of new list
else
{
this.tail = prev;
}
}
}
/**
* Generic Node
* Self-referential structure
*/
class Node<T>
{
T data; // Hold generic type T data
Node<T> next; // Reference to another Node object
// Node Constructor
Node(T data)
{
this.data = data;
this.next = null;
}
}
|
package org.codehaus.xfire.wsdl11.parser;
import java.util.Iterator;
import java.util.List;
import javax.wsdl.Binding;
import javax.wsdl.BindingFault;
import javax.wsdl.BindingInput;
import javax.wsdl.BindingOperation;
import javax.wsdl.BindingOutput;
import javax.wsdl.Fault;
import javax.wsdl.Input;
import javax.wsdl.Message;
import javax.wsdl.Output;
import javax.wsdl.Part;
import javax.wsdl.Port;
import javax.wsdl.extensions.soap.SOAPAddress;
import javax.wsdl.extensions.soap.SOAPBinding;
import javax.wsdl.extensions.soap.SOAPBody;
import javax.wsdl.extensions.soap.SOAPHeader;
import javax.wsdl.extensions.soap.SOAPOperation;
import javax.xml.namespace.QName;
import org.codehaus.xfire.XFireRuntimeException;
import org.codehaus.xfire.service.Endpoint;
import org.codehaus.xfire.service.FaultInfo;
import org.codehaus.xfire.service.MessageInfo;
import org.codehaus.xfire.service.MessagePartContainer;
import org.codehaus.xfire.service.MessagePartInfo;
import org.codehaus.xfire.service.OperationInfo;
import org.codehaus.xfire.soap.AbstractSoapBinding;
import org.codehaus.xfire.soap.Soap11Binding;
import org.codehaus.xfire.soap.SoapConstants;
import org.codehaus.xfire.wsdl.SchemaType;
public class SoapBindingAnnotator extends BindingAnnotator
{
private AbstractSoapBinding soapBinding;
private boolean useSet = false;
protected org.codehaus.xfire.service.Binding getBinding()
{
return soapBinding;
}
public AbstractSoapBinding getSoapBinding()
{
return soapBinding;
}
public void setSoapBinding(AbstractSoapBinding soapBinding)
{
this.soapBinding = soapBinding;
}
protected void visit(Binding wbinding)
{
SOAPBinding sbind = DefinitionsHelper.getSOAPBinding(wbinding);
soapBinding = new Soap11Binding(wbinding.getQName(), sbind.getTransportURI(), getService());
getService().addBinding(soapBinding);
soapBinding.setStyle(null);
setStyle(sbind.getStyle());
}
protected void visit(BindingFault bindingFault, Fault fault, FaultInfo msg)
{
visitMessage(msg, bindingFault.getExtensibilityElements());
}
protected void visit(BindingInput bindingInput, Input input, MessageInfo msg)
{
visitMessage(msg, bindingInput.getExtensibilityElements());
}
private void visitMessage(MessagePartContainer msg, List ext)
{
for (Iterator itr = ext.iterator(); itr.hasNext();)
{
Object o = itr.next();
if (o instanceof SOAPBody)
{
SOAPBody body = (SOAPBody) o;
setUse(msg, body.getUse());
}
else if (o instanceof SOAPHeader)
{
SOAPHeader header = (SOAPHeader) o;
QName msgName = header.getMessage();
Message hmsg = getDefinition().getMessage(msgName);
Part part = hmsg.getPart(header.getPart());
if (part == null)
throw new IllegalStateException("Could not find message part: " + header.getPart() +
" in message " + msgName);
QName name = part.getElementName();
QName schemaType = part.getElementName();
if (name == null)
{
name = new QName(getService().getTargetNamespace(), part.getName());
schemaType = part.getTypeName();
}
SchemaType st = getBindingProvider().getSchemaType(schemaType, getService());
MessagePartInfo info = getSoapBinding().getHeaders((MessageInfo) msg).addMessagePart(name, null);
info.setSchemaType(st);
}
}
}
protected void visit(BindingOperation operation, OperationInfo opInfo)
{
SOAPOperation soapOp = DefinitionsHelper.getSOAPOperation(operation);
AbstractSoapBinding binding = getSoapBinding();
if (soapOp != null)
{
binding.setSoapAction(opInfo, soapOp.getSoapActionURI());
String style = soapOp.getStyle();
if (style != null)
{
setStyle(style);
}
}
binding.setSerializer(opInfo, AbstractSoapBinding.getSerializer(binding.getStyle(), binding.getUse()));
}
protected void setStyle(String style)
{
if (getService().getServiceInfo().isWrapped())
style = SoapConstants.STYLE_WRAPPED;
String current = getSoapBinding().getStyle();
if (current == null)
{
getSoapBinding().setStyle(style);
}
else
{
if (!current.equals(style))
throw new XFireRuntimeException("Multiple styles not supported at this time.");
}
}
protected void setUse(MessagePartContainer msg, String use)
{
String current = getSoapBinding().getUse();
if (!useSet)
{
getSoapBinding().setUse(use);
useSet = true;
}
else
{
if (!current.equals(use))
throw new XFireRuntimeException("Multiple uses not supported at this time.");
}
}
protected void visit(BindingOutput bindingOutput, Output output, MessageInfo msg)
{
visitMessage(msg, bindingOutput.getExtensibilityElements());
}
protected boolean isUnderstood(Binding op)
{
SOAPBinding ee = DefinitionsHelper.getSOAPBinding(op);
return ee != null;
}
protected void visit(Port port)
{
SOAPAddress add = DefinitionsHelper.getSOAPAddress(port);
SOAPBinding sbind = DefinitionsHelper.getSOAPBinding(port.getBinding());
org.codehaus.xfire.service.Binding binding =
getService().getBinding(port.getBinding().getQName());
if (binding != null)
{
Endpoint ep = new Endpoint(new QName(getService().getTargetNamespace(),
port.getName()),
binding,
add.getLocationURI());
getService().addEndpoint(ep);
}
}
}
|
package barbarahliskov.cambialibros;
import android.Manifest;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Chat extends AppCompatActivity {
int huecoLibre = 0;
double lat = 0.0;
double lon = 0.0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
setTitle("Chat con <LEGENDANNY>");
LinearLayout layout1 = (LinearLayout) findViewById(R.id.layout1);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.layout2);
LinearLayout layout3 = (LinearLayout) findViewById(R.id.layout3);
LinearLayout layout4 = (LinearLayout) findViewById(R.id.layout4);
layout1.setVisibility(View.INVISIBLE);
layout2.setVisibility(View.INVISIBLE);
layout3.setVisibility(View.INVISIBLE);
layout4.setVisibility(View.INVISIBLE);
ImageView butSend = (ImageView) findViewById(R.id.boton_send);
butSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
ImageView butSendLoc = (ImageView) findViewById(R.id.boton_send_loc);
butSendLoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
}
|
package com.ociweb.iot.valveManifold;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ociweb.iot.maker.Baud;
import com.ociweb.pronghorn.iot.rs232.RS232Client;
import com.ociweb.pronghorn.pipe.DataOutputBlobWriter;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.RawDataSchema;
import com.ociweb.pronghorn.stage.PronghornStage;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.util.Appendables;
public class UARTDataStage extends PronghornStage{
private RS232Client client;
private final Pipe<RawDataSchema> output;
private int x = 0;
private Logger logger = LoggerFactory.getLogger(UARTDataStage.class);
public static void newInstance(GraphManager gm, Pipe<RawDataSchema> output) {
new UARTDataStage(gm, output);
}
public UARTDataStage(GraphManager graphManager, Pipe<RawDataSchema> output) {
super(graphManager, NONE, output);
this.output = output;
}
@Override
public void startup() {
client = new RS232Client("/dev/ttyMFD1", Baud.B_____9600);
//logger.info("started up");
}
@Override
public void shutdown() {
Pipe.spinBlockForRoom(output, Pipe.EOF_SIZE);
Pipe.publishEOF(output);
}
int iteration = 0;
@Override
public void run() {
//logger.info("enter run");
while (Pipe.hasRoomForWrite(output)) {
//logger.info("has room for write");
ByteBuffer[] buffers = Pipe.wrappedWritingBuffers(output);
int readCount = copy(buffers);
//logger.info("found bytes on UART of count {} on iteration{} ",readCount, iteration);
if (readCount<=0) {
//cancel this write
Pipe.unstoreBlobWorkingHeadPosition(output);
return;//come back later when we have some data to read.
} else {
// logger.info("found bytes on UART of count {} ",readCount);
//publish this write
final int size = Pipe.addMsgIdx(output, RawDataSchema.MSG_CHUNKEDSTREAM_1);
Pipe.moveBlobPointerAndRecordPosAndLength((int)readCount, output);
Pipe.confirmLowLevelWrite(output, size);
Pipe.publishWrites(output);
//logger.info("relayed from uart {} bytes",size);
}
}
}
private int copy(ByteBuffer[] buffers) {
int readCount = client.readInto(buffers[0].array(),
buffers[0].position(),
buffers[0].remaining(),
buffers[1].array(),
buffers[1].position(),
buffers[1].remaining());
return readCount;
}
}
|
package conceptmatcher.bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import conceptmatcher.internal.ConceptMatcher;
import am.app.mappingEngine.AbstractMatcher;
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;
ConceptMatcher matcher=new ConceptMatcher();
matcher.setName("Concept Similarity");
context.registerService(AbstractMatcher.class.getName(), matcher, null);
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
|
package am.app.mappingEngine.hierarchy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import am.GlobalStaticVariables;
import am.Utility;
import am.app.mappingEngine.AbstractMatcher;
import am.app.mappingEngine.AbstractParameters;
import am.app.mappingEngine.Mapping;
import am.app.mappingEngine.LinkedOpenData.LODOntologies;
import am.app.mappingEngine.Mapping.MappingRelation;
import am.app.ontology.Node;
import am.app.ontology.Ontology;
import am.app.ontology.ontologyParser.OntoTreeBuilder;
import am.app.ontology.ontologyParser.TreeBuilder;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntResource;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import edu.smu.tspell.wordnet.NounSynset;
import edu.smu.tspell.wordnet.Synset;
import edu.smu.tspell.wordnet.SynsetType;
import edu.smu.tspell.wordnet.WordNetDatabase;
/*The aim of this matcher is to find the subClassOf and superClassOf relationships between the classes that have been mapped by equivalence
relationship by the input matchers.*/
public class HierarchyMatcherModified extends AbstractMatcher
{
private ArrayList<Node> ListOfClassesSource;
private ArrayList<Node> ListOfClassesTarget;
private ArrayList<Node> sourceClassList;
private ArrayList<Node> targetClassList;
private ArrayList<Node> ListOfPropSource;
private ArrayList<Node> ListOfPropTarget;
private ArrayList<Node> sourcePropList;
private ArrayList<Node> targetPropList;
private ArrayList<String> sourceSynonym;
private ArrayList<String> targetSynonym;
private OntModel sourceModel1;
private WordNetDatabase WordNet;
private HashMap<String, List<String>> sourceWordNetMeaning;
double inputMatcherThreshold;
/*VARIABLES TO SET THE THRESHOLD*/
double EQUALITY_THRESHOLD_VALUE;
double SUBCLASS_THRESHOLD_VALUE;
double SUPERCLASS_THRESHOLD_VALUE;
boolean useOtherOntologies = true;
ArrayList<OntModel> otherOntologies;
public HierarchyMatcherModified()
{
super();
/*minInputMatchers & maxInputMatcher insures that the user gives the input */
minInputMatchers = 1;
maxInputMatchers = 1;
param = new AbstractParameters();
/* maxSourceAlign and maxTargetAlign set the cardinality of the alignments to many to many that is
one concept in source can be aligned to more than one concept in target*/
param.maxSourceAlign = ANY_INT;
param.maxTargetAlign = ANY_INT;
// Initialize the WordNet Interface (JAWS)
// Initialize the WordNet interface.
String cwd = System.getProperty("user.dir");
String wordnetdir = cwd + "/wordnet-3.0";
System.setProperty("wordnet.database.dir", wordnetdir);
// Instantiate
try
{
WordNet = WordNetDatabase.getFileInstance();
}
catch( Exception e )
{
Utility.displayErrorPane(e.getMessage(), "Cannot open WordNet files.\nWordNet should be in the following directory:\n" + wordnetdir);
}
}
protected void align() throws Exception{
/*miscellaneous variables used in the method*/
Node source=null;
Node target=null;
Node temp = null;
OntResource resSource = null;
OntResource resTarget = null;
double similarityValue;
ArrayList<String> sourcesyno;
ArrayList<String> targetsyno;
ArrayList<String> sourcehyper = null;
ArrayList<String> targethyper = null;
if( sourceOntology == null || targetOntology == null )
return; // cannot align just one ontology
/*it gets the inputMatches being used for this Algo and initializes the variables
* classesMatrix , propertiesMatrix */
getInputMatcher();
/*maintains a list of nodes in the ontology*/
sourceClassList = sourceOntology.getClassesList();
targetClassList = targetOntology.getClassesList();
sourcePropList = sourceOntology.getPropertiesList();
targetPropList = targetOntology.getPropertiesList();
ListOfClassesSource = sourceOntology.getClassesList();
ListOfClassesTarget = targetOntology.getClassesList();
ListOfPropSource = sourceOntology.getPropertiesList();
ListOfPropTarget = sourceOntology.getPropertiesList();
/*used for getting the individuals in the ontology*/
sourceModel1 = sourceOntology.getModel();
/*First Iteration that uses the similarity values received in the input matchers
* It calculates all the subClassOf and superClassOf relationship based on the equivalence
* relationship received form the first Matcher*/
for (int i = 0; i < ListOfClassesSource.size(); i++)
{
for(int j =0 ; j<ListOfClassesTarget.size();j++)
{
similarityValue = classesMatrix.getSimilarity(i, j);
/*Right now the similarity value is kept one as a pessimist approach
* that anything less than one will yield wrong results. It has been verified by
* runs of AM*/
if(similarityValue == 1)
{
source = ListOfClassesSource.get(i);
target = ListOfClassesTarget.get(j);
resSource = (OntResource) source.getResource();
resTarget = (OntResource) target.getResource();
matchManySourceTarget(source,target);
matchManyTargetSource(source,target);
}
}
}
String name;
String[] sourceSplitted;
Node sNode;
Node tNode;
for (int i = 0; i < sourceClassList.size(); i++) {
sNode = sourceClassList.get(i);
name = Utilities.separateWords(sNode.getLocalName());
sourceSplitted = name.split(" ");
if(sourceSplitted.length != 2) continue;
for (int j = 0; j < targetClassList.size(); j++) {
tNode = targetClassList.get(j);
if(sourceSplitted[1].equals(tNode.getLocalName())){
Mapping m = new Mapping(sNode, tNode, 1.0d, MappingRelation.SUBCLASS);
classesMatrix.set(i, j, m);
}
}
}
String[] targetSplitted;
for (int i = 0; i < targetClassList.size(); i++) {
tNode = targetClassList.get(i);
name = Utilities.separateWords(tNode.getLocalName());
targetSplitted = name.split(" ");
if(targetSplitted.length != 2) continue;
for (int j = 0; j < sourceClassList.size(); j++) {
sNode = sourceClassList.get(j);
if(targetSplitted[1].equals(sNode.getLocalName())){
Mapping m = new Mapping(sNode, tNode, 1.0d, MappingRelation.SUPERCLASS);
classesMatrix.set(j, i, m);
}
}
}
/*This is the second level of relationship mappings being done
* based on wordnet*/
/*Get the synonym set of Source*/
for (int i = 0; i < ListOfClassesSource.size(); i++)
{
Node sourceNode = ListOfClassesSource.get(i);
System.out.println(sourceNode.getLocalName());
ArrayList<NounSynset> sourceSynsetList = doLookUp(sourceNode);
ArrayList<NounSynset> dis = disambiguate(sourceNode, sourceSynsetList);
if(dis.size()>0){
System.out.println("IUPPIS: disambiguated "+ sourceNode.getLocalName());
System.out.println(dis);
sourceSynsetList = dis;
}
ArrayList<ArrayList<NounSynset>> sourceHypernymList = buildHypernymList(sourceNode, sourceSynsetList, 5);
System.out.println(sourceSynsetList);
System.out.println(dis);
System.out.println(sourceHypernymList);
for(int j =0 ; j<ListOfClassesTarget.size();j++)
{
Node targetNode = ListOfClassesTarget.get(j);
ArrayList<NounSynset> targetSynsetList = doLookUp(targetNode);
ArrayList<NounSynset> targetDis = disambiguate(targetNode, targetSynsetList);
if(targetDis.size()>0){
System.out.println("IUPPIT: disambiguated "+ targetNode.getLocalName());
System.out.println(targetDis);
//targetSynsetList = targetDis;
}
ArrayList<ArrayList<NounSynset>> targetHypernymList = buildHypernymList(targetNode, null, 5);
if( synsetIsContainedBy( sourceSynsetList, targetHypernymList ) ) {
// source > target
/*The similarity is set to be less than 0.80d as I do not want to
* overwrite alread established relationships*/
if( classesMatrix.get( sourceNode.getIndex(), targetNode.getIndex()) == null ||
classesMatrix.getSimilarity( sourceNode.getIndex(), targetNode.getIndex()) < 0.80d ) {
System.out.println("mapping >: "+sourceNode.getLocalName() + " " + targetNode.getLocalName() + sourceSynsetList);
classesMatrix.set(sourceNode.getIndex(), targetNode.getIndex(), new Mapping(sourceNode, targetNode, 0.89d, MappingRelation.SUPERCLASS));
}
} else if ( synsetIsContainedBy(targetSynsetList, sourceHypernymList) ) {
//source < target
if( classesMatrix.get( sourceNode.getIndex(), targetNode.getIndex()) == null ||
classesMatrix.getSimilarity( sourceNode.getIndex(), targetNode.getIndex()) < 0.80d ) {
System.out.println("mapping <: "+sourceNode.getLocalName() + " " + targetNode.getLocalName() + targetSynsetList);
classesMatrix.set(sourceNode.getIndex(), targetNode.getIndex(), new Mapping(sourceNode, targetNode, 0.89d, MappingRelation.SUBCLASS));
}
}
}
}
//computeTransitiveClosure();
// for (int i = 0; i < classesMatrix.getRows(); i++) {
// for (int j = 0; j < classesMatrix.getColumns(); j++) {
// System.out.println(sourceClassList.get(i).getLocalName() + " " + targetClassList.get(j).getLocalName());
// if(classesMatrix.get(i,j) == null) continue;
// if(!classesMatrix.get(i,j).getEntity1().getLocalName().equals(sourceClassList.get(i).getLocalName())
// || !classesMatrix.get(i,j).getEntity2().getLocalName().equals(targetClassList.get(j).getLocalName()))
// System.out.println("WEIRD");
if(useOtherOntologies == true){
initOtherOntologies();
useOtherOntologies();
}
filterEqualityMappings();
}
private void initOtherOntologies() {
Ontology ontology;
OntoTreeBuilder treeBuilder;
otherOntologies = new ArrayList<OntModel>();
if(!sourceOntology.getURI().equals(LODOntologies.FOAF_URI) &&
!targetOntology.getURI().equals(LODOntologies.FOAF_URI)){
System.out.println("Opening FOAF");
treeBuilder = new OntoTreeBuilder(LODOntologies.FOAF, GlobalStaticVariables.SOURCENODE,
GlobalStaticVariables.LANG_OWL,
GlobalStaticVariables.SYNTAX_RDFXML, false, true);
treeBuilder.build();
ontology = treeBuilder.getOntology();
otherOntologies.add(ontology.getModel());
}
if(!sourceOntology.getURI().equals(LODOntologies.SW_CONFERENCE_URI) &&
!targetOntology.getURI().equals(LODOntologies.SW_CONFERENCE_URI)){
System.out.println("Opening SWC");
treeBuilder = new OntoTreeBuilder(LODOntologies.SW_CONFERENCE, GlobalStaticVariables.SOURCENODE,
GlobalStaticVariables.LANG_OWL,
GlobalStaticVariables.SYNTAX_RDFXML, false, true);
treeBuilder.build();
ontology = treeBuilder.getOntology();
otherOntologies.add(ontology.getModel());
}
}
/**
* This method uses information taken from other LOD ontologies to improve the match.
* The idea is that we can use sub and superclasses of standard classes in LOD famous ontologies to
* get more information to use in the matching process.
*/
private void useOtherOntologies() {
OntModel ontology;
Node source;
Node target;
for (int i = 0; i < sourceClassList.size(); i++) {
source = sourceClassList.get(i);
for (int j = 0; j < otherOntologies.size(); j++) {
ontology = otherOntologies.get(j);
for (OntClass cl: ontology.listClasses().toList()) {
if(source.getUri().equals(cl.getURI())){
System.out.println("WOW Let's study class " + cl.getURI());
System.out.println(cl.listSuperClasses().toList());
//Subclasses of the class can help generate superclass mappings
for(OntClass subclass : cl.listSubClasses().toList()){
for(int t = 0; t < targetClassList.size(); t++){
target = targetClassList.get(t);
if(target.getLocalName().equals(subclass.getLocalName())){
//create superclass mapping source -> target
System.out.println("CREATING MAPPING "+source.getLocalName() + " " + target.getLocalName());
Mapping m = new Mapping(source, target, 1.0, MappingRelation.SUPERCLASS);
classesMatrix.set(i, t, m);
//also subclasses of target are subclasses of source:
for(OntClass child: listAllSubclasses(target.getResource().as(OntClass.class), null)){
int index = getIndex(targetClassList, child.getURI());
m = new Mapping(source, targetClassList.get(index), 1.0, MappingRelation.SUPERCLASS);
classesMatrix.set(i, index, m);
}
}
}
}
}
}
}
}
}
private void filterEqualityMappings() {
Mapping m;
for (int i = 0; i < classesMatrix.getRows(); i++) {
for (int j = 0; j < classesMatrix.getColumns(); j++) {
if(classesMatrix.get(i, j) != null){
m = classesMatrix.get(i, j);
if(m.getRelation() == MappingRelation.EQUIVALENCE && m.getSimilarity()<1.0)
classesMatrix.set(i, j, null);
}
}
}
}
private ArrayList<NounSynset> disambiguate(Node sourceNode, ArrayList<NounSynset> sourceSynsetList) {
//System.out.println("DISAMBIGUATE");
ArrayList<Node> descendants = sourceNode.getDescendants();
ArrayList<NounSynset> synsetList;
ArrayList<ArrayList<NounSynset>> hypernymList;
ArrayList<NounSynset> contained = new ArrayList<NounSynset>();
for (int i = 0; i < descendants.size(); i++) {
hypernymList = buildHypernymList(descendants.get(i), null, 5);
for (int j = 0; j < hypernymList.size(); j++) {
for (int k = 0; k < hypernymList.get(j).size(); k++) {
if(sourceSynsetList.contains(hypernymList.get(j).get(k)) && !contained.contains(hypernymList.get(j).get(k)))
contained.add(hypernymList.get(j).get(k));
}
}
}
return contained;
}
private void computeTransitiveClosure() {
Mapping m;
for (int i = 0; i < classesMatrix.getRows(); i++) {
for (int j = 0; j < classesMatrix.getColumns(); j++) {
m = classesMatrix.get(i, j);
if(m == null) continue;
if(m.getRelation() == MappingRelation.SUBCLASS){
OntClass source = sourceClassList.get(m.getSourceKey()).getResource().as(OntClass.class);
List<OntClass> subclasses = listAllSubclasses(source, null);
for(OntClass cl: subclasses){
int index = getIndex(sourceClassList, cl.getURI());
Mapping mapping = new Mapping(sourceClassList.get(index), m.getEntity2(), m.getSimilarity(), m.getRelation());
classesMatrix.set(index, j, mapping);
}
}
else if(m.getRelation() == MappingRelation.SUPERCLASS){
OntClass target = targetClassList.get(m.getTargetKey()).getResource().as(OntClass.class);
List<OntClass> subclasses = listAllSubclasses(target, null);
for(OntClass cl: subclasses){
int index = getIndex(targetClassList, cl.getURI());
Mapping mapping = new Mapping(m.getEntity1(), targetClassList.get(index), m.getSimilarity(), m.getRelation());
classesMatrix.set(i, index, mapping);
}
}
}
}
}
// private void extendToChildren(OntClass node, OntClass , MappingRelation relation, double similarity){
// List<OntClass> subclasses = node.listSubClasses().toList();
private List<OntClass> listAllSubclasses(OntClass node, List<OntClass> result){
if(result == null) result = new ArrayList<OntClass>();
List<OntClass> subclasses = node.listSubClasses().toList();
result.addAll(subclasses);
for(OntClass cl: subclasses)
listAllSubclasses(cl, result);
return result;
}
private boolean synsetIsContainedBy(ArrayList<NounSynset> sourceSynsetList,
ArrayList<ArrayList<NounSynset>> hypernymList) {
for( ArrayList<NounSynset> currentHypernymList : hypernymList ) {
for( NounSynset currentHypernym : currentHypernymList ) {
if( sourceSynsetList.contains(currentHypernym) ){
System.out.println("HYP:" + currentHypernym);
return true;
}
}
}
return false;
}
private ArrayList<ArrayList<NounSynset>> buildHypernymList(Node source, ArrayList<NounSynset> nodeLookupList, int limit) {
ArrayList<ArrayList<NounSynset>> retVal = new ArrayList<ArrayList<NounSynset>>();
if(nodeLookupList == null)
nodeLookupList = doLookUp(source);
ArrayList<NounSynset> hypernymLookupList = nodeLookupList;
/*while( true ) {
hypernymLookupList = doHypernymLookup(hypernymLookupList);
//if( !hypernymLookupList.isEmpty() ) retVal.add(hypernymLookupList);
//else break;
}*/
for(int i=0;;i++)
{
if(i<limit && !hypernymLookupList.isEmpty())
{
hypernymLookupList = doHypernymLookup(hypernymLookupList);
retVal.add(hypernymLookupList);
}
else
{
return retVal;
}
}
//return retVal;
}
/**
* This method compiles a list of NounSynsets which are the hypernyms of all the passed in NounSynsets.
* @param hypernymLookupList
* @return
*/
private ArrayList<NounSynset> doHypernymLookup(
ArrayList<NounSynset> hypernymLookupList) {
ArrayList<NounSynset> hypernymSet = new ArrayList<NounSynset>();
// lookup
for (Synset t : hypernymLookupList)
{
NounSynset[] hypernyms = ((NounSynset)t).getHypernyms();
for (int i = 0; i < hypernyms.length; i++)
{
hypernymSet.add( hypernyms[i] );
}
}
return hypernymSet;
}
/**
* This method returns the list of corresponding WordNet Synsets for given a Node.
* @param conceptNode
* @return
*/
private ArrayList<NounSynset> doLookUp(Node conceptNode)
{
int limit = 3;
ArrayList<NounSynset> synonymSet = new ArrayList<NounSynset>();
String localName = conceptNode.getLocalName();
String searchTerm = localName;
Synset[] synsets = WordNet.getSynsets(searchTerm, SynsetType.NOUN);
for (int i = 0; i < Math.min(synsets.length, limit); i++)
{
Synset currentSynset = synsets[i];
synonymSet.add( (NounSynset) currentSynset);
}
return synonymSet;
}
public void listInstancesOfOntology()
{
//System.out.println("Details of Individual");
//Save individuals of Source and Target
ArrayList<Individual> sourceIndividuals1 = new ArrayList<Individual>();
ExtendedIterator<Individual> sourceIndividualIterator = sourceModel1.listIndividuals();
while(sourceIndividualIterator.hasNext())
{
sourceIndividuals1.add(sourceIndividualIterator.next());
}
for(int i = 0; i < sourceIndividuals1.size(); i++)
{
Individual sourceIndividual = sourceIndividuals1.get(i);
if(sourceIndividual.isAnon())
{
}
else
{
String s = sourceIndividual.getLocalName();
StmtIterator anonPropertySourceItr = sourceIndividual.listProperties();
while(anonPropertySourceItr.hasNext())
{
Statement stmtFirstAnonIndi = (Statement)anonPropertySourceItr.nextStatement();
Property pFirst = (Property)stmtFirstAnonIndi.getPredicate();
RDFNode rfFirst = stmtFirstAnonIndi.getObject();
Literal lFirst;
if(rfFirst.isLiteral())
{
//System.out.println("LOCAL NAME IS "+s);
//System.out.println("URI IS "+sourceIndividual.getURI());
lFirst = (Literal)rfFirst;
//System.out.println("1- " +lFirst.toString());
//String lFirstString = lFirst.toString();
}
}
}
}
}
public void getIndividuals( Node currentNode,ArrayList<Node> list )
{
System.out.println("I am getIndividulas method I have been called by "+currentNode.getLocalName());
ArrayList<Individual> individualsList = new ArrayList<Individual>();
OntClass currentClass = (OntClass) currentNode.getResource().as(OntClass.class);
ExtendedIterator indiIter = currentClass.listInstances(true);
while( indiIter.hasNext() )
individualsList.add( (Individual) indiIter.next());
System.out.println("THE LENGTH OS THE INDIVIDUAL LIST IS "+ individualsList.size());
for (int k = 0; k < individualsList.size(); k++)
{
int row1 = getIndex(list,individualsList.get(k).getURI());
System.out.println("THE VALUE OF MY INDEX IS "+ row1);
if(row1 != -1)
{
Node sourceTemp = (Node)list.get(row1);
System.out.println("THE NODE I HAVE NOW IS AN INDIVIDUAL "+sourceTemp.getLocalName());
//System.out.println("Super Class of "+source.getLocalName()+" IS "+sourceTemp.getLocalName());
}
}
System.out.println("***********************");
}
@Override
public int getDefaultMaxSourceRelations() {
return AbstractMatcher.ANY_INT;
}
@Override
public int getDefaultMaxTargetRelations() {
return AbstractMatcher.ANY_INT;
}
private void getInputMatcher()
{
if(inputMatchers.size()>0)
{
//System.out.println("got the matchers");
AbstractMatcher input = inputMatchers.get(0);
classesMatrix = input.getClassesMatrix();
propertiesMatrix = input.getPropertiesMatrix();
double inputMatcherThreshold = input.getDefaultThreshold();
}
}
/*This function maps many Target Concepts to a source concept*/
private void matchManyTargetSource(Node source,Node target)
{
Node superClassOfTarget;
Node superClassOfSOurce;
/*GET THE INDEX OF THE INPUT PARAMETERS OF THE METHOD*/
int indexSource = source.getIndex();
int indexTarget = target.getIndex();
ExtendedIterator targetIterator;
ExtendedIterator targetSubClassIterator;
OntClass OntClasstarget;
OntClass subClass;
/*THIS ARRAY LIST COLLECTS THE FIRST LEVEL OF SUB-CLASSES*/
ArrayList<OntClass> targetSubClasses = new ArrayList<OntClass>();
ArrayList<OntClass> targetSubClassesLevel2 = new ArrayList<OntClass>();
superClassOfTarget = getSuperClass(target, targetClassList);
superClassOfSOurce = getSuperClass(source, sourceClassList);
/*CONVERTING THE TARGET NODE INTO OntClass*/
OntClasstarget = (OntClass)targetClassList.get(indexTarget).getResource().as(OntClass.class);
targetIterator = OntClasstarget.listSubClasses();
while(targetIterator.hasNext())
{
targetSubClasses.add((OntClass)targetIterator.next());
}
/*MATCHING THE FIRST LEVEL OF SUB-CLASSES*/
for (int k = 0; k < targetSubClasses.size(); k++)
{
int row = getIndex(targetClassList,targetSubClasses.get(k).getURI());
Node targetTemp = (Node)targetClassList.get(row);
if(row != -1)
{
classesMatrix.set(indexSource,targetTemp.getIndex(),new Mapping(source,targetTemp,0.85d,MappingRelation.SUPERCLASS));
}
/*IF THE SOURCE HAS A SUPER CLASS IT WILL HAVE THE SAME subClassOf RELATIONSHIP WITH THE TARGET CONCEPT*/
if(superClassOfSOurce != null)
{
classesMatrix.set(superClassOfSOurce.getIndex(),targetTemp.getIndex(),new Mapping(superClassOfSOurce,targetTemp,0.85d,MappingRelation.SUPERCLASS));
}
}
/*IF SOME FIRST LEVEL OF SUBCLASSES OF TARGET HAVE THE SECOND LEVEL C subClassOf B subClassOf A WE ARE AT LEVEL B AND GOING TO LEVEL C*/
if (targetSubClasses.size() > 0)
{
for (int i = 0; i < targetSubClasses.size(); i++)
{
subClass = targetSubClasses.get(i);
targetSubClassIterator = subClass.listSubClasses();
while(targetSubClassIterator.hasNext())
{
OntClass temp = (OntClass)targetSubClassIterator.next();
targetSubClassesLevel2.add(temp);
int index1 = getIndex(targetClassList,temp.getURI());
Node temp1 = targetClassList.get(index1);
/*HERE THE SECOND LEVEL OF SUBCLASSES ARE BEING MATCHED*/
classesMatrix.set(indexSource,temp1.getIndex(),new Mapping(source,temp1,0.85d,MappingRelation.SUPERCLASS));
if(superClassOfSOurce != null)
{
classesMatrix.set(superClassOfSOurce.getIndex(),temp1.getIndex(),new Mapping(superClassOfSOurce,temp1,0.85d,MappingRelation.SUPERCLASS));
}
}
}
}
/*IF THE THIRD LEVEL GOES TO THE FOURTH LEVEL AS IN D subClassOf C subClassOf B subClassOf A so I attempt to match D to A*/
if (targetSubClassesLevel2.size() > 0 )
{
for (int i = 0; i < targetSubClassesLevel2.size(); i++)
{
subClass = targetSubClassesLevel2.get(i);
targetSubClassIterator = subClass.listSubClasses();
while(targetSubClassIterator.hasNext())
{
OntClass temp = (OntClass)targetSubClassIterator.next();
int index1 = getIndex(targetClassList,temp.getURI());
Node temp1 = targetClassList.get(index1);
classesMatrix.set(indexSource,temp1.getIndex(),new Mapping(source,temp1,0.85d,MappingRelation.SUPERCLASS));
if(superClassOfSOurce != null)
{
classesMatrix.set(superClassOfSOurce.getIndex(),temp1.getIndex(),new Mapping(superClassOfSOurce,temp1,0.85d,MappingRelation.SUPERCLASS));
}
}
}
}
/*FINALLY MATCHING THE SUPER CLASS TO THE TARGET CONCEPT WITH subClassOf relationship*/
if(superClassOfTarget != null)
{
//System.out.println("I have matcher "+source.getLocalName() +" TO "+superClassOfTarget.getLocalName());
classesMatrix.set(source.getIndex(),superClassOfTarget.getIndex(),new Mapping(source,superClassOfTarget,0.85d,MappingRelation.SUPERCLASS));
}
}
private void matchManySourceTarget(Node source,Node target)
{
Node superClassOfSource;
Node superClassOfTarget;
ArrayList<OntClass> sourceSubClasses = new ArrayList<OntClass>();
ArrayList<OntClass> sourceSubClassesLevel2 = new ArrayList<OntClass>();
int indexSource = source.getIndex();
int indexTarget = target.getIndex();
OntClass OntClasssource;
OntClass subClass;
OntClass temp;
ExtendedIterator sourceIterator;
ExtendedIterator sourceSubClassIterator;
superClassOfSource = getSuperClass(source,sourceClassList);
superClassOfTarget = getSuperClass(target,targetClassList);
OntClasssource = (OntClass)sourceClassList.get(indexSource).getResource().as(OntClass.class);
sourceIterator = OntClasssource.listSubClasses();
while(sourceIterator.hasNext())
{
sourceSubClasses.add((OntClass)sourceIterator.next());
}
/* A node of target ontology has an EQUIVALENCE relation with source concept S
* B subClassOf A here we are matching all B to S by subClassOf relationship */
for (int k = 0; k < sourceSubClasses.size(); k++)
{
int row = getIndex(sourceClassList,sourceSubClasses.get(k).getURI());
Node sourceTemp = (Node)sourceClassList.get(row);
classesMatrix.set(sourceTemp.getIndex(),indexTarget,new Mapping(sourceTemp,target,0.85d,MappingRelation.SUBCLASS));
if(superClassOfTarget != null)
{
classesMatrix.set(sourceTemp.getIndex(),superClassOfTarget.getIndex(),new Mapping(sourceTemp,superClassOfTarget,0.85d,MappingRelation.SUBCLASS));
}
}
/*IF SOME FIRST LEVEL OF SUBCLASSES HAVE THE SECOND LEVEL C subClassOf B subClassOf A WE ARE AT LEVEL B AND GOING TO LEVEL C to A*/
if (sourceSubClasses.size() > 0)
{
//System.out.println("I will print second level of subclasses if present");
for (int i = 0; i < sourceSubClasses.size(); i++)
{
subClass = sourceSubClasses.get(i);
sourceSubClassIterator = subClass.listSubClasses();
while(sourceSubClassIterator.hasNext())
{
temp = (OntClass)sourceSubClassIterator.next();
sourceSubClassesLevel2.add(temp);
int index1 = getIndex(sourceClassList,temp.getURI());
Node temp1 = sourceClassList.get(index1);
classesMatrix.set(temp1.getIndex(),indexTarget,new Mapping(temp1,target,0.85d,MappingRelation.SUBCLASS));
if (superClassOfTarget != null)
{
classesMatrix.set(temp1.getIndex(),superClassOfTarget.getIndex(),new Mapping(temp1,superClassOfTarget,0.85d,MappingRelation.SUBCLASS));
}
}
}
}
/*IF SOME SECOND LEVEL OF SUBCLASSES HAVE THE THIRD LEVEL D subClassOf C subClassOf B subClassOf A WE ARE AT LEVEL C AND GOING TO LEVEL D and matching D to A*/
if (sourceSubClassesLevel2.size() > 0)
{
for (int i = 0; i < sourceSubClassesLevel2.size(); i++)
{
subClass = sourceSubClassesLevel2.get(i);
sourceSubClassIterator = subClass.listSubClasses();
while(sourceSubClassIterator.hasNext())
{
temp = (OntClass)sourceSubClassIterator.next();
int index1 = getIndex(sourceClassList,temp.getURI());
Node temp1 = sourceClassList.get(index1);
classesMatrix.set(temp1.getIndex(),indexTarget,new Mapping(temp1,target,0.85d,MappingRelation.SUBCLASS));
if (superClassOfTarget != null)
{
classesMatrix.set(temp1.getIndex(),superClassOfTarget.getIndex(),new Mapping(temp1,superClassOfTarget,0.85d,MappingRelation.SUBCLASS));
}
}
}
}
if(superClassOfSource != null)
{
//System.out.println("I have matcher "+source.getLocalName() +" TO "+superClassOfSource.getLocalName());
classesMatrix.set(superClassOfSource.getIndex(),target.getIndex(),new Mapping(superClassOfSource,target,0.85d,MappingRelation.SUPERCLASS));
}
}
private Node getSuperClass(Node Target,ArrayList<Node> list)
{
int indexTarget = Target.getIndex();
ArrayList<OntClass> targetSuperClasses = new ArrayList<OntClass>();
//targetSuperClasses = null;
OntClass OntClassTarget = (OntClass)list.get(indexTarget).getResource().as(OntClass.class);
ExtendedIterator targetIterator = OntClassTarget.listSuperClasses();
while(targetIterator.hasNext())
{
targetSuperClasses.add((OntClass)targetIterator.next());
}
for (int k = 0; k < targetSuperClasses.size(); k++)
{
int row1 = getIndex(list,targetSuperClasses.get(k).getURI());
if(row1 != -1)
{
Node targetTemp = (Node)list.get(row1);
//System.out.println("Node being returned is "+targetTemp.getLocalName());
return targetTemp;
}
}
return null;
}
public static int getIndex(ArrayList<Node> list, String uri)
{
for (int i = 0; i < list.size(); i++)
{
if(list.get(i).getUri().equals(uri))
return i;
}
return -1;
}
}
|
package am.app.ontology.profiling.manual;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.hp.hpl.jena.ontology.AnnotationProperty;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntProperty;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import am.app.ontology.Node;
import am.app.ontology.Ontology;
import am.app.ontology.profiling.OntologyProfiler;
import am.app.ontology.profiling.OntologyProfilerPanel;
import am.app.ontology.profiling.OntologyProfilerParameters;
import am.app.ontology.profiling.ProfilerRegistry;
import am.utility.Pair;
/**
* This ontology profiler allows the user to manually set
* profiling information.
*
* @author Cosmin Stroe @date January 25, 2011
*
*/
public class ManualOntologyProfiler implements OntologyProfiler {
private ProfilerRegistry name; // automatically set the the OntologyProfilerFactory.
private List<Property> sourceClassAnnotations;
private List<Property> targetClassAnnotations;
private List<Property> sourcePropertyAnnotations;
private List<Property> targetPropertyAnnotations;
private ManualProfilerMatchingParameters matchTimeParams;
// main constructor
public ManualOntologyProfiler(Ontology source, Ontology target) {
sourceClassAnnotations = new ArrayList<Property>();
for( Node classNode : source.getClassesList() ) createClassAnnotationsList(sourceClassAnnotations, classNode);
targetClassAnnotations = new ArrayList<Property>();
for( Node classNode : target.getClassesList() ) createClassAnnotationsList(targetClassAnnotations, classNode);
sourcePropertyAnnotations = new ArrayList<Property>();
for( Node propertyNode : source.getPropertiesList() ) createPropertyAnnotationsList(sourcePropertyAnnotations, propertyNode);
targetPropertyAnnotations = new ArrayList<Property>();
for( Node propertyNode : target.getPropertiesList() ) createPropertyAnnotationsList(targetPropertyAnnotations, propertyNode);
}
private void createPropertyAnnotationsList(
List<Property> propertyList, Node propertyNode) {
OntProperty currentProperty = (OntProperty) propertyNode.getResource().as(OntProperty.class);
StmtIterator i = currentProperty.listProperties();
while( i.hasNext() ) {
Statement s = (Statement) i.next();
Property p = s.getPredicate();
if( p.canAs( AnnotationProperty.class) ) {
if( !propertyList.contains(p) ) propertyList.add(p);
}
}
}
private void createClassAnnotationsList(
List<Property> annotationList, Node classNode) {
OntClass currentClass = (OntClass) classNode.getResource().as(OntClass.class);
StmtIterator i = currentClass.listProperties();
while( i.hasNext() ) {
Statement s = (Statement) i.next();
Property p = s.getPredicate();
if( p.canAs( AnnotationProperty.class ) ) {
// this is an annotation property
if( !annotationList.contains(p) ) annotationList.add(p);
}
}
}
@Override
public OntologyProfilerPanel getProfilerPanel(boolean initial) {
if( initial ) return null;
return new ManualProfilerMatchingPanel(sourceClassAnnotations, targetClassAnnotations, sourcePropertyAnnotations, targetPropertyAnnotations);
}
@Override
public boolean needsParams(boolean initial) {
if( initial ) return false; // this method does not require initial parameters (yet)
else return true; // this method DOES require matching parameters
}
/* Getters and Setters */
@Override public ProfilerRegistry getName() { return name; }
@Override public void setName(ProfilerRegistry name) { this.name = name; }
@Override public void setInitialParams(OntologyProfilerParameters param) { }
@Override public void setMatchTimeParams(OntologyProfilerParameters param) {
if( param instanceof ManualProfilerMatchingParameters ) {
matchTimeParams = (ManualProfilerMatchingParameters) param;
} else {
// we were passed in a different kind of parameters, not much we can do.
matchTimeParams = null;
}
}
/**
* This method returns an iterator through a list of all possible (source,target) combinations
* of the annotation properties.
*/
@Override
public Iterator<Pair<String, String>> getAnnotationIterator(Node n1, Node n2) {
List<Pair<String, String>> l = new ArrayList<Pair<String, String>>();
String sourceLocalName = n1.getLocalName();
String targetLocalName = n2.getLocalName();
if( n1.isClass() ) {
// aligning classes
// source localname <-> target localname
if( matchTimeParams.matchSourceClassLocalname && matchTimeParams.matchTargetClassLocalname ) {
l.add(new Pair<String,String>(sourceLocalName, targetLocalName) );
}
// source localname <-> target annotations
if( matchTimeParams.matchSourceClassLocalname && matchTimeParams.targetClassAnnotations != null ) {
for( Property p : matchTimeParams.targetClassAnnotations ) {
OntClass c1 = n2.getResource().as(OntClass.class);
NodeIterator nIter = c1.listPropertyValues(p);
while( nIter.hasNext() ) {
RDFNode rdfNode = nIter.next();
if( rdfNode.isLiteral() ) {
Literal lit = rdfNode.asLiteral();
l.add(new Pair<String,String>(sourceLocalName, lit.getString()));
}
}
}
}
// source annotations <-> target localname
if( matchTimeParams.sourceClassAnnotations != null && matchTimeParams.matchTargetClassLocalname) {
for( Property p : matchTimeParams.sourceClassAnnotations ) {
OntClass c1 = n1.getResource().as(OntClass.class);
NodeIterator nIter = c1.listPropertyValues(p);
while( nIter.hasNext() ) {
RDFNode rdfNode = nIter.next();
if( rdfNode.isLiteral() ) {
Literal lit = rdfNode.asLiteral();
l.add(new Pair<String,String>(lit.getString(), targetLocalName));
}
}
}
}
// source annotations <-> target annotations
// HOLY COW this is COMPLICATED. - cosmin
if( matchTimeParams.sourceClassAnnotations != null && matchTimeParams.targetClassAnnotations != null ) {
for( Property p1 : matchTimeParams.sourceClassAnnotations ) { // iterate through the source annotation properties
OntClass c1 = n1.getResource().as(OntClass.class);
NodeIterator nIter1 = c1.listPropertyValues(p1);
while( nIter1.hasNext() ) { // iterate through the values of the source annotation properties
RDFNode rdfNode1 = nIter1.next();
if( rdfNode1.isLiteral() ) { // make sure they are literals (because we want strings)
Literal lit1 = rdfNode1.asLiteral();
for( Property p2 : matchTimeParams.targetClassAnnotations ) { // for each source annotation, we iterate through all the target annotations in a similar fashion
OntClass c2 = n2.getResource().as(OntClass.class);
NodeIterator nIter2 = c2.listPropertyValues(p2);
while( nIter2.hasNext() ) { // iterate through the values of the target annotations properties
RDFNode rdfNode2 = nIter2.next();
if( rdfNode2.isLiteral() ) { // again, make sure they are literals
Literal lit2 = rdfNode2.asLiteral();
l.add(new Pair<String, String>( lit1.getString(), lit2.getString() )); // finally, we have two strings, add them to the list.
}
}
}
}
}
}
}
} else if ( n2.isProp() ) {
// aligning properties (the same thing as above, except for properties)
// source localname <-> target localname
if( matchTimeParams.matchSourcePropertyLocalname && matchTimeParams.matchTargetPropertyLocalname ) {
l.add(new Pair<String,String>(sourceLocalName, targetLocalName) );
}
// source localname <-> target annotations
if( matchTimeParams.matchSourcePropertyLocalname && matchTimeParams.targetPropertyAnnotations != null ) {
for( Property p : matchTimeParams.targetPropertyAnnotations ) {
OntProperty c1 = n1.getResource().as(OntProperty.class);
NodeIterator nIter = c1.listPropertyValues(p);
while( nIter.hasNext() ) {
RDFNode rdfNode = nIter.next();
if( rdfNode.isLiteral() ) {
Literal lit = rdfNode.asLiteral();
l.add(new Pair<String,String>(sourceLocalName, lit.getString()));
}
}
}
}
// source annotations <-> target localname
if( matchTimeParams.sourcePropertyAnnotations != null && matchTimeParams.matchTargetPropertyLocalname) {
for( Property p : matchTimeParams.sourcePropertyAnnotations ) {
OntProperty c1 = n1.getResource().as(OntProperty.class);
NodeIterator nIter = c1.listPropertyValues(p);
while( nIter.hasNext() ) {
RDFNode rdfNode = nIter.next();
if( rdfNode.isLiteral() ) {
Literal lit = rdfNode.asLiteral();
l.add(new Pair<String,String>(lit.getString(), targetLocalName));
}
}
}
}
// source annotations <-> target annotations
// HOLY COW this is COMPLICATED. - cosmin
if( matchTimeParams.sourcePropertyAnnotations != null && matchTimeParams.targetPropertyAnnotations != null ) {
for( Property p1 : matchTimeParams.sourcePropertyAnnotations ) { // iterate through the source annotation properties
OntProperty c1 = n1.getResource().as(OntProperty.class);
NodeIterator nIter1 = c1.listPropertyValues(p1);
while( nIter1.hasNext() ) { // iterate through the values of the source annotation properties
RDFNode rdfNode1 = nIter1.next();
if( rdfNode1.isLiteral() ) { // make sure they are literals (because we want strings)
Literal lit1 = rdfNode1.asLiteral();
for( Property p2 : matchTimeParams.targetPropertyAnnotations ) { // for each source annotation, we iterate through all the target annotations in a similar fashion
OntProperty c2 = n2.getResource().as(OntProperty.class);
NodeIterator nIter2 = c2.listPropertyValues(p2);
while( nIter2.hasNext() ) { // iterate through the values of the target annotations properties
RDFNode rdfNode2 = nIter2.next();
if( rdfNode2.isLiteral() ) { // again, make sure they are literals
Literal lit2 = rdfNode2.asLiteral();
l.add(new Pair<String, String>( lit1.getString(), lit2.getString() )); // finally, we have two strings, add them to the list.
}
}
}
}
}
}
}
}
return l.iterator();
}
}
|
package com.jakway.artprocessor.transcoder;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.swing.svg.JSVGComponent;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.util.SVGConstants;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.svg.SVGDocument;
import com.jakway.artprocessor.errorhandler.ArtProcessorErrorHandler;
import com.jakway.artprocessor.errorhandler.TranscoderErrorHandler;
import com.jakway.artprocessor.exception.ArtProcessorException;
import com.jakway.artprocessor.file.FileSystemChecker;
import com.jakway.artprocessor.svg.SVGValidator;
public class ArtProcessorTranscoder
{
private static final String JPEG_EXTENSION=".jpeg";
private static final JPEGRasterOutputParams[] params = {
new JPEGRasterOutputParams("drawable-ldpi", new Float(0.75f), new Float(1.0f)),
new JPEGRasterOutputParams("drawable-mdpi", new Float(1.0f), new Float(1.0f)),
new JPEGRasterOutputParams("drawable-hdpi", new Float(1.5f), new Float(1.0f)),
new JPEGRasterOutputParams("drawable-xhdpi", new Float(2.0f), new Float(1.0f)),
new JPEGRasterOutputParams("drawable-xxhdpi", new Float(3.0f), new Float(1.0f)),
//don't use drawable-xxxhdpi--it's for app icons only
};
private TranscoderErrorHandler errorHandler = null;
private File topLevelOutputDirectory = null;
private ArrayList<File> svgFiles = null;
public ArtProcessorTranscoder(File topLevelOutputDirectory, ArrayList<File> svgFiles, TranscoderErrorHandler errorHandler)
{
this.errorHandler = errorHandler;
this.topLevelOutputDirectory = topLevelOutputDirectory;
this.svgFiles = svgFiles;
}
public void convertAndWriteSVGs()
{
if(topLevelOutputDirectory == null)
{
errorHandler.fatalError(new ArtProcessorException("Passed top level art output directory is null."));
}
if(!topLevelOutputDirectory.exists())
{
topLevelOutputDirectory.mkdir();
}
//best way to check if we can write to the output directory is to try and write something
//canWrite is not sufficient because it checks that the file exists
try{
File test = new File(topLevelOutputDirectory, "test_temp_file");
test.createNewFile();
test.delete();
}
catch(IOException e)
{
errorHandler.fatalError(new ArtProcessorException("Cannot write to the top level art output directory."));
}
//write by directory, first drawables-ldpi, then drawables-mdpi, etc.
for(int i = 0; i < params.length; i++)
{
JPEGRasterOutputParams thisParam = params[i];
File outputDir = new File(topLevelOutputDirectory, thisParam.getOutputDirName());
outputDir.mkdir();
//write every SVG to every drawables directory
for(File thisSVGFile : svgFiles)
{
try {
convertAndWriteSVG(thisSVGFile, outputDir, thisParam);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
errorHandler.error(new ArtProcessorException("Could not find input SVG file: "+thisSVGFile.toString()));
}
catch(TranscoderException e)
{
e.printStackTrace();
errorHandler.error(new ArtProcessorException("Transcoder problem while converting svg file: "+thisSVGFile.toString()+" in directory: "+outputDir.toString()));
}
}
}
}
private Rectangle2D getSVGDimensions(File svgFile) throws IOException
{
org.apache.batik.gvt.GraphicsNode svgIcon = null;
try {
String xmlParser = org.apache.batik.util.XMLResourceDescriptor.getXMLParserClassName();
org.apache.batik.dom.svg.SAXSVGDocumentFactory df = new org.apache.batik.dom.svg.SAXSVGDocumentFactory(
xmlParser);
org.w3c.dom.svg.SVGDocument doc = df.createSVGDocument(SVGValidator.convertToFileURL(svgFile));
org.apache.batik.bridge.UserAgent userAgent = new org.apache.batik.bridge.UserAgentAdapter();
org.apache.batik.bridge.DocumentLoader loader = new org.apache.batik.bridge.DocumentLoader(userAgent);
org.apache.batik.bridge.BridgeContext ctx = new org.apache.batik.bridge.BridgeContext(userAgent, loader);
ctx.setDynamicState(org.apache.batik.bridge.BridgeContext.DYNAMIC);
org.apache.batik.bridge.GVTBuilder builder = new org.apache.batik.bridge.GVTBuilder();
svgIcon = builder.build(ctx, doc);
} catch (Exception excp) {
svgIcon = null;
excp.printStackTrace();
}
Rectangle2D rect = svgIcon.getPrimitiveBounds();
return rect;
}
private void convertAndWriteSVG(File inputSVG, File outputDir, JPEGRasterOutputParams param) throws FileNotFoundException, TranscoderException
{
//generate the output filename and make sure it doesn't already exist
//strip the extension from the input and add .svg
File outputFile = new File(outputDir, getFilenameNoExtension(inputSVG)+JPEG_EXTENSION);
if(outputFile.exists())
{
errorHandler.fatalError(new ArtProcessorException(outputFile.toString()+" already exists in the art output directory."));
}
FileInputStream inStream = null;
FileOutputStream outStream = null;
//write the SVG
try{
JPEGTranscoder transcoder = new JPEGTranscoder();
transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, param.getJpegQuality());
//set the size multiplier
// transcoder.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, new Float(param.getSizeMultiplier().floatValue() * ));
try {getSVGDimensions(inputSVG); } catch(IOException e) {e.printStackTrace(); }
inStream = new FileInputStream(inputSVG);
TranscoderInput transcoderInput = new TranscoderInput(inStream);
outStream = new FileOutputStream(outputFile);
TranscoderOutput transcoderOutput = new TranscoderOutput(outStream);
transcoder.transcode(transcoderInput, transcoderOutput);
}
finally
{
if(inStream != null)
{
try {inStream.close(); } catch(Throwable t) { }
}
if(outStream != null)
{
try {outStream.close(); } catch(Throwable t) { }
}
}
}
private static final String getFilenameNoExtension(File file)
{
return file.getName().replaceFirst("[.][^.]+$", "");
}
}
|
package de.tum.in.cindy3dplugin.jogl.renderers;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import de.tum.in.cindy3dplugin.jogl.ModelViewerCamera;
import de.tum.in.cindy3dplugin.jogl.primitives.Scene;
public class SupersampledFBORenderer extends DefaultRenderer {
private int width;
private int height;
private int superSampleFactor = 2;
private int colorTexture = 0;
private int depthBuffer = 0;
private int framebuffer = 0;
public SupersampledFBORenderer(Scene scene, ModelViewerCamera camera) {
super(scene, camera);
width = height = 1;
}
public int getSuperSampleFactor() {
return superSampleFactor;
}
private void createFramebuffer(GLAutoDrawable drawable, int width, int height) {
GL2 gl = drawable.getGL().getGL2();
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
gl.glBindTexture(GL2.GL_TEXTURE_2D, textures[0]);
gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_GENERATE_MIPMAP, GL2.GL_TRUE);
gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR_MIPMAP_LINEAR);
gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR_MIPMAP_LINEAR);
gl.glTexImage2D(GL2.GL_TEXTURE_2D, 0, GL2.GL_RGB, width, height, 0, GL2.GL_RGB, GL2.GL_UNSIGNED_BYTE, null);
colorTexture = textures[0];
int[] renderbuffers = new int[1];
gl.glGenRenderbuffers(1, renderbuffers, 0);
gl.glBindRenderbuffer(GL2.GL_RENDERBUFFER, renderbuffers[0]);
gl.glRenderbufferStorage(GL2.GL_RENDERBUFFER, GL2.GL_DEPTH_COMPONENT, width, height);
gl.glBindRenderbuffer(GL2.GL_RENDERBUFFER, 0);
depthBuffer = renderbuffers[0];
int[] framebuffers = new int[1];
gl.glGenFramebuffers(1, framebuffers, 0);
gl.glBindFramebuffer(GL2.GL_FRAMEBUFFER, framebuffers[0]);
gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, colorTexture, 0);
gl.glFramebufferRenderbuffer(GL2.GL_FRAMEBUFFER, GL2.GL_DEPTH_ATTACHMENT, GL2.GL_RENDERBUFFER, depthBuffer);
int status = gl.glCheckFramebufferStatus(GL2.GL_FRAMEBUFFER);
if (status != GL2.GL_FRAMEBUFFER_COMPLETE) {
System.err.println("Framebuffer creation failed");
}
gl.glBindFramebuffer(GL2.GL_FRAMEBUFFER, 0);
framebuffer = framebuffers[0];
}
private void destroyFramebuffer(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
int[] textures = { colorTexture };
gl.glDeleteTextures(1, textures, 0);
colorTexture = 0;
int[] renderbuffers = { depthBuffer };
gl.glDeleteRenderbuffers(1, renderbuffers, 0);
depthBuffer = 0;
int[] framebuffers = { framebuffer };
gl.glDeleteFramebuffers(1, framebuffers, 0);
framebuffer = 0;
}
@Override
public void dispose(GLAutoDrawable drawable) {
destroyFramebuffer(drawable);
super.dispose(drawable);
}
@Override
public void display(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
if (framebuffer == 0) {
createFramebuffer(drawable, width, height);
}
// Render to framebuffer
gl.glBindFramebuffer(GL2.GL_FRAMEBUFFER, framebuffer);
gl.glViewport(0, 0, width*superSampleFactor, height*superSampleFactor);
super.display(drawable);
gl.glBindFramebuffer(GL2.GL_FRAMEBUFFER, 0);
gl.glViewport(0,0, width, height);
// Bring framebuffer to screen by drawing a textured quad
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glDisable(GL2.GL_LIGHTING);
gl.glDisable(GL2.GL_DEPTH_TEST);
gl.glEnable(GL2.GL_TEXTURE_2D);
gl.glBindTexture(GL2.GL_TEXTURE_2D, colorTexture);
gl.glGenerateMipmap(GL2.GL_TEXTURE_2D);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2d(0, 0); gl.glVertex3d(-1, -1, 0);
gl.glTexCoord2d(1, 0); gl.glVertex3d( 1, -1, 0);
gl.glTexCoord2d(1, 1); gl.glVertex3d( 1, 1, 0);
gl.glTexCoord2d(0, 1); gl.glVertex3d(-1, 1, 0);
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_DEPTH_TEST);
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glPopMatrix();
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glPopMatrix();
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width,
int height) {
super.reshape(drawable, x, y, width, height);
this.width = width;
this.height = height;
if (framebuffer != 0) {
destroyFramebuffer(drawable);
createFramebuffer(drawable, width*superSampleFactor, height*superSampleFactor);
}
}
}
|
package imagej.ops.tests;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgFactory;
import net.imglib2.type.numeric.integer.ByteType;
import org.junit.Test;
/** Tests involving Gaussian convolution. */
public class GaussTest extends AbstractOpTest {
/** Tests the Gaussian. */
@Test
public void test() {
final Img<ByteType> in =
new ArrayImgFactory<ByteType>().create(new int[] { 20, 20 },
new ByteType());
final Img<ByteType> out = in.copy();
final double sigma = 5;
ops.run("gauss", out, in, sigma);
}
}
|
package innovimax.mixthem;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.arguments.Rule;
import innovimax.mixthem.arguments.RuleParam;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* Provides different runs for testing a rule according to the additional parameters
* @author Innovimax
* @version 1.0
*/
public class RuleRuns {
/**
* Returns a list of test runs for the rule.
* @param url The URL of rule additional parameters file
* @return Returns a list of test runs for the rule
*/
public static List<RuleRun> getRuns(final Rule rule, final URL url) throws FileNotFoundException, IOException, NumberFormatException {
final List<RuleRun> runs = new LinkedList<RuleRun>();
runs.add(new RuleRun(1, Collections.emptySet(), Collections.emptyMap()));
if (url != null) {
final File file = new File(url.getFile());
final BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8);
final Stream<String> entries = reader.lines();
entries.forEach(entry -> {
//final String[] parts = entry.split("\\s");
//if (parts.length > 0) {
// final String value = parts[0];
try {
final ObjectMapper jsonMapper = new ObjectMapper();
final JsonNode jsonParams = jsonMapper.readTree(entry);
// get selection
final Set<Integer> selection = new LinkedHashSet<Integer>();
if (jsonParams.has("selection")) {
final JsonNode node = jsonParams.get("selection");
if (node.isArray()) {
((ArrayNode) node).findValues().stream()
.mapToObj(Integer::valueOf())
.forEach(index -> selection.put(index));
}
}
// get rule parameters
final Map<RuleParam, ParamValue> params = new EnumMap<RuleParam, ParamValue>(RuleParam.class);
switch (rule) {
case ADD:
//params.put(RuleParam.FILE_LIST, RuleParam.FILE_LIST.createValue(value));
//DEPRECATED
break;
case RANDOM_ALT_LINE:
case RANDOM_ALT_CHAR:
case RANDOM_ALT_BYTE:
//params.put(RuleParam.RANDOM_SEED, ParamValue.createInt(Integer.parseInt(value)));
if (jsonParams.has(RuleParam.RANDOM_SEED.getName())) {
final JsonNode seed = jsonParams.get(RuleParam.RANDOM_SEED.getName());
if (seed.isInt()) {
params.put(RuleParam.RANDOM_SEED, ParamValue.createInt(seed.asInt()));
}
}
break;
case JOIN:
//params.put(RuleParam.JOIN_COLS, RuleParam.JOIN_COLS.createValue(value));
if (jsonParams.has(RuleParam.JOIN_COLS.getName())) {
final JsonNode cols = jsonParams.get(RuleParam.JOIN_COLS.getName());
//TODO: get as array
if (cols.isTextual()) {
params.put(RuleParam.JOIN_COLS, RuleParam.JOIN_COLS.createValue(cols.asText()));
}
}
break;
case ZIP_LINE:
case ZIP_CELL:
case ZIP_CHAR:
//params.put(RuleParam.ZIP_SEP, ParamValue.createString(value));
if (jsonParams.has(RuleParam.ZIP_SEP.getName())) {
final JsonNode sep = jsonParams.get(RuleParam.ZIP_SEP.getName());
if (sep.isTextual()) {
params.put(RuleParam.ZIP_SEP, ParamValue.createString(sep.asText()));
}
}
}
// add a rule run
if (!selection.isEmpty() || !params.isEmpty()) {
runs.add(new RuleRun(runs.size()+1, selection, params));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
// runs.add(new RuleRun(runs.size()+1, params));
});
}
return runs;
}
}
|
package io.nats.client;
import static org.junit.Assert.*;
import static io.nats.client.UnitTestUtilities.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.nats.client.Constants.ConnState;
@Category(UnitTest.class)
public class ClusterTest {
final static Logger logger = LoggerFactory.getLogger(ClusterTest.class);
@Rule
public TestCasePrinterRule pr = new TestCasePrinterRule(System.out);
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
// s = util.createServerWithConfig("auth_1222.conf");
}
@After
public void tearDown() throws Exception {
// s.shutdown();
}
final static String[] testServers = new String[] {
"nats://localhost:1222",
"nats://localhost:1223",
"nats://localhost:1224",
"nats://localhost:1225",
"nats://localhost:1226",
"nats://localhost:1227",
"nats://localhost:1228"
};
final static String[] testServersShortList = new String[] {
"nats://localhost:1222",
"nats://localhost:1223"
};
UnitTestUtilities utils = new UnitTestUtilities();
@Test
public void testServersOption() throws IOException, TimeoutException
{
ConnectionFactory cf = new ConnectionFactory();
cf.setNoRandomize(true);
cf.setServers(testServers);
// Make sure we can connect to first server if running
try (NATSServer ns = utils.createServerOnPort(1222)) {
try (Connection c = cf.createConnection()) {
assertTrue(String.format("%s != %s", testServers[0], c.getConnectedUrl()),
testServers[0].equals(c.getConnectedUrl()));
} catch (IOException | TimeoutException e) {
throw e;
}
} catch (Exception e1) {
fail(e1.getMessage());
}
// make sure we can connect to a non-first server.
try (NATSServer ns = utils.createServerOnPort(1227)) {
try (Connection c = cf.createConnection()) {
assertTrue(testServers[5] + " != " + c.getConnectedUrl(), testServers[5].equals(c.getConnectedUrl()));
} catch (IOException | TimeoutException e) {
throw e;
}
} catch (Exception e1) {
fail(e1.getMessage());
}
}
@Test
public void testAuthServers() throws IOException, TimeoutException
{
String[] plainServers = new String[] {
"nats://localhost:1222",
"nats://localhost:1224"
};
ConnectionFactory cf = new ConnectionFactory();
cf.setNoRandomize(true);
cf.setServers(plainServers);
cf.setConnectionTimeout(5000);
try (NATSServer as1 = utils.createServerWithConfig("auth_1222.conf")) {
try (NATSServer as2 = utils.createServerWithConfig("auth_1224.conf")) {
boolean exThrown=false;
try (Connection c = cf.createConnection()) {
fail("Expect Auth failure, got no error");
} catch (Exception e) {
assertTrue("Expected IOException", e instanceof IOException);
assertNotNull(e.getMessage());
assertEquals(Constants.ERR_AUTHORIZATION, e.getMessage());
exThrown=true;
}
assertTrue("Expect Auth failure, got no error", exThrown);
// Test that we can connect to a subsequent correct server.
String[] authServers = new String[] {
"nats://localhost:1222",
"nats://username:password@localhost:1224"};
cf.setServers(authServers);
try (Connection c = cf.createConnection()) {
assertTrue(c.getConnectedUrl().equals(authServers[1]));
} catch (IOException | TimeoutException e) {
if (e.getMessage().contains("Authorization")) {
// ignore Authorization Failure
}
else {
fail("Expected to connect properly: " + e.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
} // as2
} // as1
}
@Test
public void testBasicClusterReconnect()
{
try (NATSServer s1 = utils.createServerOnPort(1222)) {
try (NATSServer s2 = utils.createServerOnPort(1224)) {
final AtomicLong disconTimestamp = new AtomicLong(0L);
final AtomicLong reconElapsed = new AtomicLong(0L);
final ConnectionFactory cf = new ConnectionFactory(testServers);
cf.setMaxReconnect(2);
cf.setReconnectWait(1000);
cf.setNoRandomize(true);
final Channel<Boolean> dch = new Channel<Boolean>();
cf.setDisconnectedCallback(new DisconnectedCallback() {
public void onDisconnect(ConnectionEvent event) {
logger.trace("onDisconnect()");
disconTimestamp.set(System.nanoTime());
// Suppress any additional calls
event.getConnection().setDisconnectedCallback(null);
dch.add(true);
logger.trace("signaled disconnect");
}
});
final Channel<Boolean> rch = new Channel<Boolean>();
cf.setReconnectedCallback(new ReconnectedCallback() {
public void onReconnect(ConnectionEvent event) {
logger.trace("onReconnect()");
reconElapsed.set(TimeUnit.NANOSECONDS.toMillis(
System.nanoTime() - disconTimestamp.get()));
rch.add(true);
logger.trace("signaled reconnect");
}
});
try (Connection c = cf.createConnection()) {
assertNotNull(c.getConnectedUrl());
s1.shutdown();
// wait for disconnect
try {
logger.trace("\n\nWaiting for disconnect signal\n\n");
assertTrue("Did not receive a disconnect callback message",
dch.get(2, TimeUnit.SECONDS));
} catch (TimeoutException e) {
fail("Did not receive a disconnect callback message: " + e.getMessage());
}
sleep(3, TimeUnit.SECONDS);
try {
logger.trace("\n\nWaiting for reconnect signal\n\n");
assertTrue("Did not receive a reconnect callback message: ",
rch.get(2, TimeUnit.SECONDS));
} catch (TimeoutException e) {
fail("Did not receive a reconnect callback message: " + e.getMessage());
}
assertTrue(c.getConnectedUrl().equals(testServers[2]));
// Make sure we did not wait on reconnect for default time.
// Reconnect should be fast since it will be a switch to the
// second server and not be dependent on server restart time.
// assertTrue(reconElapsed.get() <= cf.getReconnectWait());
assertTrue(reconElapsed.get() < 100);
} catch (IOException | TimeoutException e) {
fail(e.getMessage());
}
}
}
}
@Test
public void testHotSpotReconnect()
{
int numClients = 100;
ExecutorService executor =
Executors.newFixedThreadPool(numClients,
new NATSThreadFactory("testhotspotreconnect"));
final Channel<String> rch = new Channel<String>();
final Channel<Integer> dch = new Channel<Integer>();
final AtomicBoolean shutdown = new AtomicBoolean(false);
try (NATSServer s1 = utils.createServerOnPort(1222)) {
try (NATSServer s2 = utils.createServerOnPort(1224)) {
try (NATSServer s3 = utils.createServerOnPort(1226)) {
final class NATSClient implements Runnable {
ConnectionFactory cf = new ConnectionFactory();
Connection nc = null;
final AtomicInteger numReconnects = new AtomicInteger(0);
final AtomicInteger numDisconnects = new AtomicInteger(0);
String currentUrl = null;
final AtomicInteger instance = new AtomicInteger(-1);
NATSClient(int inst) {
this.instance.set(inst);
cf.setServers(testServers);
cf.setDisconnectedCallback(new DisconnectedCallback() {
public void onDisconnect(ConnectionEvent event) {
numDisconnects.incrementAndGet();
dch.add(instance.get());
nc.setDisconnectedCallback(null);
}
});
cf.setReconnectedCallback(new ReconnectedCallback() {
public void onReconnect(ConnectionEvent event) {
numReconnects.incrementAndGet();
currentUrl = nc.getConnectedUrl();
rch.add(currentUrl);
}
});
}
@Override public void run() {
try
{
nc = cf.createConnection();
assertTrue(!nc.isClosed());
assertNotNull(nc.getConnectedUrl());
currentUrl = nc.getConnectedUrl();
// System.err.println("Instance " + instance + " connected to " + currentUrl);
while(!shutdown.get()) {
sleep(10);
}
nc.close();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
public synchronized boolean isConnected() {
return (nc!=null && !nc.isClosed());
}
public void shutdown() {
shutdown.set(true);
}
}
List<NATSClient> tasks = new ArrayList<NATSClient>(numClients);
for(int i=0; i< numClients; i++){
NATSClient r = new NATSClient(i);
tasks.add(r);
executor.submit(r);
}
Map<String, Integer> cs = new HashMap<String, Integer>();
int numReady = 0;
while (numReady < numClients) {
numReady = 0;
for (NATSClient cli : tasks) {
if (cli.isConnected()) {
numReady++;
}
}
sleep(100);
}
s1.shutdown();
sleep(1000);
int disconnected = 0;
// wait for disconnects
while (dch.getCount()>0 && disconnected<numClients) {
Integer instance = -1;
try {
instance = dch.get(5, TimeUnit.SECONDS);
assertNotNull(instance);
} catch (TimeoutException e) {
fail("timed out waiting for disconnect signal");
}
disconnected++;
}
assertTrue(disconnected > 0);
int reconnected = 0;
// wait for reconnects
for (int i=0; i<disconnected; i++) {
String url = null;
while (rch.getCount()==0) {
sleep(50);
}
try {
url = rch.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
fail("timed out waiting for reconnect signal");
}
assertNotNull(url);
reconnected++;
Integer count = cs.get(url);
if (count != null)
cs.put(url, ++count);
else
cs.put(url, new Integer(1));
}
for (NATSClient client : tasks) {
client.shutdown();
}
executor.shutdown();
try {
assertTrue(executor.awaitTermination(2, TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(disconnected, reconnected);
int numServers = 2;
assertEquals(numServers, cs.size());
int expected = numClients/numServers;
// We expect a 40 percent variance
int v = (int) ((float)expected * 0.40);
int delta = Math.abs(cs.get(testServers[2]) -
cs.get(testServers[4]));
// System.err.printf("v = %d, delta = %d\n", v, delta);
if (delta > v)
{
String s = String.format("Connected clients to servers out of range: %d/%d",
delta, v);
fail(s);
}
}
}
}
}
@Test
public void testProperReconnectDelay() throws Exception
{
try (NATSServer s1 = utils.createServerOnPort(1222))
{
ConnectionFactory cf = new ConnectionFactory();
cf.setServers(testServers);
cf.setNoRandomize(true);
final Channel<Boolean> dch = new Channel<Boolean>();
cf.setDisconnectedCallback( new DisconnectedCallback() {
public void onDisconnect(ConnectionEvent event) {
event.getConnection().setDisconnectedCallback(null);
dch.add(true);
}
});
final AtomicBoolean ccbCalled = new AtomicBoolean(false);
cf.setClosedCallback(new ClosedCallback()
{
public void onClose(ConnectionEvent event) {
ccbCalled.set(true);
}
});
try (Connection c = cf.createConnection())
{
assertFalse(c.isClosed());
s1.shutdown();
// wait for disconnect
assertTrue("Did not receive a disconnect callback message",
dch.get(2, TimeUnit.SECONDS));
// Wait, want to make sure we don't spin on reconnect to non-existent servers.
sleep (1, TimeUnit.SECONDS);
assertFalse("Closed CB was triggered, should not have been.",
ccbCalled.get());
assertEquals("Wrong state: " + c.getState(),
c.getState(), ConnState.RECONNECTING);
}
}
}
@Test
public void testProperFalloutAfterMaxAttempts()
{
ConnectionFactory cf = new ConnectionFactory();
// cf.setServers(testServersShortList);
cf.setServers(testServers);
cf.setNoRandomize(true);
cf.setMaxReconnect(5);
cf.setReconnectWait(25); // millis
final Channel<Boolean> dch = new Channel<Boolean>();
final AtomicBoolean dcbCalled = new AtomicBoolean(false);
cf.setDisconnectedCallback(new DisconnectedCallback()
{
public void onDisconnect(ConnectionEvent event) {
dcbCalled.set(true);
dch.add(true);
}
});
final AtomicBoolean closedCbCalled = new AtomicBoolean(false);
final Channel<Boolean> cch = new Channel<Boolean>();
cf.setClosedCallback(new ClosedCallback()
{
public void onClose(ConnectionEvent event) {
closedCbCalled.set(true);
cch.add(true);
}
});
try (NATSServer s1 = utils.createServerOnPort(1222))
{
try (Connection c = cf.createConnection())
{
s1.shutdown();
// wait for disconnect
try {
assertTrue("Did not receive a disconnect callback message",
dch.get(2,TimeUnit.SECONDS));
} catch (TimeoutException e) {
fail("Did not receive a disconnect callback message");
}
// Wait for ClosedCB
try {
assertTrue("Did not receive a closed callback message",
cch.get(2,TimeUnit.SECONDS));
} catch (TimeoutException e) {
fail("Did not receive a closed callback message");
}
// Make sure we are not still reconnecting.
assertTrue("Closed CB was not triggered, should have been.",
closedCbCalled.get());
// Expect connection to be closed...
assertTrue("Wrong status: " + c.getState(), c.isClosed());
} catch (IOException | TimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
@Test
public void testTimeoutOnNoServers()
{
final ConnectionFactory cf = new ConnectionFactory();
cf.setServers(testServers);
cf.setNoRandomize(true);
// 1 second total time wait
cf.setMaxReconnect(10);
cf.setReconnectWait(100);
final AtomicBoolean dcbCalled = new AtomicBoolean(false);
final Channel<Boolean> dch = new Channel<Boolean>();
cf.setDisconnectedCallback(new DisconnectedCallback() {
public void onDisconnect(ConnectionEvent ev) {
ev.getConnection().setDisconnectedCallback(null);
dcbCalled.set(true);
dch.add(true);
}
});
final Channel<Boolean> cch = new Channel<Boolean>();
cf.setClosedCallback(new ClosedCallback() {
public void onClose(ConnectionEvent ev) {
cch.add(true);
}
});
try (NATSServer s1 = new NATSServer(1222)) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
try (Connection c = cf.createConnection())
{
assertNotNull(c.getDisconnectedCallback());
s1.shutdown();
// while(dch.getCount()!=1) {
// UnitTestUtilities.sleep(50);
// wait for disconnect
assertTrue("Did not receive a disconnect callback message",
dch.get(2, TimeUnit.SECONDS));
long t0 = System.nanoTime();
// Wait for ClosedCB
assertTrue("Did not receive a closed callback message",
cch.get(2, TimeUnit.SECONDS));
long elapsedMsec = TimeUnit.NANOSECONDS.toMillis(
System.nanoTime() - t0);
// Use 500ms as variable time delta
long variable = 500;
long expected = cf.getMaxReconnect() * cf.getReconnectWait();
assertFalse("Waited too long for Closed state: " + elapsedMsec,
elapsedMsec > (expected + variable));
} catch (IOException | TimeoutException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
// TODO this test, as written in Go, makes no sense
// @Test
public void testPingReconnect() throws Exception
{
int RECONNECTS = 4;
try (NATSServer s1 = utils.createServerOnPort(1222))
{
ConnectionFactory cf = new ConnectionFactory();
cf.setServers(testServers);
cf.setNoRandomize(true);
cf.setReconnectWait(200);
cf.setPingInterval(50);
cf.setMaxPingsOut(-1);
cf.setConnectionTimeout(1000);
final Channel<Long> rch = new Channel<Long>(RECONNECTS);
final Channel<Long> dch = new Channel<Long>(RECONNECTS);
cf.setDisconnectedCallback(new DisconnectedCallback()
{
public void onDisconnect(ConnectionEvent event) {
dch.add(System.nanoTime());
System.err.println("onDisconnect(), disconnected from " + event.nc.getConnectedUrl());
}
});
cf.setReconnectedCallback(new ReconnectedCallback()
{
@Override
public void onReconnect(ConnectionEvent event) {
rch.add(System.nanoTime());
System.err.println("onReconnect()");
}
});
try (ConnectionImpl c = cf.createConnection())
{
assertFalse(c.isClosed());
s1.shutdown();
while (dch.getCount() == 0) {
Thread.sleep(5);
}
System.err.println("Proceeding");
for (int i = 0; i < RECONNECTS-1; i++)
{
System.err.println("dch.get...");
Long disconnectedAt = dch.get(5, TimeUnit.SECONDS);
assertNotNull(disconnectedAt);
System.err.println("rch.get...");
long reconnectedAt = rch.get(1, TimeUnit.SECONDS);
assertNotNull(reconnectedAt);
long pingCycle = TimeUnit.NANOSECONDS.toMillis(disconnectedAt - reconnectedAt);
assertFalse(pingCycle > 2 * c.opts.getPingInterval());
}
}
}
}
}
|
package me.pagarme;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.JsonObject;
import me.pagar.model.Address;
import me.pagar.model.BankAccount;
import me.pagar.model.Customer;
import me.pagar.model.PagarMeException;
import me.pagar.model.Phone;
import me.pagar.model.Recipient;
import me.pagar.model.SplitRule;
import me.pagar.model.Transaction;
import me.pagar.model.Transaction.CaptureMethod;
import me.pagar.util.JSONUtils;
import me.pagarme.factory.RecipientFactory;
import me.pagarme.factory.TransactionFactory;
import me.pagarme.helper.TestEndpoints;
public class TransactionTest extends BaseTest {
private RecipientFactory recipientFactory = new RecipientFactory();
private TransactionFactory transactionFactory = new TransactionFactory();
private TestEndpoints testEndpoints = new TestEndpoints();
private static Integer AMOUNT = 100;
private static Integer PAID_AMOUNT_PARTIAL = 50;
@Before
public void setUp() {
super.setUp();
transaction = new Transaction();
}
@Test
public void testCreatedDateExistence() throws PagarMeException{
transaction = transactionFactory.createCreditCardTransaction();
transaction.save();
Assert.assertNotNull(transaction.getCreatedAt());
}
@Test
public void testCreateAndCaptureTransactionWithOfflineDebitCard() throws Throwable {
transaction = transactionFactory.create("offline");
transaction.setCapture(true);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.DEBIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testCreateAndAuthorizedTransactionWithOfflineDebitCard() throws Throwable {
transaction = transactionFactory.create("offline");
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.DEBIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
}
@Test
public void testCreateAndCaptureTransactionWithOnlineDebitCard() throws Throwable {
transaction = transactionFactory.create("online");
transaction.setCapture(true);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.DEBIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testCreateAndCaptureTransactionWithCardEmv() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
String cardEmvTest = "Card Emv Testee";
String cardTrack2Test = "Card Track 2 Testee";
transaction.setCardEmvData(cardEmvTest);
transaction.setCardTrack2(cardTrack2Test);
transaction.setCaptureMethod(CaptureMethod.EMV);
transaction.save();
Assert.assertNotNull(transaction.getCardEmvResponse());
}
@Test
public void testCreateAndAuthorizedTransactionWithOnlineDebitCard() throws Throwable {
transaction = transactionFactory.create("online");
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.DEBIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
}
@Test
public void testCreateAndCaptureTransactionWithSoftDescriptor() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setSoftDescriptor("API Test");
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(transaction.getSoftDescriptor(), "API Test");
}
@Test
public void testCreateAndCaptureTransactionWithCreditCardWithoutGoingThroughFraud() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(true);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testCreateAndCaptureTransactionMetaData() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(true);
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("metadata1", "value1");
metadata.put("metadata2", "value2");
transaction.setMetadata(metadata);
transaction.save();
Transaction foundTransaction = new Transaction().find(transaction.getId());
Assert.assertEquals(foundTransaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(foundTransaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(foundTransaction.getMetadata().get("metadata1"), "value1");
Assert.assertEquals(foundTransaction.getMetadata().get("metadata2"), "value2");
}
@SuppressWarnings("unchecked")
@Test
public void testCreateAndCaptureTransactionAntifraudMetaDataMap() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(true);
Map<String, Object> antifraudMetadata = new HashMap<String, Object>();
antifraudMetadata.put("antifraudMetadata1", "value1");
antifraudMetadata.put("antifraudMetadata2", "value2");
transaction.setAntifraudMetadata(antifraudMetadata);
transaction.save();
JsonObject json = JSONUtils.treeToJson(transaction.getAntifraudMetadata());
Map<String, Object> antifraudMetadataRes = JSONUtils.getAsObject(json, HashMap.class);
Assert.assertEquals(antifraudMetadataRes.get("antifraudMetadata1"), "value1");
Assert.assertEquals(antifraudMetadataRes.get("antifraudMetadata2"), "value2");
}
@Test
public void testCreateAndCaptureTransactionAntifraudMetaDataPojo() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(true);
AntifraudMetadataPojo antifraudMetadata = new AntifraudMetadataPojo();
antifraudMetadata.setName("Philip J. Fry");
transaction.setAntifraudMetadata(antifraudMetadata);
transaction.save();
JsonObject json = JSONUtils.treeToJson(transaction.getAntifraudMetadata());
AntifraudMetadataPojo antifraudMetadataRes = JSONUtils.getAsObject(json, AntifraudMetadataPojo.class);
Assert.assertEquals(antifraudMetadataRes.getName(), "Philip J. Fry");
}
@Test
public void testCreateAndCaptureTransactionMetaDataInCapture() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(false);
transaction.save();
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("metadata1", "value1");
metadata.put("metadata2", "value2");
transaction.setMetadata(metadata);
transaction.capture(AMOUNT);
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testCreateAndAuthorizedTransactionWithCreditCardWithoutGoingThroughFraud() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
}
@Test
public void testTransactionCreatePostbackUrl() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setPostbackUrl("http://pagar.me");
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PROCESSING);
}
@Test
public void testTransactionAuthAndCaptureCaptureTotalValue() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
transaction.capture(AMOUNT);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testTransactionCanBeMadeString() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.toString();
}
@Test
public void testTransactionCanBeMadeJSON() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
transaction.capture(50);
transaction.toJson();
}
@Test
public void testTransactionAuthAndCaptureCapturePartialValue() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
transaction.capture(50);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(transaction.getPaidAmount(), PAID_AMOUNT_PARTIAL);
Assert.assertEquals(transaction.getAuthorizedAmount(), AMOUNT);
}
@Test
public void testTransactionAuthAndCaptureRefoundPartialValue() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(true);
transaction.save();
transaction.refund(50);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(transaction.getPaidAmount(), AMOUNT);
Assert.assertEquals(transaction.getRefundedAmount(), PAID_AMOUNT_PARTIAL);
Assert.assertEquals(transaction.getAuthorizedAmount(), AMOUNT);
}
@Test
public void testBoletoTransactionAuthAndCaptureRefund() throws Throwable {
Transaction transaction = transactionFactory.createBoletoTransaction();
transaction.setCapture(true);
transaction.setAmount(10000);
transaction.save();
transaction = testEndpoints.payBoleto(transaction);
Transaction transaction2 = transactionFactory.createBoletoTransaction();
transaction2.setCapture(true);
transaction2.setAmount(10000);
transaction2.save();
transaction2 = testEndpoints.payBoleto(transaction2);
BankAccount bankAccount = (BankAccount)new BankAccount().findCollection(1, 0).toArray()[0];
transaction.refund(bankAccount);
Assert.assertEquals(Transaction.Status.PENDING_REFUND, transaction.getStatus());
}
@Test
public void testTransactionAuthAndCaptureRefoundTotalValue() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(true);
transaction.save();
transaction.refund(AMOUNT);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.REFUNDED);
Assert.assertEquals(transaction.getRefundedAmount(), AMOUNT);
}
@Test
public void testCreateAndAuthorizedTransactionWithBoleto() throws Throwable {
transaction = transactionFactory.createBoletoTransaction();
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.WAITING_PAYMENT);
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.BOLETO);
}
@Test
public void testCreateTransactionWithBoleto() throws Throwable {
transaction = transactionFactory.createBoletoTransaction();
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.WAITING_PAYMENT);
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.BOLETO);
Assert.assertEquals(transaction.getBoletoUrl(), "https://pagar.me");
Assert.assertNotNull(transaction.getBoletoBarcode());
}
@Test
public void testFindTransactionById() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.save();
Integer transactionId = transaction.getId();
transaction = transaction.find(transactionId);
Assert.assertEquals(transaction.getId(), transactionId);
}
@Test
public void testCreatingCustomerTransactionThroughTheTransaction() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(true);
Customer customer = this.customerCommon();
Address address = this.addressCommon();
Phone phone = this.phoneCommon();
customer.setAddress(address);
customer.setPhone(phone);
transaction.setCustomer(customer);
transaction.save();
Customer transactionCustomer = transaction.getCustomer();
Assert.assertEquals(transactionCustomer.getName(), "lucas santos");
Assert.assertEquals(transactionCustomer.getDocumentNumber(), "15317529506");
Assert.assertEquals(transactionCustomer.getEmail(), "testelibjava@pagar.me");
Address transactionAddress = transactionCustomer.getAddress();
Assert.assertEquals(transactionAddress.getStreet(), "Rua Piraju");
Assert.assertEquals(transactionAddress.getStreetNumber(), "218");
Assert.assertEquals(transactionAddress.getComplementary(), "ao lado da consigáz");
Assert.assertEquals(transactionAddress.getNeighborhood(), "Interlagos");
Phone transactionPhone = transactionCustomer.getPhone();
Assert.assertEquals(transactionPhone.getDdd(), "11");
Assert.assertEquals(transactionPhone.getNumber(), "55284132");
}
@Test
public void testSplitTransaction() throws Throwable {
transaction = transactionFactory.createCreditCardTransaction();
transaction.setCapture(true);
transaction.setAmount(10000);
Collection<SplitRule> splitRules = new ArrayList<SplitRule>();
Recipient recipient1 = recipientFactory.create();
recipient1.save();
SplitRule splitRule = new SplitRule();
splitRule.setRecipientId(recipient1.getId());
splitRule.setPercentage(50);
splitRule.setLiable(true);
splitRule.setChargeProcessingFee(true);
splitRules.add(splitRule);
Recipient recipient2 = recipientFactory.create();
SplitRule splitRule2 = new SplitRule();
recipient2.save();
splitRule2.setRecipientId(recipient2.getId());
splitRule2.setPercentage(50);
splitRule2.setLiable(true);
splitRule2.setChargeProcessingFee(true);
splitRules.add(splitRule2);
transaction.setSplitRules(splitRules);
transaction.save();
Transaction foundTransaction = new Transaction().find(transaction.getId());
Collection<SplitRule> foundSplitRules = foundTransaction.getSplitRules();
Assert.assertEquals(splitRules.size(), foundSplitRules.size());
}
// private String getRecipientId(Boolean documentNumber) {
// int bankAccountId = this.getBankAccountId(documentNumber);
// recipient.setTransferInterval(Recipient.TransferInterval.WEEKLY);
// recipient.setTransferDay(TRANSFER_DAY);
// recipient.setTransferEnabled(TRANSFER_ENABLE);
// recipient.setBankAccountId(bankAccountId);
// try {
// recipient.save();
// return recipient.getId();
// } catch (PagarMeException exception) {
// throw new UnsupportedOperationException(exception);
// /**
// *
// * @return
// */
// private Integer getBankAccountId(Boolean documentNumber) {
// System.out.print("Hello " + documentNumber);
// if (documentNumber == true) {
// bankAccount = new BankAccount();
// bankAccount.setAgencia(AGENCIA);
// bankAccount.setAgenciaDv(AGENCIA_DV);
// bankAccount.setConta(CONTA);
// bankAccount.setContaDv(CONTA_DV);
// bankAccount.setBankCode(BANK_CODE);
// bankAccount.setDocumentNumber(DOCUMENT_NUMBER);
// } else {
// bankAccount = new BankAccount();
// System.out.print("Hello " + bankAccount.getConta());
// bankAccount.setAgencia("0173");
// bankAccount.setAgenciaDv("1");
// bankAccount.setConta("506725");
// bankAccount.setContaDv(CONTA_DV);
// bankAccount.setBankCode(BANK_CODE);
// bankAccount.setDocumentNumber("55278368128");
// try {
// bankAccount.save();
// return bankAccount.getId();
// } catch (PagarMeException exception) {
// throw new UnsupportedOperationException(exception);
}
|
package cmput301t4.gameswap.Activities;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import cmput301t4.gameswap.Managers.ServerManager;
import cmput301t4.gameswap.Managers.UserManager;
import cmput301t4.gameswap.R;
public class ViewItemActivity extends Activity {
/*Declaring all the listViews here*/
private TextView name;
private TextView quality;
private TextView description;
private TextView platform;
private TextView date;
private Boolean status;
private String statusDisplay;
private TextView statusView;
private ImageView imageView;
private TextView location;
private ArrayList<String> platformList;
private String platformString;
private Integer platformIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_item);
name = (TextView) findViewById(R.id.viewItemName);
quality = (TextView) findViewById(R.id.viewItemQuality);
description = (TextView) findViewById(R.id.viewItemDesciption);
platform = (TextView) findViewById(R.id.viewItemPlatform);
date = (TextView) findViewById(R.id.viewItemDate);
name = (TextView) findViewById(R.id.viewItemName);
statusView = (TextView) findViewById(R.id.viewStatus);
location =(TextView) findViewById(R.id.locationDescription);
imageView = (ImageView) findViewById(R.id.gameImageView);
Intent intent = getIntent();
Bundle b = intent.getExtras();
if(b!=null){
description.setText(b.getString("description"));
status = b.getBoolean("private");
if (status == Boolean.TRUE){
statusDisplay = "Private";
}
else {
statusDisplay = "Public";
}
name.setText(b.getString("name"));
date.setText(b.getString("releaseDate"));
quality.setText(b.getString("quality"));
platform.setText(b.getString("platform"));
statusView.setText(statusDisplay.toUpperCase());
location.setText("Latitude: " + b.getDouble("Latitude") + ", Longitude: " + b.getDouble("Longitude"));
ServerManager.loadImage(b.getInt("itemId"));
//ServerManager.loadImage(8);
System.out.println("reached load image");
//byte[] decodeImage = Base64.decode(UserManager.getImage().getImage(), Base64.DEFAULT);
if(UserManager.imageRdy == 1) {
byte[] byteArray = UserManager.getImage().getImage();
Bitmap image = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imageView.setImageBitmap(image);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_view_item, 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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public TextView getNameText() {
return name;
}
public TextView getQualityText() {
return quality;
}
public TextView getDescritionText() {
return description;
}
public TextView getPlatformText() {
return platform;
}
public TextView getDateText() {
return date;
}
public String getStatusText() {
return statusDisplay;
}
}
|
package org.takes.rs.xe;
import com.jcabi.matchers.XhtmlMatchers;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.cactoos.Scalar;
import org.cactoos.text.TextOf;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test;
import org.llorllale.cactoos.matchers.Assertion;
/**
* Test case for {@link XeWhen}.
* @since 0.13
*/
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
final class XeWhenTest {
/**
* XeWhen can build XML response.
*
* @throws IOException If some problem inside
*/
@Test
void buildsXmlResponse() throws IOException {
MatcherAssert.assertThat(
IOUtils.toString(
new RsXembly(
new XeAppend(
"test",
new XeWhen(
true,
new XeDate()
)
)
).body(),
StandardCharsets.UTF_8
),
XhtmlMatchers.hasXPaths(
"/test[@date]"
)
);
}
/**
* XeWhen can build XML response with positive condition.
*
* @throws IOException If some problem inside
*/
@Test
void buildsXmlResponseFromPositiveCondition() throws IOException {
MatcherAssert.assertThat(
IOUtils.toString(
new RsXembly(
new XeAppend(
"positive",
new XeWhen(
true,
new XeDate(),
new XeMemory()
)
)
).body(),
StandardCharsets.UTF_8
),
XhtmlMatchers.hasXPaths(
"/positive[@date]"
)
);
}
/**
* XeWhen can build XML response with negative condition.
*
* @throws IOException If some problem inside
*/
@Test
void buildsXmlResponseFromNegativeCondition() throws IOException {
MatcherAssert.assertThat(
IOUtils.toString(
new RsXembly(
new XeAppend(
"negative",
new XeWhen(
false,
new Scalar<XeSource>() {
@Override
public XeSource value() throws IOException {
return new XeDate();
}
},
new Scalar<XeSource>() {
@Override
public XeSource value() throws IOException {
return new XeMemory();
}
})
)
).body(),
StandardCharsets.UTF_8
),
XhtmlMatchers.hasXPaths(
"/negative/memory"
)
);
new Assertion<>(
"Must be empty when negative condition without negative source",
new TextOf(
new RsXembly(
new XeAppend(
"negative",
new XeWhen(
false,
new XeDate()
)
)
).body()
).asString(),
XhtmlMatchers.hasXPaths(
"/negative"
)
).affirm();
}
}
|
package ro.antiprotv.radioclock;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class RadioAlarmManager extends BroadcastReceiver {
private final static int DEFAULT_SNOOZE = 10;//minutes
private final static int DEFAULT_ALARM_PLAY_TIME = 300;//Seconds (=5minutes)
private final ImageButton alarmButton;
private final ImageButton cancelButton;
private final ImageButton snoozeButton;
private final TextView alarmText;
private final ImageButton alarmOffButton;
private final AlarmManager alarmMgr;
private final PendingIntent alarmIntent;
private final ClockActivity clockActivity;
private final ButtonManager buttonManager;
private MediaPlayer player;
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
public RadioAlarmManager(ClockActivity context, ButtonManager buttonManager) {
this.buttonManager = buttonManager;
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent("alarmReceiver");
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
clockActivity = context;
alarmButton = clockActivity.findViewById(R.id.alarm_icon);
alarmText = clockActivity.findViewById(R.id.alarm_time);
alarmOffButton = clockActivity.findViewById(R.id.alarm_icon_turn_off);
cancelButton = clockActivity.findViewById(R.id.alarm_icon_cancel);
snoozeButton = clockActivity.findViewById(R.id.alarm_icon_snooze);
alarmOffButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cancelAlarm();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
shutDownDefaultAlarm();
shutDownRadioAlarm();
}
});
snoozeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
snooze();
}
});
}
public void setAlarm(int hour, int minute) {
Calendar now = Calendar.getInstance();
now.setTimeInMillis(System.currentTimeMillis());
int today = now.get(Calendar.DAY_OF_MONTH);
Calendar next = Calendar.getInstance();
next.set(Calendar.DAY_OF_MONTH, today);
next.set(Calendar.HOUR_OF_DAY, hour);
next.set(Calendar.MINUTE, minute);
next.set(Calendar.SECOND, 0);
boolean tomorrow = false;
if (next.getTimeInMillis() - now.getTimeInMillis() <= 0) {
tomorrow = true;
next.add(Calendar.DAY_OF_MONTH, 1);
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, next.getTimeInMillis(), alarmIntent);
} else {
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, next.getTimeInMillis(), alarmIntent);
}
//TESTING: enable this line to have the alarm in 5 secs;
//alarmMgr.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, alarmIntent);
Toast.makeText(clockActivity, String.format("Alarm set for %s at %s", (tomorrow) ? clockActivity.getString(R.string.text_tomorrow) : clockActivity.getString(R.string.today), sdf.format(next.getTime())), Toast.LENGTH_SHORT).show();
alarmText.setText(clockActivity.getString(R.string.text_alarm_set_for, sdf.format(next.getTime())));
alarmText.setVisibility(View.VISIBLE);
alarmButton.setImageResource(R.drawable.ic_alarm_on_black_24dp);
alarmOffButton.setVisibility(View.VISIBLE);
hideSnoozeAndCancel();
}
private void hideSnoozeAndCancel() {
//not sure how necessary is this here, but we seem to have a race condition
//in which the runnable started by the Executor (MedaPlayerCanceler)
//finishes before both actions are completed
//which makes no sense at the moment
clockActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
cancelButton.setVisibility(View.GONE);
snoozeButton.setVisibility(View.GONE);
}
});
}
private void showSnoozeAndCancel() {
snoozeButton.setVisibility(View.VISIBLE);
cancelButton.setVisibility(View.VISIBLE);
}
private void cancelAlarm() {
alarmMgr.cancel(alarmIntent);
Toast.makeText(clockActivity, R.string.text_alarm_canceled, Toast.LENGTH_SHORT).show();
clockActivity.setAlarmPlaying(false);
changeAlarmIconAndTextOnCancel();
}
private void snooze() {
shutDownDefaultAlarm();
Toast toast = Toast.makeText(clockActivity, clockActivity.getString(R.string.snooze_toast_text, 10), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 0);
toast.show();
shutDownRadioAlarm();
Calendar now = Calendar.getInstance();
now.setTimeInMillis(System.currentTimeMillis());
//now.add(Calendar.SECOND, DEFAULT_SNOOZE);//FOR TESTING
now.add(Calendar.MINUTE, DEFAULT_SNOOZE);//FOR PRODUCTION
setAlarm(now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE));
}
private void shutDownRadioAlarm() {
clockActivity.stopPlaying();
hideSnoozeAndCancel();
}
/**
* restores the alarm view
* to its original state
*/
void changeAlarmIconAndTextOnCancel() {
alarmButton.setImageResource(R.drawable.ic_alarm_add_black_24dp);
alarmText.setVisibility(View.GONE);
alarmOffButton.setVisibility(View.GONE);
}
void cancelSnooze() {
hideSnoozeAndCancel();
}
void playDefaultAlarmOnStreamError() {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
player = MediaPlayer.create(clockActivity, notification);
player.start();
executor.schedule(new MediaPlayerCanceller(), DEFAULT_ALARM_PLAY_TIME, TimeUnit.MINUTES);//PROD
//executor.schedule(new MediaPlayerCanceller(), 5, TimeUnit.SECONDS);//TEST
clockActivity.setAlarmPlaying(false);
showSnoozeAndCancel();
}
void shutDownDefaultAlarm() {
if (player != null && player.isPlaying()) {
player.stop();
hideSnoozeAndCancel();
}
}
@Override
public void onReceive(Context context, Intent intent) {
//what do we play?
int memory;
if (buttonManager.getButtonClicked() == null) {
memory = R.id.stream1;
buttonManager.setButtonClicked((Button) clockActivity.findViewById(R.id.stream1));
} else {
memory = buttonManager.getButtonClicked().getId();
}
Toast.makeText(context, context.getString(R.string.text_alarm_playing, memory), Toast.LENGTH_SHORT).show();
changeAlarmIconAndTextOnCancel();
showSnoozeAndCancel();
clockActivity.setAlarmPlaying(true);
clockActivity.play(memory);
clockActivity.show();
}
private class MediaPlayerCanceller implements Runnable {
public void run() {
shutDownDefaultAlarm();
}
}
}
|
package spark;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static spark.Spark.after;
import static spark.Spark.before;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import spark.examples.books.Books;
import spark.utils.IOUtils;
public class BooksIntegrationTest {
private static int PORT = 4567;
private static String AUTHOR = "FOO";
private static String TITLE = "BAR";
private static String NEW_TITLE = "SPARK";
private String bookId;
@After
public void tearDown() {
Books.books.clear();
Spark.stop();
}
@Before
public void setup() {
before((request, response) -> {
response.header("FOZ", "BAZ");
});
Books.main(null);
after((request, response) -> {
response.header("FOO", "BAR");
});
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
@Test
public void canCreateBook() {
UrlResponse response = createBookViaPOST();
assertNotNull(response);
assertNotNull(response.body);
assertTrue(Integer.valueOf(response.body) > 0);
assertEquals(201, response.status);
}
@Test
public void canListBooks() {
bookId = createBookViaPOST().body.trim();
UrlResponse response = doMethod("GET", "/books", null);
assertNotNull(response);
String body = response.body.trim();
assertNotNull(body);
assertTrue(Integer.valueOf(body) > 0);
assertEquals(200, response.status);
assertTrue(response.body.contains(bookId));
}
@Test
public void canGetBook() {
bookId = createBookViaPOST().body.trim();
UrlResponse response = doMethod("GET", "/books/" + bookId, null);
String result = response.body;
assertNotNull(response);
assertNotNull(response.body);
assertEquals(200, response.status);
assertTrue(result.contains(AUTHOR));
assertTrue(result.contains(TITLE));
assertTrue(beforeFilterIsSet(response));
assertTrue(afterFilterIsSet(response));
}
@Test
public void canUpdateBook() {
bookId = createBookViaPOST().body.trim();
UrlResponse response = updateBook();
String result = response.body;
assertNotNull(response);
assertNotNull(response.body);
assertEquals(200, response.status);
assertTrue(result.contains(bookId));
assertTrue(result.contains("updated"));
}
@Test
public void canGetUpdatedBook() {
bookId = createBookViaPOST().body.trim();
updateBook();
UrlResponse response = doMethod("GET", "/books/" + bookId, null);
String result = response.body;
assertNotNull(response);
assertNotNull(response.body);
assertEquals(200, response.status);
assertTrue(result.contains(AUTHOR));
assertTrue(result.contains(NEW_TITLE));
}
@Test
public void canDeleteBook() {
bookId = createBookViaPOST().body.trim();
UrlResponse response = doMethod("DELETE", "/books/" + bookId, null);
String result = response.body;
assertNotNull(response);
assertNotNull(response.body);
assertEquals(200, response.status);
assertTrue(result.contains(bookId));
assertTrue(result.contains("deleted"));
}
@Test(expected = FileNotFoundException.class)
public void wontFindBook() throws IOException {
getResponse("GET", "/books/" + bookId, null);
}
private static UrlResponse doMethod(String requestMethod, String path, String body) {
UrlResponse response = new UrlResponse();
try {
getResponse(requestMethod, path, response);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
private static void getResponse(String requestMethod, String path, UrlResponse response)
throws MalformedURLException, IOException, ProtocolException {
URL url = new URL("http://localhost:" + PORT + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
connection.connect();
String res = IOUtils.toString(connection.getInputStream());
response.body = res;
response.status = connection.getResponseCode();
response.headers = connection.getHeaderFields();
}
private static class UrlResponse {
public Map<String, List<String>> headers;
private String body;
private int status;
}
private UrlResponse createBookViaPOST() {
return doMethod("POST", "/books?author=" + AUTHOR + "&title=" + TITLE, null);
}
private UrlResponse updateBook() {
return doMethod("PUT", "/books/" + bookId + "?title=" + NEW_TITLE, null);
}
private boolean afterFilterIsSet(UrlResponse response) {
return response.headers.get("FOO").get(0).equals("BAR");
}
private boolean beforeFilterIsSet(UrlResponse response) {
return response.headers.get("FOZ").get(0).equals("BAZ");
}
}
|
package spark;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.FileNotFoundException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import spark.examples.books.Books;
import spark.utils.IOUtils;
public class BooksIntegrationTest {
private static int PORT = 4567;
private static String AUTHOR = "FOO";
private static String TITLE = "BAR";
private static String NEW_TITLE = "SPARK";
@After
public void tearDown() {
Spark.stop();
}
@Before
public void setup() {
Spark.before(new Filter() {
@Override
public void handle(Request request, Response response) {
response.header("FOZ", "BAZ");
}
});
Books.main(null);
Spark.after(new Filter() {
@Override
public void handle(Request request, Response response) {
response.header("FOO", "BAR");
}
});
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
private static String bookId;
@Test
public void testCreateBook() {
try {
UrlResponse response = createBookViaPOST();
assertNotNull(response);
assertNotNull(response.body);
assertTrue(Integer.valueOf(response.body) > 0);
assertEquals(201, response.status);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Test
public void testListBooks() {
try {
bookId = createBookViaPOST().body.trim();
UrlResponse response = doMethod("GET", "/books", null);
assertNotNull(response);
String body = response.body.trim();
System.out.println("BODY: " + body);
assertNotNull(body);
assertTrue(Integer.valueOf(body) > 0);
assertEquals(200, response.status);
assertTrue(response.body.contains(bookId));
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Test
public void testGetBook() {
try {
bookId = createBookViaPOST().body.trim();
UrlResponse response = doMethod("GET", "/books/" + bookId, null);
String result = response.body;
assertNotNull(response);
assertNotNull(response.body);
assertEquals(200, response.status);
assertTrue(result.contains(AUTHOR));
assertTrue(result.contains(TITLE));
// verify response header set by filters:
assertTrue(response.headers.get("FOZ").get(0).equals("BAZ"));
assertTrue(response.headers.get("FOO").get(0).equals("BAR"));
// delete the book again
// Comment this delete to ensure the running of the tests
// testDeleteBook();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Ignore
@Test
public void testUpdateBook() {
try {
UrlResponse response = doMethod("PUT", "/books/" + bookId + "?title=" + NEW_TITLE, null);
String result = response.body;
assertNotNull(response);
assertNotNull(response.body);
assertEquals(200, response.status);
assertTrue(result.contains(bookId));
assertTrue(result.contains("updated"));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Ignore
@Test
public void testGetUpdatedBook() {
try {
UrlResponse response = doMethod("GET", "/books/" + bookId, null);
String result = response.body;
assertNotNull(response);
assertNotNull(response.body);
assertEquals(200, response.status);
assertTrue(result.contains(AUTHOR));
assertTrue(result.contains(NEW_TITLE));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Test
public void testDeleteBook() {
try {
UrlResponse response = doMethod("DELETE", "/books/" + bookId, null);
String result = response.body;
assertNotNull(response);
assertNotNull(response.body);
assertEquals(200, response.status);
assertTrue(result.contains(bookId));
assertTrue(result.contains("deleted"));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Test
public void testBookNotFound() {
try {
doMethod("GET", "/books/" + bookId, null);
} catch (Exception e) {
if (e instanceof FileNotFoundException) {
assertTrue(true);
} else {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
private static UrlResponse doMethod(String requestMethod, String path, String body) throws Exception {
URL url = new URL("http://localhost:" + PORT + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
// connection.setDoOutput(true);
connection.connect();
// connection.getOutputStream().flush();
String res = IOUtils.toString(connection.getInputStream());
UrlResponse response = new UrlResponse();
response.body = res;
response.status = connection.getResponseCode();
response.headers = connection.getHeaderFields();
return response;
}
private static class UrlResponse {
public Map<String, List<String>> headers;
private String body;
private int status;
}
private UrlResponse createBookViaPOST() throws Exception {
return doMethod("POST", "/books?author=" + AUTHOR + "&title=" + TITLE, null);
}
}
|
package timeline;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static timeline.builder.UserBuilder.aUser;
import java.util.List;
import org.junit.Test;
public class SocialNetworkTest {
private static final User ALICE = aUser().withName("Alice").create();
private static final User BOB = aUser().withName("Bob").create();;
@Test
public void givenFollowingWhenAskedForTheFollowingThenItReturnsNoFollowers() {
SocialNetwork socialNetwork = new SocialNetwork();
List<User> following = socialNetwork.getFollowing(aUser().create());
assertThat(following, is(empty()));
}
@Test
public void givenOneRegisteredFollowingWhenAskedForTheFollowingThenItReturnsThatFollowers() {
SocialNetwork socialNetwork = new SocialNetwork();
socialNetwork.registerFollowing(ALICE, BOB);
List<User> following = socialNetwork.getFollowing(ALICE);
assertThat(following, contains(BOB));
}
}
|
package arena;
/* Default libraries */
import java.util.Random;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Comparator;
/* Libraries */
import exception.*;
import operation.*;
import parameters.*;
// Import links
import static parameters.Game.*;
/**
* <b>Auxiliar class RobotList</b><br>
* Impelments a list to be used within
* the World to control the arena.
*
* @author Renato Cordeiro Ferreira
* @author Vinicius Silva
*/
final public class RobotList implements Iterable<Robot>
{
// Robot's list and info
private Robot[] armies;
private HashMap <Integer,Double> speedy
= new HashMap <Integer,Double>();
private HashMap <Robot,Operation> actions
= new HashMap <Robot,Operation>();
// Random number generator
final private Random rand = RAND;
// Last empty space
private int population = 0;
private int emptySpace = 0;
/**
* Default Constructor<br>
* Create a list of robots for 'n' players,
* with ROBOTS_NUM_MAX robots for each.
*
* @param nPlayers Number of players
*/
RobotList(int nPlayers)
{
Debugger.say("[RobotList] Builded");
armies = new Robot[nPlayers * ROBOTS_NUM_MAX];
}
/**
* Add a robot in the list.
* @param robot Reference to a robot
*/
void add(Robot robot)
{
/* TODO: When the three initial are created,
* we will not need this test any more */
if(robot == null) return;
armies[emptySpace++] = robot;
speedy.put(robot.ID, 1.0 * robot.speed);
actions.put(robot, null);
population++;
}
/**
* Remove a robot from the list.
* @param robot Reference to the robot
* up to be removed
*/
void remove(Robot robot)
{
for(int i = 0; i < emptySpace; i++)
{
if(armies[i] == robot)
{
Robot r = armies[i];
armies[i] = null;
speedy.remove(r.ID);
actions.remove(robot);
break;
}
}
}
/**
* Upload an operation for a given robot,
* for being used as a sort method.
* @param robot Robot of the turn
* @param op Operation to be stored
*/
void setOperation(Robot robot, Operation op)
throws NotInitializedException
{
if(actions.containsKey(robot))
actions.put(robot, op);
else throw new NotInitializedException(robot.toString());
}
/**
* Recover the operation for the robot
* of the turn.
* @return Stored operation
*/
Operation getOperation(Robot robot)
throws NotInitializedException
{
if(actions.containsKey(robot))
return actions.get(robot);
else throw new NotInitializedException(robot.toString());
}
/**
* Generate a new iterator.
* @return Iterator to the robot list
*/
public Iterator<Robot> iterator()
{
return new RobotListIterator(emptySpace);
}
/**
* Sort the robot list accordingly to
* the robots speed. If there are conflicts,
* solve the randomically.
*/
void sort()
{
// TODO: redefine priority method
for(Robot r: armies)
{
if(r == null) continue;
speedy.put(r.ID, rand.nextDouble() + r.speed);
Debugger.say("[SPEED][", r, "] ", speedy.get(r.ID));
}
// Debug (unordered array)
Debugger.print("[INIT] ");
for(int i = 0; i < emptySpace; i++)
{
Robot r = armies[i];
Debugger.print( (r != null) ? r : "null" );
if(i != emptySpace-1) Debugger.print(", ");
}
Debugger.say();
// Sorts array untill the first known empty space
quickSort(0, emptySpace-1);
// Updates first empty space position
emptySpace = 0;
for(Robot r: armies)
if(r == null) break;
else emptySpace++;
// Debug (sorted array)
Debugger.print("[SORT] ");
for(int i = 0; i < emptySpace; i++)
{
Robot r = armies[i];
Debugger.print( (r != null) ? r : "null" );
if(i != emptySpace-1) Debugger.print(", ");
}
Debugger.say("\n");
}
/**
* Prints in a more legible format the
* list with the robots (mainly with
* debug purposes).
* @return List with robots
*/
public String toString()
{
String robotList = "";
for(Robot r: armies)
robotList += (r + " ");
return robotList;
}
/**
* Number of robots created.
* @return Number of robots built
* along the game
*/
int getPopulation()
{
return this.population;
}
/**
* Quicksort implementation to be
* used over the Robot List.
* @param begin Start of the subarray
* @param end End of the subarray
*/
private void quickSort(int begin, int end)
{
if(begin < end)
{
int middle = divide(begin, end);
quickSort(begin, middle-1);
quickSort(middle +1, end);
}
}
/**
* Auxiliar funcion for quicksort
* @param begin Start of the subarray
* @param end End of the subarray
*/
private int divide(int begin, int end)
{
int i = begin -1;
Robot x = armies[end];
for(int j = begin; j <= end; j++)
if(cmpLessRobot(armies[j], x))
{
Robot t = armies[++i];
armies[i] = armies[j];
armies[j] = t;
}
return i;
}
/**
* Comparison function used for quicksort
* @param robotA First robot
* @param robotB Second robot
*/
private boolean cmpLessRobot(Robot robotA, Robot robotB)
{
if(robotB == null) return true;
if(robotA == null) return false;
/* Comparison function */
double costA = speedy.get(robotA.ID);
double costB = speedy.get(robotB.ID);
return (costA <= costB);
}
/**
* <b>Inner class for iterator</b><br>
* Inner class implementing interface
* Iterator to run over the Robot List.
*/
private class RobotListIterator implements Iterator<Robot>
{
private int nextRobot = -1;
final private int emptySpace;
/**
* Default constructor<br>
* @param emptySpace Position untill which
* it is possible to find
* robots
*/
public RobotListIterator(int emptySpace)
{
this.emptySpace = emptySpace;
}
/* Interface Iterator */
public boolean hasNext()
{
return nextRobot + 1 != emptySpace;
}
/* Interface Iterator */
public Robot next()
{
nextRobot++;
return armies[nextRobot];
}
/* Interface Iterator */
public void remove()
{
Robot r = armies[nextRobot];
armies[nextRobot] = null;
speedy.remove(r.ID);
}
}
}
|
package com.ecyrd.jspwiki.filters;
import junit.framework.*;
public class AllTests extends TestCase
{
public AllTests( String s )
{
super( s );
}
public static Test suite()
{
TestSuite suite = new TestSuite("PageFilter tests");
suite.addTest( FilterManagerTest.suite() );
return suite;
}
}
|
package generator;
import com.trolltech.qt.*;
import com.trolltech.qt.QtJambiObject.QPrivateConstructor;
import com.trolltech.qt.core.*;
class QObject___ extends QObject {
@com.trolltech.qt.QtBlockedSlot
public final java.util.List<QObject> findChildren() {
return findChildren(null, (QRegExp) null);
}
@com.trolltech.qt.QtBlockedSlot
public final java.util.List<QObject> findChildren(Class < ? > cl) {
return findChildren(cl, (QRegExp) null);
}
@com.trolltech.qt.QtBlockedSlot
public final java.util.List<QObject> findChildren(Class < ? > cl, String name) {
return com.trolltech.qt.internal.QtJambiInternal.findChildren(this, cl, name);
}
@com.trolltech.qt.QtBlockedSlot
public final java.util.List<QObject> findChildren(Class < ? > cl, QRegExp name) {
return com.trolltech.qt.internal.QtJambiInternal.findChildren(this, cl, name);
}
@com.trolltech.qt.QtBlockedSlot
public final QObject findChild() {
return findChild(null, null);
}
@com.trolltech.qt.QtBlockedSlot
public final QObject findChild(Class < ? > cl) {
return findChild(cl, null);
}
@com.trolltech.qt.QtBlockedSlot
public final QObject findChild(Class < ? > cl, String name) {
return com.trolltech.qt.internal.QtJambiInternal.findChild(this, cl, name);
}
@com.trolltech.qt.QtBlockedSlot
public final void setProperty(String name, Object value) {
setProperty(QNativePointer.createCharPointer(name), value);
}
@com.trolltech.qt.QtBlockedSlot
public final Object property(String name) {
return property(QNativePointer.createCharPointer(name));
}
@com.trolltech.qt.QtBlockedSlot
public final QtProperty userProperty() {
return com.trolltech.qt.internal.QtJambiInternal.userProperty(nativeId());
}
@com.trolltech.qt.QtBlockedSlot
public final java.util.List<com.trolltech.qt.QtProperty> properties() {
return com.trolltech.qt.internal.QtJambiInternal.properties(nativeId());
}
@com.trolltech.qt.QtBlockedSlot
public final int indexOfProperty(String name) {
return com.trolltech.qt.internal.QtJambiInternal.indexOfProperty(nativeId(), name);
}
@com.trolltech.qt.QtBlockedSlot
public final void connectSlotsByName() {
com.trolltech.qt.internal.QtJambiInternal.connectSlotsByName(this);
}
}// class
abstract class QAbstractItemModel___ extends QAbstractItemModel {
private native boolean setData_native(long id, int row, int col, Object value, int role);
public final boolean setData(int row, int col, Object value) {
return setData_native(nativeId(), row, col, value, com.trolltech.qt.core.Qt.ItemDataRole.DisplayRole);
}
public final boolean setData(int row, int col, Object value, int role) {
return setData_native(nativeId(), row, col, value, role);
}
private native Object data_native(long id, int row, int col, int role);
public final Object data(int row, int col, int role) {
return data_native(nativeId(), row, col, role);
}
public final Object data(int row, int col) {
return data_native(nativeId(), row, col, Qt.ItemDataRole.DisplayRole);
}
}// class
class QTimer___ extends QTimer {
static private class QSingleShotTimer extends QObject {
private int timerId = -1;
public Signal0 timeout = new Signal0();
public QSingleShotTimer(int msec, QObject obj, String method) {
super(obj);
timeout.connect(obj, method);
timerId = startTimer(msec);
}
protected void disposed() {
if (timerId > 0)
killTimer(timerId);
super.disposed();
}
protected void timerEvent(QTimerEvent e) {
if (timerId > 0)
killTimer(timerId);
timerId = -1;
timeout.emit();
disposeLater();
}
}
public static void singleShot(int msec, QObject obj, String method) {
new QSingleShotTimer(msec, obj, method);
}
}// class
class QCoreApplication___ extends QCoreApplication {
protected static QCoreApplication m_instance = null;
public QCoreApplication(String args[]) {
this(argc(args), argv(args));
}
public QCoreApplication(String applicationName, String args[]) {
this(argc(args), argv(applicationName, args));
}
public static String translate(String context, String sourceText, String comment) {
QTextCodec codec = QTextCodec.codecForName("UTF-8");
return translate(context != null ? codec.fromUnicode(context).data() : null, sourceText != null ? codec.fromUnicode(sourceText).data() : null,
comment != null ? codec.fromUnicode(comment).data() : null, Encoding.CodecForTr);
}
public static String translate(String context, String sourceText) {
return translate(context, sourceText, null);
}
public static String translate(String context, String sourceText, String comment, int n) {
QTextCodec codec = QTextCodec.codecForName("UTF-8");
return translate(context != null ? codec.fromUnicode(context).data() : null, sourceText != null ? codec.fromUnicode(sourceText).data() : null,
comment != null ? codec.fromUnicode(comment).data() : null, Encoding.CodecForTr, n);
}
public static void initialize(String applicationName, String args[]) {
if (m_instance != null)
throw new RuntimeException("QCoreApplication can only be initialized once");
com.trolltech.qt.internal.HelperFunctions.setAsMainThread();
String path = Utilities.unpackPlugins();
if (path != null)
addLibraryPath(path);
else
com.trolltech.qt.internal.QtJambiInternal.setupDefaultPluginPath();
m_instance = new QCoreApplication(applicationName, args);
m_instance.aboutToQuit.connect(m_instance, "disposeOfMyself()");
}
public static void initialize(String args[]) {
if (m_instance != null)
throw new RuntimeException("QCoreApplication can only be initialized once");
com.trolltech.qt.internal.HelperFunctions.setAsMainThread();
String path = Utilities.unpackPlugins();
if (path != null)
addLibraryPath(path);
else
com.trolltech.qt.internal.QtJambiInternal.setupDefaultPluginPath();
m_instance = new QCoreApplication(args);
m_instance.aboutToQuit.connect(m_instance, "disposeOfMyself()");
}
public static void shutdown() {
QCoreApplication app = instance();
if(app != null) {
app = null; // discard hard-reference
processEvents(QEventLoop.ProcessEventsFlag.DeferredDeletion); // allow deleteLater() to work some magic
quit(); // finish up cause an aboutToQuit() to fire
processEvents(); // process quit
processEvents(QEventLoop.ProcessEventsFlag.DeferredDeletion); // allow deleteLater() to work some magic
}
if (m_instance != null) // this should be a QtJambi qWarning()
System.err.println("WARNING: QCoreApplication.shutdown() m_instance!=null");
System.gc();
System.runFinalization();
}
/**
*
* @see #execStatic()
*/
public int exec() {
return exec_internal();
}
/**
*
* @see #exec()
*/
public static int execStatic() {
if (m_instance == null)
throw new RuntimeException("QCoreApplication has not been initialized with QCoreApplication.initialize()");
return exec_internal();
}
private void disposeOfMyself() {
synchronized(this) {
// To force compiler/JVM not to move/optimized when
m_instance = null;
}
System.gc();
System.runFinalization();
this.disposeLater();
}
protected final static com.trolltech.qt.QNativePointer argv(String args[]) {
String newArgs[] = new String[args.length + 1];
System.arraycopy(args, 0, newArgs, 1, args.length);
try {
newArgs[0] = System.getProperty("qt.application.path", "Qt Jambi application");
} catch (Exception e) {
newArgs[0] = "Qt Jambi application";
}
argv = com.trolltech.qt.QNativePointer.createCharPointerPointer(newArgs);
return argv;
}
protected final static com.trolltech.qt.QNativePointer argv(String applicationName, String args[]) {
String newArgs[] = new String[args.length + 1];
System.arraycopy(args, 0, newArgs, 1, args.length);
if (applicationName != null && applicationName.length() != 0) {
newArgs[0] = applicationName;
} else {
newArgs[0] = "Qt Jambi application";
}
argv = com.trolltech.qt.QNativePointer.createCharPointerPointer(newArgs);
return argv;
}
protected final static com.trolltech.qt.QNativePointer argc(String args[]) {
if (argc != null) {
throw new RuntimeException("There can only exist one QCoreApplication instance");
}
argc = new com.trolltech.qt.QNativePointer(com.trolltech.qt.QNativePointer.Type.Int);
argc.setIntValue(args.length + 1);
return argc;
}
@Override
protected void disposed() {
argc = null;
argv = null;
m_instance = null;
super.disposed();
}
public boolean isDisposed() {
if (m_instance == null)
return true;
return false;
}
public static void invokeLater(java.lang.Runnable runnable) {
postEvent(new QInvokable(runnable), new QEvent(QInvokable.INVOKABLE_EVENT));
}
/**
* Executes the runnable's run() method in the main thread and waits for it
* to return. If the current thread is not the main thread, an event loop
* must be running in the main thread, or this method will wait
* indefinitely.
*/
public static void invokeAndWait(Runnable runnable) {
// Specialcase invoke and wait for the case of running on the current thread...
if (Thread.currentThread() == instance().thread()) {
runnable.run();
return;
}
QSynchronousInvokable invokable = new QSynchronousInvokable(runnable);
QCoreApplication.postEvent(invokable, new QEvent(QSynchronousInvokable.SYNCHRONOUS_INVOKABLE_EVENT));
invokable.waitForInvoked();
invokable.disposeLater();
}
/**
* Executes the task in the application's main thread after the
* specified timeout. This is done by starting a timer so this
* method does not block.
* @param timeout The time to wait, in milliseconds
* @param task The task to perform...
*/
public static void invokeLater(int timeout, final Runnable task) {
QTimer.singleShot(timeout, new QObject() {
public void todo() {
task.run();
disposeLater();
}
}
, "todo()");
}
private static com.trolltech.qt.QNativePointer argc, argv;
}// class
class QTranslator___ extends QTranslator {
public final boolean load(byte data[]) {
return load(com.trolltech.qt.internal.QtJambiInternal.byteArrayToNativePointer(data), data.length);
}
}// class
class QProcess___ extends QProcess {
public static class DetachedProcessInfo {
public DetachedProcessInfo(boolean success, long pid) {
this.success = success;
this.pid = pid;
}
public boolean success;
public long pid;
}
public static DetachedProcessInfo startDetached(String program, java.util.List<String> arguments, String workingDirectory) {
QNativePointer pid = new QNativePointer(QNativePointer.Type.Long);
boolean success = startDetached(program, arguments, workingDirectory, pid);
return new DetachedProcessInfo(success, pid.longValue());
}
}// class
class QDataStream___ extends QDataStream {
private QNativePointer srb = new QNativePointer(QNativePointer.Type.Byte, 32) {
{
setVerificationEnabled(false);
}
};
public final boolean readBoolean() {
operator_shift_right_boolean(srb);
return srb.booleanValue();
}
public final byte readByte() {
operator_shift_right_byte(srb);
return srb.byteValue();
}
public final short readShort() {
operator_shift_right_short(srb);
return srb.shortValue();
}
public final int readInt() {
operator_shift_right_int(srb);
return srb.intValue();
}
public final long readLong() {
operator_shift_right_long(srb);
return srb.longValue();
}
public final char readChar() {
operator_shift_right_char(srb);
return srb.charValue();
}
public final float readFloat() {
operator_shift_right_float(srb);
return srb.floatValue();
}
public final double readDouble() {
operator_shift_right_double(srb);
return srb.doubleValue();
}
public final QDataStream writeShort(short s) {
writeShort_char((char) s);
return this;
}
private native String readString_private(long nativeId);
private native void writeString_private(long nativeId, String string);
public final String readString() {
if (nativeId() == 0)
throw new QNoNativeResourcesException("Function call on incomplete object of type: " + getClass().getName());
return readString_private(nativeId());
}
public final void writeString(String string) {
if (nativeId() == 0)
throw new QNoNativeResourcesException("Function call on incomplete object of type: " + getClass().getName());
writeString_private(nativeId(), string);
}
private native int writeBytes(long id, byte buffer[], int length);
private native int readBytes(long id, byte buffer[], int length);
public final int writeBytes(byte buffer[]) {
return writeBytes(buffer, buffer.length);
}
public final int writeBytes(byte buffer[], int length) {
return writeBytes(nativeId(), buffer, length);
}
public final int readBytes(byte buffer[]) {
return readBytes(buffer, buffer.length);
}
public final int readBytes(byte buffer[], int length) {
return readBytes(nativeId(), buffer, length);
}
}// class
class QTextStream___ extends QTextStream {
public final void setCodec(String codecName) {
setCodec(QNativePointer.createCharPointer(codecName));
if (codec() != __rcCodec)
__rcCodec = null;
}
private QNativePointer srb = new QNativePointer(QNativePointer.Type.Byte, 32) {
{
setVerificationEnabled(false);
}
};
public final byte readByte() {
operator_shift_right_byte(srb);
return srb.byteValue();
}
public final short readShort() {
operator_shift_right_short(srb);
return srb.shortValue();
}
public final int readInt() {
operator_shift_right_int(srb);
return srb.intValue();
}
public final long readLong() {
operator_shift_right_long(srb);
return srb.longValue();
}
public final float readFloat() {
operator_shift_right_float(srb);
return srb.floatValue();
}
public final double readDouble() {
operator_shift_right_double(srb);
return srb.doubleValue();
}
public final QTextStream writeShort(short s) {
writeShort_char((char) s);
return this;
}
public final QTextStream writeChar(char c) {
writeShort_char(c);
return this;
}
public final char readChar() {
operator_shift_right_short(srb);
return srb.charValue();
}
public final String readString() {
return readString_native(nativeId());
}
public final void writeString(String string) {
writeString_native(nativeId(), string);
}
/**
This function makes the text tream operate on a string instead
of a QIODevice.
<p>
The <tt>string</tt> parameter is the initial contents of the string that the text stream
will work on. If <tt>string</tt> is <tt>null</tt>, an empty string will be created.
The stream can both be written to and read from, depending on <tt>openMode</tt>.
The contents of the string can at any time be retrieved by <tt>string()</tt>.
For example:
<pre class="snippet">
QTextStream stream = QTextStream.createStringStream("TestString\n55",
new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadWrite));
stream.writeString(" ");
stream.writeString("Hei");
stream.seek(0);
System.err.println(stream.readString()); // == "TestString"
System.err.println(stream.string()); // == "TestString\n55 Hei"
</pre>
<p>
If the text stream already has a QIODevice set, it will flush this.
@param string The initial content of the string.
@param openMode Specifies access priveledges to the stream.
@return A QTextStream operating on a String instead of a QIODevice.
*/
public static QTextStream createStringStream(String string, com.trolltech.qt.core.QIODevice.OpenMode openMode) {
QTextStream instance = new StringStream(string, openMode);
return instance;
}
/**
Returns the contents of the string that this text stream is working on.
<p>
After creating a string stream with the createStringStream() method,
you can fetch the contents of the string the text stream is working on with this
method.
<p>
If this QTextStream was not created using createStringStream(), this function returns <tt>null</tt>.
@return Returns the contents of QTextStreams created with createStringStream()
*/
public String string() {
return null;
}
private static final class StringStream extends QTextStream {
protected StringStream(String string, com.trolltech.qt.core.QIODevice.OpenMode openMode) {
stringPtr = createString(nativeId(), string, openMode.value());
}
public String string() {
return string_native(nativeId());
}
@Override
public void disposed() {
deleteString(stringPtr);
}
private native long createString(long id, String str, int openMode);
private native void deleteString(long strPtr);
private native String string_native(long id);
private long stringPtr = 0;
}
private final native String readString_native(long id);
private final native void writeString_native(long id, String string);
}// class
class QBitArray___ extends QBitArray {
@com.trolltech.qt.QtBlockedSlot
public final void xor(QBitArray other) {
operator_xor_assign(other);
}
@com.trolltech.qt.QtBlockedSlot
public final void and(QBitArray other) {
operator_and_assign(other);
}
@com.trolltech.qt.QtBlockedSlot
public final void or(QBitArray other) {
operator_or_assign(other);
}
@com.trolltech.qt.QtBlockedSlot
public final void set(QBitArray other) {
operator_assign(other);
}
@com.trolltech.qt.QtBlockedSlot
public final QBitArray inverted() {
return operator_negate();
}
}// class
// hfr
class QDate___ extends QDate {
public final int weekNumber() {
return weekNumber(null);
}
public final int yearOfWeekNumber() {
QNativePointer np = new QNativePointer(QNativePointer.Type.Int);
weekNumber(np);
return np.intValue();
}
}// class
class QDir___ extends QDir {
@com.trolltech.qt.QtBlockedSlot
public String at(int i) {
return operator_subscript(i);
}
}// class
class QByteArray___ extends QByteArray {
public QByteArray(String s) {
this();
append(s);
}
public QByteArray(byte data[]) {
this(com.trolltech.qt.internal.QtJambiInternal.byteArrayToNativePointer(data), data.length);
}
public final boolean contains(String str) {
return contains(new QByteArray(str));
}
public final int count(String str) {
return count(new QByteArray(str));
}
public final boolean endsWith(String str) {
return endsWith(new QByteArray(str));
}
public final QByteArray prepend(String str) {
return prepend(new QByteArray(str));
}
public final QByteArray replace(QByteArray before, String after) {
return replace(before, new QByteArray(after));
}
public final QByteArray replace(String before, String after) {
return replace(new QByteArray(before), new QByteArray(after));
}
public final boolean startsWith(String str) {
return startsWith(new QByteArray(str));
}
public final byte[] toByteArray() {
byte[] res = new byte[size()];
for (int i = 0; i < size(); i++) {
res[i] = at(i);
}
return res;
}
@com.trolltech.qt.QtBlockedSlot
public final QByteArray set(QByteArray other) {
operator_assign(other);
return this;
}
}// class
class QFile___ extends QFile {
public static String decodeName(String localFileName) {
return decodeName(com.trolltech.qt.QNativePointer.createCharPointer(localFileName));
}
}// class
class QIODevice___ extends QIODevice {
/**
* Gets a byte from the device.
*
* @return -1 on failure, or the value of the byte on success
*/
public final int getByte() {
QNativePointer np = new QNativePointer(QNativePointer.Type.Byte);
boolean success = getByte(np);
return success ? np.byteValue() : -1;
}
}// class
class QCryptographicHash___ extends QCryptographicHash {
public final void addData(byte data[]) {
QNativePointer np = com.trolltech.qt.internal.QtJambiInternal.byteArrayToNativePointer(data);
addData(np, data.length);
}
}// class
class QTextCodec___ extends QTextCodec {
static {
setCodecForTr(QTextCodec.codecForName("UTF-8"));
}
public static QTextCodec codecForName(String name) {
return codecForName(com.trolltech.qt.QNativePointer.createCharPointer(name));
}
}// class
class QBuffer___ extends QBuffer {
// retain a reference to avoid gc
private Object strongDataReference = null;
public QBuffer(QByteArray byteArray, QObject parent) {
this(byteArray.nativePointer(), parent);
strongDataReference = byteArray;
}
public QBuffer(QByteArray byteArray) {
this(byteArray, null);
}
public final void setBuffer(QByteArray byteArray) {
setBuffer(byteArray.nativePointer());
strongDataReference = byteArray;
}
public final void setData(byte data[]) {
QNativePointer np = com.trolltech.qt.internal.QtJambiInternal.byteArrayToNativePointer(data);
setData(np, data.length);
}
}// class
class QSignalMapper___ extends QSignalMapper {
private java.util.Hashtable<QObject, QObject> __rcObjectForObject = new java.util.Hashtable<QObject, QObject>();
private java.util.Hashtable<QObject, Object> __rcWidgetForObject = new java.util.Hashtable<QObject, Object>();
}// class
class QAbstractFileEngine_MapExtensionReturn___ extends QAbstractFileEngine_MapExtensionReturn {
private QNativePointer currentAddressNativePointer; // don't garbage collect while in use
public final void setAddress(String address) {
currentAddressNativePointer = address != null ? QNativePointer.createCharPointer(address) : null;
address_private(currentAddressNativePointer);
}
public final String address() {
QNativePointer np = address_private();
return np != null ? com.trolltech.qt.internal.QtJambiInternal.charPointerToString(np) : null;
}
}// class
class QAbstractFileEngine___ extends QAbstractFileEngine {
/**
* Adds <tt>path</tt> to the set of paths in which Qt Jambi should search for resources. Resources
* can be accessed using the "classpath:" scheme.
*/
public static void addSearchPathForResourceEngine(String path) {
com.trolltech.qt.internal.QClassPathEngine.addSearchPath(path, false);
}
/**
* Removes <tt>path</tt> from the set of paths in which Qt Jambi searches
* for resources.
*/
public static void removeSearchPathForResourceEngine(String path) {
com.trolltech.qt.internal.QClassPathEngine.removeSearchPath(path);
}
}// class
class QAbstractFileEngine_UnMapExtensionOption___ extends QAbstractFileEngine_UnMapExtensionOption {
private QNativePointer currentAddressNativePointer; // don't garbage collect while in use
public final void setAddress(String address) {
currentAddressNativePointer = address != null ? QNativePointer.createCharPointer(address) : null;
address_private(currentAddressNativePointer);
}
public final String address() {
QNativePointer np = address_private();
return np != null ? com.trolltech.qt.internal.QtJambiInternal.charPointerToString(np) : null;
}
}// class
class QFutureWatcher___ extends QFutureWatcher {
public final QFuture<T> future() {
if (nativeId() == 0)
throw new QNoNativeResourcesException("Function call on incomplete object of type: " + getClass().getName());
return __qt_future(nativeId());
}
private native QFuture<T> __qt_future(long nativeId);
}// class
class QFutureWatcherVoid___ extends QFutureWatcherVoid {
public final QFutureVoid future() {
if (nativeId() == 0)
throw new QNoNativeResourcesException("Function call on incomplete object of type: " + getClass().getName());
return __qt_future(nativeId());
}
private native QFutureVoid __qt_future(long nativeId);
}// class
class QFutureSynchronizer___ extends QFutureSynchronizer {
public final java.util.List<QFuture<T>> futures() {
if (nativeId() == 0)
throw new QNoNativeResourcesException("Function call on incomplete object of type: " + getClass().getName());
return __qt_futures(nativeId());
}
private native java.util.List<QFuture<T>> __qt_futures(long nativeId);
}// class
class QFutureSynchronizerVoid___ extends QFutureSynchronizerVoid {
public final java.util.List<QFutureVoid> futures() {
if (nativeId() == 0)
throw new QNoNativeResourcesException("Function call on incomplete object of type: " + getClass().getName());
return __qt_futures(nativeId());
}
private native java.util.List<QFutureVoid> __qt_futures(long nativeId);
}// class
/**
The QtConcurrent class contains static methods for running computations in parallel (using separate threads)
on the items in a java.util.Collection, such as a Vector or LinkedList. We will now describe these methods.
The QtConcurrent::map(), QtConcurrent::mapped() and QtConcurrent::mappedReduced() functions run computations in parallel on the items in a sequence such as a QList or a QVector. QtConcurrent::map() modifies a sequence in-place, QtConcurrent::mapped() returns a new sequence containing the modified content, and QtConcurrent::mappedReduced() returns a single result.
Concurrent Map
<p>
QtConcurrent::mapped() takes an input sequence and a map function. This map function is then called for each item in the sequence, and a new sequence containing the return values from the map function is returned.
<p>
The map function must be of the form:
<pre>
U function(const T &t);
</pre>
T and U can be any type (and they can even be the same type), but T must match the type stored in the sequence. The function returns the modified or mapped content.
<p>
This example shows how to apply a scale function to all the items in a sequence:
<pre>
QImage scaled(const QImage &image)
{
return image.scaled(100, 100);
}
QList <QImage> images = ...;
QFuture<QImage> thumbnails = QtConcurrent::mapped(images, scaled);
</pre>
The results of the map are made available through QFuture. See the QFuture and QFutureWatcher documentation for more information on how to use QFuture in your applications.
<p>
If you want to modify a sequence in-place, use QtConcurrent::map(). The map function must then be of the form:
<pre>
U function(T &t);
</pre>
Note that the return value and return type of the map function are not used.
<p>
Using QtConcurrent::map() is similar to using QtConcurrent::mapped():
<pre>
void scale(QImage &image)
{
image = image.scaled(100, 100);
}
QList<QImage> images = ...;
QFuture<void> future = QtConcurrent::map(images, scale);
</pre>
Since the sequence is modified in place, QtConcurrent::map() does not return any results via QFuture. However, you can still use QFuture and QFutureWatcher to monitor the status of the map.
Concurrent Map-Reduce
<p>
QtConcurrent::mappedReduced() is similar to QtConcurrent::mapped(), but instead of returning a sequence with the new results, the results are combined into a single value using a reduce function.
<p>
The reduce function must be of the form:
<pre>
V function(T &result, const U &intermediate)
</pre>
T is the type of the final result, U is the return type of the map function. Note that the return value and return type of the reduce function are not used.
<p>
Call QtConcurrent::mappedReduced() like this:
<pre>
void addToCollage(QImage &collage, const QImage &thumbnail)
{
QPainter p(&collage);
static QPoint offset = QPoint(0, 0);
p.drawImage(offset, thumbnail);
offset += ...;
}
QList<QImage> images = ...;
QFuture<QImage> collage = QtConcurrent::mappedReduced(images, scaled, addToCollage);
</pre>
The reduce function will be called once for each result returned by the map function, and should merge the intermediate into the result variable. QtConcurrent::mappedReduced() guarantees that only one thread will call reduce at a time, so using a mutex to lock the result variable is not neccesary. The QtConcurrent::ReduceOptions enum provides a way to control the order in which the reduction is done. If QtConcurrent::UnorderedReduce is used (the default), the order is undefined, while QtConcurrent::OrderedReduce ensures that the reduction is done in the order of the original sequence.
Additional API Features
Using Iterators instead of Sequence
<p>
Each of the above functions has a variant that takes an iterator range instead of a sequence. You use them in the same way as the sequence variants:
<pre>
QList<QImage> images = ...;
QFuture<QImage> thumbnails = QtConcurrent::mapped(images.constBegin(), images.constEnd(), scaled);
// map in-place only works on non-const iterators
QFuture<void> future = QtConcurrent::map(images.begin(), images.end(), scale);
QFuture<QImage> collage = QtConcurrent::mappedReduced(images.constBegin(), images.constEnd(), scaled, addToCollage);
</pre>
Blocking Variants
<p>
Each of the above functions has a blocking variant that returns the final result instead of a QFuture. You use them in the same way as the asynchronous variants.
<pre>
QList<QImage> images = ...;
// each call blocks until the entire operation is finished
QList<QImage> future = QtConcurrent::blockingMapped(images, scaled);
QtConcurrent::blockingMap(images, scale);
QImage collage = QtConcurrent::blockingMappedReduced(images, scaled, addToCollage);
</pre>
Note that the result types above are not QFuture objects, but real result types (in this case, QList<QImage> and QImage).
Using Member Functions
<p>
QtConcurrent::map(), QtConcurrent::mapped(), and QtConcurrent::mappedReduced() accept pointers to member functions. The member function class type must match the type stored in the sequence:
<pre>
// squeeze all strings in a QStringList
QStringList strings = ...;
QFuture<void> squeezedStrings = QtConcurrent::map(strings, &QString::squeeze);
// swap the rgb values of all pixels on a list of images
QList<QImage> images = ...;
QFuture<QImage> bgrImages = QtConcurrent::mapped(images, &QImage::rgbSwapped);
// create a set of the lengths of all strings in a list
QStringList strings = ...;
QFuture<QSet<int> > wordLengths = QtConcurrent::mappedReduced(string, &QString::length, &QSet<int>::insert);
</pre>
Note that when using QtConcurrent::mappedReduced(), you can mix the use of normal and member functions freely:
<p>
<pre>
// can mix normal functions and member functions with QtConcurrent::mappedReduced()
// compute the average length of a list of strings
extern void computeAverage(int &average, int length);
QStringList strings = ...;
QFuture<int> averageWordLength = QtConcurrent::mappedReduced(strings, &QString::length, computeAverage);
// create a set of the color distribution of all images in a list
extern int colorDistribution(const QImage &string);
QList<QImage> images = ...;
QFuture<QSet<int> > totalColorDistribution = QtConcurrent::mappedReduced(images, colorDistribution, QSet<int>::insert);
</pre>
Using Function Objects
<p>
QtConcurrent::map(), QtConcurrent::mapped(), and QtConcurrent::mappedReduced() accept function objects, which can be used to add state to a function call. The result_type typedef must define the result type of the function call operator:
<pre>
struct Scaled
{
Scaled(int size)
: m_size(size) { }
typedef QImage result_type;
QImage operator()(const QImage &image)
{
return image.scaled(m_size, m_size);
}
int m_size;
};
QList<QImage> images = ...;
QFuture<QImage> thumbnails = QtConcurrent::mapped(images, Scaled(100));
</pre>
Using Bound Function Arguments
<p>
Note that Qt does not provide support for bound functions. This is provided by 3rd party libraries like Boost or C++ TR1 Library Extensions.
<p>
If you want to use a map function that takes more than one argument you can use boost::bind() or std::tr1::bind() to transform it onto a function that takes one argument.
<p>
As an example, we'll use QImage::scaledToWidth():
<pre>
QImage QImage::scaledToWidth(int width, Qt::TransformationMode) const;
</pre>
scaledToWidth takes three arguments (including the "this" pointer) and can't be used with QtConcurrent::mapped() directly, because QtConcurrent::mapped() expects a function that takes one argument. To use QImage::scaledToWidth() with QtConcurrent::mapped() we have to provide a value for the width and the transformation mode:
<pre>
boost::bind(&QImage::scaledToWidth, 100 Qt::SmoothTransformation)
</pre>
The return value from boost::bind() is a function object (functor) with the following signature:
<pre>
QImage scaledToWith(const QImage &image)
</pre>
This matches what QtConcurrent::mapped() expects, and the complete example becomes:
<pre>
QList>QImage< images = ...;
QFuture>QImage< thumbnails = QtConcurrent::mapped(images, boost::bind(&QImage::scaledToWidth, 100 Qt::SmoothTransformation));
</pre>
*/
class QtConcurrent___ extends QtConcurrent {
static {
com.trolltech.qt.QtJambi_LibraryInitializer.init();
com.trolltech.qt.core.QtJambi_LibraryInitializer.init();
}
/**
* An implemetation of this interface is given one to QtConcurrent's map() methods.
* The map() method of this interface is called for each object in a java.util.Collection.
*
*/
public interface MapFunctor<T> {
/**
* This function is called for each item in the Collection. The function is then free to alter <tt>object</tt> as it see fit.
*/
public void map(T object);
}
/**
* Calls function once for each item in sequence. The function is passed a reference to the item, so that any modifications done to the item will appear in sequence.
*/
public static native <T> QFutureVoid map(java.util.Collection<T> sequence, MapFunctor<T> functor);
/**
* Calls function once for each item in sequence. The function is passed a reference to the item, so that any modifications done to the item will appear in sequence.
*/
public static native <T> void blockingMap(java.util.Collection<T> sequence, MapFunctor<T> functor);
/**
* Implement this interface to perform a mapped operation. An implementation of the interface is sendt
* to ome of the mapped methods of QtConcurrent, which applies the MappedFunctor.map() method to all elements in a collection,
* and returns the result.
*/
public interface MappedFunctor<U, T> {
/**
* This method is called for each object in a collection. It should returned a new altered
* object.
*/
public U map(T object);
}
/**
* Calls function once for each item in sequence and returns a future with each mapped item as a result. You can QFutureIterator to iterate through the results.
*
*/
public static native <U, T> QFuture<U> mapped(java.util.Collection<T> sequence, MappedFunctor<U, T> functor);
/**
* Calls function once for each item in sequence and returns a future with each mapped item as a result. You can QFutureIterator to iterate through the results.
*/
public static native <U, T> java.util.List<U> blockingMapped(java.util.Collection<T> sequence, MappedFunctor<U, T> functor);
/**
* Implement this interface in order to perform a reduce operation.
* <p>
* The reduce method will be called once per intermediate result (the result of the mapping of the data)
* and the very first time the reduce() method is called for the particular data set, the result is set to
* the returned value of the defaultResult() method.
*/
public interface ReducedFunctor<U, T> {
public U defaultResult();
/**
* Performs a reduce operation on <tt>intermediate</tt>. <tt>result</tt> is the result of the reduction.
*/
public void reduce(U result, T intermediate);
}
/**
* This is an overloaded method provided for convenience.
* <p>
* It is equivalent of mappedReduced(sequence, functor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce)
*/
public static <U, V, T> QFuture<U> mappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor) {
return mappedReduced(sequence, functor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce);
}
/**
* This is an overloaded method provided for convenience.
* <p>
* Note that while mapFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is determined by reduceOptions.
*
*/
public static <U, V, T> QFuture<U> mappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, ReduceOption ... options) {
return mappedReduced(sequence, functor, reducedFunctor, new ReduceOptions(options));
}
/**
* Calls mapFunction once for each item in sequence. The return value of each mapFunction is passed to reduceFunction.
* <p>
* Note that while mapFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is determined by reduceOptions.
*
*/
public static <U, V, T> QFuture<U> mappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, ReduceOptions options) {
return mappedReduced(sequence, functor, reducedFunctor, options.value());
}
private native static <U, V, T> QFuture<U> mappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, int options);
/**
* This is an overloaded method provided for convenience.
* <p>
* It is equivalent of calling blockingMappedReduced(sequence, functor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce)
*
*/
public static <U, V, T> U blockingMappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor) {
return blockingMappedReduced(sequence, functor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce);
}
/**
* Calls mapFunction once for each item in sequence. The return value of each mapFunction is passed to reduceFunction.
* <p>
* Note that while mapFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is determined by reduceOptions.
* <p>
* Note: This function will block until all items in the sequence have been processed.
*/
public static <U, V, T> U blockingMappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, ReduceOption ... options) {
return blockingMappedReduced(sequence, functor, reducedFunctor, new ReduceOptions(options));
}
/**
* Calls mapFunction once for each item in sequence. The return value of each mapFunction is passed to reduceFunction.
* <p>
* Note that while mapFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is determined by reduceOptions.
* <p>
* Note: This function will block until all items in the sequence have been processed.
*/
public static <U, V, T> U blockingMappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, ReduceOptions options) {
return blockingMappedReduced(sequence, functor, reducedFunctor, options.value());
}
private native static <U, V, T> U blockingMappedReduced(java.util.Collection<T> sequence, MappedFunctor<V, T> functor, ReducedFunctor<U, V> reducedFunctor, int options);
/**
* An implementation of this interface is given to one of QtConcurrent's filtered() methods.
* The filter method if this interface is called for each item in a java.util.Collection.
*
*/
public interface FilteredFunctor<T> {
/**
* This method is called for each item in a java.util.Collection. The items for which
* this method returns true are removed from the collection.
*/
public boolean filter(T object);
}
/**
* Calls filterFunctor's filtered() method once for each item in sequence and returns a new Sequence of kept items. If filterFunction returns true, a copy of the item is put in the new Sequence. Otherwise, the item will not appear in the new Sequence.
*/
public native static <T> QFuture<T> filtered(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor);
/**
* Calls filterFunctor's filtered() method once for each item in sequence and returns a new Sequence of kept items. If filterFunction returns true, a copy of the item is put in the new Sequence. Otherwise, the item will not appear in the new Sequence.
*/
public native static <T> java.util.List<T> blockingFiltered(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor);
/**
* This is an overloaded method provided for convenience. It is equivalent of calling filteredReduced(sequence, filteredFunctor, ReduceOption.UnorderedReduce, ReduceOption.Seq This is an overloaded method provided for convenience. It is equivalent of calling filteredReduced)
*/
public static <U, T> QFuture<U> filteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor) {
return filteredReduced(sequence, filteredFunctor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce);
}
/**
* Calls filterFunction once for each item in sequence. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true.
* <p>
* Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, reduceFunction is called in the order of the original sequence.
*/
public static <U, T> QFuture<U> filteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, ReduceOption ... options) {
return filteredReduced(sequence, filteredFunctor, reducedFunctor, new ReduceOptions(options));
}
/**
* Calls filterFunction once for each item in sequence. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true.
* <p>
* Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, reduceFunction is called in the order of the original sequence.
*/
public static <U, T> QFuture<U> filteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, ReduceOptions options) {
return filteredReduced(sequence, filteredFunctor, reducedFunctor, options.value());
}
private native static <U, T> QFuture<U> filteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, int options);
/**
* This is an overloaded method provided for convenience. It is the equivalent of calling blockingFilteredReduced(sequence, filteredFunctor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce)
*/
public static <U, T> U blockingFilteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor) {
return blockingFilteredReduced(sequence, filteredFunctor, reducedFunctor, ReduceOption.UnorderedReduce, ReduceOption.SequentialReduce);
}
/**
* Calls filterFunction once for each item in sequence. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true.
* <p>
* Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, reduceFunction is called in the order of the original sequence.
*/
public static <U, T> U blockingFilteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, ReduceOption ... options) {
return blockingFilteredReduced(sequence, filteredFunctor, reducedFunctor, new ReduceOptions(options));
}
/**
* Calls filterFunction once for each item in sequence. If filterFunction returns true for an item, that item is then passed to reduceFunction. In other words, the return value is the result of reduceFunction for each item where filterFunction returns true.
* <p>
* Note that while filterFunction is called concurrently, only one thread at a time will call reduceFunction. The order in which reduceFunction is called is undefined if reduceOptions is QtConcurrent::UnorderedReduce. If reduceOptions is QtConcurrent::OrderedReduce, reduceFunction is called in the order of the original sequence.
*/
public static <U, T> U blockingFilteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, ReduceOptions options) {
return blockingFilteredReduced(sequence, filteredFunctor, reducedFunctor, options.value());
}
private native static <U, T> U blockingFilteredReduced(java.util.Collection<T> sequence, FilteredFunctor<T> filteredFunctor, ReducedFunctor<U, T> reducedFunctor, int options);
/**
* Executes the method <tt>m</tt> through the QtConcurrent framework with the given arguments. The returned QFuture object's result wil be the
* return value of <tt>m</tt>. Note that this method does not accept function that return void. use runVoidMethod() for this.
*/
public static <T> QFuture<T> run(Object _this, java.lang.reflect.Method m, Object ... args) {
if (m.getReturnType() == null || m.getReturnType().equals(Void.TYPE))
throw new IllegalArgumentException("Cannot call run on method returning void. Use 'runVoidMethod' instead.");
return runPrivate(_this, m.getDeclaringClass(), m, args, com.trolltech.qt.internal.QtJambiInternal.resolveConversionSchema(m.getParameterTypes(), m.getParameterTypes()), com.trolltech.qt.internal.QtJambiInternal.typeConversionCode(m.getReturnType()));
}
private native static <T> QFuture<T> runPrivate(Object _this, Class < ? > declaringClass, java.lang.reflect.Method m, Object args[], int conversionScheme[], byte returnType);
/**
* Executes the method <tt>m</tt> with the given arguments using the QtConcurrent framework. Notice that runVoidMethod() does not
* accept methods that has a return value. Use the run() method for this purpose.
*/
public static QFutureVoid runVoidMethod(Object _this, java.lang.reflect.Method m, Object ... args) {
if (m.getReturnType() != null && !m.getReturnType().equals(Void.TYPE))
throw new IllegalArgumentException("Cannot call runVoidMethod on method returning non-void type. Use 'run' instead.");
return runVoidMethodPrivate(_this, m.getDeclaringClass(), m, args, com.trolltech.qt.internal.QtJambiInternal.resolveConversionSchema(m.getParameterTypes(), m.getParameterTypes()));
}
private native static QFutureVoid runVoidMethodPrivate(Object _this, Class < ? > declaringClass, java.lang.reflect.Method m, Object args[], int conversionScheme[]);
}// class
class QXmlStreamWriter___ extends QXmlStreamWriter {
public QXmlStreamWriter(com.trolltech.qt.core.QByteArray array) {
this(array.nativePointer());
__rcDevice = array;
}
public final void setCodec(String codecName) {
setCodec(QNativePointer.createCharPointer(codecName));
__rcCodec = null;
}
}// class
|
package no.hvl.dat104.controller.deltager;
import static no.hvl.dat104.controller.UrlMappings.PAAMELDING_URL;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class PaaMeldingBekreftelse
*/
public class PaameldingBekreftelseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if ((boolean) request.getSession().getAttribute("registrert")) {
request.getRequestDispatcher("WEB-INF/jsp/deltager/paameldingsbekreftelse.jsp").forward(request, response);
} else {
response.sendRedirect(PAAMELDING_URL);
}
}
}
|
package com.openparts.utils.mongodb;
import com.openparts.utils.mongodb.MongoDBConfig;
import com.openparts.utils.ImageSizeEnum;
import com.openparts.utils.mongodb.MongoDBCredential;
import com.openparts.utils.mongodb.MongoDBDriver;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.imgscalr.Scalr;
import com.cnpc.framework.utils.SpringContextUtil;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.Adler32;
import com.openparts.base.dao.impl.MongodbDaoClient;
import com.cnpc.framework.utils.CompressEncoding;
import com.cnpc.framework.utils.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GridFSClient {
private static Logger logger = LoggerFactory.getLogger(GridFSClient.class);
private MongodbDaoClient mongodbDaoClient = null;
private GridFS _gridFS = null;
private Object lock = new Object();
private String bucket = null;
protected static final String[] IMAGE_FORMAT = { "jpg", "jpeg", "png" };
/**
* Creates a GridFS instance for the default bucket "fs" in the given database.
*/
GridFSClient() {
this.bucket = null;
}
/**
* Creates a GridFS instance for the specified bucket in the given database.
*/
GridFSClient(String bucket) {
this.bucket = bucket;
}
public GridFS getInstance() {
if (_gridFS != null) {
return _gridFS;
}
synchronized (lock) {
if (_gridFS != null) {
return _gridFS;
}
if (mongodbDaoClient == null) {
mongodbDaoClient = (MongodbDaoClient)SpringContextUtil.getBean("mongodbDaoClient");
}
if (StrUtil.isBlank(bucket)) {
_gridFS = new GridFS(mongodbDaoClient.getDB());
} else {
_gridFS = new GridFS(mongodbDaoClient.getDB(), bucket);
}
return _gridFS;
}
}
public String saveFile(InputStream inputStream, String filename, String format, String uid) {
try {
GridFS gridFS = getInstance();
if (StrUtil.isBlank(filename)) {
filename = this.randomFileName();
}
// filename
while (true) {
GridFSDBFile _current = gridFS.findOne(filename);
if (_current == null) {
break;
}
filename = this.randomFileName();
}
GridFSInputFile file = gridFS.createFile(inputStream, filename);
if (format != null) {
file.put("format", format);
}
if (uid != null) {
file.put("uid", uid);
}
file.put("contentType", "application/octet-stream");
file.save();
return concat(filename, format);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
inputStream.close();
} catch (Exception ex) {
}
}
}
private String concat(String filename, String format) {
if (format == null) {
return filename;
}
if (format.startsWith(".")) {
return filename + format;
}
return filename + "." + format;
}
private String randomFileName() {
return CompressEncoding.CompressNumber(System.currentTimeMillis(),6) + "-" + RandomStringUtils.random(32, true, true).toLowerCase();
}
public void delete(String filename) {
GridFS gridFS = getInstance();
gridFS.remove(filename);
}
public InputStream getFile(String filename) {
GridFS gridFS = getInstance();
GridFSDBFile _current = gridFS.findOne(filename);
if (_current == null) {
return null;
}
return _current.getInputStream();
}
public InputStream getImage(String filename, String path) throws Exception {
if (ImageSizeEnum.valueOfPath(path) == null) {
return null;
}
GridFS gridFS = getInstance();
GridFSDBFile _current = gridFS.findOne(filename);
if (_current == null) {
return null;
}
int size = ImageSizeEnum.valueOfPath(path).size;
int max = (Integer) _current.get("max");
InputStream result = null;
if (size < max) {
InputStream inputStream = _current.getInputStream();
BufferedImage image = ImageIO.read(inputStream);
inputStream.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedImage thumbnail = Scalr.resize(image, size);
String format = (String) _current.get("format");
ImageIO.write(thumbnail, format, bos);
result = new ByteArrayInputStream(bos.toByteArray());
} else {
result = _current.getInputStream();
}
return result;
}
/**
*
* @param inputStream
*
* @return
* @throws Exception
*/
public String saveImage(InputStream inputStream, String uid) {
BundleEntry bundleEntry = this.drain(inputStream);
if (bundleEntry == null) {
logger.debug("file isn't a image!");
return null;
}
ByteArrayInputStream bis = bundleEntry.inputStream;
String _currentFileName = this.isExistedImage(bundleEntry);
// md5
if (_currentFileName != null) {
return _currentFileName;
}
String format = bundleEntry.format;
GridFS gridFS = getInstance();
String filename = this.randomFileName();
while (true) {
GridFSDBFile _current = gridFS.findOne(filename);
if (_current == null) {
break;
}
filename = randomFileName();
}
bis.reset();
GridFSInputFile _inputFile = gridFS.createFile(bis, filename);
if (uid != null) {
_inputFile.put("uid", uid);
}
_inputFile.put("max", bundleEntry.max);
_inputFile.put("crc", bundleEntry.crc);
_inputFile.put("format", format);
_inputFile.put("md5_source", bundleEntry.md5);
_inputFile.save();
return concat(filename, format);
}
private String isExistedImage(BundleEntry entry) {
GridFS gridFS = getInstance();
DBObject query = new BasicDBObject();
query.put("crc", entry.crc);
query.put("md5_source", entry.md5);
GridFSDBFile _current = gridFS.findOne(query);
// MD5
if (_current == null) {
return null;
}
String format = (String) _current.get("format");
if (format.startsWith(".")) {
return _current.getFilename() + format;
}
return _current.getFilename() + "." + format;
}
/**
* streamreset
*
* @param inputStream
* @return
* @throws Exception
*/
protected BundleEntry drain(InputStream inputStream) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// md5crc
Adler32 crc = new Adler32();
try {
while (true) {
int _c = inputStream.read();
if (_c == -1) {
break;
}
bos.write(_c);
crc.update(_c);
}
} catch (Exception e) {
logger.debug("RuntimeException(e)");
}
List<String> formats = new ArrayList<String>();
BufferedImage image;
String md5;
int max;
String format;
try {
ImageInputStream imageInputStream = ImageIO.createImageInputStream(new ByteArrayInputStream(bos.toByteArray()));
imageInputStream.mark();
Iterator<ImageReader> it = ImageIO.getImageReaders(imageInputStream);
while (it.hasNext()) {
ImageReader reader = it.next();
format = reader.getFormatName().toLowerCase();
if (ArrayUtils.contains(IMAGE_FORMAT, format)) {
formats.add(format);
}
}
if (formats.isEmpty()) {
return null;
}
// MD5crc
md5 = DigestUtils.md5Hex(bos.toByteArray());
imageInputStream.reset();
image = ImageIO.read(imageInputStream);
max = Math.max(image.getHeight(), image.getWidth());
bos = new ByteArrayOutputStream();
// resize
if (max > ImageSizeEnum.PIXELS_MAX.size) {
max = ImageSizeEnum.PIXELS_MAX.size;
}
format = formats.get(0);
BufferedImage thumbnail = Scalr.resize(image, max);
ImageIO.write(thumbnail, format, bos);
} catch (Exception ex) {
return null;
}
return new BundleEntry(new ByteArrayInputStream(bos.toByteArray()), md5, crc.getValue(), format, max);
}
protected class BundleEntry {
String md5;
long crc;
String format;
int max;
ByteArrayInputStream inputStream;
BundleEntry(ByteArrayInputStream inputStream, String md5, long crc, String format, int max) {
this.md5 = md5;
this.crc = crc;
this.inputStream = inputStream;
this.format = format;
this.max = max;
}
}
public static void testMain() {
MongoDBDriver mongoDBDriver = null;
try {
GridFSClient client = new GridFSClient();
testUpload(client);
// testClear(client.getInstance());
// testGetImage(client.getInstance(),"xhgcguccxumuyl9hzdombgfvzgriv7rf",null);
} catch (Exception e) {
e.printStackTrace();
} finally {
mongoDBDriver.close();
}
}
protected static void testClear(GridFS gridFS) {
DBCursor cursor = gridFS.getFileList();
while (cursor.hasNext()) {
DBObject dbObject = cursor.next();
String filename = (String) cursor.next().get("filename");
System.out.println(filename);
System.out.println(dbObject.toString());
gridFS.remove(filename);
}
cursor.close();
}
protected static void testUpload(GridFSClient client) throws Exception {
FileInputStream inputStream = new FileInputStream(new File("/data/tmp/222222222.jpg"));
// client.saveFile(inputStream, "filename", "jpg", "1");
try {
String filename = client.saveImage(inputStream, null);
if (filename == null) {
System.out.println("saveImage error!");
return;
}
System.out.println(filename);
String source = filename.substring(0, filename.lastIndexOf("."));
System.out.println(source);
InputStream result = client.getImage(source, "x4");
if (result == null) {
System.out.println("not found!");
}
// vejibw36famkscjyksgke7bugzonnyan
FileOutputStream outputStream = new FileOutputStream("/data/tmp/" + filename);
while (true) {
int i = result.read();
if (i == -1) {
break;
}
outputStream.write(i);
}
outputStream.flush();
outputStream.close();
result.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
}
}
protected static void testGetImage(GridFS gridFS, String filename, String path) {
DBObject query = new BasicDBObject();
query.put("md5_source", "9e131ae4ed7337d4712650229b827725");
GridFSDBFile file = gridFS.findOne(query);
if (file != null) {
System.out.println(file.getFilename());
}
}
}
|
package weatherhandler.parser;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import weatherhandler.data.Measurement;
public class WeatherHandler extends DefaultHandler {
private List<Measurement> measurements = new ArrayList<Measurement>();
private String tagName = null;
private Measurement mes = null;
public List<Measurement> getList() {
return measurements;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("MEASUREMENT")) {
//initialize Measurement object
mes = new Measurement();
} else {
this.tagName = qName;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("MEASUREMENT")) {
//add Measurement object to list
measurements.add(mes);
}
this.tagName = null;
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (tagName == null || length == 0) {
return;
}
String slice = new String(ch, start, length);
if (tagName.equalsIgnoreCase("STN")) {
mes.setStation(slice);
} else if (tagName.equalsIgnoreCase("DATE")) {
mes.setDate(slice);
} else if (tagName.equalsIgnoreCase("TIME")) {
mes.setTime(slice);
} else if (tagName.equalsIgnoreCase("TEMP") && slice.length() > 0) {
mes.setTemperature(Float.parseFloat(slice));
} else if (tagName.equalsIgnoreCase("DEWP") && slice.length() > 0) {
mes.setDewPoint(Float.parseFloat(slice));
} else if (tagName.equalsIgnoreCase("STP") && slice.length() > 0) {
mes.setStationPressure(Float.parseFloat(slice));
} else if (tagName.equalsIgnoreCase("SLP") && slice.length() > 0) {
mes.setSeaLevelPressure(Float.parseFloat(slice));
} else if (tagName.equalsIgnoreCase("VISIB") && slice.length() > 0) {
mes.setVisibility(Float.parseFloat(slice));
} else if (tagName.equalsIgnoreCase("WDSP") && slice.length() > 0) {
mes.setWindSpeed(Float.parseFloat(slice));
} else if (tagName.equalsIgnoreCase("PRCP") && slice.length() > 0) {
mes.setPrecipitation(Float.parseFloat(slice));
} else if (tagName.equalsIgnoreCase("SNDP") && slice.length() > 0) {
mes.setSnowDepth(Float.parseFloat(slice));
} else if (tagName.equalsIgnoreCase("FRSHTT") && slice.length() > 0) {
mes.setEvents(slice);
} else if (tagName.equalsIgnoreCase("CLDC") && slice.length() > 0) {
mes.setCloudCover(Float.parseFloat(slice));
} else if (tagName.equalsIgnoreCase("WNDDIR") && slice.length() > 0) {
mes.setWindDirection(Integer.parseInt(slice));
}
}
}
|
package org.bimserver.database.queries.om;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.bimserver.emf.PackageMetaData;
import org.bimserver.shared.QueryException;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EReference;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class JsonQueryObjectModelConverter {
private static final Map<String, Include> CACHED_DEFINES = new HashMap<>();
private PackageMetaData packageMetaData;
public JsonQueryObjectModelConverter(PackageMetaData packageMetaData) {
this.packageMetaData = packageMetaData;
}
public ObjectNode toJson(Query query) {
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode queryNode = objectMapper.createObjectNode();
Map<String, Include> defines = query.getDefines();
ObjectNode definesNode = objectMapper.createObjectNode();
queryNode.set("defines", definesNode);
for (String key : defines.keySet()) {
ObjectNode includeNode = objectMapper.createObjectNode();
Include include = defines.get(key);
ArrayNode fieldsNode = objectMapper.createArrayNode();
for (EReference eReference : include.getFields()) {
fieldsNode.add(eReference.getName());
}
definesNode.set(key, includeNode);
}
ArrayNode queryPartsNode = objectMapper.createArrayNode();
queryNode.set("queries", queryPartsNode);
for (QueryPart queryPart : query.getQueryParts()) {
ObjectNode queryPartNode = objectMapper.createObjectNode();
if (queryPart.hasTypes()) {
ArrayNode typesNode = objectMapper.createArrayNode();
queryPartNode.set("types", typesNode);
for (EClass type : queryPart.getTypes()) {
typesNode.add(type.getName());
}
}
if (queryPart.hasOids()) {
ArrayNode oidsNode = objectMapper.createArrayNode();
queryPartNode.set("oids", oidsNode);
for (long oid : queryPart.getOids()) {
oidsNode.add(oid);
}
}
queryPartsNode.add(queryPartNode);
}
return queryNode;
}
public Query parseJson(String queryName, ObjectNode fullQuery) throws QueryException {
Query query = new Query(queryName, packageMetaData);
if (fullQuery.has("defines")) {
JsonNode defines = fullQuery.get("defines");
if (defines instanceof ObjectNode) {
parseDefines(query, (ObjectNode)fullQuery.get("defines"));
} else {
throw new QueryException("\"defines\" must be of type object");
}
}
if (fullQuery.has("queries")) {
JsonNode queriesNode = fullQuery.get("queries");
if (queriesNode instanceof ArrayNode) {
ArrayNode queries = (ArrayNode) fullQuery.get("queries");
if (queries.size() == 0) {
throw new QueryException("\"queries\" must contain at least one query");
}
for (int i=0; i<queries.size(); i++) {
parseJsonQuery(query, (ObjectNode)queries.get(i));
}
} else {
throw new QueryException("\"queries\" must be of type array");
}
} else if (fullQuery.has("query")) {
JsonNode queryNode = fullQuery.get("query");
if (queryNode instanceof ObjectNode) {
parseJsonQuery(query, (ObjectNode) fullQuery.get("query"));
} else {
throw new QueryException("\"query\" must be of type object");
}
} else if (!fullQuery.has("defines")) {
parseJsonQuery(query, fullQuery);
}
return query;
}
private void parseDefines(Query query, ObjectNode jsonNode) throws QueryException {
Iterator<String> fieldNames = jsonNode.fieldNames();
int i=0;
// First pass, get all the name and create stub includes, using two passing to allow the usage of includes defined later in the structure
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode defineNode = jsonNode.get(fieldName);
if (defineNode instanceof ObjectNode) {
Include include = new Include(packageMetaData);
query.addDefine(fieldName, include);
} else {
throw new QueryException("\"defines\"[" + i + "] must be of type object");
}
i++;
}
// Second pass, actually construct the includes
fieldNames = jsonNode.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode defineNode = jsonNode.get(fieldName);
ObjectNode define = (ObjectNode)defineNode;
parseInclude(query, define, query.getDefine(fieldName));
}
}
private Include parseInclude(Query query, ObjectNode jsonNode, Include include) throws QueryException {
if (include == null) {
include = new Include(packageMetaData);
}
if (!jsonNode.has("type") && !jsonNode.has("types")) {
throw new QueryException("includes require a \"type\" or \"types\" field " + jsonNode);
}
if (jsonNode.has("type")) {
JsonNode typeNode = jsonNode.get("type");
if (typeNode.isTextual()) {
EClass eClass = packageMetaData.getEClassIncludingDependencies(typeNode.asText());
if (eClass == null) {
throw new QueryException("Cannot find type \"" + typeNode.asText() + "\"");
}
include.addType(eClass, false);
} else {
throw new QueryException("\"type\" field mst be of type string");
}
}
if (jsonNode.has("types")) {
JsonNode typesNode = jsonNode.get("types");
if (typesNode instanceof ArrayNode) {
ArrayNode types = (ArrayNode)typesNode;
if (types.size() == 0) {
throw new QueryException("\"types\" must have a least one element");
}
for (int i=0; i<types.size(); i++) {
JsonNode typeNode = types.get(i);
if (typeNode.isTextual()) {
EClass eClass = packageMetaData.getEClass(typeNode.asText());
include.addType(eClass, false);
} else {
throw new QueryException("\"types\"[" + i + "] field mst be of type string");
}
}
} else {
throw new QueryException("\"types\" must be of type array");
}
}
if (jsonNode.has("outputType")) {
JsonNode typeNode = jsonNode.get("outputType");
if (typeNode.isTextual()) {
EClass eClass = packageMetaData.getEClassIncludingDependencies(typeNode.asText());
include.addOutputType(eClass);
} else {
throw new QueryException("\"outputType\" field mst be of type string");
}
}
if (jsonNode.has("outputTypes")) {
JsonNode typesNode = jsonNode.get("outputTypes");
if (typesNode instanceof ArrayNode) {
ArrayNode types = (ArrayNode)typesNode;
if (types.size() == 0) {
throw new QueryException("\"outputTypes\" must have a least one element");
}
for (int i=0; i<types.size(); i++) {
JsonNode typeNode = types.get(i);
if (typeNode.isTextual()) {
EClass eClass = packageMetaData.getEClass(typeNode.asText());
include.addOutputType(eClass);
} else {
throw new QueryException("\"outputTypes\"[" + i + "] field mst be of type string");
}
}
} else {
throw new QueryException("\"outputTypes\" must be of type array");
}
}
if (jsonNode.has("field")) {
JsonNode fieldNode = jsonNode.get("field");
if (fieldNode.isTextual()) {
include.addField(fieldNode.asText());
} else {
throw new QueryException("\"field\" must be of type string");
}
}
if (jsonNode.has("fields")) {
JsonNode fieldsNode = jsonNode.get("fields");
if (fieldsNode instanceof ArrayNode) {
ArrayNode fields = (ArrayNode)fieldsNode;
for (int i=0; i<fields.size(); i++) {
JsonNode fieldNode = fields.get(i);
if (fieldNode.isTextual()) {
include.addField(fieldNode.asText());
} else {
throw new QueryException("\"fields\"[" + i + "] must be of type string");
}
}
} else {
throw new QueryException("\"fields\" must be of type array");
}
}
if (jsonNode.has("include")) {
JsonNode includeNode = jsonNode.get("include");
processSubInclude(query, include, includeNode);
}
if (jsonNode.has("includes")) {
JsonNode includesNode = jsonNode.get("includes");
if (includesNode instanceof ArrayNode) {
ArrayNode includes = (ArrayNode)includesNode;
for (int i=0; i<includes.size(); i++) {
processSubInclude(query, include, includes.get(i));
}
} else {
throw new QueryException("\"includes\" must be of type array");
}
}
return include;
}
// TODO thread safety and cache invalidation on file updates
public Include getDefineFromFile(String includeName) throws QueryException {
Include include = CACHED_DEFINES.get(includeName);
if (include != null) {
return include;
}
String namespaceString = includeName.substring(0, includeName.indexOf(":"));
String singleIncludeName = includeName.substring(includeName.indexOf(":") + 1);
URL resource;
try {
resource = getClass().getClassLoader().loadClass("org.bimserver.database.queries.StartFrame").getResource("json/" + namespaceString + ".json");
if (resource == null) {
throw new QueryException("Could not find '" + namespaceString + "' namespace in predefined queries");
}
} catch (ClassNotFoundException e1) {
throw new QueryException("Could not find '" + namespaceString + "' namespace in predefined queries");
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
try {
ObjectNode predefinedQuery = objectMapper.readValue(resource, ObjectNode.class);
JsonQueryObjectModelConverter converter = new JsonQueryObjectModelConverter(packageMetaData);
Query query = converter.parseJson(namespaceString, predefinedQuery);
Include define = query.getDefine(singleIncludeName);
if (define == null) {
throw new QueryException("Could not find '" + singleIncludeName + "' in defines in namespace " + query.getName());
}
CACHED_DEFINES.put(includeName, define);
return define;
} catch (JsonParseException e) {
throw new QueryException(e);
} catch (JsonMappingException e) {
throw new QueryException(e);
} catch (IOException e) {
throw new QueryException(e);
}
}
private void processSubInclude(Query query, CanInclude parentInclude, JsonNode includeNode) throws QueryException {
if (includeNode instanceof ObjectNode) {
ObjectNode innerInclude = (ObjectNode)includeNode;
parentInclude.addInclude(parseInclude(query, innerInclude, null));
} else if (includeNode.isTextual()) {
String includeName = includeNode.asText();
if (includeName.contains(":")) {
parentInclude.addInclude(getDefineFromFile(includeName));
} else {
Include otherInclude = query.getDefine(includeName);
if (otherInclude == null) {
throw new QueryException("Cannot find define \"" + includeName + "\"");
}
parentInclude.addInclude(otherInclude);
}
} else {
throw new QueryException("\"include\" must be of type object or string");
}
}
private void parseJsonQuery(Query query, ObjectNode objectNode) throws QueryException {
QueryPart queryPart = new QueryPart(packageMetaData);
if (objectNode.has("type")) {
JsonNode typeNode = objectNode.get("type");
if (typeNode.isTextual()) {
String type = typeNode.asText();
addType(objectNode, queryPart, type);
} else {
throw new QueryException("\"type\" must be of type string");
}
}
if (objectNode.has("types")) {
JsonNode typesNode = objectNode.get("types");
if (typesNode instanceof ArrayNode) {
ArrayNode types = (ArrayNode)typesNode;
for (int i=0; i<types.size(); i++) {
JsonNode typeNode = types.get(i);
if (typeNode.isTextual()) {
String type = typeNode.asText();
addType(objectNode, queryPart, type);
} else {
throw new QueryException("\"types\"[" + i + "] must be of type string");
}
}
} else {
throw new QueryException("\"types\" must be of type array");
}
}
if (objectNode.has("includeAllFields") && objectNode.get("includeAllFields").asBoolean()) {
queryPart.setIncludeAllFields(true);
}
if (objectNode.has("oid")) {
JsonNode oidNode = objectNode.get("oid");
if (oidNode.isNumber()) {
queryPart.addOid(oidNode.asLong());
} else {
throw new QueryException("\"oid\" must be of type number");
}
}
if (objectNode.has("oids")) {
JsonNode oidsNode = objectNode.get("oids");
if (oidsNode instanceof ArrayNode) {
ArrayNode oids = (ArrayNode)oidsNode;
for (int i=0; i<oids.size(); i++) {
JsonNode oidNode = oids.get(i);
if (oidNode.isNumber()) {
queryPart.addOid(oidNode.asLong());
} else {
throw new QueryException("\"oids\"[" + i + "] must be of type number");
}
}
} else {
throw new QueryException("\"oids\" must be of type array");
}
}
if (objectNode.has("guid")) {
JsonNode guidNode = objectNode.get("guid");
if (guidNode.isTextual()) {
queryPart.addGuid(guidNode.asText());
} else {
throw new QueryException("\"guid\" must be of type string");
}
}
if (objectNode.has("guids")) {
JsonNode guidsNode = objectNode.get("guids");
if (guidsNode instanceof ArrayNode) {
ArrayNode guids = (ArrayNode)guidsNode;
for (int i=0; i<guids.size(); i++) {
JsonNode guidNode = guids.get(i);
if (guidNode.isTextual()) {
queryPart.addGuid(guidNode.asText());
} else {
throw new QueryException("\"guids\"[" + i + "] must be of type string");
}
}
} else {
throw new QueryException("\"guids\" must be of type array");
}
}
if (objectNode.has("properties")) {
JsonNode propertiesNode = objectNode.get("properties");
if (propertiesNode instanceof ObjectNode) {
ObjectNode properties = (ObjectNode) objectNode.get("properties");
Iterator<Entry<String, JsonNode>> fields = properties.fields();
while (fields.hasNext()) {
Entry<String, JsonNode> entry = fields.next();
JsonNode value = entry.getValue();
if (value.isValueNode()) {
queryPart.addProperty(entry.getKey(), value.asBoolean());
} else {
throw new QueryException("property \"" + entry.getKey() + "\" type not supported");
}
}
} else {
throw new QueryException("\"properties\" must be of type object");
}
}
if (objectNode.has("inBoundingBox")) {
JsonNode boundingBoxNode = objectNode.get("inBoundingBox");
if (boundingBoxNode instanceof ObjectNode) {
ObjectNode boundingBox = (ObjectNode) boundingBoxNode;
double x = checkFloat(boundingBox, "x");
double y = checkFloat(boundingBox, "y");
double z = checkFloat(boundingBox, "z");
double width = checkFloat(boundingBox, "width");
double height = checkFloat(boundingBox, "height");
double depth = checkFloat(boundingBox, "depth");
queryPart.setInBoundingBox(new InBoundingBox(x, y, z, width, height, depth));
} else {
throw new QueryException("\"inBoundingBox\" should be of type object");
}
}
if (objectNode.has("include")) {
JsonNode includeNode = objectNode.get("include");
processSubInclude(query, queryPart, includeNode);
}
if (objectNode.has("includes")) {
JsonNode includesNode = objectNode.get("includes");
if (includesNode instanceof ArrayNode) {
ArrayNode includes = (ArrayNode)includesNode;
for (int i=0; i<includes.size(); i++) {
JsonNode include = includes.get(i);
processSubInclude(query, queryPart, include);
}
} else {
throw new QueryException("\"includes\" should be of type array");
}
}
if (objectNode.has("fields")) {
objectNode.get("fields"); // fields node
}
Iterator<String> fieldNames = objectNode.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
if (fieldName.equals("includeAllFields") || fieldName.equals("type") || fieldName.equals("types") || fieldName.equals("oid") || fieldName.equals("oids") || fieldName.equals("guid") || fieldName.equals("guids") || fieldName.equals("properties") || fieldName.equals("inBoundingBox") || fieldName.equals("include") || fieldName.equals("includes") || fieldName.equals("includeAllSubtypes")) {
// fine
} else {
throw new QueryException("Unknown field: \"" + fieldName + "\"");
}
}
query.addQueryPart(queryPart);
}
private double checkFloat(ObjectNode node, String key) throws QueryException {
if (!node.has(key)) {
throw new QueryException("\"" + key + "\" not found on \"inBoundingBox\"");
}
JsonNode jsonNode = node.get(key);
if (jsonNode.isNumber()) {
return jsonNode.asDouble();
} else {
throw new QueryException("\"" + key + "\" should be of type number");
}
}
private void addType(ObjectNode objectNode, QueryPart queryPart, String type) throws QueryException {
if (type.equals("Object")) {
// no type filter
return;
}
EClass eClass = packageMetaData.getEClassIncludingDependencies(type);
if (eClass == null) {
throw new QueryException("Type \"" + type + "\" not found");
}
queryPart.addType(eClass, objectNode.has("includeAllSubtypes") && objectNode.get("includeAllSubtypes").asBoolean());
}
}
|
package waffle.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import javax.security.auth.Subject;
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 javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import waffle.servlet.spi.SecurityFilterProvider;
import waffle.servlet.spi.SecurityFilterProviderCollection;
import waffle.util.AuthorizationHeader;
import waffle.util.CorsPreflightCheck;
import waffle.windows.auth.IWindowsAuthProvider;
import waffle.windows.auth.IWindowsIdentity;
import waffle.windows.auth.IWindowsImpersonationContext;
import waffle.windows.auth.PrincipalFormat;
import waffle.windows.auth.impl.WindowsAuthProviderImpl;
/**
* A Negotiate (NTLM/Kerberos) Security Filter.
*
* @author dblock[at]dblock[dot]org
*/
public class NegotiateSecurityFilter implements Filter {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(NegotiateSecurityFilter.class);
/** The Constant PRINCIPALSESSIONKEY. */
private static final String PRINCIPALSESSIONKEY = NegotiateSecurityFilter.class.getName() + ".PRINCIPAL";
/** The principal format. */
private PrincipalFormat principalFormat = PrincipalFormat.FQN;
/** The role format. */
private PrincipalFormat roleFormat = PrincipalFormat.FQN;
/** The providers. */
private SecurityFilterProviderCollection providers;
/** The auth. */
private IWindowsAuthProvider auth;
/** The exclusion filter. */
private String[] excludePatterns;
/** The allow guest login. */
private boolean allowGuestLogin = true;
/** The impersonate. */
private boolean impersonate;
/** The exclusion bearer authorization. */
private boolean excludeBearerAuthorization;
/** The exclusions cors pre flight. */
private boolean excludeCorsPreflight;
/**
* Instantiates a new negotiate security filter.
*/
public NegotiateSecurityFilter() {
NegotiateSecurityFilter.LOGGER.debug("[waffle.servlet.NegotiateSecurityFilter] loaded");
}
@Override
public void destroy() {
NegotiateSecurityFilter.LOGGER.info("[waffle.servlet.NegotiateSecurityFilter] stopped");
}
@Override
public void doFilter(final ServletRequest sreq, final ServletResponse sres, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) sreq;
final HttpServletResponse response = (HttpServletResponse) sres;
NegotiateSecurityFilter.LOGGER.debug("{} {}, contentlength: {}", request.getMethod(), request.getRequestURI(),
Integer.valueOf(request.getContentLength()));
// If excluded URL, resume the filter chain
if (request.getRequestURL() != null && this.excludePatterns != null) {
final String url = request.getRequestURL().toString();
for (final String pattern : this.excludePatterns) {
if (url.matches(pattern)) {
NegotiateSecurityFilter.LOGGER.info("Pattern :{} excluded URL:{}", url, pattern);
chain.doFilter(sreq, sres);
return;
}
}
}
// If exclude cores pre-flight and is pre flight, resume the filter chain
if (this.excludeCorsPreflight && CorsPreflightCheck.isPreflight(request)) {
NegotiateSecurityFilter.LOGGER.debug("[waffle.servlet.NegotiateSecurityFilter] CORS preflight");
chain.doFilter(sreq, sres);
return;
}
final AuthorizationHeader authorizationHeader = new AuthorizationHeader(request);
// If exclude bearer authorization and is bearer authorization, result the filter chain
if (this.excludeBearerAuthorization && authorizationHeader.isBearerAuthorizationHeader()) {
NegotiateSecurityFilter.LOGGER.debug("[waffle.servlet.NegotiateSecurityFilter] Authorization: Bearer");
chain.doFilter(sreq, sres);
return;
}
if (this.doFilterPrincipal(request, response, chain)) {
// previously authenticated user
return;
}
// authenticate user
if (!authorizationHeader.isNull()) {
// log the user in using the token
IWindowsIdentity windowsIdentity;
try {
windowsIdentity = this.providers.doFilter(request, response);
if (windowsIdentity == null) {
return;
}
} catch (final IOException e) {
NegotiateSecurityFilter.LOGGER.warn("error logging in user: {}", e.getMessage());
NegotiateSecurityFilter.LOGGER.trace("", e);
this.sendUnauthorized(response, true);
return;
}
IWindowsImpersonationContext ctx = null;
try {
if (!this.allowGuestLogin && windowsIdentity.isGuest()) {
NegotiateSecurityFilter.LOGGER.warn("guest login disabled: {}", windowsIdentity.getFqn());
this.sendUnauthorized(response, true);
return;
}
NegotiateSecurityFilter.LOGGER.debug("logged in user: {} ({})", windowsIdentity.getFqn(),
windowsIdentity.getSidString());
final HttpSession session = request.getSession(true);
if (session == null) {
throw new ServletException("Expected HttpSession");
}
Subject subject = (Subject) session.getAttribute("javax.security.auth.subject");
if (subject == null) {
subject = new Subject();
}
WindowsPrincipal windowsPrincipal;
if (this.impersonate) {
windowsPrincipal = new AutoDisposableWindowsPrincipal(windowsIdentity, this.principalFormat,
this.roleFormat);
} else {
windowsPrincipal = new WindowsPrincipal(windowsIdentity, this.principalFormat, this.roleFormat);
}
NegotiateSecurityFilter.LOGGER.debug("roles: {}", windowsPrincipal.getRolesString());
subject.getPrincipals().add(windowsPrincipal);
request.getSession(false).setAttribute("javax.security.auth.subject", subject);
NegotiateSecurityFilter.LOGGER.info("successfully logged in user: {}", windowsIdentity.getFqn());
request.getSession(false).setAttribute(NegotiateSecurityFilter.PRINCIPALSESSIONKEY, windowsPrincipal);
final NegotiateRequestWrapper requestWrapper = new NegotiateRequestWrapper(request, windowsPrincipal);
if (this.impersonate) {
NegotiateSecurityFilter.LOGGER.debug("impersonating user");
ctx = windowsIdentity.impersonate();
}
chain.doFilter(requestWrapper, response);
} finally {
if (this.impersonate && ctx != null) {
NegotiateSecurityFilter.LOGGER.debug("terminating impersonation");
ctx.revertToSelf();
} else {
windowsIdentity.dispose();
}
}
return;
}
NegotiateSecurityFilter.LOGGER.debug("authorization required");
this.sendUnauthorized(response, false);
}
/**
* Filter for a previously logged on user.
*
* @param request
* HTTP request.
* @param response
* HTTP response.
* @param chain
* Filter chain.
* @return True if a user already authenticated.
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ServletException
* the servlet exception
*/
private boolean doFilterPrincipal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain chain) throws IOException, ServletException {
Principal principal = request.getUserPrincipal();
if (principal == null) {
final HttpSession session = request.getSession(false);
if (session != null) {
principal = (Principal) session.getAttribute(NegotiateSecurityFilter.PRINCIPALSESSIONKEY);
}
}
if (principal == null) {
// no principal in this request
return false;
}
if (this.providers.isPrincipalException(request)) {
// the providers signal to authenticate despite an existing principal, eg. NTLM post
return false;
}
// user already authenticated
if (principal instanceof WindowsPrincipal) {
NegotiateSecurityFilter.LOGGER.debug("previously authenticated Windows user: {}", principal.getName());
final WindowsPrincipal windowsPrincipal = (WindowsPrincipal) principal;
if (this.impersonate && windowsPrincipal.getIdentity() == null) {
// This can happen when the session has been serialized then de-serialized
// and because the IWindowsIdentity field is transient. In this case re-ask an
// authentication to get a new identity.
return false;
}
final NegotiateRequestWrapper requestWrapper = new NegotiateRequestWrapper(request, windowsPrincipal);
IWindowsImpersonationContext ctx = null;
if (this.impersonate) {
NegotiateSecurityFilter.LOGGER.debug("re-impersonating user");
ctx = windowsPrincipal.getIdentity().impersonate();
}
try {
chain.doFilter(requestWrapper, response);
} finally {
if (this.impersonate && ctx != null) {
NegotiateSecurityFilter.LOGGER.debug("terminating impersonation");
ctx.revertToSelf();
}
}
} else {
NegotiateSecurityFilter.LOGGER.debug("previously authenticated user: {}", principal.getName());
chain.doFilter(request, response);
}
return true;
}
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
final Map<String, String> implParameters = new HashMap<>();
NegotiateSecurityFilter.LOGGER.debug("[waffle.servlet.NegotiateSecurityFilter] starting");
String authProvider = null;
String[] providerNames = null;
if (filterConfig != null) {
final Enumeration<String> parameterNames = filterConfig.getInitParameterNames();
NegotiateSecurityFilter.LOGGER.debug("[waffle.servlet.NegotiateSecurityFilter] processing filterConfig");
while (parameterNames.hasMoreElements()) {
final String parameterName = parameterNames.nextElement();
final String parameterValue = filterConfig.getInitParameter(parameterName);
NegotiateSecurityFilter.LOGGER.debug("Init Param: '{}={}'", parameterName, parameterValue);
switch (parameterName) {
case "principalFormat":
this.principalFormat = PrincipalFormat.valueOf(parameterValue.toUpperCase(Locale.ENGLISH));
break;
case "roleFormat":
this.roleFormat = PrincipalFormat.valueOf(parameterValue.toUpperCase(Locale.ENGLISH));
break;
case "allowGuestLogin":
this.allowGuestLogin = Boolean.parseBoolean(parameterValue);
break;
case "impersonate":
this.impersonate = Boolean.parseBoolean(parameterValue);
break;
case "securityFilterProviders":
providerNames = parameterValue.split("\\s+");
break;
case "authProvider":
authProvider = parameterValue;
break;
case "excludePatterns":
this.excludePatterns = parameterValue.split("\\s+");
break;
case "excludeCorsPreflight":
this.setExcludeCorsPreflight(Boolean.parseBoolean(parameterValue));
break;
case "excludeBearerAuthorization":
this.setExcludeBearerAuthorization(Boolean.parseBoolean(parameterValue));
break;
default:
implParameters.put(parameterName, parameterValue);
break;
}
}
}
NegotiateSecurityFilter.LOGGER.debug("[waffle.servlet.NegotiateSecurityFilter] authProvider");
if (authProvider != null) {
try {
this.auth = (IWindowsAuthProvider) Class.forName(authProvider).getConstructor().newInstance();
} catch (final ClassNotFoundException | IllegalArgumentException | SecurityException
| InstantiationException | IllegalAccessException | InvocationTargetException
| NoSuchMethodException e) {
NegotiateSecurityFilter.LOGGER.error("error loading '{}': {}", authProvider, e.getMessage());
NegotiateSecurityFilter.LOGGER.trace("", e);
throw new ServletException(e);
}
}
if (this.auth == null) {
this.auth = new WindowsAuthProviderImpl();
}
if (providerNames != null) {
this.providers = new SecurityFilterProviderCollection(providerNames, this.auth);
}
// create default providers if none specified
if (this.providers == null) {
NegotiateSecurityFilter.LOGGER.debug("initializing default security filter providers");
this.providers = new SecurityFilterProviderCollection(this.auth);
}
// apply provider implementation parameters
NegotiateSecurityFilter.LOGGER.debug("[waffle.servlet.NegotiateSecurityFilter] load provider parameters");
for (final Entry<String, String> implParameter : implParameters.entrySet()) {
final String[] classAndParameter = implParameter.getKey().split("/", 2);
if (classAndParameter.length == 2) {
try {
NegotiateSecurityFilter.LOGGER.debug("setting {}, {}={}", classAndParameter[0],
classAndParameter[1], implParameter.getValue());
final SecurityFilterProvider provider = this.providers.getByClassName(classAndParameter[0]);
provider.initParameter(classAndParameter[1], implParameter.getValue());
} catch (final ClassNotFoundException e) {
NegotiateSecurityFilter.LOGGER.error("invalid class: {} in {}", classAndParameter[0],
implParameter.getKey());
throw new ServletException(e);
} catch (final Exception e) {
NegotiateSecurityFilter.LOGGER.error("{}: error setting '{}': {}", classAndParameter[0],
classAndParameter[1], e.getMessage());
NegotiateSecurityFilter.LOGGER.trace("", e);
throw new ServletException(e);
}
} else {
NegotiateSecurityFilter.LOGGER.error("Invalid parameter: {}", implParameter.getKey());
throw new ServletException("Invalid parameter: " + implParameter.getKey());
}
}
NegotiateSecurityFilter.LOGGER.info("[waffle.servlet.NegotiateSecurityFilter] started");
}
/**
* Set the principal format.
*
* @param format
* Principal format.
*/
public void setPrincipalFormat(final String format) {
this.principalFormat = PrincipalFormat.valueOf(format.toUpperCase(Locale.ENGLISH));
NegotiateSecurityFilter.LOGGER.info("principal format: {}", this.principalFormat);
}
/**
* Principal format.
*
* @return Principal format.
*/
public PrincipalFormat getPrincipalFormat() {
return this.principalFormat;
}
/**
* Set the principal format.
*
* @param format
* Role format.
*/
public void setRoleFormat(final String format) {
this.roleFormat = PrincipalFormat.valueOf(format.toUpperCase(Locale.ENGLISH));
NegotiateSecurityFilter.LOGGER.info("role format: {}", this.roleFormat);
}
/**
* Principal format.
*
* @return Role format.
*/
public PrincipalFormat getRoleFormat() {
return this.roleFormat;
}
/**
* Send a 401 Unauthorized along with protocol authentication headers.
*
* @param response
* HTTP Response
* @param close
* Close connection.
*/
private void sendUnauthorized(final HttpServletResponse response, final boolean close) {
try {
this.providers.sendUnauthorized(response);
if (close) {
response.setHeader("Connection", "close");
} else {
response.setHeader("Connection", "keep-alive");
}
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
response.flushBuffer();
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
/**
* Windows auth provider.
*
* @return IWindowsAuthProvider.
*/
public IWindowsAuthProvider getAuth() {
return this.auth;
}
/**
* Set Windows auth provider.
*
* @param provider
* Class implements IWindowsAuthProvider.
*/
public void setAuth(final IWindowsAuthProvider provider) {
this.auth = provider;
}
/**
* True if guest login is allowed.
*
* @return True if guest login is allowed, false otherwise.
*/
public boolean isAllowGuestLogin() {
return this.allowGuestLogin;
}
/**
* Enable/Disable impersonation.
*
* @param value
* true to enable impersonation, false otherwise
*/
public void setImpersonate(final boolean value) {
this.impersonate = value;
}
/**
* Checks if is impersonate.
*
* @return true if impersonation is enabled, false otherwise
*/
public boolean isImpersonate() {
return this.impersonate;
}
/**
* Security filter providers.
*
* @return A collection of security filter providers.
*/
public SecurityFilterProviderCollection getProviders() {
return this.providers;
}
public void setExcludeBearerAuthorization(boolean excludeBearerAuthorization) {
this.excludeBearerAuthorization = excludeBearerAuthorization;
}
public void setExcludeCorsPreflight(boolean excludeCorsPreflight) {
this.excludeCorsPreflight = excludeCorsPreflight;
}
}
|
package org.objectweb.asmx;
import com.sun.tools.javac.code.TargetType;
import com.sun.tools.javac.code.TypeAnnotationPosition.TypePathEntry;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* A Java class parser to make a {@link ClassVisitor} visit an existing class.
* This class parses a byte array conforming to the Java class file format and
* calls the appropriate visit methods of a given class visitor for each field,
* method and bytecode instruction encountered.
*
* @author Eric Bruneton
* @author Eugene Kuleshov
*/
public class ClassReader {
/**
* True to enable signatures support.
*/
static final boolean SIGNATURES = true;
/**
* True to enable annotations support.
*/
static final boolean ANNOTATIONS = true;
/**
* True to enable stack map frames support.
*/
static final boolean FRAMES = true;
/**
* True to enable bytecode writing support.
*/
static final boolean WRITER = true;
/**
* True to enable JSR_W and GOTO_W support.
*/
static final boolean RESIZE = true;
/**
* Flag to skip method code. If this class is set <code>CODE</code>
* attribute won't be visited. This can be used, for example, to retrieve
* annotations for methods and method parameters.
*/
public static final int SKIP_CODE = 1;
/**
* Flag to skip the debug information in the class. If this flag is set the
* debug information of the class is not visited, i.e. the
* {@link MethodVisitor#visitLocalVariable visitLocalVariable} and
* {@link MethodVisitor#visitLineNumber visitLineNumber} methods will not be
* called.
*/
public static final int SKIP_DEBUG = 2;
/**
* Flag to skip the stack map frames in the class. If this flag is set the
* stack map frames of the class is not visited, i.e. the
* {@link MethodVisitor#visitFrame visitFrame} method will not be called.
* This flag is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is
* used: it avoids visiting frames that will be ignored and recomputed from
* scratch in the class writer.
*/
public static final int SKIP_FRAMES = 4;
/**
* Flag to expand the stack map frames. By default stack map frames are
* visited in their original format (i.e. "expanded" for classes whose
* version is less than V1_6, and "compressed" for the other classes). If
* this flag is set, stack map frames are always visited in expanded format
* (this option adds a decompression/recompression step in ClassReader and
* ClassWriter which degrades performances quite a lot).
*/
public static final int EXPAND_FRAMES = 8;
/**
* The class to be parsed. <i>The content of this array must not be
* modified. This field is intended for {@link Attribute} sub classes, and
* is normally not needed by class generators or adapters.</i>
*/
public final byte[] b;
/**
* The start index of each constant pool item in {@link #b b}, plus one.
* The one byte offset skips the constant pool item tag that indicates its
* type.
*/
private final int[] items;
/**
* The String objects corresponding to the CONSTANT_Utf8 items. This cache
* avoids multiple parsing of a given CONSTANT_Utf8 constant pool item,
* which GREATLY improves performance (by a factor 2 to 3). This caching
* strategy could be extended to all constant pool items, but its benefit
* would not be so great for these items (because they are much less
* expensive to parse than CONSTANT_Utf8 items).
*/
private final String[] strings;
/**
* Maximum length of the strings contained in the constant pool of the
* class.
*/
private final int maxStringLength;
/**
* Start index of the class header information (access, name...) in
* {@link #b b}.
*/
public final int header;
/**
* The start index of each bootstrap method.
*/
int[] bootstrapMethods;
// Constructors
/**
* Constructs a new {@link ClassReader} object.
*
* @param b the bytecode of the class to be read.
*/
public ClassReader(final byte[] b) {
this(b, 0, b.length);
}
/**
* Constructs a new {@link ClassReader} object.
*
* @param b the bytecode of the class to be read.
* @param off the start offset of the class data.
* @param len the length of the class data.
*/
public ClassReader(final byte[] b, final int off, final int len) {
this.b = b;
// parses the constant pool
items = new int[readUnsignedShort(off + 8)];
int ll = items.length;
strings = new String[ll];
int max = 0;
int index = off + 10;
for (int i = 1; i < ll; ++i) {
items[i] = index + 1;
int tag = b[index];
int size;
switch (tag) {
case ClassWriter.FIELD:
case ClassWriter.METH:
case ClassWriter.IMETH:
case ClassWriter.INT:
case ClassWriter.FLOAT:
case ClassWriter.NAME_TYPE:
case ClassWriter.INDY:
size = 5;
break;
case ClassWriter.LONG:
case ClassWriter.DOUBLE:
size = 9;
++i;
break;
case ClassWriter.UTF8:
size = 3 + readUnsignedShort(index + 1);
if (size > max) {
max = size;
}
break;
case ClassWriter.HANDLE:
size = 4;
break;
// case ClassWriter.CLASS:
// case ClassWriter.STR:
// case ClassWriter.MTYPE
default:
size = 3;
break;
}
index += size;
}
maxStringLength = max;
// the class header information starts just after the constant pool
header = index;
}
/**
* Copies the constant pool data into the given {@link ClassWriter}. Should
* be called before the {@link #accept(ClassVisitor,boolean)} method.
*
* @param classWriter the {@link ClassWriter} to copy constant pool into.
*/
void copyPool(final ClassWriter classWriter) {
char[] buf = new char[maxStringLength];
int ll = items.length;
Item[] items2 = new Item[ll];
for (int i = 1; i < ll; i++) {
int index = items[i];
int tag = b[index - 1];
Item item = new Item(i);
int nameType;
switch (tag) {
case ClassWriter.FIELD:
case ClassWriter.METH:
case ClassWriter.IMETH:
nameType = items[readUnsignedShort(index + 2)];
item.set(tag,
readClass(index, buf),
readUTF8(nameType, buf),
readUTF8(nameType + 2, buf));
break;
case ClassWriter.INT:
item.set(readInt(index));
break;
case ClassWriter.FLOAT:
item.set(Float.intBitsToFloat(readInt(index)));
break;
case ClassWriter.NAME_TYPE:
item.set(tag,
readUTF8(index, buf),
readUTF8(index + 2, buf),
null);
break;
case ClassWriter.LONG:
item.set(readLong(index));
++i;
break;
case ClassWriter.DOUBLE:
item.set(Double.longBitsToDouble(readLong(index)));
++i;
break;
case ClassWriter.UTF8: {
String s = strings[i];
if (s == null) {
index = items[i];
s = strings[i] = readUTF(index + 2,
readUnsignedShort(index),
buf);
}
item.set(tag, s, null, null);
break;
}
case ClassWriter.HANDLE: {
int fieldOrMethodRef = items[readUnsignedShort(index + 1)];
nameType = items[readUnsignedShort(fieldOrMethodRef + 2)];
item.set(ClassWriter.HANDLE_BASE + readByte(index),
readClass(fieldOrMethodRef, buf),
readUTF8(nameType, buf),
readUTF8(nameType + 2, buf));
break;
}
case ClassWriter.INDY:
if (classWriter.bootstrapMethods == null) {
copyBootstrapMethods(classWriter, items2, buf);
}
nameType = items[readUnsignedShort(index + 2)];
item.set(readUTF8(nameType, buf),
readUTF8(nameType + 2, buf),
readUnsignedShort(index));
break;
// case ClassWriter.STR:
// case ClassWriter.CLASS:
// case ClassWriter.MTYPE
default:
item.set(tag, readUTF8(index, buf), null, null);
break;
}
int index2 = item.hashCode % items2.length;
item.next = items2[index2];
items2[index2] = item;
}
int off = items[1] - 1;
classWriter.pool.putByteArray(b, off, header - off);
classWriter.items = items2;
classWriter.threshold = (int) (0.75d * ll);
classWriter.index = ll;
}
/**
* Copies the bootstrap method data into the given {@link ClassWriter}.
* Should be called before the {@link #accept(ClassVisitor,int)} method.
*
* @param classWriter
* the {@link ClassWriter} to copy bootstrap methods into.
*/
private void copyBootstrapMethods(final ClassWriter classWriter,
final Item[] items, final char[] c) {
// finds the "BootstrapMethods" attribute
int u = getAttributes();
boolean found = false;
for (int i = readUnsignedShort(u); i > 0; --i) {
String attrName = readUTF8(u + 2, c);
if ("BootstrapMethods".equals(attrName)) {
found = true;
break;
}
u += 6 + readInt(u + 4);
}
if (!found) {
return;
}
// copies the bootstrap methods in the class writer
int boostrapMethodCount = readUnsignedShort(u + 8);
for (int j = 0, v = u + 10; j < boostrapMethodCount; j++) {
int position = v - u - 10;
int hashCode = readConst(readUnsignedShort(v), c).hashCode();
for (int k = readUnsignedShort(v + 2); k > 0; --k) {
hashCode ^= readConst(readUnsignedShort(v + 4), c).hashCode();
v += 2;
}
v += 4;
Item item = new Item(j);
item.set(position, hashCode & 0x7FFFFFFF);
int index = item.hashCode % items.length;
item.next = items[index];
items[index] = item;
}
int attrSize = readInt(u + 4);
ByteVector bootstrapMethods = new ByteVector(attrSize + 62);
bootstrapMethods.putByteArray(b, u + 10, attrSize - 2);
classWriter.bootstrapMethodsCount = boostrapMethodCount;
classWriter.bootstrapMethods = bootstrapMethods;
}
/**
* Constructs a new {@link ClassReader} object.
*
* @param is an input stream from which to read the class.
* @throws IOException if a problem occurs during reading.
*/
public ClassReader(final InputStream is) throws IOException {
this(readClass(is));
}
/**
* Constructs a new {@link ClassReader} object.
*
* @param name the fully qualified name of the class to be read.
* @throws IOException if an exception occurs during reading.
*/
public ClassReader(final String name) throws IOException {
this(ClassLoader.getSystemResourceAsStream(name.replace('.', '/')
+ ".class"));
}
/**
* Reads the bytecode of a class.
*
* @param is an input stream from which to read the class.
* @return the bytecode read from the given input stream.
* @throws IOException if a problem occurs during reading.
*/
private static byte[] readClass(final InputStream is) throws IOException {
if (is == null) {
throw new IOException("Class not found");
}
byte[] b = new byte[is.available()];
int len = 0;
while (true) {
int n = is.read(b, len, b.length - len);
if (n == -1) {
if (len < b.length) {
byte[] c = new byte[len];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
return b;
}
len += n;
if (len == b.length) {
int last = is.read();
if (last < 0) {
return b;
}
byte[] c = new byte[b.length + 1000];
System.arraycopy(b, 0, c, 0, len);
c[len++] = (byte) last;
b = c;
}
}
}
// Public methods
/**
* Makes the given visitor visit the Java class of this {@link ClassReader}.
* This class is the one specified in the constructor (see
* {@link #ClassReader(byte[]) ClassReader}).
*
* @param classVisitor the visitor that must visit this class.
* @param skipDebug <tt>true</tt> if the debug information of the class
* must not be visited. In this case the
* {@link MethodVisitor#visitLocalVariable visitLocalVariable} and
* {@link MethodVisitor#visitLineNumber visitLineNumber} methods will
* not be called.
*/
public void accept(final ClassVisitor classVisitor, final boolean skipDebug)
{
accept(classVisitor, new Attribute[0], skipDebug);
}
/**
* Makes the given visitor visit the Java class of this {@link ClassReader}.
* This class is the one specified in the constructor (see
* {@link #ClassReader(byte[]) ClassReader}).
*
* @param classVisitor the visitor that must visit this class.
* @param attrs prototypes of the attributes that must be parsed during the
* visit of the class. Any attribute whose type is not equal to the
* type of one the prototypes will be ignored.
* @param skipDebug <tt>true</tt> if the debug information of the class
* must not be visited. In this case the
* {@link MethodVisitor#visitLocalVariable visitLocalVariable} and
* {@link MethodVisitor#visitLineNumber visitLineNumber} methods will
* not be called.
*/
public void accept(
final ClassVisitor classVisitor,
final Attribute[] attrs,
final boolean skipDebug)
{
byte[] b = this.b; // the bytecode array
char[] c = new char[maxStringLength]; // buffer used to read strings
int i, j, k; // loop variables
int u, v, w; // indexes in b
Attribute attr;
int access;
String name;
String desc;
String attrName;
String signature;
int anns = 0;
int ianns = 0;
int xanns = 0;
int ixanns = 0;
Attribute cattrs = null;
// visits the header
u = header; // u = u2 access_flags
access = readUnsignedShort(u);
name = readClass(u + 2, c); // name = u2 this_class
v = items[readUnsignedShort(u + 4)]; // u + 4 = u2 super_class
String superClassName = v == 0 ? null : readUTF8(v, c);
String[] implementedItfs = new String[readUnsignedShort(u + 6)];
// u + 6 = u2 interfaces_count;
w = 0;
u += 8; // u + 8 = interfaces[interfaces_count]
for (i = 0; i < implementedItfs.length; ++i) {
implementedItfs[i] = readClass(u, c);
u += 2;
}
// u = u2 fields_count
// skips fields and methods
v = u;
i = readUnsignedShort(v); // i = u2 fields_count
v += 2; // v = field_info fields[fields_count]
for (; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for (; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
i = readUnsignedShort(v); // i = u2 methods_count
v += 2; // v = method_info methods[methods_count]
for (; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for (; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
// reads the class's attributes
signature = null;
String sourceFile = null;
String sourceDebug = null;
String enclosingOwner = null;
String enclosingName = null;
String enclosingDesc = null;
i = readUnsignedShort(v); // i = u2 attributes_count
v += 2; // v = attribute_info attributes[attributes_count]
for (; i > 0; --i) {
attrName = readUTF8(v, c);
if (attrName.equals("SourceFile")) {
sourceFile = readUTF8(v + 6, c);
} else if (attrName.equals("Deprecated")) {
access |= Opcodes.ACC_DEPRECATED;
} else if (attrName.equals("Synthetic")) {
access |= Opcodes.ACC_SYNTHETIC;
} else if (attrName.equals("Annotation")) {
access |= Opcodes.ACC_ANNOTATION;
} else if (attrName.equals("Enum")) {
access |= Opcodes.ACC_ENUM;
} else if (attrName.equals("InnerClasses")) {
w = v + 6;
} else if (attrName.equals("Signature")) {
signature = readUTF8(v + 6, c);
} else if (attrName.equals("SourceDebugExtension")) {
int len = readInt(v + 2);
sourceDebug = readUTF(v + 6, len, new char[len]);
} else if (attrName.equals("EnclosingMethod")) {
enclosingOwner = readClass(v + 6, c);
int item = readUnsignedShort(v + 8);
if (item != 0) {
enclosingName = readUTF8(items[item], c);
enclosingDesc = readUTF8(items[item] + 2, c);
}
} else if (attrName.equals("RuntimeVisibleAnnotations")) {
anns = v + 6;
} else if (attrName.equals("RuntimeInvisibleAnnotations")) {
ianns = v + 6;
} else if (attrName.equals("RuntimeVisibleTypeAnnotations")) {
xanns = v + 6;
} else if (attrName.equals("RuntimeInvisibleTypeAnnotations")) {
ixanns = v + 6;
} else if (attrName.equals("BootstrapMethods")) {
bootstrapMethods = new int[readUnsignedShort(v + 6)];
for (j = 0, u = v + 8; j < bootstrapMethods.length; j++) {
bootstrapMethods[j] = u;
u += 2 + readUnsignedShort(u + 2) << 1;
}
} else {
attr = readAttribute(attrs,
attrName,
v + 6,
readInt(v + 2),
c,
-1,
null);
if (attr != null) {
attr.next = cattrs;
cattrs = attr;
}
}
v += 6 + readInt(v + 2);
}
// calls the visit method
classVisitor.visit(readInt(4),
access,
name,
signature,
superClassName,
implementedItfs);
// calls the visitSource method
if (sourceFile != null || sourceDebug != null) {
classVisitor.visitSource(sourceFile, sourceDebug);
}
// calls the visitOuterClass method
if (enclosingOwner != null) {
classVisitor.visitOuterClass(enclosingOwner,
enclosingName,
enclosingDesc);
}
// visits the class annotations
for (i = 1; i >= 0; --i) {
v = i == 0 ? ianns : anns;
if (v != 0) {
j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
desc = readUTF8(v, c);
v += 2;
v = readAnnotationValues(v,
c,
classVisitor.visitAnnotation(desc, i != 0));
}
}
}
// TODO
// visits the class extended annotations
for (i = 1; i >= 0; --i) {
v = i == 0 ? ixanns : xanns;
if (v != 0) {
j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
v = readTypeAnnotationValues(v,
c, classVisitor, i != 0);
}
}
}
// visits the class attributes
while (cattrs != null) {
attr = cattrs.next;
cattrs.next = null;
classVisitor.visitAttribute(cattrs);
cattrs = attr;
}
// class the visitInnerClass method
if (w != 0) {
i = readUnsignedShort(w);
w += 2;
for (; i > 0; --i) {
classVisitor.visitInnerClass(readUnsignedShort(w) == 0
? null
: readClass(w, c), readUnsignedShort(w + 2) == 0
? null
: readClass(w + 2, c), readUnsignedShort(w + 4) == 0
? null
: readUTF8(w + 4, c), readUnsignedShort(w + 6));
w += 8;
}
}
// visits the fields
u = header + 8 + 2 * implementedItfs.length;
i = readUnsignedShort(u); // i = u2 fields_count
u += 2; // u = field_info[fields_count]
for (; i > 0; --i) {
access = readUnsignedShort(u);
name = readUTF8(u + 2, c);
desc = readUTF8(u + 4, c);
// visits the field's attributes and looks for a ConstantValue
// attribute
int fieldValueItem = 0;
signature = null;
anns = 0;
ianns = 0;
xanns = 0;
ixanns = 0;
cattrs = null;
j = readUnsignedShort(u + 6); // j = u2 attributes_count
u += 8; // u = attributes[attributes_count]
for (; j > 0; --j) {
attrName = readUTF8(u, c);
if (attrName.equals("ConstantValue")) {
fieldValueItem = readUnsignedShort(u + 6);
} else if (attrName.equals("Synthetic")) {
access |= Opcodes.ACC_SYNTHETIC;
} else if (attrName.equals("Deprecated")) {
access |= Opcodes.ACC_DEPRECATED;
} else if (attrName.equals("Enum")) {
access |= Opcodes.ACC_ENUM;
} else if (attrName.equals("Signature")) {
signature = readUTF8(u + 6, c);
} else if (attrName.equals("RuntimeVisibleAnnotations")) {
anns = u + 6;
} else if (attrName.equals("RuntimeInvisibleAnnotations")) {
ianns = u + 6;
} else if (attrName.equals("RuntimeVisibleTypeAnnotations")) {
xanns = u + 6;
} else if (attrName.equals("RuntimeInvisibleTypeAnnotations")) {
ixanns = u + 6;
} else {
attr = readAttribute(attrs,
attrName,
u + 6,
readInt(u + 2),
c,
-1,
null);
if (attr != null) {
attr.next = cattrs;
cattrs = attr;
}
}
u += 6 + readInt(u + 2);
}
// reads the field's value, if any
Object value = (fieldValueItem == 0
? null
: readConst(fieldValueItem, c));
// visits the field
FieldVisitor fv = classVisitor.visitField(access,
name,
desc,
signature,
value);
// visits the field annotations and attributes
if (fv != null) {
for (j = 1; j >= 0; --j) {
v = j == 0 ? ianns : anns;
if (v != 0) {
k = readUnsignedShort(v);
v += 2;
for (; k > 0; --k) {
desc = readUTF8(v, c);
v += 2;
v = readAnnotationValues(v,
c,
fv.visitAnnotation(desc, j != 0));
}
}
}
//TODO
// now visit the extended annotations
if(xanns != 0) {
v = xanns;
k = readUnsignedShort(v);
v += 2;
for(; k > 0; --k) {
v = readTypeAnnotationValues(v,
c, fv, true);
}
}
if(ixanns != 0) {
v = ixanns;
k = readUnsignedShort(v);
v += 2;
for(; k > 0; --k) {
v = readTypeAnnotationValues(v,
c, fv, false);
}
}
while (cattrs != null) {
attr = cattrs.next;
cattrs.next = null;
fv.visitAttribute(cattrs);
cattrs = attr;
}
fv.visitEnd();
}
}
// visits the methods
i = readUnsignedShort(u);
u += 2;
for (; i > 0; --i) {
int u0 = u + 6;
access = readUnsignedShort(u);
name = readUTF8(u + 2, c);
desc = readUTF8(u + 4, c);
signature = null;
anns = 0;
ianns = 0;
//jaime
xanns = 0;
ixanns = 0;
// end jaime
int dann = 0;
int mpanns = 0;
int impanns = 0;
cattrs = null;
v = 0;
w = 0;
// looks for Code and Exceptions attributes
j = readUnsignedShort(u + 6);
u += 8;
for (; j > 0; --j) {
attrName = readUTF8(u, c);
u += 2;
int attrSize = readInt(u);
u += 4;
if (attrName.equals("Code")) {
v = u;
} else if (attrName.equals("Exceptions")) {
w = u;
} else if (attrName.equals("Synthetic")) {
access |= Opcodes.ACC_SYNTHETIC;
} else if (attrName.equals("Varargs")) {
access |= Opcodes.ACC_VARARGS;
} else if (attrName.equals("Bridge")) {
access |= Opcodes.ACC_BRIDGE;
} else if (attrName.equals("Deprecated")) {
access |= Opcodes.ACC_DEPRECATED;
} else if (attrName.equals("Signature")) {
signature = readUTF8(u, c);
} else if (attrName.equals("AnnotationDefault")) {
dann = u;
} else if (attrName.equals("RuntimeVisibleAnnotations")) {
anns = u;
} else if (attrName.equals("RuntimeInvisibleAnnotations")) {
ianns = u;
} else if (attrName.equals("RuntimeVisibleTypeAnnotations")) {
xanns = u;
} else if (attrName.equals("RuntimeInvisibleTypeAnnotations")) {
ixanns = u;
} else if (attrName.equals("RuntimeVisibleParameterAnnotations")) {
mpanns = u;
} else if (attrName.equals("RuntimeInvisibleParameterAnnotations")) {
impanns = u;
} else {
attr = readAttribute(attrs,
attrName,
u,
attrSize,
c,
-1,
null);
if (attr != null) {
attr.next = cattrs;
cattrs = attr;
}
}
u += attrSize;
}
// reads declared exceptions
String[] exceptions;
if (w == 0) {
exceptions = null;
} else {
exceptions = new String[readUnsignedShort(w)];
w += 2;
for (j = 0; j < exceptions.length; ++j) {
exceptions[j] = readClass(w, c);
w += 2;
}
}
// visits the method's code, if any
MethodVisitor mv = classVisitor.visitMethod(access,
name,
desc,
signature,
exceptions);
if (mv != null) {
/*
* if the returned MethodVisitor is in fact a MethodWriter, it
* means there is no method adapter between the reader and the
* writer. If, in addition, the writer's constant pool was
* copied from this reader (mw.cw.cr == this), and the signature
* and exceptions of the method have not been changed, then it
* is possible to skip all visit events and just copy the
* original code of the method to the writer (the access, name
* and descriptor can have been changed, this is not important
* since they are not copied as is from the reader).
*/
if (mv instanceof MethodWriter) {
MethodWriter mw = (MethodWriter) mv;
if (mw.cw.cr == this) {
if (signature == mw.signature) {
boolean sameExceptions = false;
if (exceptions == null) {
sameExceptions = mw.exceptionCount == 0;
} else {
if (exceptions.length == mw.exceptionCount) {
sameExceptions = true;
for (j = exceptions.length - 1; j >= 0; --j)
{
w -= 2;
if (mw.exceptions[j] != readUnsignedShort(w))
{
sameExceptions = false;
break;
}
}
}
}
if (sameExceptions) {
/*
* we do not copy directly the code into
* MethodWriter to save a byte array copy
* operation. The real copy will be done in
* ClassWriter.toByteArray().
*/
mw.classReaderOffset = u0;
mw.classReaderLength = u - u0;
continue;
}
}
}
}
if (dann != 0) {
AnnotationVisitor dv = mv.visitAnnotationDefault();
readAnnotationValue(dann, c, null, dv);
dv.visitEnd();
}
for (j = 1; j >= 0; --j) {
w = j == 0 ? ianns : anns;
if (w != 0) {
k = readUnsignedShort(w);
w += 2;
for (; k > 0; --k) {
desc = readUTF8(w, c);
w += 2;
w = readAnnotationValues(w,
c,
mv.visitAnnotation(desc, j != 0));
}
}
}
// now visit the method extended annotations
for (j = 1; j >= 0; --j) {
w = j == 0 ? ixanns : xanns;
if (w != 0) {
k = readUnsignedShort(w);
w += 2;
for (; k > 0; --k) {
w = readTypeAnnotationValuesBodies(w,
c, mv, j != 0);
}
}
}
if (mpanns != 0) {
readParameterAnnotations(mpanns, c, true, mv);
}
if (impanns != 0) {
readParameterAnnotations(impanns, c, false, mv);
}
while (cattrs != null) {
attr = cattrs.next;
cattrs.next = null;
mv.visitAttribute(cattrs);
cattrs = attr;
}
}
if (mv != null && v != 0) {
int maxStack = readUnsignedShort(v);
int maxLocals = readUnsignedShort(v + 2);
int codeLength = readInt(v + 4);
v += 8;
int codeStart = v;
int codeEnd = v + codeLength;
mv.visitCode();
// 1st phase: finds the labels
int label;
Label[] labels = new Label[codeLength + 1];
while (v < codeEnd) {
int opcode = b[v] & 0xFF;
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
case ClassWriter.IMPLVAR_INSN:
v += 1;
break;
case ClassWriter.LABEL_INSN:
label = v - codeStart + readShort(v + 1);
if (labels[label] == null) {
labels[label] = new Label();
}
v += 3;
break;
case ClassWriter.LABELW_INSN:
label = v - codeStart + readInt(v + 1);
if (labels[label] == null) {
labels[label] = new Label();
}
v += 5;
break;
case ClassWriter.WIDE_INSN:
opcode = b[v + 1] & 0xFF;
if (opcode == Opcodes.IINC) {
v += 6;
} else {
v += 4;
}
break;
case ClassWriter.TABL_INSN:
// skips 0 to 3 padding bytes
w = v - codeStart;
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v);
v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
j = readInt(v);
v += 4;
j = readInt(v) - j + 1;
v += 4;
for (; j > 0; --j) {
label = w + readInt(v);
v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
}
break;
case ClassWriter.LOOK_INSN:
// skips 0 to 3 padding bytes
w = v - codeStart;
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v);
v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
j = readInt(v);
v += 4;
for (; j > 0; --j) {
v += 4; // skips key
label = w + readInt(v);
v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
}
break;
case ClassWriter.VAR_INSN:
case ClassWriter.SBYTE_INSN:
case ClassWriter.LDC_INSN:
v += 2;
break;
case ClassWriter.SHORT_INSN:
case ClassWriter.LDCW_INSN:
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.TYPE_INSN:
case ClassWriter.IINC_INSN:
v += 3;
break;
case ClassWriter.ITFMETH_INSN:
case ClassWriter.INDY:
v += 5;
break;
// case MANA_INSN:
default:
v += 4;
break;
}
}
// parses the try catch entries
j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
label = readUnsignedShort(v);
Label start = labels[label];
if (start == null) {
labels[label] = start = new Label();
}
label = readUnsignedShort(v + 2);
Label end = labels[label];
if (end == null) {
labels[label] = end = new Label();
}
label = readUnsignedShort(v + 4);
Label handler = labels[label];
if (handler == null) {
labels[label] = handler = new Label();
}
int type = readUnsignedShort(v + 6);
if (type == 0) {
mv.visitTryCatchBlock(start, end, handler, null);
} else {
mv.visitTryCatchBlock(start,
end,
handler,
readUTF8(items[type], c));
}
v += 8;
}
// parses the local variable, line number tables, and code
// attributes
int varTable = 0;
int varTypeTable = 0;
cattrs = null;
j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
attrName = readUTF8(v, c);
if (attrName.equals("LocalVariableTable")) {
if (!skipDebug) {
varTable = v + 6;
k = readUnsignedShort(v + 6);
w = v + 8;
for (; k > 0; --k) {
label = readUnsignedShort(w);
if (labels[label] == null) {
labels[label] = new Label();
}
label += readUnsignedShort(w + 2);
if (labels[label] == null) {
labels[label] = new Label();
}
w += 10;
}
}
} else if (attrName.equals("LocalVariableTypeTable")) {
varTypeTable = v + 6;
} else if (attrName.equals("LineNumberTable")) {
if (!skipDebug) {
k = readUnsignedShort(v + 6);
w = v + 8;
for (; k > 0; --k) {
label = readUnsignedShort(w);
if (labels[label] == null) {
labels[label] = new Label();
}
labels[label].line = readUnsignedShort(w + 2);
w += 4;
}
}
} else if (attrName.equals("RuntimeInvisibleTypeAnnotations")) {
k = readUnsignedShort(v + 6);
w = v + 8;
for (; k > 0; --k) {
w = readTypeAnnotationValues(w,
c, mv, false);
}
} else if (attrName.equals("RuntimeVisibleTypeAnnotations")) {
k = readUnsignedShort(v + 6);
w = v + 8;
for (; k > 0; --k) {
w = readTypeAnnotationValues(w,
c, mv, true);
}
} else {
for (k = 0; k < attrs.length; ++k) {
if (attrs[k].type.equals(attrName)) {
attr = attrs[k].read(this,
v + 6,
readInt(v + 2),
c,
codeStart - 8,
labels);
if (attr != null) {
attr.next = cattrs;
cattrs = attr;
}
}
}
}
v += 6 + readInt(v + 2);
}
// 2nd phase: visits each instruction
v = codeStart;
PrecompiledMethodVisitor pmv =
(mv instanceof PrecompiledMethodVisitor)
? (PrecompiledMethodVisitor) mv : null;
Label l;
while (v < codeEnd) {
w = v - codeStart;
if (pmv != null)
pmv.visitCurrentPosition(w);
l = labels[w];
if (l != null) {
mv.visitLabel(l);
if (!skipDebug && l.line > 0) {
mv.visitLineNumber(l.line, l);
}
}
int opcode = b[v] & 0xFF;
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
mv.visitInsn(opcode);
v += 1;
break;
case ClassWriter.IMPLVAR_INSN:
if (opcode > Opcodes.ISTORE) {
opcode -= 59; // ISTORE_0
mv.visitVarInsn(Opcodes.ISTORE + (opcode >> 2),
opcode & 0x3);
} else {
opcode -= 26; // ILOAD_0
mv.visitVarInsn(Opcodes.ILOAD + (opcode >> 2),
opcode & 0x3);
}
v += 1;
break;
case ClassWriter.LABEL_INSN:
mv.visitJumpInsn(opcode, labels[w
+ readShort(v + 1)]);
v += 3;
break;
case ClassWriter.LABELW_INSN:
mv.visitJumpInsn(opcode - 33, labels[w
+ readInt(v + 1)]);
v += 5;
break;
case ClassWriter.WIDE_INSN:
opcode = b[v + 1] & 0xFF;
if (opcode == Opcodes.IINC) {
mv.visitIincInsn(readUnsignedShort(v + 2),
readShort(v + 4));
v += 6;
} else {
mv.visitVarInsn(opcode,
readUnsignedShort(v + 2));
v += 4;
}
break;
case ClassWriter.TABL_INSN:
// skips 0 to 3 padding bytes
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v);
v += 4;
int min = readInt(v);
v += 4;
int max = readInt(v);
v += 4;
Label[] table = new Label[max - min + 1];
for (j = 0; j < table.length; ++j) {
table[j] = labels[w + readInt(v)];
v += 4;
}
mv.visitTableSwitchInsn(min,
max,
labels[label],
table);
break;
case ClassWriter.LOOK_INSN:
// skips 0 to 3 padding bytes
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v);
v += 4;
j = readInt(v);
v += 4;
int[] keys = new int[j];
Label[] values = new Label[j];
for (j = 0; j < keys.length; ++j) {
keys[j] = readInt(v);
v += 4;
values[j] = labels[w + readInt(v)];
v += 4;
}
mv.visitLookupSwitchInsn(labels[label],
keys,
values);
break;
case ClassWriter.VAR_INSN:
mv.visitVarInsn(opcode, b[v + 1] & 0xFF);
v += 2;
break;
case ClassWriter.SBYTE_INSN:
mv.visitIntInsn(opcode, b[v + 1]);
v += 2;
break;
case ClassWriter.SHORT_INSN:
mv.visitIntInsn(opcode, readShort(v + 1));
v += 3;
break;
case ClassWriter.LDC_INSN:
mv.visitLdcInsn(readConst(b[v + 1] & 0xFF, c));
v += 2;
break;
case ClassWriter.LDCW_INSN:
mv.visitLdcInsn(readConst(readUnsignedShort(v + 1),
c));
v += 3;
break;
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.ITFMETH_INSN:
int cpIndex = items[readUnsignedShort(v + 1)];
String iowner = readClass(cpIndex, c);
cpIndex = items[readUnsignedShort(cpIndex + 2)];
String iname = readUTF8(cpIndex, c);
String idesc = readUTF8(cpIndex + 2, c);
if (opcode < Opcodes.INVOKEVIRTUAL) {
mv.visitFieldInsn(opcode, iowner, iname, idesc);
} else {
mv.visitMethodInsn(opcode, iowner, iname, idesc);
}
if (opcode == Opcodes.INVOKEINTERFACE) {
v += 5;
} else {
v += 3;
}
break;
case ClassWriter.TYPE_INSN:
mv.visitTypeInsn(opcode, readClass(v + 1, c));
v += 3;
break;
case ClassWriter.IINC_INSN:
mv.visitIincInsn(b[v + 1] & 0xFF, b[v + 2]);
v += 3;
break;
case ClassWriter.INDY:
cpIndex = items[readUnsignedShort(v + 1)];
int bsmIndex = bootstrapMethods[readUnsignedShort(cpIndex)];
Handle bsm = (Handle) readConst(readUnsignedShort(bsmIndex), c);
int bsmArgCount = readUnsignedShort(bsmIndex + 2);
Object[] bsmArgs = new Object[bsmArgCount];
bsmIndex += 4;
for (j = 0; j < bsmArgCount; j++) {
bsmArgs[j] = readConst(readUnsignedShort(bsmIndex), c);
bsmIndex += 2;
}
cpIndex = items[readUnsignedShort(cpIndex + 2)];
iname = readUTF8(cpIndex, c);
idesc = readUTF8(cpIndex + 2, c);
mv.visitInvokeDynamicInsn(iname, idesc, bsm, bsmArgs);
v += 5;
break;
// case MANA_INSN:
default:
mv.visitMultiANewArrayInsn(readClass(v + 1, c),
b[v + 3] & 0xFF);
v += 4;
break;
}
}
l = labels[codeEnd - codeStart];
if (l != null) {
if (pmv != null)
pmv.visitCurrentPosition(codeEnd - codeStart);
mv.visitLabel(l);
}
// visits the local variable tables
if (!skipDebug && varTable != 0) {
int[] typeTable = null;
if (varTypeTable != 0) {
w = varTypeTable;
k = readUnsignedShort(w) * 3;
w += 2;
typeTable = new int[k];
while (k > 0) {
typeTable[--k] = w + 6; // signature
typeTable[--k] = readUnsignedShort(w + 8); // index
typeTable[--k] = readUnsignedShort(w); // start
w += 10;
}
}
w = varTable;
k = readUnsignedShort(w);
w += 2;
for (; k > 0; --k) {
int start = readUnsignedShort(w);
int length = readUnsignedShort(w + 2);
int index = readUnsignedShort(w + 8);
String vsignature = null;
if (typeTable != null) {
for (int a = 0; a < typeTable.length; a += 3) {
if (typeTable[a] == start
&& typeTable[a + 1] == index)
{
vsignature = readUTF8(typeTable[a + 2], c);
break;
}
}
}
mv.visitLocalVariable(readUTF8(w + 4, c),
readUTF8(w + 6, c),
vsignature,
labels[start],
labels[start + length],
index);
w += 10;
}
}
// visits the other attributes
while (cattrs != null) {
attr = cattrs.next;
cattrs.next = null;
mv.visitAttribute(cattrs);
cattrs = attr;
}
// visits the max stack and max locals values
mv.visitMaxs(maxStack, maxLocals);
}
if (mv != null) {
mv.visitEnd();
}
}
// visits the end of the class
classVisitor.visitEnd();
}
/**
* Reads parameter annotations and makes the given visitor visit them.
*
* @param v start offset in {@link #b b} of the annotations to be read.
* @param buf buffer to be used to call {@link #readUTF8 readUTF8},
* {@link #readClass(int,char[]) readClass} or
* {@link #readConst readConst}.
* @param visible <tt>true</tt> if the annotations to be read are visible
* at runtime.
* @param mv the visitor that must visit the annotations.
*/
private void readParameterAnnotations(
int v,
final char[] buf,
final boolean visible,
final MethodVisitor mv)
{
int n = b[v++] & 0xFF;
for (int i = 0; i < n; ++i) {
int j = readUnsignedShort(v);
v += 2;
for (; j > 0; --j) {
String desc = readUTF8(v, buf);
v += 2;
AnnotationVisitor av = mv.visitParameterAnnotation(i,
desc,
visible);
v = readAnnotationValues(v, buf, av);
}
}
}
/**
* Reads the values of an annotation and makes the given visitor visit them.
*
* @param v the start offset in {@link #b b} of the values to be read
* (including the unsigned short that gives the number of values).
* @param buf buffer to be used to call {@link #readUTF8 readUTF8},
* {@link #readClass(int,char[]) readClass} or
* {@link #readConst readConst}.
* @param av the visitor that must visit the values.
* @return the end offset of the annotations values.
*/
private int readAnnotationValues(
int v,
final char[] buf,
final AnnotationVisitor av)
{
int i = readUnsignedShort(v);
v += 2;
for (; i > 0; --i) {
String name = readUTF8(v, buf);
v += 2;
v = readAnnotationValue(v, buf, name, av);
}
av.visitEnd();
return v;
}
/**
* Reads the values and reference info of an extended annotation
* and makes the given visitor visit them. Should not be used for reading
* methods' extended annotations due to JDK-8198945; use
* {@link #readTypeAnnotationValuesBodies readTypeAnnotationValuesBodies}
* instead.
*
* @param v the start offset in {@link #b b} of the values to be read
* (including the unsigned short that gives the number of values).
* @param buf buffer to be used to call {@link #readUTF8 readUTF8},
* {@link #readClass(int,char[]) readClass} or
* {@link #readConst readConst}.
* @param mv the visitor to generate the visitor that must visit the values.
* @param visible {@code true} if the annotation is visible at runtime.
* @return the end offset of the annotations values.
* @author jaimeq
*/
private int readTypeAnnotationValues(
int v,
final char[] buf,
final MemberVisitor mv,
final boolean visible)
{
return readTypeAnnotationValuesHelper(v, buf, mv, visible, false);
}
/**
* This is a method for the work-around related to the bug JDK-8198945.
* All type annotations should be read using the original method
* except methods' extended annotations for which this method should be used.
*
* @param v the start offset in {@link #b b} of the values to be read
* (including the unsigned short that gives the number of values).
* @param buf buffer to be used to call {@link #readUTF8 readUTF8},
* {@link #readClass(int,char[]) readClass} or
* {@link #readConst readConst}.
* @param mv the visitor to generate the visitor that must visit the values.
* @param visible {@code true} if the annotation is visible at runtime.
* @return the end offset of the annotations values.
*/
private int readTypeAnnotationValuesBodies(
int v,
final char[] buf,
final MemberVisitor mv,
final boolean visible)
{
return readTypeAnnotationValuesHelper(v, buf, mv, visible, true);
}
/**
* Reads the values and reference info of an extended annotation
* and makes the given visitor visit them.
*
* @param v the start offset in {@link #b b} of the values to be read
* (including the unsigned short that gives the number of values).
* @param buf buffer to be used to call {@link #readUTF8 readUTF8},
* {@link #readClass(int,char[]) readClass} or
* {@link #readConst readConst}.
* @param mv the visitor to generate the visitor that must visit the values.
* @param visible {@code true} if the annotation is visible at runtime.
* @param isMethodBody {@code true} if this method is
* called to read a method's extended annotations; needs to be
* {@code false} for all other cases.
* @return the end offset of the annotations values.
* @author jaimeq
*/
private int readTypeAnnotationValuesHelper(
int v,
final char[] buf,
final MemberVisitor mv,
final boolean visible,
final boolean isMethodBody)
{
// first handle
// u1 target_type
// } reference_info
int target_type_value = readByte(v);
v += 1;
Integer offset = null;
Integer location_length = null;
List<TypePathEntry> locations = new ArrayList<TypePathEntry>();
Integer start_pc = null;
Integer length = null;
Integer index = null;
Integer param_index = null;
Integer bound_index = null;
Integer type_index = null;
Integer exception_index = null;
Integer table_length = null;
TargetType target_type = TargetType.fromTargetTypeValue(target_type_value);
switch(target_type) {
// type test (instanceof)
// object creation
// constructor/method reference receiver
// u2 offset;
// } reference_info;
case INSTANCEOF:
case NEW:
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
offset = readUnsignedShort(v);
v += 2;
break;
// method receiver
// } reference_info;
case METHOD_RECEIVER:
break;
// local variable
// u2 table_length;
// u2 start_pc;
// u2 length;
// u2 index;
// } reference_info;
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
table_length = readUnsignedShort(v);
v += 2;
assert table_length == 1; // FIXME
start_pc = readUnsignedShort(v);
v += 2;
length = readUnsignedShort(v);
v += 2;
index = readUnsignedShort(v);
v += 2;
break;
// method return type
// } reference_info;
case METHOD_RETURN:
break;
// method parameter
// u1 param;
// } reference_info;
case METHOD_FORMAL_PARAMETER:
param_index = readByte(v);
v++;
break;
// field
// } reference_info;
case FIELD:
break;
// class type parameter bound
// method type parameter bound
// u1 param_index;
// u1 bound_index;
// } reference_info;
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
param_index = readByte(v);
v++;
bound_index = readByte(v);
v++;
break;
// class extends/implements
// exception type in throws
// u1 type_index;
// } reference_info;
case CLASS_EXTENDS:
type_index = readUnsignedShort(v);
if (type_index == 0xFFFF) type_index = -1;
v += 2;
break;
case THROWS:
type_index = readUnsignedShort(v);
v += 2;
break;
case EXCEPTION_PARAMETER:
exception_index = readUnsignedShort(v);
v += 2;
break;
// typecast
// type argument in constructor call
// type argument in method call
// type argument in constructor reference
// type argument in method reference
// u2 offset;
// u1 type_index;
// } reference_info;
case CAST:
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
offset = readUnsignedShort(v);
v += 2;
type_index = readByte(v);
v++;
break;
// method type parameter
// u1 param_index;
// } reference_info;
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
param_index = readByte(v);
v++;
break;
default: throw new RuntimeException(
"Unrecognized target type: " + target_type);
}
// now read in the location information
{
location_length = readByte(v);
v += 1;
for (int m = 0; m < location_length; m++) {
int loctag = readByte(v);
int locarg = readByte(v + 1);
v += TypePathEntry.bytesPerEntry;
locations.add(TypePathEntry.fromBinary(loctag, locarg));
}
}
String desc = readUTF8(v, buf);
v += 2;
TypeAnnotationVisitor xav = mv.visitTypeAnnotation(desc, visible, false);
xav.visitXTargetType(target_type_value);
if (start_pc != null) {
xav.visitXStartPc(start_pc);
}
if (length != null) {
xav.visitXLength(length);
}
if (index != null) {
xav.visitXIndex(index);
}
if (offset != null) {
xav.visitXOffset(offset);
}
if (type_index != null) {
xav.visitXTypeIndex(type_index);
}
if (param_index != null) {
xav.visitXParamIndex(param_index);
}
if (bound_index != null) {
xav.visitXBoundIndex(bound_index);
}
if (exception_index != null) {
xav.visitXExceptionIndex(exception_index);
}
if (location_length != null) {
xav.visitXLocationLength(location_length);
}
for (TypePathEntry location : locations) {
xav.visitXLocation(location);
}
// Visit the annotation name and save space for the values count.
xav.visitXNameAndArgsSize();
// then read annotation values
int i = readUnsignedShort(v);
v += 2;
for (; i > 0; --i) {
String name = readUTF8(v, buf);
v += 2;
// can use the same method as for declaration annotations because
// the first part of an extended annotation matches the normal
// annotations
v = readAnnotationValue(v, buf, name, xav);
}
// Work around
// which has only been fixed in JDK 12, by not running the
// visitor if an invalid CLASS_EXTENDS is found in a method body.
// A similar workaround is located at
// https://github.com/eisop/checker-framework/blob/abdb77758e6eb2dcb9dc569ff9f34341dda8b776/framework/src/main/java/org/checkerframework/framework/util/element/MethodApplier.java#L81
// which explains why it is TargetType.CLASS_EXTENDS.
if (!(isMethodBody && target_type == TargetType.CLASS_EXTENDS)) {
xav.visitEnd();
}
return v;
}
/**
* Reads a value of an annotation and makes the given visitor visit it.
*
* @param v the start offset in {@link #b b} of the value to be read (<i>not
* including the value name constant pool index</i>).
* @param buf buffer to be used to call {@link #readUTF8 readUTF8},
* {@link #readClass(int,char[]) readClass} or
* {@link #readConst readConst}.
* @param name the name of the value to be read.
* @param av the visitor that must visit the value.
* @return the end offset of the annotation value.
*/
private int readAnnotationValue(
int v,
final char[] buf,
final String name,
final AnnotationVisitor av)
{
int i;
switch (readByte(v++)) {
case 'I': // pointer to CONSTANT_Integer
case 'J': // pointer to CONSTANT_Long
case 'F': // pointer to CONSTANT_Float
case 'D': // pointer to CONSTANT_Double
av.visit(name, readConst(readUnsignedShort(v), buf));
v += 2;
break;
case 'B': // pointer to CONSTANT_Byte
av.visit(name,
new Byte((byte) readInt(items[readUnsignedShort(v)])));
v += 2;
break;
case 'Z': // pointer to CONSTANT_Boolean
boolean b = readInt(items[readUnsignedShort(v)]) == 0;
av.visit(name, b ? Boolean.FALSE : Boolean.TRUE);
v += 2;
break;
case 'S': // pointer to CONSTANT_Short
av.visit(name,
new Short((short) readInt(items[readUnsignedShort(v)])));
v += 2;
break;
case 'C': // pointer to CONSTANT_Char
av.visit(name,
new Character((char) readInt(items[readUnsignedShort(v)])));
v += 2;
break;
case 's': // pointer to CONSTANT_Utf8
av.visit(name, readUTF8(v, buf));
v += 2;
break;
case 'e': // enum_const_value
av.visitEnum(name, readUTF8(v, buf), readUTF8(v + 2, buf));
v += 4;
break;
case 'c': // class_info
av.visit(name, Type.getType(readUTF8(v, buf)));
v += 2;
break;
case '@': // annotation_value
String desc = readUTF8(v, buf);
v += 2;
v = readAnnotationValues(v, buf, av.visitAnnotation(name, desc));
break;
case '[': // array_value
int size = readUnsignedShort(v);
v += 2;
if (size == 0) {
av.visitArray(name).visitEnd();
return v;
}
switch (readByte(v++)) {
case 'B':
byte[] bv = new byte[size];
for (i = 0; i < size; i++) {
bv[i] = (byte) readInt(items[readUnsignedShort(v)]);
v += 3;
}
av.visit(name, bv);
--v;
break;
case 'Z':
boolean[] zv = new boolean[size];
for (i = 0; i < size; i++) {
zv[i] = readInt(items[readUnsignedShort(v)]) != 0;
v += 3;
}
av.visit(name, zv);
--v;
break;
case 'S':
short[] sv = new short[size];
for (i = 0; i < size; i++) {
sv[i] = (short) readInt(items[readUnsignedShort(v)]);
v += 3;
}
av.visit(name, sv);
--v;
break;
case 'C':
char[] cv = new char[size];
for (i = 0; i < size; i++) {
cv[i] = (char) readInt(items[readUnsignedShort(v)]);
v += 3;
}
av.visit(name, cv);
--v;
break;
case 'I':
int[] iv = new int[size];
for (i = 0; i < size; i++) {
iv[i] = readInt(items[readUnsignedShort(v)]);
v += 3;
}
av.visit(name, iv);
--v;
break;
case 'J':
long[] lv = new long[size];
for (i = 0; i < size; i++) {
lv[i] = readLong(items[readUnsignedShort(v)]);
v += 3;
}
av.visit(name, lv);
--v;
break;
case 'F':
float[] fv = new float[size];
for (i = 0; i < size; i++) {
fv[i] = Float.intBitsToFloat(readInt(items[readUnsignedShort(v)]));
v += 3;
}
av.visit(name, fv);
--v;
break;
case 'D':
double[] dv = new double[size];
for (i = 0; i < size; i++) {
dv[i] = Double.longBitsToDouble(readLong(items[readUnsignedShort(v)]));
v += 3;
}
av.visit(name, dv);
--v;
break;
default:
v
AnnotationVisitor aav = av.visitArray(name);
for (i = size; i > 0; --i) {
v = readAnnotationValue(v, buf, null, aav);
}
aav.visitEnd();
}
}
return v;
}
/**
* Returns the start index of the attribute_info structure of this class.
*
* @return the start index of the attribute_info structure of this class.
*/
private int getAttributes() {
// skips the header
int u = header + 8 + readUnsignedShort(header + 6) * 2;
// skips fields and methods
for (int i = readUnsignedShort(u); i > 0; --i) {
for (int j = readUnsignedShort(u + 8); j > 0; --j) {
u += 6 + readInt(u + 12);
}
u += 8;
}
u += 2;
for (int i = readUnsignedShort(u); i > 0; --i) {
for (int j = readUnsignedShort(u + 8); j > 0; --j) {
u += 6 + readInt(u + 12);
}
u += 8;
}
// the attribute_info structure starts just after the methods
return u + 2;
}
/**
* Reads an attribute in {@link #b b}.
*
* @param attrs prototypes of the attributes that must be parsed during the
* visit of the class. Any attribute whose type is not equal to the
* type of one the prototypes is ignored (i.e. an empty
* {@link Attribute} instance is returned).
* @param type the type of the attribute.
* @param off index of the first byte of the attribute's content in
* {@link #b b}. The 6 attribute header bytes, containing the type
* and the length of the attribute, are not taken into account here
* (they have already been read).
* @param len the length of the attribute's content.
* @param buf buffer to be used to call {@link #readUTF8 readUTF8},
* {@link #readClass(int,char[]) readClass} or
* {@link #readConst readConst}.
* @param codeOff index of the first byte of code's attribute content in
* {@link #b b}, or -1 if the attribute to be read is not a code
* attribute. The 6 attribute header bytes, containing the type and
* the length of the attribute, are not taken into account here.
* @param labels the labels of the method's code, or <tt>null</tt> if the
* attribute to be read is not a code attribute.
* @return the attribute that has been read, or <tt>null</tt> to skip this
* attribute.
*/
private Attribute readAttribute(
final Attribute[] attrs,
final String type,
final int off,
final int len,
final char[] buf,
final int codeOff,
final Label[] labels)
{
for (int i = 0; i < attrs.length; ++i) {
if (attrs[i].type.equals(type)) {
return attrs[i].read(this, off, len, buf, codeOff, labels);
}
}
return new Attribute(type).read(this, off, len, null, -1, null);
}
// Utility methods: low level parsing
/**
* Returns the start index of the constant pool item in {@link #b b}, plus
* one. <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param item the index a constant pool item.
* @return the start index of the constant pool item in {@link #b b}, plus
* one.
*/
public int getItem(final int item) {
return items[item];
}
/**
* Reads a byte value in {@link #b b}. <i>This method is intended for
* {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readByte(final int index) {
return b[index] & 0xFF;
}
/**
* Reads an unsigned short value in {@link #b b}. <i>This method is
* intended for {@link Attribute} sub classes, and is normally not needed by
* class generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readUnsignedShort(final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF);
}
/**
* Reads a signed short value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public short readShort(final int index) {
byte[] b = this.b;
return (short) (((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF));
}
/**
* Reads a signed int value in {@link #b b}. <i>This method is intended for
* {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readInt(final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16)
| ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF);
}
/**
* Reads a signed long value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public long readLong(final int index) {
long l1 = readInt(index);
long l0 = readInt(index + 4) & 0xFFFFFFFFL;
return (l1 << 32) | l0;
}
/**
* Reads an UTF8 string constant pool item in {@link #b b}. <i>This method
* is intended for {@link Attribute} sub classes, and is normally not needed
* by class generators or adapters.</i>
*
* @param index the start index of an unsigned short value in {@link #b b},
* whose value is the index of an UTF8 constant pool item.
* @param buf buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified UTF8 item.
*/
public String readUTF8(int index, final char[] buf) {
int item = readUnsignedShort(index);
String s = strings[item];
if (s != null) {
return s;
}
index = items[item];
return strings[item] = readUTF(index + 2, readUnsignedShort(index), buf);
}
/**
* Reads UTF8 string in {@link #b b}.
*
* @param index start offset of the UTF8 string to be read.
* @param utfLen length of the UTF8 string to be read.
* @param buf buffer to be used to read the string. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified UTF8 string.
*/
private String readUTF(int index, int utfLen, char[] buf) {
int endIndex = index + utfLen;
byte[] b = this.b;
int strLen = 0;
int c, d, e;
while (index < endIndex) {
c = b[index++] & 0xFF;
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
buf[strLen++] = (char) c;
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
d = b[index++];
buf[strLen++] = (char) (((c & 0x1F) << 6) | (d & 0x3F));
break;
default:
// 1110 xxxx 10xx xxxx 10xx xxxx
d = b[index++];
e = b[index++];
buf[strLen++] = (char) (((c & 0x0F) << 12)
| ((d & 0x3F) << 6) | (e & 0x3F));
break;
}
}
return new String(buf, 0, strLen);
}
/**
* Reads a class constant pool item in {@link #b b}. <i>This method is
* intended for {@link Attribute} sub classes, and is normally not needed by
* class generators or adapters.</i>
*
* @param index the start index of an unsigned short value in {@link #b b},
* whose value is the index of a class constant pool item.
* @param buf buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified class item.
*/
public String readClass(final int index, final char[] buf) {
// computes the start index of the CONSTANT_Class item in b
// and reads the CONSTANT_Utf8 item designated by
// the first two bytes of this CONSTANT_Class item
return readUTF8(items[readUnsignedShort(index)], buf);
}
/**
* Reads a numeric or string constant pool item in {@link #b b}. <i>This
* method is intended for {@link Attribute} sub classes, and is normally not
* needed by class generators or adapters.</i>
*
* @param item the index of a constant pool item.
* @param buf buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the {@link Integer}, {@link Float}, {@link Long},
* {@link Double}, {@link String} or {@link Type} corresponding to
* the given constant pool item.
*/
public Object readConst(final int item, final char[] buf) {
int index = items[item];
switch (b[index - 1]) {
case ClassWriter.INT:
return new Integer(readInt(index));
case ClassWriter.FLOAT:
return new Float(Float.intBitsToFloat(readInt(index)));
case ClassWriter.LONG:
return new Long(readLong(index));
case ClassWriter.DOUBLE:
return new Double(Double.longBitsToDouble(readLong(index)));
case ClassWriter.CLASS:
String s = readUTF8(index, buf);
return Type.getType(s.charAt(0) == '[' ? s : "L" + s + ";");
case ClassWriter.STR:
return readUTF8(index, buf);
case ClassWriter.MTYPE:
return Type.getMethodType(readUTF8(index, buf));
default: // case ClassWriter.HANDLE_BASE + [1..9]:
int tag = readByte(index);
int[] items = this.items;
int cpIndex = items[readUnsignedShort(index + 1)];
String owner = readClass(cpIndex, buf);
cpIndex = items[readUnsignedShort(cpIndex + 2)];
String name = readUTF8(cpIndex, buf);
String desc = readUTF8(cpIndex + 2, buf);
return new Handle(tag, owner, name, desc);
}
}
}
|
package com.krishagni.catissueplus.rest.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
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.multipart.MultipartFile;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenInfo;
import com.krishagni.catissueplus.core.biospecimen.repository.SpecimenListCriteria;
import com.krishagni.catissueplus.core.biospecimen.services.MobileAppService;
import com.krishagni.catissueplus.core.biospecimen.services.impl.MobileAppServiceImpl;
import com.krishagni.catissueplus.core.common.events.MobileUploadJobDetail;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import com.krishagni.catissueplus.core.common.repository.MobileUploadJobsListCriteria;
import com.krishagni.catissueplus.core.common.util.ConfigUtil;
import com.krishagni.catissueplus.core.common.util.Utility;
import com.krishagni.catissueplus.core.de.events.FormDataDetail;
import edu.common.dynamicextensions.domain.nui.Container;
import edu.common.dynamicextensions.napi.FormData;
import edu.common.dynamicextensions.nutility.ContainerJsonSerializer;
import edu.common.dynamicextensions.nutility.ContainerSerializer;
import edu.common.dynamicextensions.nutility.IoUtil;
@Controller
@RequestMapping("/mobile-app")
public class MobileAppController {
private MobileAppService mobileAppSvc = new MobileAppServiceImpl();
@RequestMapping(method = RequestMethod.GET, value="/ping")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, String> ping(@RequestParam("msg") String msg) {
return Collections.singletonMap("pong", msg);
}
@RequestMapping(method = RequestMethod.GET, value = "/collection-protocol")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Object> getCollectionProtocol(
@RequestParam(value = "shortTitle")
String shortTitle) {
return ResponseEvent.unwrap(mobileAppSvc.getCpDetail(RequestEvent.wrap(shortTitle)));
}
@RequestMapping(method = RequestMethod.GET, value = "/form")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void getForm(
@RequestParam(value = "cpId")
Long cpId,
@RequestParam(value = "entity")
String entity,
@RequestParam(value = "viewForm")
String viewForm,
@RequestParam(value = "maxPvs", required = false, defaultValue = "0")
int maxPvListSize,
HttpServletResponse httpResp)
throws IOException {
Map<String, Object> params = new HashMap<>();
params.put("cpId", cpId);
params.put("entity", entity);
params.put("viewForm", viewForm);
ResponseEvent<Container> resp = mobileAppSvc.getForm(RequestEvent.wrap(params));
Container form = ResponseEvent.unwrap(resp);
sendForm(httpResp, form, maxPvListSize);
}
@RequestMapping(method = RequestMethod.POST, value = "/form-data")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Object> saveFormData(@RequestBody Map<String, Object> valueMap) {
Map<String, Object> appData = (Map<String, Object>) valueMap.get("appData");
if (!valueMap.containsKey("id")) {
valueMap.put("id", appData.get("recordId"));
}
String formName = (String) appData.get("formName");
Container form = Container.getContainer(formName);
FormData formData = FormData.getFormData(form, valueMap, true, null);
FormDataDetail detail = new FormDataDetail();
detail.setFormId(form.getId());
detail.setFormData(formData);
detail.setRecordId(formData.getRecordId());
return ResponseEvent.unwrap(mobileAppSvc.saveFormData(RequestEvent.wrap(detail)));
}
@RequestMapping(method = RequestMethod.GET, value = "/form-data")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Object> getFormData(
@RequestParam(value = "action")
String action,
@RequestParam
Map<String, String> input) {
input.put("action", action);
return ResponseEvent.unwrap(mobileAppSvc.getFormData(RequestEvent.wrap(input)));
}
@RequestMapping(method = RequestMethod.GET, value = "/specimens")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<? extends SpecimenInfo> getSpecimens(
@RequestParam(value = "cpId")
Long cpId,
@RequestParam(value = "cprId")
Long cprId,
@RequestParam(value = "label", required = false)
String label) {
SpecimenListCriteria crit = new SpecimenListCriteria()
.cpId(cpId).cprId(cprId)
.lineages(new String[] { "New"})
.startAt(0)
.maxResults(100)
.limitItems(true);
if (label != null) {
crit.labels(Collections.singletonList(label)).exactMatch(false);
}
return ResponseEvent.unwrap(mobileAppSvc.getSpecimens(RequestEvent.wrap(crit)));
}
@RequestMapping(method = RequestMethod.GET, value = "/child-specimens")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<? extends SpecimenInfo> getSpecimens(
@RequestParam(value = "parentSpecimenId")
Long parentId,
@RequestParam(value = "label", required = false)
String label) {
SpecimenListCriteria crit = new SpecimenListCriteria()
.ancestorId(parentId)
.lineages(new String[] { "Aliquot"})
.startAt(0)
.maxResults(100)
.limitItems(true);
if (label != null) {
crit.labels(Collections.singletonList(label)).exactMatch(false);
}
return ResponseEvent.unwrap(mobileAppSvc.getSpecimens(RequestEvent.wrap(crit)));
}
@RequestMapping(method = RequestMethod.GET, value = "/upload-jobs")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<MobileUploadJobDetail> getJobs(
@RequestParam(value = "cpId")
Long cpId,
@RequestParam(value = "startAt", defaultValue = "0", required = false)
int startAt,
@RequestParam(value = "maxResults", defaultValue = "100", required = false)
int maxResults) {
MobileUploadJobsListCriteria crit = new MobileUploadJobsListCriteria()
.cpId(cpId)
.startAt(startAt)
.maxResults(maxResults);
return ResponseEvent.unwrap(mobileAppSvc.getUploadJobs(RequestEvent.wrap(crit)));
}
@RequestMapping(method = RequestMethod.POST, value = "/upload-jobs")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Map<String, Object> uploadData(
@RequestParam(value = "cpId")
Long cpId,
@PathVariable("file") MultipartFile file)
throws IOException {
OutputStream out = null;
try {
File mobileAppDir = new File(ConfigUtil.getInstance().getDataDir(), "mobile-app");
File uploadDir = new File(mobileAppDir, "uploads");
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
File uploadedFile = new File(uploadDir, UUID.randomUUID().toString() + ".zip");
out = new FileOutputStream(uploadedFile);
IoUtil.copy(file.getInputStream(), out);
Map<String, Object> params = new HashMap<>();
params.put("cpId", cpId);
params.put("file", uploadedFile);
return ResponseEvent.unwrap(mobileAppSvc.uploadData(RequestEvent.wrap(params)));
} finally {
IOUtils.closeQuietly(out);
}
}
@RequestMapping(method = RequestMethod.GET, value = "/upload-jobs/{jobId}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public MobileUploadJobDetail getJob(@PathVariable("jobId") Long jobId) {
return ResponseEvent.unwrap(mobileAppSvc.getUploadJob(RequestEvent.wrap(jobId)));
}
@RequestMapping(method = RequestMethod.GET, value = "/upload-jobs/{jobId}/report")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void getJob(HttpServletResponse httpResp, @PathVariable("jobId") Long jobId) {
File reportFile = ResponseEvent.unwrap(mobileAppSvc.getUploadJobReport(RequestEvent.wrap(jobId)));
Utility.sendToClient(
httpResp,
"UploadJob_" + jobId + ".zip",
"application/octet-stream",
reportFile);
}
private void sendForm(HttpServletResponse httpResp, Container form, int maxPvListSize)
throws IOException {
httpResp.setCharacterEncoding("UTF-8");
Writer writer = httpResp.getWriter();
ContainerSerializer serializer = new ContainerJsonSerializer(form, writer);
serializer.serialize(maxPvListSize);
writer.flush();
}
}
|
package ti.modules.titanium.ui.widget;
import ti.modules.titanium.ui.ToolbarProxy;
import ti.modules.titanium.ui.android.DrawerLayoutProxy;
import ti.modules.titanium.ui.WindowProxy;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiRHelper;
import org.appcelerator.titanium.util.TiRHelper.ResourceNotFoundException;
import org.appcelerator.titanium.view.TiCompositeLayout;
import org.appcelerator.titanium.view.TiUIView;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.LayoutParams;
import android.support.v4.widget.ViewDragHelper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import java.lang.reflect.Field;
public class TiUIDrawerLayout extends TiUIView
{
private DrawerLayout layout = null;
private ActionBarDrawerToggle drawerToggle = null;
private FrameLayout leftFrame = null;
private FrameLayout rightFrame = null;
private int leftWidth;
private int rightWidth;
private Toolbar toolbar;
private boolean toolbarEnabled = true;
private boolean themeHasActionBar = true;
private TiViewProxy leftView;
private TiViewProxy rightView;
private TiViewProxy centerView;
private AppCompatActivity activity;
private static final String TAG = "TiUIDrawerLayout";
static int id_drawer_open_string = 0;
static int id_drawer_close_string = 0;
static int id_drawer_layout = 0;
static int id_drawer_layout_container = 0;
static int id_toolbar = 0;
public TiUIDrawerLayout(final DrawerLayoutProxy proxy)
{
super(proxy);
try {
if (id_drawer_open_string == 0) {
id_drawer_open_string = TiRHelper.getResource("string.drawer_layout_open");
}
if (id_drawer_close_string == 0) {
id_drawer_close_string = TiRHelper.getResource("string.drawer_layout_close");
}
if (id_drawer_layout == 0) {
id_drawer_layout = TiRHelper.getResource("layout.titanium_ui_drawer_layout");
}
if (id_drawer_layout_container == 0) {
id_drawer_layout_container = TiRHelper.getResource("id.drawer_layout_container");
}
if (id_toolbar == 0) {
id_toolbar = TiRHelper.getResource("id.drawer_layout_toolbar");
}
} catch (ResourceNotFoundException e) {
Log.e(TAG, "XML resources could not be found!!!");
}
this.activity = (AppCompatActivity) proxy.getActivity();
LayoutInflater inflater = LayoutInflater.from(this.activity);
layout = (DrawerLayout) inflater.inflate(id_drawer_layout, null, false);
toolbar = (Toolbar) layout.findViewById(id_toolbar);
// Check if the theme provides a default ActionBar
if (this.activity.getSupportActionBar() == null) {
this.themeHasActionBar = false;
}
setNativeView(layout);
}
private void setToolbarVisible(boolean visible)
{
if (visible) {
toolbar.setVisibility(View.VISIBLE);
} else {
toolbar.setVisibility(View.GONE);
}
}
private void drawerClosedEvent(View drawerView)
{
if (proxy.hasListeners(TiC.EVENT_CLOSE)) {
KrollDict options = new KrollDict();
if (drawerView.equals(leftFrame)) {
options.put("drawer", "left");
} else if (drawerView.equals(rightFrame)) {
options.put("drawer", "right");
}
proxy.fireEvent(TiC.EVENT_CLOSE, options);
}
}
private void drawerOpenedEvent(View drawerView)
{
if (proxy.hasListeners(TiC.EVENT_OPEN)) {
KrollDict options = new KrollDict();
if (drawerView.equals(leftFrame)) {
options.put("drawer", "left");
} else if (drawerView.equals(rightFrame)) {
options.put("drawer", "right");
}
proxy.fireEvent(TiC.EVENT_OPEN, options);
}
}
private void drawerStateChangedEvent(int state)
{
if (proxy.hasListeners(TiC.EVENT_CHANGE)) {
KrollDict options = new KrollDict();
options.put("state", state);
options.put("idle", (state == DrawerLayout.STATE_IDLE));
options.put("dragging", (state == DrawerLayout.STATE_DRAGGING));
options.put("settling", (state == DrawerLayout.STATE_SETTLING));
proxy.fireEvent(TiC.EVENT_CHANGE, options);
}
}
private void drawerSlideEvent(View drawerView, float slideOffset)
{
if (proxy.hasListeners(TiC.EVENT_SLIDE)) {
KrollDict options = new KrollDict();
options.put("offset", slideOffset);
if (drawerView.equals(leftFrame)) {
options.put("drawer", "left");
} else if (drawerView.equals(rightFrame)) {
options.put("drawer", "right");
}
proxy.fireEvent(TiC.EVENT_SLIDE, options);
}
}
private class DrawerListener implements DrawerLayout.DrawerListener
{
@Override
public void onDrawerClosed(View drawerView)
{
drawerClosedEvent(drawerView);
}
@Override
public void onDrawerOpened(View drawerView)
{
drawerOpenedEvent(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
drawerSlideEvent(drawerView, slideOffset);
}
@Override
public void onDrawerStateChanged(int state)
{
drawerStateChangedEvent(state);
}
}
public void toggleLeft()
{
if (layout.isDrawerOpen(Gravity.START)) {
closeLeft();
} else {
openLeft();
}
}
public void openLeft()
{
layout.openDrawer(Gravity.START);
}
public void closeLeft()
{
layout.closeDrawer(Gravity.START);
}
public void toggleRight()
{
if (layout.isDrawerOpen(Gravity.END)) {
closeRight();
} else {
openRight();
}
}
public void openRight()
{
layout.openDrawer(Gravity.END);
}
public void closeRight()
{
layout.closeDrawer(Gravity.END);
}
public boolean isLeftOpen()
{
return layout.isDrawerOpen(Gravity.START);
}
public boolean isRightOpen()
{
return layout.isDrawerOpen(Gravity.END);
}
public boolean isLeftVisible()
{
return layout.isDrawerVisible(Gravity.START);
}
public boolean isRightVisible()
{
return layout.isDrawerVisible(Gravity.END);
}
private void initDrawerToggle()
{
final AppCompatActivity activity = (AppCompatActivity) proxy.getActivity();
if (activity != null && activity.getSupportActionBar() == null) {
return;
}
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
activity.getSupportActionBar().setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(activity, layout, id_drawer_open_string, id_drawer_close_string) {
@Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
drawerClosedEvent(drawerView);
}
@Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
drawerOpenedEvent(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
drawerSlideEvent(drawerView, slideOffset);
}
@Override
public void onDrawerStateChanged(int state)
{
super.onDrawerStateChanged(state);
drawerStateChangedEvent(state);
}
};
layout.addDrawerListener(drawerToggle);
layout.post(new Runnable() {
@Override
public void run()
{
drawerToggle.syncState();
}
});
}
private void initLeft()
{
if (leftFrame != null) {
return;
}
leftFrame = new FrameLayout(proxy.getActivity());
LayoutParams frameLayout = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
frameLayout.gravity = Gravity.START;
leftFrame.setLayoutParams(frameLayout);
layout.addView(leftFrame);
if (drawerToggle == null) {
initDrawerToggle();
}
}
private void initRight()
{
if (rightFrame != null) {
return;
}
rightFrame = new FrameLayout(proxy.getActivity());
LayoutParams frameLayout = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
frameLayout.gravity = Gravity.END;
rightFrame.setLayoutParams(frameLayout);
layout.addView(rightFrame);
}
public void setCenterView(TiViewProxy viewProxy)
{
if (viewProxy == null || viewProxy == this.centerView) {
return;
}
viewProxy.setActivity(proxy.getActivity());
TiUIView contentView = viewProxy.getOrCreateView();
View view = contentView.getOuterView();
LinearLayout container = (LinearLayout) layout.findViewById(id_drawer_layout_container);
TiCompositeLayout content = (TiCompositeLayout) container.getChildAt(1);
ViewParent viewParent = view.getParent();
if (viewParent != null && viewParent != content && viewParent instanceof ViewGroup) {
((ViewGroup) viewParent).removeView(view);
}
content.addView(view, contentView.getLayoutParams());
if (this.centerView != null) {
content.removeView(this.centerView.getOrCreateView().getNativeView());
}
this.centerView = viewProxy;
}
private void setDrawMargin(Integer width)
{
try {
Field mDragger = layout.getClass().getDeclaredField("mLeftDragger");
mDragger.setAccessible(true);
ViewDragHelper draggerObj = (ViewDragHelper) mDragger.get(layout);
Field mEdgeSize = draggerObj.getClass().getDeclaredField("mEdgeSize");
mEdgeSize.setAccessible(true);
mEdgeSize.setInt(draggerObj, width);
} catch (NoSuchFieldException e) {
Log.e(TAG, e.toString());
} catch (IllegalAccessException e) {
Log.e(TAG, e.toString());
}
}
@Override
public void processProperties(KrollDict d)
{
if (d.containsKey(TiC.PROPERTY_LEFT_VIEW)) {
Object leftView = d.get(TiC.PROPERTY_LEFT_VIEW);
if (leftView != null && leftView instanceof TiViewProxy) {
if (leftView instanceof WindowProxy) {
throw new IllegalStateException("cannot add window as a child view of other window");
}
this.leftView = (TiViewProxy) leftView;
this.initLeft();
this.leftFrame.addView(getNativeView(this.leftView));
} else {
Log.e(TAG, "invalid type for leftView");
}
}
if (d.containsKey(TiC.PROPERTY_RIGHT_VIEW)) {
Object rightView = d.get(TiC.PROPERTY_RIGHT_VIEW);
if (rightView != null && rightView instanceof TiViewProxy) {
if (rightView instanceof WindowProxy) {
throw new IllegalStateException("cannot add window as a child view of other window");
}
this.rightView = (TiViewProxy) rightView;
this.initRight();
this.rightFrame.addView(getNativeView(this.rightView));
} else {
Log.e(TAG, "invalid type for rightView");
}
}
if (d.containsKey(TiC.PROPERTY_CENTER_VIEW)) {
Object centerView = d.get(TiC.PROPERTY_CENTER_VIEW);
if (centerView != null && centerView instanceof TiViewProxy) {
if (centerView instanceof WindowProxy) {
throw new IllegalStateException("cannot use window as a child view of other window");
}
setCenterView((TiViewProxy) centerView);
} else {
Log.e(TAG, "invalid type for centerView");
}
}
if (d.containsKey(TiC.PROPERTY_LEFT_WIDTH)) {
if (leftFrame != null) {
if (d.get(TiC.PROPERTY_LEFT_WIDTH).equals(TiC.LAYOUT_SIZE)) {
leftFrame.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
} else if (d.get(TiC.PROPERTY_LEFT_WIDTH).equals(TiC.LAYOUT_FILL)) {
leftFrame.getLayoutParams().width = LayoutParams.MATCH_PARENT;
} else if (!d.get(TiC.PROPERTY_LEFT_WIDTH).equals(TiC.SIZE_AUTO)) {
leftWidth = getDevicePixels(d.get(TiC.PROPERTY_LEFT_WIDTH));
leftFrame.getLayoutParams().width = leftWidth;
}
}
} else {
if (leftFrame != null) {
leftFrame.getLayoutParams().width = LayoutParams.MATCH_PARENT;
}
}
if (d.containsKey(TiC.PROPERTY_RIGHT_WIDTH)) {
if (rightFrame != null) {
if (d.get(TiC.PROPERTY_RIGHT_WIDTH).equals(TiC.LAYOUT_SIZE)) {
rightFrame.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
} else if (d.get(TiC.PROPERTY_RIGHT_WIDTH).equals(TiC.LAYOUT_FILL)) {
rightFrame.getLayoutParams().width = LayoutParams.MATCH_PARENT;
} else if (!d.get(TiC.PROPERTY_RIGHT_WIDTH).equals(TiC.SIZE_AUTO)) {
rightWidth = getDevicePixels(d.get(TiC.PROPERTY_RIGHT_WIDTH));
rightFrame.getLayoutParams().width = rightWidth;
}
}
} else {
if (rightFrame != null) {
rightFrame.getLayoutParams().width = LayoutParams.MATCH_PARENT;
}
}
if (d.containsKey(TiC.PROPERTY_DRAWER_LOCK_MODE)) {
layout.setDrawerLockMode(TiConvert.toInt(d.get(TiC.PROPERTY_DRAWER_LOCK_MODE)));
}
// If theme has default ActionBar ignore `toolbarEnabled` and `toolbar` properties
if (!this.themeHasActionBar) {
if (d.containsKey(TiC.PROPERTY_TOOLBAR_ENABLED)) {
toolbarEnabled = TiConvert.toBoolean(d.get(TiC.PROPERTY_TOOLBAR_ENABLED));
setToolbarVisible(toolbarEnabled);
}
if (d.containsKey(TiC.PROPERTY_TOOLBAR)) {
// Hide embedded toolbar if a custom one was provided
setToolbarVisible(false);
ViewGroup.LayoutParams layoutParams = this.toolbar.getLayoutParams();
// Replace the current toolbar reference with the custom one
this.toolbar = ((Toolbar) ((ToolbarProxy) d.get(TiC.PROPERTY_TOOLBAR)).getToolbarInstance());
// Add it as a first child in the layout container
((LinearLayout) layout.findViewById(id_drawer_layout_container)).addView(this.toolbar, 0, layoutParams);
setToolbarVisible(toolbarEnabled);
}
// Only set the toolbar as ActionBar after we have processes proxy's properties
this.activity.setSupportActionBar(this.toolbar);
}
if (d.containsKey(TiC.PROPERTY_DRAG_MARGIN)) {
setDrawMargin(getDevicePixels(d.get(TiC.PROPERTY_DRAG_MARGIN)));
}
super.processProperties(d);
}
@Override
public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy)
{
if (key.equals(TiC.PROPERTY_LEFT_VIEW)) {
if (newValue == null || newValue == this.leftView) {
return;
}
TiViewProxy newProxy = null;
int index = 0;
if (this.leftView != null) {
index = this.leftFrame.indexOfChild(this.leftView.getOrCreateView().getNativeView());
}
if (newValue instanceof TiViewProxy) {
if (newValue instanceof WindowProxy) {
throw new IllegalStateException("cannot add window as a child view of other window");
}
newProxy = (TiViewProxy) newValue;
initLeft();
this.leftFrame.addView(newProxy.getOrCreateView().getOuterView(), index);
} else {
Log.e(TAG, "invalid type for leftView");
}
if (this.leftView != null) {
this.leftFrame.removeView(this.leftView.getOrCreateView().getNativeView());
}
this.leftView = newProxy;
} else if (key.equals(TiC.PROPERTY_RIGHT_VIEW)) {
if (newValue == null || newValue == this.rightView) {
return;
}
TiViewProxy newProxy = null;
int index = 0;
if (this.rightView != null) {
index = this.rightFrame.indexOfChild(this.rightView.getOrCreateView().getNativeView());
}
if (newValue instanceof TiViewProxy) {
if (newValue instanceof WindowProxy) {
throw new IllegalStateException("cannot add window as a child view of other window");
}
newProxy = (TiViewProxy) newValue;
initRight();
this.rightFrame.addView(newProxy.getOrCreateView().getOuterView(), index);
} else {
Log.e(TAG, "invalid type for rightView");
}
if (this.rightView != null) {
this.rightFrame.removeView(this.rightView.getOrCreateView().getNativeView());
}
this.rightView = newProxy;
} else if (key.equals(TiC.PROPERTY_CENTER_VIEW)) {
TiViewProxy newProxy = (TiViewProxy) newValue;
setCenterView(newProxy);
} else if (key.equals(TiC.PROPERTY_LEFT_WIDTH)) {
if (leftFrame == null) {
return;
}
initLeft();
if (newValue.equals(TiC.LAYOUT_SIZE)) {
leftWidth = LayoutParams.WRAP_CONTENT;
} else if (newValue.equals(TiC.LAYOUT_FILL)) {
leftWidth = LayoutParams.MATCH_PARENT;
} else if (!newValue.equals(TiC.SIZE_AUTO)) {
leftWidth = getDevicePixels(newValue);
}
LayoutParams leftFrameLayout = new LayoutParams(leftWidth, LayoutParams.MATCH_PARENT);
leftFrameLayout.gravity = Gravity.START;
this.leftFrame.setLayoutParams(leftFrameLayout);
} else if (key.equals(TiC.PROPERTY_RIGHT_WIDTH)) {
if (rightFrame == null) {
return;
}
initRight();
if (newValue.equals(TiC.LAYOUT_SIZE)) {
rightWidth = LayoutParams.WRAP_CONTENT;
} else if (newValue.equals(TiC.LAYOUT_FILL)) {
rightWidth = LayoutParams.MATCH_PARENT;
} else if (!newValue.equals(TiC.SIZE_AUTO)) {
rightWidth = getDevicePixels(newValue);
}
LayoutParams rightFrameLayout = new LayoutParams(rightWidth, LayoutParams.MATCH_PARENT);
rightFrameLayout.gravity = Gravity.END;
this.rightFrame.setLayoutParams(rightFrameLayout);
} else if (key.equals(TiC.PROPERTY_DRAWER_LOCK_MODE)) {
layout.setDrawerLockMode(TiConvert.toInt(newValue));
} else if (key.equals(TiC.PROPERTY_DRAWER_INDICATOR_ENABLED)) {
if (drawerToggle != null) {
drawerToggle.setDrawerIndicatorEnabled((Boolean) newValue);
}
} else if (key.equals(TiC.PROPERTY_TOOLBAR_ENABLED)) {
// If we already have a Toolbar set ignore this property
if (!this.themeHasActionBar) {
toolbarEnabled = TiConvert.toBoolean(newValue);
setToolbarVisible(toolbarEnabled);
}
} else if (key.equals(TiC.PROPERTY_DRAG_MARGIN)) {
setDrawMargin(getDevicePixels(newValue));
} else {
super.propertyChanged(key, oldValue, newValue, proxy);
}
}
@Override
public void release()
{
if (layout != null) {
layout.removeAllViews();
layout.removeDrawerListener(drawerToggle);
layout = null;
}
if (leftFrame != null) {
leftFrame.removeAllViews();
leftFrame = null;
}
if (rightFrame != null) {
rightFrame.removeAllViews();
rightFrame = null;
}
if (leftView != null) {
leftView.releaseViews();
leftView = null;
}
if (rightView != null) {
rightView.releaseViews();
rightView = null;
}
if (centerView != null) {
centerView.releaseViews();
centerView = null;
}
if (toolbar != null) {
toolbar.removeAllViews();
toolbar = null;
}
super.release();
proxy = null;
}
private int getDevicePixels(Object value)
{
TiDimension nativeSize = TiConvert.toTiDimension(TiConvert.toString(value), TiDimension.TYPE_WIDTH);
return nativeSize.getAsPixels(layout);
}
private View getNativeView(TiViewProxy viewProxy)
{
TiUIView view = viewProxy.getOrCreateView();
View outerView = view.getOuterView();
View nativeView = outerView != null ? outerView : view.getNativeView();
ViewGroup parentViewGroup = (ViewGroup) nativeView.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeAllViews();
}
return nativeView;
}
}
|
package com.mapswithme.maps.bookmarks;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import com.mapswithme.maps.R;
import com.mapswithme.maps.bookmarks.data.BookmarkCategory;
import com.mapswithme.maps.bookmarks.data.BookmarkManager;
import com.mapswithme.util.BottomSheetHelper;
import com.mapswithme.util.SharedPropertiesUtils;
import com.mapswithme.util.UiUtils;
import com.mapswithme.util.sharing.TargetUtils;
import com.mapswithme.util.statistics.Statistics;
public class CachedBookmarkCategoriesFragment extends BaseBookmarkCategoriesFragment implements
BookmarkManager.BookmarksCatalogListener
{
@SuppressWarnings("NullableProblems")
@NonNull
private ViewGroup mEmptyViewContainer;
@SuppressWarnings("NullableProblems")
@NonNull
private View mPayloadContainer;
@SuppressWarnings("NullableProblems")
@NonNull
private View mProgressContainer;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
mProgressContainer = view.findViewById(R.id.placeholder_loading);
mEmptyViewContainer = view.findViewById(R.id.placeholder_container);
mPayloadContainer = view.findViewById(R.id.cached_bookmarks_payload_container);
View downloadBtn = mEmptyViewContainer.findViewById(R.id.download_routers_btn);
downloadBtn.setOnClickListener(new DownloadRoutesClickListener());
View closeHeaderBtn = view.findViewById(R.id.header_close);
closeHeaderBtn.setOnClickListener(new CloseHeaderClickListener());
boolean isClosed = SharedPropertiesUtils.isCatalogCategoriesHeaderClosed(getContext());
UiUtils.showIf(!isClosed, closeHeaderBtn);
}
@Override
protected int getLayoutRes()
{
return R.layout.fragment_catalog_bookmark_categories;
}
@NonNull
@Override
protected CatalogBookmarkCategoriesAdapter createAdapter()
{
return new CatalogBookmarkCategoriesAdapter(getContext());
}
@Override
public void onFooterClick()
{
openBookmarksCatalogScreen();
}
@Override
protected void onShareActionSelected(@NonNull BookmarkCategory category)
{
String deepLink = BookmarkManager.INSTANCE.getCatalogDeeplink(category.getId());
Intent intent = new Intent(Intent.ACTION_SEND)
.setType(TargetUtils.TYPE_TEXT_PLAIN)
.putExtra(Intent.EXTRA_SUBJECT, deepLink)
.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_bookmarks_email_body));
startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
@Override
protected void onDeleteActionSelected(@NonNull BookmarkCategory category)
{
super.onDeleteActionSelected(category);
updateLoadingPlaceholder();
}
@Override
protected void updateLoadingPlaceholder()
{
super.updateLoadingPlaceholder();
boolean showLoadingPlaceholder = BookmarkManager.INSTANCE.isAsyncBookmarksLoadingInProgress();
if (showLoadingPlaceholder)
{
mProgressContainer.setVisibility(View.VISIBLE);
mPayloadContainer.setVisibility(View.GONE);
mEmptyViewContainer.setVisibility(View.GONE);
}
else
{
boolean isEmptyAdapter = getAdapter().getItemCount() == 0;
UiUtils.showIf(isEmptyAdapter, mEmptyViewContainer);
mPayloadContainer.setVisibility(isEmptyAdapter ? View.GONE : View.VISIBLE);
mProgressContainer.setVisibility(View.GONE);
}
}
@Override
public void onStart()
{
super.onStart();
BookmarkManager.INSTANCE.addCatalogListener(this);
}
@Override
public void onStop()
{
super.onStop();
BookmarkManager.INSTANCE.removeCatalogListener(this);
}
@Override
protected int getCategoryMenuResId()
{
return R.menu.menu_catalog_bookmark_categories;
}
private void openBookmarksCatalogScreen()
{
Intent intent = new Intent(getActivity(), BookmarksCatalogActivity.class)
.putExtra(BookmarksCatalogFragment.EXTRA_BOOKMARKS_CATALOG_URL,
getCatalogUrl());
startActivityForResult(intent, BookmarksCatalogActivity.REQ_CODE_CATALOG);
Statistics.INSTANCE.trackOpenCatalogScreen();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == BookmarksCatalogActivity.REQ_CODE_CATALOG && resultCode == Activity.RESULT_OK)
{
getActivity().setResult(Activity.RESULT_OK, data);
getActivity().finish();
}
}
@NonNull
private String getCatalogUrl()
{
return BookmarkManager.INSTANCE.getCatalogFrontendUrl();
}
@Override
public void onMoreOperationClick(@NonNull BookmarkCategory item)
{
showBottomMenu(item);
}
@Override
public void onImportStarted(@NonNull String serverId)
{
mProgressContainer.setVisibility(View.VISIBLE);
mEmptyViewContainer.setVisibility(View.GONE);
mPayloadContainer.setVisibility(View.GONE);
}
@Override
public void onImportFinished(@NonNull String serverId, long catId, boolean successful)
{
if (successful)
{
mPayloadContainer.setVisibility(View.VISIBLE);
mProgressContainer.setVisibility(View.GONE);
mEmptyViewContainer.setVisibility(View.GONE);
getAdapter().notifyDataSetChanged();
}
else
{
boolean isEmptyAdapter = getAdapter().getItemCount() == 0;
mProgressContainer.setVisibility(View.GONE);
UiUtils.showIf(isEmptyAdapter, mEmptyViewContainer);
mPayloadContainer.setVisibility(isEmptyAdapter ? View.GONE : View.VISIBLE);
}
}
@Override
protected void prepareBottomMenuItems(@NonNull BottomSheetHelper.Builder builder)
{
setEnableForMenuItem(R.id.delete_list, builder, true);
setEnableForMenuItem(R.id.share_list, builder, false);
}
private class CloseHeaderClickListener implements View.OnClickListener
{
@Override
public void onClick(View v)
{
View header = mPayloadContainer.findViewById(R.id.header);
header.setVisibility(View.GONE);
SharedPropertiesUtils.setCatalogCategoriesHeaderClosed(getContext(), true);
}
}
private class DownloadRoutesClickListener implements View.OnClickListener
{
@Override
public void onClick(View v)
{
openBookmarksCatalogScreen();
}
}
}
|
package org.sana.android.content.core;
import java.io.File;
import org.sana.android.db.ModelWrapper;
import org.sana.android.provider.BaseContract;
import org.sana.android.provider.Observations;
import org.sana.api.IObservation;
import org.sana.core.Concept;
import org.sana.core.Encounter;
import org.sana.core.Observation;
import org.sana.util.DateUtil;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabaseCorruptException;
import android.net.Uri;
import android.text.TextUtils;
/**
* @author Sana Development
*
*/
public class ObservationWrapper extends ModelWrapper<IObservation> implements
IObservation
{
public static final String TAG = ObservationWrapper.class.getSimpleName();
private static final String SELECTION_UNIQUE =
BaseContract.UUID + "=CAST(? AS TEXT) OR ("
+ Observations.Contract.ENCOUNTER + "=CAST(? AS TEXT) AND "
+ Observations.Contract.ID + "=CAST(? AS TEXT))";
/**
* @param cursor
*/
public ObservationWrapper(Cursor cursor) {
super(cursor);
}
/* (non-Javadoc)
* @see org.sana.api.IObservation#getId()
*/
@Override
public String getId() {
return getStringField(Observations.Contract.ID);
}
/* (non-Javadoc)
* @see org.sana.api.IObservation#getEncounter()
*/
@Override
public Encounter getEncounter() {
Encounter encounter = new Encounter();
encounter.setUuid(getStringField(Observations.Contract.ENCOUNTER));
return encounter;
}
/* (non-Javadoc)
* @see org.sana.api.IObservation#getConcept()
*/
@Override
public Concept getConcept() {
Concept concept = new Concept();
concept.setName(getStringField(Observations.Contract.CONCEPT));
return concept;
}
/* (non-Javadoc)
* @see org.sana.api.IObservation#getValue_complex()
*/
@Override
public String getValue_complex() {
return getStringField(Observations.Contract.VALUE);
}
/* (non-Javadoc)
* @see org.sana.api.IObservation#getValue_text()
*/
@Override
public String getValue_text() {
return getStringField(Observations.Contract.VALUE);
}
/* (non-Javadoc)
* @see org.sana.android.db.ModelWrapper#getObject()
*/
@Override
public IObservation getObject() {
Observation obj = new Observation();
obj.setUuid(getUuid());
obj.setCreated(getCreated());
obj.setModified(getModified());
obj.setConcept(getConcept());
obj.setValue(getValue_text());
obj.setEncounter(getEncounter());
return obj;
}
public static Uri getReferenceByEncounterAndId(ContentResolver resolver,
String encounter, String id){
return ModelWrapper.getOneReferenceByFields(
Observations.CONTENT_URI,
new String[]{ Observations.Contract.ENCOUNTER, Observations.Contract.ID },
new String[]{ encounter, id }, resolver);
}
public static IObservation getOneByUuid(ContentResolver resolver, String uuid){
ObservationWrapper wrapper = new ObservationWrapper(ModelWrapper.getOneByUuid(
Observations.CONTENT_URI,resolver, uuid));
IObservation object = null;
if(wrapper != null)
try{
object = wrapper.next();
} finally {
wrapper.close();
}
return object;
}
/**
* Convenience wrapper to return a wrapped cursor which references all of
* the entries ordered by {@link org.sana.android.provider.BaseContract#CREATED CREATED}
* in ascending order, or, oldest first.
*
* @param resolver The resolver which will perform the query.
* @return A cursor with the result or null.
*/
public static ObservationWrapper getAllByCreatedAsc(ContentResolver resolver)
{
return new ObservationWrapper(ModelWrapper.getAllByCreatedAsc(
Observations.CONTENT_URI,resolver));
}
/**
* Convenience wrapper to return a wrapped cursor which references all of
* the entries ordered by {@link org.sana.android.provider.BaseContract#CREATED CREATED}
* in descending order, or, newest first.
*
* @param resolver The resolver which will perform the query.
* @return A cursor with the result or null.
*/
public static ObservationWrapper getAllByCreatedDesc(ContentResolver resolver)
{
return new ObservationWrapper(ModelWrapper.getAllByCreatedDesc(
Observations.CONTENT_URI,resolver));
}
/**
* Convenience wrapper to return a wrapped cursor which references all of
* the entries ordered by {@link org.sana.android.provider.BaseContract#MODIFIED MODIFIED}
* in ascending order, or, oldest first.
*
* @param resolver The resolver which will perform the query.
* @return A cursor with the result or null.
*/
public static ObservationWrapper getAllByModifiedAsc(ContentResolver resolver)
{
return new ObservationWrapper(ModelWrapper.getAllByModifiedAsc(
Observations.CONTENT_URI,resolver));
}
/**
* Convenience wrapper to return a wrapped cursor which references all of
* the entries ordered by {@link org.sana.android.provider.BaseContract#MODIFIED MODIFIED}
* in descending order, or, newest first.
*
* @param resolver The resolver which will perform the query.
* @return A cursor with the result or null.
*/
public static ObservationWrapper getAllByModifiedDesc(ContentResolver resolver)
{
return new ObservationWrapper(ModelWrapper.getAllByModifiedDesc(
Observations.CONTENT_URI,resolver));
}
/**
* Returns a single observation within an encounter.
* @param resolver A content resolver.
* @param encounter The encounter uuid.
* @param id The node id.
* @return The row values in an IObservation object.
*/
public static IObservation getOneByEncounterAndId(ContentResolver resolver,
String encounter, String id)
{
ObservationWrapper wrapper = new ObservationWrapper(ModelWrapper.getOneByFields(
Observations.CONTENT_URI,resolver,
new String[]{ Observations.Contract.ENCOUNTER,
Observations.Contract.ID },
new String[]{ encounter, id}));
IObservation object = null;
if(wrapper != null)
try{
object = wrapper.next();
} finally {
wrapper.close();
}
return object;
}
public static Uri getByEncounterAndId(Context context, String encounter,
String id)
{
Uri result = Uri.EMPTY;
Cursor cursor = null;
boolean multipleExist = false;
try {
final String[] projection = new String[]{ BaseContract._ID };
final String selection = Observations.Contract.ENCOUNTER + "='"+encounter+"'"
+ " AND " + Observations.Contract.ID + "='"+id+"'";
String[] selectionArgs = new String[]{ id };
cursor = context.getContentResolver().query(
Observations.CONTENT_URI, projection, selection,
null, null);
if (cursor != null)
if(cursor.getCount() == 1 && cursor.moveToFirst())
result = ContentUris.withAppendedId(Observations.CONTENT_URI, cursor.getLong(0));
else if(cursor.getCount() > 1)
multipleExist = true;
} catch(Exception e){
e.printStackTrace();
} finally {
if(cursor != null) cursor.close();
}
if(multipleExist)
throw new SQLiteDatabaseCorruptException("");
return result;
}
public static Uri getUnique(Context context, Observation object)
{
return getUnique(context, object.getUuid(),
object.getEncounter().getUuid(),
object.getId());
}
public static Uri getUnique(Context context, String uuid,
String encounter, String node)
{
Uri result = Uri.EMPTY;
Cursor cursor = null;
boolean multipleExist = false;
final String[] selectionArgs = new String[]{
uuid,
encounter,
node
};
try {
final String[] projection = new String[]{ BaseContract._ID };
cursor = context.getContentResolver().query(
Observations.CONTENT_URI,
projection,
SELECTION_UNIQUE,
selectionArgs,
null);
if (cursor != null)
if(cursor.getCount() == 1 && cursor.moveToFirst())
result = ContentUris.withAppendedId(Observations.CONTENT_URI, cursor.getLong(0));
else if(cursor.getCount() > 1)
multipleExist = true;
} catch(Exception e){
e.printStackTrace();
} finally {
if(cursor != null) cursor.close();
}
if(multipleExist)
throw new SQLiteDatabaseCorruptException("Uniqueness on uuid or encounter and node violated!");
return result;
}
/**
* Returns a all of the observations within an encounter.
*
* @param resolver A content resolver.
* @param encounter The encounter uuid.
* @return
*/
public ObservationWrapper getAllByEncounter(ContentResolver resolver, String encounter)
{
return new ObservationWrapper(ModelWrapper.getAllByField(
Observations.CONTENT_URI,resolver, Observations.Contract.ENCOUNTER, encounter));
}
/**
* Returns a all of the observations with the specified concept.
*
* @param resolver A content resolver.
* @param concept The uuid of the concept.
* @return
*/
public static ObservationWrapper getAllByConcept(ContentResolver resolver, String concept)
{
return new ObservationWrapper(ModelWrapper.getAllByField(
Observations.CONTENT_URI,resolver, Observations.Contract.ENCOUNTER, concept));
}
/**
* Returns a all of the observations for a given subject.
*
* @param resolver A content resolver.
* @param subject The uuid of the subject.
* @return
*/
public static ObservationWrapper getAllBySubject(ContentResolver resolver, String subject)
{
return new ObservationWrapper(ModelWrapper.getAllByField(
Observations.CONTENT_URI,resolver, Observations.Contract.ENCOUNTER, subject));
}
/**
* Returns a all of the observations for a given subject with a specified
* concept
*
* @param resolver A content resolver.
* @param subject The uuid of the subject.
* @param concept The uuid of the concept.
* @return
*/
public static ObservationWrapper getAllBySubjectAndConcept(
ContentResolver resolver, String subject, String concept)
{
return new ObservationWrapper(ModelWrapper.getAllByFields(
Observations.CONTENT_URI,resolver,
new String[]{ Observations.Contract.SUBJECT,
Observations.Contract.CONCEPT },
new String[]{ subject,concept }));
}
public static File getComplexData(ContentResolver resolver, Uri obs){
Cursor cursor = null;
String path = null;
try{
String[] projection = new String[]{ Observations.Contract.VALUE };
cursor = resolver.query(obs, projection, null,null,null);
if(cursor != null && cursor.moveToFirst())
path = cursor.getString(0);
} finally {
if(cursor != null) cursor.close();
}
return (TextUtils.isEmpty(path))? null: new File(path);
}
public static boolean existsByEncounterAndId(Context context,
String encounter, String id)
{
boolean exists = false;
ObservationWrapper wrapper = null;
try {
wrapper = new ObservationWrapper(ModelWrapper.getOneByFields(
Observations.CONTENT_URI, context.getContentResolver(),
new String[]{Observations.Contract.ENCOUNTER,
Observations.Contract.ID},
new String[]{"'" + encounter + "'", id}));
if (wrapper != null && wrapper.getCount() == 1)
exists = true;
} catch(Exception e){
e.printStackTrace();
} finally {
wrapper.close();
}
return exists;
}
public static int deleteCorrupted(Context context, String uuid,
String encounter, String node) {
Uri result = Uri.EMPTY;
int deleted = 0;
final String[] selectionArgs = new String[]{
uuid,
encounter,
node
};
try {
final String[] projection = new String[]{BaseContract._ID};
deleted = context.getContentResolver().delete(
Observations.CONTENT_URI,
SELECTION_UNIQUE,
selectionArgs);
} catch (Exception e) {
e.printStackTrace();
}
return deleted;
}
public static int deleteCorrupted(Context context, Observation object) {
return deleteCorrupted(context, object.getUuid(),
object.getEncounter().getUuid(),
object.getId());
}
public static ContentValues toValues(Observation obj){
ContentValues values = new ContentValues();
values.put(BaseContract.UUID , obj.getUuid());
values.put(BaseContract.CREATED ,
DateUtil.format(obj.getCreated()));
values.put(BaseContract.MODIFIED ,
DateUtil.format(obj.getModified()));
values.put(Observations.Contract.ENCOUNTER, obj.getEncounter().getUuid());
values.put(Observations.Contract.ID, obj.getId());
values.put(Observations.Contract.CONCEPT, obj.getConcept().getName());
values.put(Observations.Contract.VALUE, obj.getValue_text());
values.put(Observations.Contract.SUBJECT, obj.getEncounter().getSubject().getUuid());
return values;
}
}
|
package ca.com.androidbinnersproject.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
public class StartAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent();
// if(isLogged()) {
intent.setClass(this, MainActivity.class);
// } else {
// intent.setClass(this, LoginActivity.class);
// startActivityForResult(intent, LoginActivity.FROM_LOGIN);
// return;
startActivity(intent);
}
public boolean isLogged() {
SharedPreferences preferences = getSharedPreferences(LoginActivity.USER_AUTHENTICATED, 0);
return preferences.getBoolean(LoginActivity.IS_AUTHENTICATED, false);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == LoginActivity.FROM_LOGIN) {
if(resultCode == RESULT_OK) {
Intent intent = new Intent();
intent.setClass(this, MainActivity.class);
startActivity(intent);
}
else {
Log.e("BinnersApp", "Failed to log in: " + resultCode);
}
}
else {
Log.e("BinnersApp", "Received unknown activity result: " + resultCode);
}
}
}
|
package com.example.vladimirsinicyn.thermostat.model;
import java.io.Serializable;
import java.util.ArrayList;
public class DaySchedule implements Serializable {
private ArrayList<TemperatureChange> changes;
private int dayChanges = 0;
private int nightChanges = 0;
public DaySchedule() {
changes = new ArrayList<TemperatureChange>();
dayChanges++;
nightChanges++;
changes.add(WeekSchedule.firstDefaultTemperatureChange);
changes.add(WeekSchedule.lastDefaultTemperatureChange);
}
public void clear() {
changes = new ArrayList<TemperatureChange>();
}
public TemperatureChange findClosest(Time time) {
int min = Integer.MAX_VALUE;
int compareTime = time.toMinutes();
TemperatureChange closest = null;
for (int i = 0; i < changes.size(); i++) {
int tempValue = changes.get(i).getTime().toMinutes() - compareTime;
if (tempValue >= 0 && tempValue < min) {
closest = changes.get(i);
min = tempValue;
}
}
return closest;
}
public TemperatureChange findClosestLess(Time time) {
int min = Integer.MAX_VALUE;
int compareTime = time.toMinutes();
TemperatureChange closest = null;
for (int i = 0; i < changes.size(); i++) {
int tempValue = changes.get(i).getTime().toMinutes() - compareTime;
if (tempValue < 0 && -tempValue < min) {
closest = changes.get(i);
min = -tempValue;
}
}
return closest;
}
public void addChange(TemperatureChange change) throws Exception {
if (find(change.getTime())!= null) {
throw new Exception("Similar times mustn't present.");
}
if (change.getTargetCondition() == LightCondition.DAY) {
dayChanges++;
} else {
nightChanges++;
}
if (dayChanges == 6) {
dayChanges
throw new Exception("Too many day changes.");
}
if (nightChanges == 6) {
nightChanges
throw new Exception("Too many night changes.");
}
changes.add(change);
}
public void deleteTimeChange(TemperatureChange change) throws Exception {
for (int i = 0; i < changes.size(); i++) {
if (changes.get(i).equals(change)) {
changes.remove(changes.get(i));
if (change.getType() == ChangeType.DAY) {
dayChanges
} else {
nightChanges
}
break;
}
}
}
public TemperatureChange find(Time time) {
for (int i = 0; i < changes.size(); i++) {
if (time.equals(changes.get(i).getTime())) {
return changes.get(i);
}
}
return null;
}
public void print() {
for (int i = 0; i < changes.size(); i++) {
System.out.println("light condition: " + changes.get(i).getTargetCondition() + ", time: " + changes.get(i).getTime().toString());
}
}
public ArrayList<TemperatureChange> getChanges() {
return changes;
}
}
|
package com.luanthanhthai.android.liteworkouttimer;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class TimerFragment extends Fragment implements View.OnClickListener {
private Button mPauseButton;
private ViewGroup timerClockView;
private TextView mMinutesView;
private TextView mSecondsView;
private ViewGroup keypadPanel;
private ViewGroup pauseBarPanel;
private int[] keypadButtons = {
R.id.button_0, R.id.button_1, R.id.button_2,
R.id.button_3, R.id.button_4, R.id.button_5,
R.id.button_6, R.id.button_7, R.id.button_8,
R.id.button_9
};
private int finalMinutesValue = 0;
private int finalSecondsValue = 0;
private boolean firstDigitHasValue = false;
private boolean isRunning = false;
public static TimerFragment newInstance() {
return new TimerFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_timer, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
// The sliding panels
keypadPanel = (ViewGroup) view.findViewById(R.id.start_button_bar_with_keypad);
pauseBarPanel = (ViewGroup) view.findViewById(R.id.pause_button_bar);
// Timer buttons
Button startButton = (Button) view.findViewById(R.id.button_start);
startButton.setOnClickListener(this);
Button restButton = (Button) view.findViewById(R.id.button_rest);
restButton.setOnClickListener(this);
mPauseButton = (Button) view.findViewById(R.id.button_pause);
mPauseButton.setOnClickListener(this);
Button restartButton = (Button) view.findViewById(R.id.button_restart);
restartButton.setOnClickListener(this);
Button resetButton = (Button) view.findViewById(R.id.button_reset);
resetButton.setOnClickListener(this);
// Keypad numeric buttons
for (int keypadId : keypadButtons) {
Button keypadButtonId = (Button) view.findViewById(keypadId);
keypadButtonId.setOnClickListener(keypadListener);
}
// Keypad backspace button
ImageButton mDelButton = (ImageButton) view.findViewById(R.id.button_del);
mDelButton.setOnClickListener(this);
// Timer clock view
timerClockView = (ViewGroup) view.findViewById(R.id.timer_clock_view);
// Digital timer view
mMinutesView = (TextView) view.findViewById(R.id.timer_minutes_text_view);
mSecondsView = (TextView) view.findViewById(R.id.timer_seconds_text_view);
mMinutesView.setOnClickListener(timerTextViewListener);
mSecondsView.setOnClickListener(timerTextViewListener);
// For backwards compatibility set this
// near the end
setHasOptionsMenu(true);
return view;
}
public void WorkoutTimer(long millisUntilFinished) {
int countDownInterval = 1000;
new CountDownTimer(millisUntilFinished, countDownInterval) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
// Reset timer
// or run next timer
// (for now only reset timer)
}
}.start();
}
View.OnClickListener keypadListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedButton = v.getId();
for (int digit = 0; digit < keypadButtons.length; ++digit) {
if (selectedButton == keypadButtons[digit]) {
if (mMinutesView.isSelected()) {
if (!firstDigitHasValue) {
setTimerClock(mMinutesView, true, digit);
} else {
setTimerClock(mMinutesView, false, digit);
}
} else if (mSecondsView.isSelected()) {
if (!firstDigitHasValue) {
setTimerClock(mSecondsView, true, digit);
} else {
setTimerClock(mSecondsView, false, digit);
}
}
return;
}
}
}
};
public void setTimerClock(TextView selectedTimerView, boolean b, int i) {
if (b) {
firstDigitHasValue = true;
finalSecondsValue = i;
} else {
firstDigitHasValue = false;
finalSecondsValue = checkValidValue(
concatenateDigits(finalSecondsValue, i)
);
if (selectedTimerView == mMinutesView) {
selectTimerTextView(mSecondsView, mMinutesView);
}
}
selectedTimerView.setText(String.format("%02d", finalSecondsValue));
}
public int concatenateDigits(int second, int first) {
return (second * 10) + first;
}
public int checkValidValue(int userInput) {
if (userInput < 60) {
return userInput;
} else {
return 59;
}
}
View.OnClickListener timerTextViewListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView selectedView = (TextView) v;
if (selectedView == mMinutesView) {
selectTimerTextView(mMinutesView, mSecondsView);
} else if (selectedView == mSecondsView) {
selectTimerTextView(mSecondsView, mMinutesView);
}
}
};
public void selectTimerTextView(TextView selectView, TextView deselectView) {
selectView.setSelected(true);
deselectView.setSelected(false);
selectView.setTextColor(getColor(getContext(), R.color.LightBlue_500));
deselectView.setTextColor(getColor(getContext(), R.color.Black_opacity_87));
firstDigitHasValue = false;
}
@SuppressWarnings("deprecation")
public static int getColor(Context context, int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= Build.VERSION_CODES.M) {
return ContextCompat.getColor(context, id);
} else {
// getColor deprecated on Android Marshmallow(API 23)
return context.getResources().getColor(id);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_start:
animSlidePanelDown(keypadPanel);
animSlidePanelUp(pauseBarPanel);
animSlideClockToCenter(timerClockView);
isRunning = true;
break;
case R.id.button_rest:
animSlidePanelDown(keypadPanel);
animSlidePanelUp(pauseBarPanel);
animSlideClockToCenter(timerClockView);
isRunning = true;
break;
case R.id.button_pause:
mPauseButton.setVisibility(View.INVISIBLE);
isRunning = false;
break;
case R.id.button_restart:
mPauseButton.setVisibility(View.VISIBLE);
isRunning = true;
break;
case R.id.button_reset:
animSlideClockUp(timerClockView);
animSlidePanelDown(pauseBarPanel);
animSlidePanelUp(keypadPanel);
mPauseButton.setVisibility(View.VISIBLE);
isRunning = false;
break;
case R.id.button_del:
// Backspace insert later
break;
default:
break;
}
}
public void animSlideClockToCenter(ViewGroup slideClockToCenter) {
Animation slideToCenter = AnimationUtils.loadAnimation(getContext(), R.anim.timer_clock_slide_to_center);
slideClockToCenter.startAnimation(slideToCenter);
}
public void animSlideClockUp(ViewGroup slideClockUp) {
Animation slideLayoutUp = AnimationUtils.loadAnimation(getContext(), R.anim.timer_clock_slide_up);
slideClockUp.startAnimation(slideLayoutUp);
}
public void animSlidePanelUp(ViewGroup slidePanelUp) {
Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.panel_slide_up);
slidePanelUp.startAnimation(slideUp);
slidePanelUp.setVisibility(View.VISIBLE);
}
public void animSlidePanelDown(ViewGroup slidePanelDown) {
Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.panel_slide_down);
slidePanelDown.startAnimation(slideDown);
slidePanelDown.setVisibility(View.GONE);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_timer, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment;
switch (item.getItemId()) {
case R.id.menu_ic_create_routine:
fragment = new CreateRoutinesFragment();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
return true;
case R.id.menu_ic_settings:
fragment = new SettingsFragment();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package com.marverenic.music.dialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import com.marverenic.music.JockeyApplication;
import com.marverenic.music.R;
import com.marverenic.music.data.store.PlaylistStore;
import com.marverenic.music.instances.Playlist;
import com.marverenic.music.instances.Song;
import com.marverenic.music.utils.Themes;
import java.util.List;
import javax.inject.Inject;
import rx.Observable;
import rx.subjects.BehaviorSubject;
public class CreatePlaylistDialogFragment extends DialogFragment implements TextWatcher {
private static final String SAVED_TITLE = "CreatePlaylistDialogFragment.Name";
private static final String SAVED_SNACKBAR_VIEW = "AppendPlaylistDialogFragment.Snackbar";
@Inject PlaylistStore mPlaylistStore;
private AlertDialog mDialog;
private TextInputLayout mInputLayout;
private AppCompatEditText mEditText;
private BehaviorSubject<Playlist> mSubject = BehaviorSubject.create();
private List<Song> mSongs;
@IdRes private int mSnackbarView;
public static CreatePlaylistDialogFragment newInstance() {
return new CreatePlaylistDialogFragment();
}
public CreatePlaylistDialogFragment setSongs(List<Song> songs) {
mSongs = songs;
return this;
}
public CreatePlaylistDialogFragment showSnackbarIn(@IdRes int viewId) {
mSnackbarView = viewId;
return this;
}
public Observable<Playlist> getCreated() {
return mSubject;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
JockeyApplication.getComponent(this).inject(this);
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (savedInstanceState == null) {
onCreateDialogLayout(null);
} else {
mSnackbarView = savedInstanceState.getInt(SAVED_SNACKBAR_VIEW);
onCreateDialogLayout(savedInstanceState.getString(SAVED_TITLE));
}
mDialog = new AlertDialog.Builder(getContext())
.setTitle(R.string.header_create_playlist)
.setView(mInputLayout)
.setPositiveButton(R.string.action_create, (dialog, which) -> {createPlaylist();})
.setNegativeButton(R.string.action_cancel, null)
.show();
updateDialogButtons(true);
int padding = (int) getResources().getDimension(R.dimen.alert_padding);
((View) mInputLayout.getParent()).setPadding(
padding - mInputLayout.getPaddingLeft(),
padding,
padding - mInputLayout.getPaddingRight(),
mInputLayout.getPaddingBottom());
return mDialog;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SAVED_TITLE, mEditText.getText().toString());
outState.putInt(SAVED_SNACKBAR_VIEW, mSnackbarView);
}
private void onCreateDialogLayout(@Nullable String restoredName) {
mInputLayout = new TextInputLayout(getContext());
mEditText = new AppCompatEditText(getContext());
mEditText.setInputType(InputType.TYPE_CLASS_TEXT);
mEditText.setHint(R.string.hint_playlist_name);
mEditText.setText(restoredName);
mInputLayout.addView(mEditText);
mInputLayout.setErrorEnabled(true);
mEditText.addTextChangedListener(this);
}
private void createPlaylist() {
String name = mEditText.getText().toString();
mSubject.onNext(mPlaylistStore.makePlaylist(name, mSongs));
mSubject.onCompleted();
}
private void updateDialogButtons(boolean error) {
Button button = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setEnabled(!error);
if (error) {
button.setTextColor(ResourcesCompat.getColor(getResources(),
R.color.secondary_text_disabled, getActivity().getTheme()));
} else {
button.setTextColor(Themes.getAccent());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String error = mPlaylistStore.verifyPlaylistName(s.toString());
mInputLayout.setError(error);
mDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(error == null && s.length() > 0);
updateDialogButtons(error != null || s.length() == 0);
}
@Override
public void afterTextChanged(Editable s) {
}
}
|
package balboa;
public class Test
{
/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Yo Yo Yo");
}
}
|
package com.team2052.frckrawler.fragments.scout;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.firebase.crash.FirebaseCrash;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.team2052.frckrawler.R;
import com.team2052.frckrawler.database.metric.MetricValue;
import com.team2052.frckrawler.db.Event;
import com.team2052.frckrawler.db.Metric;
import com.team2052.frckrawler.db.PitDatum;
import com.team2052.frckrawler.db.Robot;
import com.team2052.frckrawler.tba.JSON;
import com.team2052.frckrawler.util.MetricHelper;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.Date;
import java.util.List;
import butterknife.ButterKnife;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class ScoutPitFragment extends BaseScoutFragment {
private static final String TAG = "ScoutPitFragment";
Observable<List<MetricValue>> metricValueObservable = robotObservable()
.map(robot -> {
List<MetricValue> metricValues = Lists.newArrayList();
final QueryBuilder<Metric> metricQueryBuilder = rxDbManager.getMetricsTable().query(MetricHelper.ROBOT_METRICS, null, mEvent.getGame_id(), true);
List<Metric> metrics = metricQueryBuilder.list();
for (int i = 0; i < metrics.size(); i++) {
Metric metric = metrics.get(i);
//Query for existing data
QueryBuilder<PitDatum> matchDataQueryBuilder = rxDbManager.getPitDataTable().query(robot.getId(), metric.getId(), mEvent.getId());
PitDatum currentData = matchDataQueryBuilder.unique();
//Add the metric values
metricValues.add(new MetricValue(metric, currentData == null ? null : JSON.getAsJsonObject(currentData.getData())));
}
return metricValues;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
Observable<String> metricCommentObservable = robotObservable()
.flatMap(robot -> Observable.just(Strings.nullToEmpty(robot.getComments())))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
public static ScoutPitFragment newInstance(Event event) {
Bundle args = new Bundle();
args.putLong(EVENT_ID, event.getId());
ScoutPitFragment fragment = new ScoutPitFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_scouting_pit, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
ButterKnife.bind(this, view);
super.onViewCreated(view, savedInstanceState);
}
@Override
public void updateMetricValues() {
subscriptions.add(metricValueObservable.subscribe(this::setMetricValues, onError -> {
//Most likely part of the robot observable not being initiated, no big deal
if (onError instanceof ArrayIndexOutOfBoundsException) {
return;
}
FirebaseCrash.log("Pit: Error Updating Metric Values");
FirebaseCrash.report(onError);
}));
subscriptions.add(metricCommentObservable.subscribe(RxTextView.text(mCommentsView.getEditText()), onError -> {
//Most likely part of the robot observable not being initiated, no big deal
if (onError instanceof ArrayIndexOutOfBoundsException) {
return;
}
FirebaseCrash.log("Pit: Error Updating Comment");
FirebaseCrash.report(onError);
}));
}
@Override
public Observable<Boolean> getSaveMetricObservable() {
return Observable.combineLatest(
robotObservable(),
Observable.defer(() -> Observable.just(getValues())),
metricCommentObservable,
PitScoutSaveMetric::new)
.map(pitScoutSaveMetric -> {
boolean saved = false;
Robot robot = pitScoutSaveMetric.robot;
for (MetricValue widget : pitScoutSaveMetric.metricValues) {
PitDatum pitDatum = new PitDatum(null);
pitDatum.setRobot(robot);
pitDatum.setMetric(widget.getMetric());
pitDatum.setEvent(mEvent);
//pitDatum.setUser_id(user != null ? user.getId() : null); NOOP
pitDatum.setData(JSON.getGson().toJson(widget.getValue()));
if (rxDbManager.getPitDataTable().insertWithSaved(pitDatum) && !saved)
saved = true;
}
robot.setComments(pitScoutSaveMetric.comment);
robot.setLast_updated(new Date());
robot.update();
return saved;
});
}
public static class PitScoutSaveMetric {
Robot robot;
List<MetricValue> metricValues;
private String comment;
public PitScoutSaveMetric(Robot robot, List<MetricValue> metricValues, String comment) {
this.robot = robot;
this.metricValues = metricValues;
this.comment = comment;
}
}
}
|
package de.fau.cs.mad.kwikshop.android.view;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import javax.inject.Inject;
import butterknife.ButterKnife;
import dagger.ObjectGraph;
import de.fau.cs.mad.kwikshop.android.R;
import de.fau.cs.mad.kwikshop.android.di.KwikShopModule;
import de.fau.cs.mad.kwikshop.android.model.InternetHelper;
import de.fau.cs.mad.kwikshop.android.model.ListStorageFragment;
import de.fau.cs.mad.kwikshop.android.model.SessionHandler;
import de.fau.cs.mad.kwikshop.android.model.messages.MagicSortProgressDialogEvent;
import de.fau.cs.mad.kwikshop.android.model.messages.StartSharingCodeIntentEvent;
import de.fau.cs.mad.kwikshop.android.restclient.RestClientFactory;
import de.fau.cs.mad.kwikshop.android.util.SharedPreferencesHelper;
import de.fau.cs.mad.kwikshop.android.view.interfaces.EditModeActivity;
import de.fau.cs.mad.kwikshop.android.viewmodel.ShoppingListViewModel;
import de.fau.cs.mad.kwikshop.android.viewmodel.common.ViewLauncher;
import de.greenrobot.event.EventBus;
public class ShoppingListActivity extends BaseActivity implements EditModeActivity {
@Inject
RestClientFactory clientFactory;
@Inject
ViewLauncher viewLauncher;
public static final String SHOPPING_LIST_ID = "shopping_list_id";
public static final String SHOPPING_MODE = "shopping_mode";
public static final String EDIT_MODE = "edit_mode";
public Menu menu;
private int listId = -1;
private ShoppingListViewModel viewModel;
private ProgressDialog progressDialog;
public static Intent getIntent(Context context, int shoppingListId) {
Intent intent = new Intent(context, ShoppingListActivity.class);
intent.putExtra(SHOPPING_LIST_ID, shoppingListId);
return intent;
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
// no overflow menu in edit mode
if(!getIntent().getExtras().getBoolean(EDIT_MODE)){
getMenuInflater().inflate(R.menu.overflow_action_menu, menu);
getMenuInflater().inflate(R.menu.shoppinglist_replacement_menu, menu);
// shopping mode is on
if(getIntent().getExtras().getBoolean(SHOPPING_MODE)){
menu.findItem(R.id.action_shopping_mode).setVisible(false);
menu.findItem(R.id.action_shopping_mode_disable).setVisible(true);
}
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu){
MenuItem findLocationItem = menu.findItem(R.id.refresh_current_supermarket);
if(findLocationItem != null){
if(SharedPreferencesHelper.loadBoolean(SharedPreferencesHelper.LOCATION_PERMISSION, false, this))
findLocationItem.setVisible(true);
else
findLocationItem.setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
ItemSortType type = null;
switch (item.getItemId()) {
case R.id.sort_by_magicsort_option:
/* Check if user is logged in */
if(!SessionHandler.isAuthenticated(getApplicationContext())) {
AlertDialog.Builder messageBox = new AlertDialog.Builder(this);
messageBox.setPositiveButton(getResources().getString(android.R.string.ok), null);
messageBox.setMessage(getResources().getString(R.string.magicsort_notloggedin));
messageBox.create().show();
break;
}
/* Check for internet connection */
if(!InternetHelper.checkInternetConnection(this)) {
AlertDialog.Builder messageBox = new AlertDialog.Builder(ShoppingListActivity.this);
messageBox.setPositiveButton(getResources().getString(android.R.string.ok), null);
messageBox.setMessage(R.string.alert_dialog_connection_message);
messageBox.create().show();
break;
}
/* Synchronize if serverId is 0, then start the intent */
startMagicSortIntent = true;
SyncingActivity.requestSync();
break;
case R.id.sort_by_group_option: type = ItemSortType.GROUP; break;
case R.id.sort_by_alphabet_option: type = ItemSortType.ALPHABETICALLY; break;
case R.id.action_shopping_mode:
/* start shopping mode */
viewLauncher.showShoppingListInShoppingMode(listId);
break;
case R.id.action_shopping_mode_disable:
/* end shopping mode */
viewModel.showDialogLeaveShoppingMode(listId);
break;
case R.id.refresh_current_supermarket:
return false;
case R.id.share_option:
/* Check if user is logged in */
if(!SessionHandler.isAuthenticated(getApplicationContext())) {
AlertDialog.Builder messageBox = new AlertDialog.Builder(this);
messageBox.setPositiveButton(getResources().getString(android.R.string.ok), null);
messageBox.setMessage(getResources().getString(R.string.share_notloggedin));
messageBox.create().show();
break;
}
/* Check for internet connection */
if(!InternetHelper.checkInternetConnection(this)) {
AlertDialog.Builder messageBox = new AlertDialog.Builder(ShoppingListActivity.this);
messageBox.setPositiveButton(getResources().getString(android.R.string.ok), null);
messageBox.setMessage(R.string.alert_dialog_connection_message);
messageBox.create().show();
break;
}
/* Synchronize, then start the intent */
int serverIdShare = ListStorageFragment.getLocalListStorage().loadList(listId).getServerId();
if(serverIdShare == 0) {
startSharingCodeIntent = true;
SyncingActivity.requestSync();
} else {
startSharingCodeIntent(serverIdShare);
}
break;
case R.id.action_edit_items:
/* start edit mode */
viewLauncher.showShoppingListInEditMode(listId);
break;
}
if(type != null) EventBus.getDefault().post(type);
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("unused")
public void onEventMainThread(StartSharingCodeIntentEvent event) {
int serverId = ListStorageFragment.getLocalListStorage().loadList(listId).getServerId();
startSharingCodeIntent(serverId);
}
protected void startSharingCodeIntent(final Integer serverId) {
new AsyncTask<Integer, Void, String>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(ShoppingListActivity.this);
progressDialog.setMessage(ShoppingListActivity.this.getResources().getString(R.string.loading));
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
}
@Override
protected String doInBackground(Integer... id) {
try {
if(serverId == null)
return null;
return clientFactory.getShoppingListClient().getSharingCode(serverId.intValue()).getSharingCode();
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(String result) {
if(result == null) {
progressDialog.setMessage(getApplicationContext().getResources().getString(R.string.error));
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
progressDialog.dismiss();
}
}, 1000);
} else {
/* Create intent and send it */
progressDialog.dismiss();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,
String.format(getResources().getString(R.string.share_intentstring), result));
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
}
}.execute();
}
@SuppressWarnings("unused")
public void onEventMainThread(MagicSortProgressDialogEvent event) {
switch(event.getType()) {
case Started:
progressDialog = new ProgressDialog(ShoppingListActivity.this);
progressDialog.setMessage(ShoppingListActivity.this.getResources().getString(R.string.loading));
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
break;
case Failed:
progressDialog.dismiss();
progressDialog = new ProgressDialog(ShoppingListActivity.this);
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
progressDialog.setMessage(getApplicationContext().getResources().getString(R.string.error));
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
progressDialog.dismiss();
}
}, 1000);
break;
case NoPlace:
progressDialog.dismiss();
progressDialog = new ProgressDialog(ShoppingListActivity.this);
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
progressDialog.setMessage(getApplicationContext().getResources().getString(R.string.no_last_location_dialog_message));
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
public void run() {
progressDialog.dismiss();
}
}, 1000);
break;
case Success:
progressDialog.hide();
progressDialog.dismiss();
SyncingActivity.requestSync();
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.inject(this);
ObjectGraph objectGraph = ObjectGraph.create(new KwikShopModule(this));
viewModel = objectGraph.get(ShoppingListViewModel.class);
objectGraph.inject(this);
//Get Shopping List ID
listId = -1;
Bundle extras = getIntent().getExtras();
if (extras != null) {
listId = extras.getInt(SHOPPING_LIST_ID);
if(extras.getBoolean(EDIT_MODE)){
showCustomActionBar();
}
}
if (savedInstanceState == null) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(frameLayout.getId(), ShoppingListFragment.newInstance(listId)).commit();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
// check for barcode scanner fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
Fragment BarcodeScannerFragment = fragmentManager.findFragmentByTag("BARCODE_SCANNER_FRAGMENT");
if (BarcodeScannerFragment != null && BarcodeScannerFragment.isVisible()) {
startActivity(getIntent().putExtra(ShoppingListFragment.DO_NOT_ASK_FOR_SUPERMARKET, true));
return;
}
// check for shopping mode
if(baseViewModel.isShoppingModeEnabled()){
viewModel.showDialogLeaveShoppingMode(listId);
return;
}
}
protected void showCustomActionBar() {
//hide default action bar
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
//show custom action bar
View view = getLayoutInflater().inflate(R.layout.actionbar_edit_mode, null);
actionBar.setCustomView(view);
}
@Override
public ImageButton getSaveButton() {
ActionBar actionBar = getSupportActionBar();
return (ImageButton) actionBar.getCustomView().findViewById(R.id.button_save);
}
@Override
public ImageButton getDeleteButton() {
ActionBar actionBar = getSupportActionBar();
return (ImageButton) actionBar.getCustomView().findViewById(R.id.button_remove);
}
@Override
public ImageButton getAddToShoppingCartButton() {
ActionBar actionBar = getSupportActionBar();
return (ImageButton) actionBar.getCustomView().findViewById(R.id.button_add_to_cart);
}
@Override
public ImageButton getRemoveFromShoppingCartButton() {
ActionBar actionBar = getSupportActionBar();
return (ImageButton) actionBar.getCustomView().findViewById(R.id.button_remove_from_cart);
}
@Override
public TextView getMarkedItemsCountTextView() {
ActionBar actionBar = getSupportActionBar();
return (TextView) actionBar.getCustomView().findViewById(R.id.textView_marked_items_count);
}
}
|
package de.fau.cs.mad.kwikshop.android.view;
//import android.app.Fragment;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.ListAdapter;
import android.support.v4.app.Fragment;
import android.widget.ScrollView;
import com.melnykov.fab.FloatingActionButton;
import com.nhaarman.listviewanimations.itemmanipulation.DynamicListView;
import com.nhaarman.listviewanimations.itemmanipulation.dragdrop.OnItemMovedListener;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.OnDismissCallback;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.SimpleSwipeUndoAdapter;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.undo.TimedUndoAdapter;
import butterknife.ButterKnife;
import butterknife.*;
import dagger.ObjectGraph;
import de.fau.cs.mad.kwikshop.android.R;
import de.fau.cs.mad.kwikshop.android.common.*;
import de.fau.cs.mad.kwikshop.android.model.*;
import de.fau.cs.mad.kwikshop.android.model.messages.*;
import de.fau.cs.mad.kwikshop.android.model.mock.SpaceTokenizer;
import de.fau.cs.mad.kwikshop.android.view.binding.ButtonBinding;
import de.fau.cs.mad.kwikshop.android.view.binding.ListViewItemCommandBinding;
import de.fau.cs.mad.kwikshop.android.viewmodel.ShoppingListViewModel;
import de.fau.cs.mad.kwikshop.android.viewmodel.common.*;
import de.fau.cs.mad.kwikshop.android.viewmodel.common.ObservableArrayList;
import de.fau.cs.mad.kwikshop.android.viewmodel.di.KwikShopViewModelModule;
import de.greenrobot.event.EventBus;
public class ShoppingListFragment
extends Fragment
implements ShoppingListViewModel.Listener, ObservableArrayList.Listener<Item> {
private static final String ARG_LISTID = "list_id";
private int listID = -1;
private AutoCompletionHelper autoCompletion;
private ShoppingListViewModel viewModel;
private boolean updatingViewModel;
@InjectView(R.id.list_shoppingList)
DynamicListView shoppingListView;
@InjectView(R.id.list_shoppingListBought)
DynamicListView shoppingListViewBought;
@InjectView(R.id.textView_quickAdd)
MultiAutoCompleteTextView textView_QuickAdd;
@InjectView(R.id.fab)
FloatingActionButton floatingActionButton;
@InjectView(R.id.button_quickAdd)
View button_QuickAdd;
@InjectView(R.id.shoppinglist_scrollview)
ScrollView scrollView;
public static ShoppingListFragment newInstance(int listID) {
ShoppingListFragment fragment = new ShoppingListFragment();
Bundle args = new Bundle();
args.putInt(ARG_LISTID, listID);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
listID = getArguments().getInt(ARG_LISTID);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
EventBus.getDefault().register(this);
new ListStorageFragment().SetupLocalListStorageFragment(getActivity());
View rootView = inflater.inflate(R.layout.fragment_shoppinglist, container, false);
ButterKnife.inject(this, rootView);
ObjectGraph objectGraph = ObjectGraph.create(new KwikShopViewModelModule(getActivity()));
DisplayHelper displayHelper = objectGraph.get(DisplayHelper.class);
viewModel = objectGraph.get(ShoppingListViewModel.class);
autoCompletion = objectGraph.get(AutoCompletionHelper.class);
viewModel.initialize(this.listID);
getActivity().setTitle(viewModel.getName());
viewModel.addListener(this);
viewModel.getItems().addListener(this);
viewModel.getBoughtItems().addListener(this);
ShoppingListAdapter shoppingListAdapter = new ShoppingListAdapter(getActivity(), viewModel,
viewModel.getItems(), displayHelper);
shoppingListView.setAdapter(shoppingListAdapter);
new ListViewItemCommandBinding(ListViewItemCommandBinding.ListViewItemCommandType.Click,
shoppingListView,
viewModel.getSelectItemCommand());
SimpleSwipeUndoAdapter swipeUndoAdapter = new TimedUndoAdapter(shoppingListAdapter, getActivity(),
new OnDismissCallback() {
@Override
public void onDismiss(@NonNull final ViewGroup listView, @NonNull final int[] reverseSortedPositions) {
Command<Integer> command = viewModel.getToggleIsBoughtCommand();
for (int position : reverseSortedPositions) {
if (command.getCanExecute()) {
try {
Item item = viewModel.getItems().get(position);
command.execute(item.getId());
} catch (IndexOutOfBoundsException ex) {
//nothing to do
}
}
}
}
});
swipeUndoAdapter.setAbsListView(shoppingListView);
shoppingListView.setAdapter(swipeUndoAdapter);
shoppingListView.enableSimpleSwipeUndo();
shoppingListView.enableDragAndDrop();
shoppingListView.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
//disable events on observable list during drag&drop to prevent lag
//IMPORTANT: Make sure to reenable events afterwards
viewModel.getItems().disableEvents();
scrollView.requestDisallowInterceptTouchEvent(true);
shoppingListView.startDragging(position);
//sets value of the Spinner to the first entry, in this case Manual
return true;
}
}
);
shoppingListView.setOnItemMovedListener(new OnItemMovedListener() {
@Override
public void onItemMoved(int i, int i1) {
viewModel.itemsSwapped(i, i1);
//IMPORTANT: reenable events of the observable list after drag and drop has finished
viewModel.getItems().enableEvents();
}
});
justifyListViewHeightBasedOnChildren(shoppingListView);
shoppingListViewBought.enableSwipeToDismiss(
new OnDismissCallback() {
@Override
public void onDismiss(@NonNull final ViewGroup listView, @NonNull final int[] reverseSortedPositions) {
Command<Integer> command = viewModel.getToggleIsBoughtCommand();
for (int position : reverseSortedPositions) {
if (command.getCanExecute()) {
Item item = viewModel.getBoughtItems().get(position);
command.execute(item.getId());
}
}
}
});
shoppingListViewBought.setAdapter(new ShoppingListAdapter(getActivity(), viewModel, viewModel.getBoughtItems(), displayHelper));
shoppingListViewBought.setOnItemMovedListener(new OnItemMovedListener() {
@Override
public void onItemMoved(int i, int i1) {
viewModel.boughtItemsSwapped(i, i1);
}
});
shoppingListViewBought.enableDragAndDrop();
justifyListViewHeightBasedOnChildren(shoppingListViewBought);
new ButtonBinding(floatingActionButton, viewModel.getAddItemCommand(), false);
new ButtonBinding(button_QuickAdd, viewModel.getQuickAddCommand());
//TODO: quick add long click
textView_QuickAdd.setFocusableInTouchMode(true);
textView_QuickAdd.requestFocus();
textView_QuickAdd.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
synchronized (viewModel) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
viewModel.getQuickAddCommand().execute(null);
return true;
}
return false;
}
}
});
textView_QuickAdd.setTokenizer(new SpaceTokenizer());
RegularlyRepeatHelper.getRegularlyRepeatHelper(getActivity()); // to make sure it is initialized when needed in ShoppingListViewModel
refreshQuickAddAutoCompletion();
disableFloatingButtonWhileSoftKeyboardIsShown();
return rootView;
}
@Override
public void onResume() {
super.onResume();
Window window = getActivity().getWindow();
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
@Override
public void onDestroyView() {
super.onDestroyView();
viewModel.onDestroyView();
EventBus.getDefault().unregister(this);
}
/**
* call this method to initialize or refresh the data used by QuickAdd's auto completion
*/
private void refreshQuickAddAutoCompletion() {
textView_QuickAdd.setAdapter(autoCompletion.getNameAdapter(getActivity()));
}
private void disableFloatingButtonWhileSoftKeyboardIsShown() {
final View activityRootView = BaseActivity.frameLayout;
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//r will be populated with the coordinates of your view that area still visible.
Rect r = new Rect();
activityRootView.getWindowVisibleDisplayFrame(r);
int screenHeight = activityRootView.getRootView().getHeight();
// r.bottom is the position above soft keypad or device button.
// if keypad is shown, the r.bottom is smaller than that before.
int keypadHeight = screenHeight - r.bottom;
if (keypadHeight > screenHeight * 0.15) {
//hide right away (fade out animation looks weird if the keyboard is showing up at the same moment)
floatingActionButton.setVisibility(View.GONE);
floatingActionButton.hide();
} else {
//make visible so ew can see the fade in animation
floatingActionButton.setVisibility(View.VISIBLE);
floatingActionButton.show();
}
}
});
}
public void justifyListViewHeightBasedOnChildren(DynamicListView listView) {
ListAdapter adapter = listView.getAdapter();
if (adapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < adapter.getCount(); i++) {
View listItem = adapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams par = listView.getLayoutParams();
par.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
listView.setLayoutParams(par);
listView.requestLayout();
}
public void onEvent(AutoCompletionHistoryDeletedEvent event) {
if (autoCompletion != null) {
refreshQuickAddAutoCompletion();
}
}
@OnTextChanged(R.id.textView_quickAdd)
@SuppressWarnings("unused")
public void textView_ShoppingListName_OnTextChanged(CharSequence s) {
synchronized (viewModel) {
//send updated value for shopping list name to the view model
updatingViewModel = true;
viewModel.setQuickAddText(s != null ? s.toString() : "");
updatingViewModel = false;
}
}
@Override
public void onQuickAddTextChanged() {
if (!updatingViewModel) {
this.textView_QuickAdd.setText(viewModel.getQuickAddText());
}
}
@Override
public void onItemSortTypeChanged() {
}
@Override
public void onNameChanged(String value) {
// set title for actionbar
getActivity().setTitle(viewModel.getName());
}
@Override
public void onFinish() {
}
@Override
public void onItemAdded(Item newItem) {
//TODO: It might make sense to move autocompletion handling to the view model
//IMPORTANT
if(autoCompletion != null) {
refreshQuickAddAutoCompletion();
}
justifyListViewHeightBasedOnChildren(shoppingListView);
justifyListViewHeightBasedOnChildren(shoppingListViewBought);
}
@Override
public void onItemRemoved(Item removedItem) {
justifyListViewHeightBasedOnChildren(shoppingListView);
justifyListViewHeightBasedOnChildren(shoppingListViewBought);
}
@Override
public void onItemModified(Item modifiedItem) {
justifyListViewHeightBasedOnChildren(shoppingListView);
justifyListViewHeightBasedOnChildren(shoppingListViewBought);
}
}
|
package de.tum.in.securebitcoinwallet.smartcard;
import android.content.Context;
import de.tum.in.securebitcoinwallet.smartcard.exception.AppletAlreadyInitializedException;
import de.tum.in.securebitcoinwallet.smartcard.exception.AppletNotInitializedException;
import de.tum.in.securebitcoinwallet.smartcard.exception.AuthenticationFailedExeption;
import de.tum.in.securebitcoinwallet.smartcard.exception.KeyNotFoundException;
import de.tum.in.securebitcoinwallet.smartcard.exception.KeyStoreFullException;
import de.tum.in.securebitcoinwallet.smartcard.exception.SmartcardException;
import de.tum.in.securebitcoinwallet.smartcard.exception.SmartcardRuntimeException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.ECPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
/**
* Manager providing functions for the communication with the smartcard.
*
* @author Benedikt Schlagberger
*/
public class SmartCardManager {
private final SmartCard smartCard;
/**
* Constructor. Initializes the smartcard and manages its state.
*/
public SmartCardManager(Context context) {
this.smartCard = new SmartCard(context);
}
/**
* Triggers the setup feature on the smartcard.
*
* @return The PUK of the smartcard.
* @throws SmartcardException If the card could not be found or is not connected.
* @throws AppletAlreadyInitializedException If the applet has already been initialized.
*/
public byte[] setup() throws SmartcardException {
APDUCommand setupInstruction =
new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA, AppletInstructions.INS_SETUP,
(byte) 0, (byte) 0);
APDUResponse response = smartCard.sendAPDU(setupInstruction);
closeSession();
if (!response.wasSuccessful()) {
short statusCode = response.getStatusCode();
switch (statusCode) {
case StatusCodes.COMMAND_NOT_ALLOWED:
throw new AppletAlreadyInitializedException();
default:
throw new SmartcardRuntimeException("Unknown Statuscode: " + statusCode);
}
}
closeSession();
return response.getData();
}
/**
* Generates a new public and private keypair on the smartcard. The private key is stored on the
* card, the public key is returned. After generation, the private key can be used to sign
* messages by using the bitcoin address calculated from the returned public key.
*
* @return The public key of the generated keypair.
* @throws SmartcardException If the communication with the card failed
* @throws AppletNotInitializedException If the applet has not been initialized yet. This can be
* done with {@link #setup()}.
*/
public PublicKey generateNewKey() throws SmartcardException {
authenticate();
APDUCommand generateKeyCommand = new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_GENERATE_KEY, (byte) 0, (byte) 0);
APDUResponse response = smartCard.sendAPDU(generateKeyCommand);
if (!response.wasSuccessful()) {
throw new RuntimeException(
"Error during key generation. Unknown statuscode: " + response.getStatusCode());
}
PublicKey publicKey;
try {
publicKey =
KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(response.getData()));
} catch (InvalidKeySpecException e) {
throw new RuntimeException("Could not convert key!", e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Algorithm not found!", e);
}
// Lock the card.
closeSession();
return publicKey;
}
/**
* Imports the given private key into the keystore on the smartcard.
*
* @param privateKey The private key to import. Has to be 256 bits.
* @param bitcoinAddress The Bitcoin address of the private key. // TODO: calculate?
* @throws KeyStoreFullException If no more space is left on the smartcard
* @throws SmartcardException If communication with the smartcard failed
*/
public void importKey(ECPrivateKey privateKey, String bitcoinAddress) throws SmartcardException {
byte[] secret = privateKey.getS().toByteArray();
if (secret.length != 32) {
throw new RuntimeException("Private key has wrong length!");
}
byte[] address = bitcoinAddress.getBytes();
validateBitcoinAddress(address);
authenticate();
APDUCommand importKeyCommand = new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_IMPORT_PRIVATE_KEY, (byte) address.length, (byte) secret.length,
address);
importKeyCommand.appendData(secret);
APDUResponse response = smartCard.sendAPDU(importKeyCommand);
if (!response.wasSuccessful()) {
switch (response.getStatusCode()) {
case StatusCodes.KEYSTORE_FULL:
throw new KeyStoreFullException();
default:
throw new SmartcardRuntimeException(
"Error during import. Unknown statuscode: " + response.getStatusCode());
}
}
// Lock the card.
closeSession();
}
/**
* Gets the encrypted private key for the given Bitcoin address from the card.
*
* @param bitcoinAddress The Bitcoin address for which the private key will be fetched.
* @return The encrypted private key
* @throws SmartcardException If communication with the smartcard failed
* @throws KeyNotFoundException If the requested key could not be found
*/
public byte[] exportEncryptedPrivateKey(String bitcoinAddress) throws SmartcardException {
byte[] address = bitcoinAddress.getBytes();
validateBitcoinAddress(address);
authenticate();
APDUCommand exportKeyCommand = new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_GET_PRIVATE_KEY, (byte) 0x00, (byte) 0x00, address);
APDUResponse response = smartCard.sendAPDU(exportKeyCommand);
if (!response.wasSuccessful()) {
switch (response.getStatusCode()) {
case StatusCodes.KEY_NOT_FOUND:
throw new RuntimeException("KeySelection failed.");
default:
throw new SmartcardRuntimeException(
"Error during export. Unknown statuscode: " + response.getStatusCode());
}
}
// Lock the card.
closeSession();
return response.getData();
}
/**
* Deletes the private key specified by the given Bitcoin address.
*
* @param bitcoinAddress The Bitcoin address for which the key should be deleted
* @throws SmartcardException If communication with the smartcard failed
*/
public void deleteKey(String bitcoinAddress) throws SmartcardException {
byte[] address = bitcoinAddress.getBytes();
validateBitcoinAddress(address);
authenticate();
APDUCommand deleteKeyCommand = new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_DELETE_PRIVATE_KEY, (byte) 0x00, (byte) 0x00, address);
APDUResponse response = smartCard.sendAPDU(deleteKeyCommand);
if (!response.wasSuccessful()) {
throw new SmartcardRuntimeException(
"Error during key deletion. Unknown statuscode: " + response.getStatusCode());
}
// Lock the card.
closeSession();
}
/**
* Signs the given transaction.
*
* @param hash The SHA-256 hash to sign. Has to be 32 bytes.
* @param bitcoinAddress The Bitcoin address of which the private key should be used to sign the
* hash
* @return The signature of the transaction
* @throws KeyNotFoundException If the key for the Bitcoin address could not be found.
* @throws SmartcardException If communication with the smartcard failed
*/
public byte[] signSHA256Hash(byte[] hash, String bitcoinAddress) throws SmartcardException {
// SHA256 has 256 bits.
if (hash.length != 32) {
throw new RuntimeException("Incorrect hash length");
}
authenticate();
selectPrivateKey(bitcoinAddress.getBytes());
APDUCommand signCommand = new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_SIGN_SHA256_HASH, (byte) 0, (byte) 0, hash);
APDUResponse response = smartCard.sendAPDU(signCommand);
if (!response.wasSuccessful()) {
switch (response.getStatusCode()) {
case StatusCodes.CONDITIONS_NOT_SATISFIED:
throw new SmartcardRuntimeException("KeySelection failed.");
default:
throw new SmartcardRuntimeException(
"Error during signing. Unknown statuscode: " + response.getStatusCode());
}
}
// Lock the card.
closeSession();
return response.getData();
}
/**
* Changes the PIN to the desired value.
*
* @param newPin The new PIN
* @throws SmartcardException If communication with the smartcard failed
*/
public void changePIN(byte[] newPin) throws SmartcardException {
if (newPin.length > 8 || newPin.length < 4) {
throw new RuntimeException("PIN has wrong length. May only be between 4 and 8 characters");
}
authenticate();
APDUCommand changePINCommand = new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_CHANGE_PIN, (byte) 0, (byte) 0, newPin);
APDUResponse response = smartCard.sendAPDU(changePINCommand);
if (!response.wasSuccessful()) {
throw new SmartcardRuntimeException(
"Error during changing PIN. Unknown statuscode: " + response.getStatusCode());
}
}
/**
* Unlocks the card if the PIN has been entered wrong too many times.
*
* @param puk The PUK from the setup feature
* @param newPin The new PIN
* @throws AuthenticationFailedExeption If the PUk is wrong
* @throws SmartcardException If communication with the smartcard failed
*/
public void unlock(byte[] puk, byte[] newPin) throws SmartcardException {
if (puk.length != 8) {
throw new RuntimeException("PUK has wrong length! Has to be 8 characters");
}
if (newPin.length < 4 || newPin.length > 8) {
throw new RuntimeException("New PIN has wrong length! Has to be between 4 and 8 characters");
}
APDUCommand unlockCommand =
new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA, AppletInstructions.INS_UNLOCK,
(byte) puk.length, (byte) newPin.length, puk);
unlockCommand.appendData(newPin);
APDUResponse response = smartCard.sendAPDU(unlockCommand);
if (!response.wasSuccessful()) {
switch (response.getStatusCode()) {
case StatusCodes.AUTH_FAILED:
throw new AuthenticationFailedExeption();
default:
throw new SmartcardRuntimeException(
"Error during unlock. Unknown statuscode: " + response.getStatusCode());
}
}
}
/**
* Gets the remaining free slots for private keys.
*
* @throws SmartcardException If communication with the smartcard failed.
*/
public int getFreeSlots() throws SmartcardException {
APDUCommand getFreeSlotsCommand = new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_GET_REMAINING_MEMORY, (byte) 0, (byte) 0);
APDUResponse response = smartCard.sendAPDU(getFreeSlotsCommand);
if (!response.wasSuccessful()) {
throw new SmartcardRuntimeException(
"Error during requesting free slots. Unknown statuscode: " + response.getStatusCode());
}
// Lock the card.
closeSession();
byte[] data = response.getData();
return (data[0] << 8) + data[1];
}
/**
* Validates the given Bitcoin address.
*
* @param address The Bitcoin address to validate.
*/
private void validateBitcoinAddress(byte[] address) {
if (address.length < 26 || address.length > 35) {
throw new RuntimeException("Bitcoin address is faulty");
}
}
/**
* Selects the private key of the given address for the signing process.
*
* @param bitcoinAddress The bitcoin address for which the private key will be selected.
* @throws KeyNotFoundException If the key for the given address could not be found.
* @throws SmartcardException If communication with the card failed.
*/
private void selectPrivateKey(byte[] bitcoinAddress) throws SmartcardException {
if (bitcoinAddress.length < 20 || bitcoinAddress.length > 40) {
throw new RuntimeException("Bitcoin address has wrong length: " + new String(bitcoinAddress));
}
APDUCommand selectKeyCommand = new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_SELECT_KEY, (byte) 0, (byte) 0, bitcoinAddress);
APDUResponse response = smartCard.sendAPDU(selectKeyCommand);
if (!response.wasSuccessful()) {
switch (response.getStatusCode()) {
case StatusCodes.KEY_NOT_FOUND:
throw new KeyNotFoundException();
case StatusCodes.PIN_VERIFICATION_REQUIRED:
throw new SmartcardRuntimeException("PIN not validated. Should not have happened");
default:
throw new SmartcardRuntimeException("Unknown statuscode: " + response.getStatusCode());
}
}
}
/**
* Authenticates with the given PIN. Shows a dialog asking the user for the PIN.
*
* @throws SmartcardException If the communication with the card failed.
*/
private void authenticate() throws SmartcardException {
if (isPINValidated()) {
return;
}
APDUCommand authenticateCommand = new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_AUTHENTICATE, (byte) 0, (byte) 0, getPINFromUser());
APDUResponse response = smartCard.sendAPDU(authenticateCommand);
if (!response.wasSuccessful()) {
switch (response.getStatusCode()) {
case StatusCodes.CARD_LOCKED:
// TODO: unlock
break;
case StatusCodes.AUTH_FAILED:
// TODO: retry?
break;
default:
throw new SmartcardRuntimeException("Unknown statuscode: " + response.getStatusCode());
}
}
}
/**
* Checks whether the user is authenticated at the card.
*
* @return True, if the user is authenticated and may perform secure operations.
* @throws SmartcardException If the communication with the card failed.
* @throws AppletNotInitializedException If the applet has not been initialized yet
*/
private boolean isPINValidated() throws SmartcardException {
APDUCommand checkAuthenticationCommand =
new APDUCommand(AppletInstructions.SECURE_BITCOIN_WALLET_CLA,
AppletInstructions.INS_PIN_VALIDATED, (byte) 0, (byte) 0);
APDUResponse response = smartCard.sendAPDU(checkAuthenticationCommand);
if (!response.wasSuccessful()) {
switch (response.getStatusCode()) {
case StatusCodes.CONDITIONS_NOT_SATISFIED:
throw new AppletNotInitializedException();
default:
throw new SmartcardRuntimeException("Unknown statuscode: " + response.getStatusCode());
}
}
return response.getData()[0] != 0;
}
/**
* Has to be called after operations using the pin.
*/
private void closeSession() {
smartCard.closeSession();
}
/**
* TODO
*/
private byte[] getPINFromUser() {
// TODO implement
return new byte[0];
}
}
|
package info.nightscout.androidaps.plugins.PumpCombo;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import de.jotomo.ruffy.spi.BasalProfile;
import de.jotomo.ruffy.spi.BolusProgressReporter;
import de.jotomo.ruffy.spi.CommandResult;
import de.jotomo.ruffy.spi.PumpState;
import de.jotomo.ruffy.spi.PumpWarningCodes;
import de.jotomo.ruffy.spi.RuffyCommands;
import de.jotomo.ruffy.spi.history.Bolus;
import de.jotomo.ruffy.spi.history.PumpHistory;
import de.jotomo.ruffy.spi.history.PumpHistoryRequest;
import de.jotomo.ruffy.spi.history.Tbr;
import de.jotomo.ruffy.spi.history.WarningOrErrorCode;
import de.jotomo.ruffyscripter.RuffyCommandsV1Impl;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.PumpCombo.events.EventComboPumpUpdateGUI;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import static de.jotomo.ruffy.spi.BolusProgressReporter.State.FINISHED;
public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(ComboPlugin.class);
private static ComboPlugin plugin = null;
private boolean fragmentEnabled = false;
private boolean fragmentVisible = false;
private final static PumpDescription pumpDescription = new PumpDescription();
static {
// these properties can't be changed on the pump, some via desktop configuration software
pumpDescription.isBolusCapable = true;
pumpDescription.bolusStep = 0.1d;
pumpDescription.isExtendedBolusCapable = false;
pumpDescription.extendedBolusStep = 0.1d;
pumpDescription.extendedBolusDurationStep = 15;
pumpDescription.extendedBolusMaxDuration = 12 * 60;
pumpDescription.isTempBasalCapable = true;
pumpDescription.tempBasalStyle = PumpDescription.PERCENT;
pumpDescription.maxTempPercent = 500;
pumpDescription.tempPercentStep = 10;
pumpDescription.tempDurationStep = 15;
pumpDescription.tempMaxDuration = 24 * 60;
pumpDescription.isSetBasalProfileCapable = false;
pumpDescription.basalStep = 0.01d;
pumpDescription.basalMinimumRate = 0.0d;
pumpDescription.isRefillingCapable = true;
}
@NonNull
private final RuffyCommands ruffyScripter;
private static ComboPump pump = new ComboPump();
private volatile boolean bolusInProgress;
private volatile boolean cancelBolus;
private Bolus lastRequestedBolus;
private long pumpHistoryLastChecked;
public static ComboPlugin getPlugin() {
if (plugin == null)
plugin = new ComboPlugin();
return plugin;
}
private static PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult()
.success(false).enacted(false).comment(MainApp.sResources.getString(R.string.combo_pump_unsupported_operation));
private ComboPlugin() {
ruffyScripter = RuffyCommandsV1Impl.getInstance(MainApp.instance());
}
public ComboPump getPump() {
return pump;
}
@Override
public String getFragmentClass() {
return ComboFragment.class.getName();
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.combopump);
}
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.combopump_shortname);
if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
// use long name as fallback
return getName();
}
String getStateSummary() {
PumpState ps = pump.state;
if (ps.activeAlert != null) {
return ps.activeAlert.errorCode != null
? "E" + ps.activeAlert.errorCode + ": " + ps.activeAlert.message
: "W" + ps.activeAlert.warningCode + ": " + ps.activeAlert.message;
} else if (ps.menu == null)
return MainApp.sResources.getString(R.string.combo_pump_state_disconnected);
else if (ps.suspended && (ps.batteryState == PumpState.EMPTY || ps.insulinState == PumpState.EMPTY))
return MainApp.sResources.getString(R.string.combo_pump_state_suspended_due_to_error);
else if (ps.suspended)
return MainApp.sResources.getString(R.string.combo_pump_state_suspended_by_user);
return MainApp.sResources.getString(R.string.combo_pump_state_running);
}
@Override
public boolean isEnabled(int type) {
if (type == PluginBase.PUMP) return fragmentEnabled;
else if (type == PluginBase.CONSTRAINTS) return fragmentEnabled;
return false;
}
@Override
public boolean isVisibleInTabs(int type) {
return type == PUMP && fragmentVisible;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public boolean hasFragment() {
return true;
}
@Override
public boolean showInList(int type) {
return true;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == PUMP) this.fragmentEnabled = fragmentEnabled;
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == PUMP) this.fragmentVisible = fragmentVisible;
}
@Override
public int getPreferencesId() {
return R.xml.pref_combo;
}
@Override
public int getType() {
return PluginBase.PUMP;
}
@Override
public boolean isInitialized() {
return pump.initialized;
}
@Override
public boolean isSuspended() {
return pump.state.suspended;
}
@Override
public boolean isBusy() {
return ruffyScripter.isPumpBusy();
}
@Override
public synchronized int setNewBasalProfile(Profile profile) {
if (!isInitialized()) {
log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.sResources.getString(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
return PumpInterface.FAILED;
}
BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile);
if (pump.basalProfile.equals(requestedBasalProfile)) {
//dismiss previously "FAILED" overview notifications
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
return PumpInterface.NOT_NEEDED;
}
CommandResult setResult = runCommand(MainApp.sResources.getString(R.string.combo_activity_setting_basal_profile), 0,
() -> ruffyScripter.setBasalProfile(requestedBasalProfile));
if (!setResult.success) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.sResources.getString(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
return PumpInterface.FAILED;
}
CommandResult readResult = runCommand(MainApp.sResources.getString(R.string.combo_activity_setting_basal_profile), 0,
ruffyScripter::readBasalProfile);
pump.basalProfile = readResult.basalProfile;
if(readResult.success && readResult.basalProfile.equals(requestedBasalProfile)){
//dismiss previously "FAILED" overview notifications
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
//issue success notification
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.sResources.getString(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
return PumpInterface.SUCCESS;
} else {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.sResources.getString(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
return PumpInterface.FAILED;
}
}
@Override
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized())
return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS
if (pump.basalProfile == null)
return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS
return pump.basalProfile.equals(convertProfileToComboProfile(profile));
}
@NonNull
private BasalProfile convertProfileToComboProfile(Profile profile) {
BasalProfile basalProfile = new BasalProfile();
for (int i = 0; i < 24; i++) {
double rate = profile.getBasal(Integer.valueOf(i * 60 * 60));
/*The Combo pump does hava a different granularity for basal rate:
* 0.01 - if below 1U/h
* 0.05 - if above 1U/h
* */
if(rate < 1){
//round to 0.01 granularity;
rate = Math.round(rate/0.01)*0.01;
} else {
//round to 0.05 granularity;
rate = Math.round(rate/0.05)*0.05;
}
basalProfile.hourlyRates[i] = rate;
}
return basalProfile;
}
@NonNull
@Override
public Date lastDataTime() {
return new Date(pump.lastSuccessfulCmdTime);
}
/**
* Runs pump initializing if needed, checks for boluses given on the pump, updates the
* reservoir level and checks the running TBR on the pump.
*/
@Override
public synchronized void refreshDataFromPump(String reason) {
log.debug("RefreshDataFromPump called");
if (!pump.initialized) {
long maxWait = System.currentTimeMillis() + 15 * 1000;
while (!ruffyScripter.isPumpAvailable()) {
log.debug("Waiting for ruffy service to come up ...");
SystemClock.sleep(100);
if (System.currentTimeMillis() > maxWait) {
log.debug("ruffy service unavailable, wtf");
return;
}
}
}
CommandResult stateResult = runCommand(pump.initialized ? MainApp.sResources.getString(R.string.combo_pump_action_refreshing) : MainApp.sResources.getString(R.string.combo_pump_action_initializing),
1, ruffyScripter::readReservoirLevelAndLastBolus);
if (!stateResult.success) {
return;
}
// ensure time and date(!) are current; connect triggers a notification on mismatch
/* menu not supported by ruffy v1
if (!pump.initialized) {
if (!runCommand("Updating pump clock", 2, ruffyScripter::setDateAndTime).success) {
return;
}
}
*/
// read basal profile into cache
if (!pump.initialized) {
CommandResult readBasalResult = runCommand("Reading basal profile", 2, ruffyScripter::readBasalProfile);
if (!readBasalResult.success) {
return;
}
pump.basalProfile = readBasalResult.basalProfile;
}
if (!checkPumpHistory()) {
return;
}
if (!pump.initialized) {
pump.initialized = true;
MainApp.bus().post(new EventInitializationChanged());
}
// ComboFragment updates state fully only after the pump has initialized,
// this fetches state again and updates the UI proper
runCommand(null, 0, ruffyScripter::readPumpState);
}
private void updateLocalData(CommandResult result) {
if (result.reservoirLevel != PumpState.UNKNOWN) {
pump.reservoirLevel = result.reservoirLevel;
}
if (result.lastBolus != null) {
pump.lastBolus = result.lastBolus;
} else if (result.history != null && !result.history.bolusHistory.isEmpty()) {
pump.lastBolus = result.history.bolusHistory.get(0);
}
if (result.state.menu != null) {
pump.state = result.state;
}
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
@Override
public double getBaseBasalRate() {
int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
return pump.basalProfile.hourlyRates[currentHour];
}
private static BolusProgressReporter nullBolusProgressReporter = (state, percent, delivered) -> {
};
private static BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> {
EventOverviewBolusProgress event = EventOverviewBolusProgress.getInstance();
switch (state) {
case PROGRAMMING:
event.status = MainApp.sResources.getString(R.string.combo_programming_bolus);
break;
case DELIVERING:
event.status = String.format(MainApp.sResources.getString(R.string.bolusdelivering), delivered);
break;
case DELIVERED:
event.status = String.format(MainApp.sResources.getString(R.string.bolusdelivered), delivered);
break;
case STOPPING:
event.status = MainApp.sResources.getString(R.string.bolusstopping);
break;
case STOPPED:
event.status = MainApp.sResources.getString(R.string.bolusstopped);
break;
case FINISHED:
// no state, just percent below to close bolus progress dialog
break;
}
event.percent = percent;
MainApp.bus().post(event);
};
/**
* Updates Treatment records with carbs and boluses and delivers a bolus if needed
*/
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
try {
if (detailedBolusInfo.insulin == 0 && detailedBolusInfo.carbs == 0) {
// neither carbs nor bolus requested
log.error("deliverTreatment: Invalid input");
return new PumpEnactResult().success(false).enacted(false)
.bolusDelivered(0d).carbsDelivered(0d)
.comment(MainApp.instance().getString(R.string.danar_invalidinput));
} else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it
return deliverBolus(detailedBolusInfo);
} else {
// no bolus required, carb only treatment
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
bolusingEvent.percent = 100;
MainApp.bus().post(bolusingEvent);
return new PumpEnactResult().success(true).enacted(true)
.bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs)
.comment(MainApp.instance().getString(R.string.virtualpump_resultok));
}
} finally {
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
}
@NonNull
private PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) {
// guard against boluses issued multiple times within a minute
if (lastRequestedBolus != null
&& Math.abs(lastRequestedBolus.amount - detailedBolusInfo.insulin) < 0.01
&& lastRequestedBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) {
return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.sResources.getString(R.string.bolus_frequency_exceeded));
}
lastRequestedBolus = new Bolus(System.currentTimeMillis(), detailedBolusInfo.insulin, true);
Bolus lastKnownBolus = pump.lastBolus;
try {
pump.activity = MainApp.sResources.getString(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin);
MainApp.bus().post(new EventComboPumpUpdateGUI());
// refresh pump data
CommandResult reservoirBolusResult = runCommand(null, 3,
ruffyScripter::readReservoirLevelAndLastBolus);
if (!reservoirBolusResult.success) {
return new PumpEnactResult().success(false).enacted(false);
}
// check enough insulin left for bolus
if (Math.round(detailedBolusInfo.insulin + 0.5) > reservoirBolusResult.reservoirLevel) {
return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.sResources.getString(R.string.combo_reservoir_level_insufficient_for_bolus));
}
// verify we're update to date and know the most recent bolus
if (!Objects.equals(lastKnownBolus, reservoirBolusResult.lastBolus)) {
new Thread(this::checkPumpHistory).start();
return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.sResources.getString(R.string.combo_pump_bolus_history_state_mismatch));
}
if (cancelBolus) {
return new PumpEnactResult().success(true).enacted(false);
}
// start bolus delivery
bolusInProgress = true;
CommandResult bolusCmdResult = runCommand(null, 0,
() -> ruffyScripter.deliverBolus(detailedBolusInfo.insulin,
detailedBolusInfo.isSMB ? nullBolusProgressReporter : bolusProgressReporter));
bolusInProgress = false;
if (!bolusCmdResult.success) {
new Thread(this::checkPumpHistory).start();
return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.sResources.getString(R.string.combo_bolus_bolus_delivery_failed));
}
// verify delivered bolus
reservoirBolusResult = runCommand(null, 3, ruffyScripter::readReservoirLevelAndLastBolus);
if (!reservoirBolusResult.success) {
return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.sResources.getString(R.string.combo_pump_bolus_verification_failed));
}
Bolus lastPumpBolus = reservoirBolusResult.lastBolus;
if (cancelBolus) {
// if cancellation was requested, the delivered bolus is allowed to differ from requested
} else if (lastPumpBolus == null || lastPumpBolus.amount != detailedBolusInfo.insulin) {
return new PumpEnactResult().success(false).enacted(false).
comment(MainApp.sResources.getString(R.string.combo_pump_bolus_verification_failed));
}
// add treatment record to DB (if it wasn't cancelled)
if (lastPumpBolus != null && (lastPumpBolus.amount > 0)) {
detailedBolusInfo.date = reservoirBolusResult.lastBolus.timestamp;
detailedBolusInfo.insulin = lastPumpBolus.amount;
detailedBolusInfo.date = lastPumpBolus.timestamp;
MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo);
return new PumpEnactResult().success(true).enacted(true)
.bolusDelivered(lastPumpBolus.amount).carbsDelivered(detailedBolusInfo.carbs);
} else {
return new PumpEnactResult().success(true).enacted(false);
}
} finally {
// BolusCommand.execute() intentionally doesn't close the progress dialog if an error
// occurred so it stays open while the connection was re-established if needed and/or
// this method did recovery
bolusProgressReporter.report(FINISHED, 100, 0);
pump.activity = null;
MainApp.bus().post(new EventComboPumpUpdateGUI());
MainApp.bus().post(new EventRefreshOverview("Combo Bolus"));
cancelBolus = false;
}
}
@Override
public void stopBolusDelivering() {
if (bolusInProgress) {
ruffyScripter.cancelBolus();
}
cancelBolus = true;
}
// Note: AAPS calls this only to enact OpenAPS recommendations
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean force) {
// the force parameter isn't used currently since we always set the tbr - there might be room for optimization to
// first test the currently running tbr and only change it if it differs (as the DanaR plugin does).
// This approach might have other issues though (what happens if the tbr which wasn't re-set to the new value
// (and thus still has the old duration of e.g. 1 min) expires?)
log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min.");
int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10);
if (unroundedPercentage != roundedPercentage) {
log.debug("Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%");
}
return setTempBasalPercent(roundedPercentage, durationInMinutes);
}
// Note: AAPS calls this only for setting a temp basal issued by the user
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes) {
log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min");
int adjustedPercent = percent;
if (adjustedPercent > pumpDescription.maxTempPercent) {
log.debug("Reducing requested TBR to the maximum support by the pump: " + percent + " -> " + pumpDescription.maxTempPercent);
adjustedPercent = pumpDescription.maxTempPercent;
}
if (adjustedPercent % 10 != 0) {
Long rounded = Math.round(adjustedPercent / 10d) * 10;
log.debug("Rounded requested percentage:" + adjustedPercent + " -> " + rounded);
adjustedPercent = rounded.intValue();
}
int finalAdjustedPercent = adjustedPercent;
CommandResult commandResult = runCommand(MainApp.sResources.getString(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes),
3, () -> ruffyScripter.setTbr(finalAdjustedPercent, durationInMinutes));
if (!commandResult.success) {
return new PumpEnactResult().success(false).enacted(false);
}
PumpState state = commandResult.state;
if (state.tbrActive && state.tbrPercent == percent
&& (state.tbrRemainingDuration == durationInMinutes || state.tbrRemainingDuration == durationInMinutes - 1)) {
TemporaryBasal tempStart = new TemporaryBasal();
tempStart.date = state.timestamp / (60 * 1000) * (60 * 1000);
tempStart.durationInMinutes = durationInMinutes;
tempStart.percentRate = adjustedPercent;
tempStart.isAbsolute = false;
tempStart.source = Source.USER;
tempStart.pumpId = tempStart.date;
ConfigBuilderPlugin treatmentsInterface = MainApp.getConfigBuilder();
treatmentsInterface.addToHistoryTempBasal(tempStart);
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
return new PumpEnactResult().success(true).enacted(true).isPercent(true)
.percent(state.tbrPercent).duration(state.tbrRemainingDuration);
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
return OPERATION_NOT_SUPPORTED;
}
@Override
public PumpEnactResult cancelTempBasal(boolean userRequested) {
log.debug("cancelTempBasal called");
final TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp == null) {
return new PumpEnactResult().success(false).enacted(false);
}
if (userRequested) {
log.debug("cancelTempBasal: hard-cancelling TBR since user requested");
CommandResult commandResult = runCommand(MainApp.sResources.getString(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr);
if (!commandResult.state.tbrActive) {
TemporaryBasal tempBasal = new TemporaryBasal();
tempBasal.date = commandResult.state.timestamp;
tempBasal.durationInMinutes = 0;
tempBasal.source = Source.USER;
tempBasal.pumpId = activeTemp.pumpId;
MainApp.getConfigBuilder().addToHistoryTempBasal(tempBasal);
return new PumpEnactResult().isTempCancel(true).success(true).enacted(true);
} else {
return new PumpEnactResult().success(false).enacted(false);
}
} else if ((activeTemp.percentRate >= 90 && activeTemp.percentRate <= 110) && activeTemp.getPlannedRemainingMinutes() <= 15) {
// Let fake neutral temp keep run (see below)
log.debug("cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins.");
return new PumpEnactResult().success(true).enacted(true)
.comment("cancelTempBasal skipping changing tbr since it already is at "
+ activeTemp.percentRate + "% and running for another "
+ activeTemp.getPlannedRemainingMinutes() + " mins.");
} else {
// Set a fake neutral temp to avoid TBR cancel alert. Decide 90% vs 110% based on
// on whether the TBR we're cancelling is above or below 100%.
final int percentage = (activeTemp.percentRate > 100) ? 110 : 90;
log.debug("cancelTempBasal: changing TBR to " + percentage + "% for 15 mins.");
CommandResult commandResult = runCommand(MainApp.sResources.getString(R.string.combo_pump_action_cancelling_tbr), 2, () -> ruffyScripter.setTbr(percentage, 15));
if (commandResult.state.tbrActive && commandResult.state.tbrPercent == percentage
&& (commandResult.state.tbrRemainingDuration == 15 || commandResult.state.tbrRemainingDuration == 14)) {
TemporaryBasal tempBasal = new TemporaryBasal();
tempBasal.date = System.currentTimeMillis() / (60 * 1000) * (60 * 1000);
tempBasal.durationInMinutes = 15;
tempBasal.source = Source.USER;
tempBasal.pumpId = tempBasal.date;
tempBasal.percentRate = percentage;
tempBasal.isAbsolute = false;
MainApp.getConfigBuilder().addToHistoryTempBasal(tempBasal);
return new PumpEnactResult().success(true).enacted(true);
} else {
return new PumpEnactResult().success(false).enacted(false);
}
}
}
private interface CommandExecution {
CommandResult execute();
}
/**
* Runs a command, sets an activity if provided, retries if requested and updates fields
* concerned with last connection.
* NO history, reservoir level fields are updated, this make be done separately if desired.
*/
private synchronized CommandResult runCommand(String activity, int retries, CommandExecution commandExecution) {
CommandResult commandResult;
try {
if (activity != null) {
pump.activity = activity;
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
if (!ruffyScripter.isConnected()) {
CommandResult preCheckError = runOnConnectChecks();
if (preCheckError != null) {
updateLocalData(preCheckError);
return preCheckError;
}
}
commandResult = commandExecution.execute();
if (!commandResult.success && retries > 0) {
for (int retryAttempts = 1; !commandResult.success && retryAttempts <= retries; retryAttempts++) {
log.debug("Command was not successful, retries requested, doing retry #" + retryAttempts);
commandResult = commandExecution.execute();
}
}
for (Integer forwardedWarning : commandResult.forwardedWarnings) {
notifyAboutPumpWarning(new WarningOrErrorCode(forwardedWarning, null, null));
}
if (commandResult.success) {
pump.lastSuccessfulCmdTime = System.currentTimeMillis();
}
if (commandResult.success) {
updateLocalData(commandResult);
}
} finally {
if (activity != null) {
pump.activity = null;
MainApp.bus().post(new EventComboPumpUpdateGUI());
}
}
if (pump.initialized && pumpHistoryLastChecked + 15 * 60 * 1000 < System.currentTimeMillis()) {
checkPumpHistory();
}
checkForUnsafeUsage(commandResult);
return commandResult;
}
/**
* Returns the command result of running ReadPumpState if it wasn't successful, indicating
* an error condition. Returns null otherwise.
*/
private CommandResult runOnConnectChecks() {
// connect, get status and check if an alarm is active
CommandResult preCheckResult = ruffyScripter.readPumpState();
if (!preCheckResult.success) {
return preCheckResult;
}
WarningOrErrorCode activeAlert = preCheckResult.state.activeAlert;
// note if multiple alerts are active this will and should fail; e.g. if pump was stopped
// due to empty cartridge alert, which might also trigger TBR cancelled alert
if (activeAlert != null) {
if (activeAlert.warningCode != null
&& (activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW ||
activeAlert.warningCode == PumpWarningCodes.BATTERY_LOW)) {
// turn benign warnings into notifications
notifyAboutPumpWarning(activeAlert);
ruffyScripter.confirmAlert(activeAlert.warningCode);
} else {
Notification notification = new Notification();
notification.date = new Date();
notification.id = Notification.COMBO_PUMP_ALARM;
notification.level = Notification.URGENT;
notification.text = MainApp.sResources.getString(R.string.combo_is_in_error_state);
MainApp.bus().post(new EventNewNotification(notification));
return preCheckResult.success(false);
}
}
// check if TBR was cancelled or set by user
boolean mismatch = checkForTbrMismatch(preCheckResult.state);
if (mismatch) checkPumpHistory();
// raise notification if clock is off (setting clock is not supported by ruffy)
if (preCheckResult.state.pumpTimeMinutesOfDay != 0) {
Date now = new Date();
int minutesOfDayNow = now.getHours() * 60 + now.getMinutes();
if ((Math.abs(preCheckResult.state.pumpTimeMinutesOfDay - minutesOfDayNow) > 3)) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.sResources.getString(R.string.combo_notification_check_time_date), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
// runCommand("Updating pump clock", 2, ruffyScripter::setDateAndTime);
}
}
return null;
}
private void notifyAboutPumpWarning(WarningOrErrorCode activeAlert) {
if (activeAlert.warningCode == null || (activeAlert.warningCode.equals(PumpWarningCodes.CARTRIDGE_LOW) && activeAlert.warningCode.equals(PumpWarningCodes.BATTERY_LOW))) {
throw new IllegalArgumentException(activeAlert.toString());
}
Notification notification = new Notification();
notification.date = new Date();
notification.id = Notification.COMBO_PUMP_ALARM;
notification.level = Notification.NORMAL;
notification.text = activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW
? MainApp.sResources.getString(R.string.combo_pump_cartridge_low_warrning)
: MainApp.sResources.getString(R.string.combo_pump_battery_low_warrning);
MainApp.bus().post(new EventNewNotification(notification));
}
private void checkForUnsafeUsage(CommandResult commandResult) {
long lastViolation = 0;
if (commandResult.state.unsafeUsageDetected) {
lastViolation = System.currentTimeMillis();
}
if (commandResult.lastBolus != null && !commandResult.lastBolus.isValid) {
lastViolation = commandResult.lastBolus.timestamp;
} else if (commandResult.history != null) {
for (Bolus bolus : commandResult.history.bolusHistory) {
if (!bolus.isValid && bolus.timestamp > lastViolation) {
lastViolation = bolus.timestamp;
}
}
}
if (lastViolation > 0) {
closedLoopDisabledUntil = lastViolation + 6 * 60 * 60 * 1000;
if (closedLoopDisabledUntil > System.currentTimeMillis() && violationWarningRaisedFor != closedLoopDisabledUntil) {
Notification n = new Notification(Notification.COMBO_PUMP_ALARM,
MainApp.sResources.getString(R.string.combo_force_disabled_notification),
Notification.URGENT);
n.soundId = R.raw.alarm;
MainApp.bus().post(new EventNewNotification(n));
violationWarningRaisedFor = closedLoopDisabledUntil;
}
}
}
/**
* Checks the main screen to determine if TBR on pump matches app state.
*/
private boolean checkForTbrMismatch(PumpState state) {
TemporaryBasal aapsTbr = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
boolean sync = false;
if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration <= 2) {
// pump runs TBR AAPS is unaware off
log.debug("Pump runs TBR AAPS is unaware of, cancelling TBR so it can be read from history properly");
runCommand(null, 0, ruffyScripter::cancelTbr);
sync = true;
} else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) {
// AAPS has a TBR but the pump isn't running a TBR
log.debug("AAPS shows TBR but pump isn't running a TBR; deleting TBR in AAPS and reading pump history");
MainApp.getDbHelper().delete(aapsTbr);
sync = true;
} else if (aapsTbr != null && state.tbrActive) {
// both AAPS and pump have a TBR ...
if (aapsTbr.percentRate != state.tbrPercent) {
// ... but they have different percentages
log.debug("TBR percentage differs between AAPS and pump; deleting TBR in AAPS and reading pump history");
MainApp.getDbHelper().delete(aapsTbr);
sync = true;
}
int durationDiff = Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration);
if (durationDiff > 2) {
// ... but they have different runtimes
log.debug("TBR duration differs between AAPS and pump; deleting TBR in AAPS and reading pump history");
MainApp.getDbHelper().delete(aapsTbr);
sync = true;
}
}
if (sync) {
log.debug("Sync requested from checkTbrMismatch");
}
return sync;
}
/**
* Checks if there are any changes on the pump not in the DB yet and if so, issues a history
* read to get the DB up to date.
*/
private synchronized boolean checkPumpHistory() {
// set here, rather at the end so that if this runs into an error it's not tried
// over and over since it's called at the end of runCommand
pumpHistoryLastChecked = System.currentTimeMillis();
CommandResult commandResult = runCommand(MainApp.sResources.getString(R.string.combo_pump_action_checking_history), 3, () ->
ruffyScripter.readHistory(
new PumpHistoryRequest()
.bolusHistory(PumpHistoryRequest.LAST)
.tbrHistory(PumpHistoryRequest.LAST)));
if (!commandResult.success || commandResult.history == null) {
return false;
}
PumpHistoryRequest request = new PumpHistoryRequest();
// note: sync only ever happens one way from pump to aaps;
// db records are only added after delivering a bolus and confirming them via pump history
// so whatever is in the DB is either right, added by the user (possibly injecton)
// so don't delete records, only get the last from the pump and check if that one is in
// the DB (valid or note)
// last bolus
Bolus pumpBolus = null;
List<Bolus> bolusHistory = commandResult.history.bolusHistory;
if (!bolusHistory.isEmpty()) {
pumpBolus = bolusHistory.get(0);
}
Treatment aapsBolus = null;
if (pumpBolus != null) {
aapsBolus = MainApp.getDbHelper().getTreatmentByDate(pumpBolus.timestamp);
}
// there's a pump bolus AAPS doesn't know, or we only know one within the same minute but different amount
if (pumpBolus != null && (aapsBolus == null || Math.abs(aapsBolus.insulin - pumpBolus.amount) >= 0.01)) {
log.debug("Last bolus on pump is unknown, refreshing bolus history");
request.bolusHistory = aapsBolus == null ? PumpHistoryRequest.FULL : aapsBolus.date;
}
// last TBR (TBRs are added to history upon completion so here we don't need to care about TBRs cancelled
// by the user, checkTbrMismatch() takes care of that)
Tbr pumpTbr = null;
List<Tbr> tbrHistory = commandResult.history.tbrHistory;
if (!tbrHistory.isEmpty()) {
pumpTbr = tbrHistory.get(0);
}
TemporaryBasal aapsTbr = null;
if (pumpTbr != null) {
aapsTbr = MainApp.getDbHelper().getTemporaryBasalsDataByDate(pumpTbr.timestamp);
}
if (pumpTbr != null && (aapsTbr == null || pumpTbr.percent != aapsTbr.percentRate || pumpTbr.duration != aapsTbr.durationInMinutes)) {
log.debug("Last TBR on pump is unknown, refreshing TBR history");
request.tbrHistory = aapsTbr == null ? PumpHistoryRequest.FULL : aapsTbr.date;
}
if (request.bolusHistory != PumpHistoryRequest.SKIP
|| request.tbrHistory != PumpHistoryRequest.SKIP
|| request.pumpErrorHistory != PumpHistoryRequest.SKIP
|| request.tddHistory != PumpHistoryRequest.SKIP) {
log.debug("History reads needed to get up to date: " + request);
return readHistory(request);
}
return true;
}
/**
* Reads the pump's history and updates the DB accordingly.
*/
private boolean readHistory(final PumpHistoryRequest request) {
CommandResult historyResult = runCommand(MainApp.sResources.getString(R.string.combo_activity_reading_pump_history), 3, () -> ruffyScripter.readHistory(request));
if (!historyResult.success) {
return false;
}
// update local cache
PumpHistory history = historyResult.history;
if (!history.bolusHistory.isEmpty()) {
pump.lastHistoryBolusTime = history.bolusHistory.get(0).timestamp;
}
if (!history.tbrHistory.isEmpty()) {
pump.lastHistoryTbrTime = history.tbrHistory.get(0).timestamp;
}
if (!history.pumpAlertHistory.isEmpty()) {
pump.errorHistory = history.pumpAlertHistory;
}
if (!history.tddHistory.isEmpty()) {
pump.tddHistory = history.tddHistory;
}
updateDbFromPumpHistory(history);
return historyResult.success;
}
private synchronized void updateDbFromPumpHistory(@NonNull PumpHistory history) {
DatabaseHelper dbHelper = MainApp.getDbHelper();
// boluses
for (Bolus pumpBolus : history.bolusHistory) {
Treatment aapsBolus = dbHelper.getTreatmentByDate(pumpBolus.timestamp);
if (aapsBolus == null) {
log.debug("Creating bolus record from pump bolus: " + pumpBolus);
DetailedBolusInfo dbi = new DetailedBolusInfo();
dbi.date = pumpBolus.timestamp;
dbi.pumpId = pumpBolus.timestamp;
dbi.source = Source.PUMP;
dbi.insulin = pumpBolus.amount;
dbi.eventType = CareportalEvent.CORRECTIONBOLUS;
MainApp.getConfigBuilder().addToHistoryTreatment(dbi);
}
}
// TBRs
for (Tbr pumpTbr : history.tbrHistory) {
TemporaryBasal aapsTbr = dbHelper.getTemporaryBasalsDataByDate(pumpTbr.timestamp);
if (aapsTbr == null) {
log.debug("Creating TBR from pump TBR: " + pumpTbr);
TemporaryBasal temporaryBasal = new TemporaryBasal();
temporaryBasal.date = pumpTbr.timestamp;
temporaryBasal.pumpId = pumpTbr.timestamp;
temporaryBasal.source = Source.PUMP;
temporaryBasal.percentRate = pumpTbr.percent;
temporaryBasal.durationInMinutes = pumpTbr.duration;
temporaryBasal.isAbsolute = false;
MainApp.getConfigBuilder().addToHistoryTempBasal(temporaryBasal);
}
}
}
void readAllPumpData() {
readHistory(new PumpHistoryRequest()
.bolusHistory(pump.lastHistoryBolusTime)
.tbrHistory(pump.lastHistoryTbrTime)
.pumpErrorHistory(PumpHistoryRequest.FULL)
.tddHistory(PumpHistoryRequest.FULL));
CommandResult reservoirResult = runCommand("Checking reservoir level", 2,
ruffyScripter::readReservoirLevelAndLastBolus);
if (!reservoirResult.success) {
return;
}
CommandResult basalResult = runCommand("Reading basal profile", 2, ruffyScripter::readBasalProfile);
if (!basalResult.success) {
return;
}
pump.basalProfile = basalResult.basalProfile;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
return OPERATION_NOT_SUPPORTED;
}
@Override
public JSONObject getJSONStatus() {
if (!pump.initialized) {
return null;
}
try {
JSONObject pumpJson = new JSONObject();
pumpJson.put("clock", DateUtil.toISOString(pump.lastSuccessfulCmdTime));
pumpJson.put("reservoir", pump.reservoirLevel);
JSONObject statusJson = new JSONObject();
statusJson.put("status", getStateSummary());
statusJson.put("timestamp", pump.lastSuccessfulCmdTime);
pumpJson.put("status", statusJson);
JSONObject extendedJson = new JSONObject();
extendedJson.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
extendedJson.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName());
if (pump.lastBolus != null) {
extendedJson.put("LastBolus", new Date(pump.lastBolus.timestamp).toLocaleString());
extendedJson.put("LastBolusAmount", DecimalFormatter.to1Decimal(pump.lastBolus.amount));
}
PumpState ps = pump.state;
if (ps.tbrActive) {
extendedJson.put("TempBasalAbsoluteRate", ps.tbrRate);
extendedJson.put("TempBasalPercent", ps.tbrPercent);
extendedJson.put("TempBasalRemaining", ps.tbrRemainingDuration);
}
if (ps.activeAlert != null && ps.activeAlert.errorCode != null) {
extendedJson.put("ErrorCode", ps.activeAlert.errorCode);
}
pumpJson.put("extended", extendedJson);
JSONObject batteryJson = new JSONObject();
int battery;
switch (ps.batteryState) {
case PumpState.EMPTY:
battery = 0;
break;
case PumpState.LOW:
battery = 25;
break;
default:
battery = 75;
break;
}
batteryJson.put("percent", battery);
pumpJson.put("battery", batteryJson);
return pumpJson;
} catch (Exception e) {
log.warn("Failed to gather device status for upload", e);
}
return null;
}
@Override
public String deviceID() {
return "Combo";
}
@Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@Override
public String shortStatus(boolean veryShort) {
return getStateSummary();
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return false;
}
// Constraints interface
private long closedLoopDisabledUntil = 0;
private long violationWarningRaisedFor = 0;
@Override
public boolean isLoopEnabled() {
return closedLoopDisabledUntil < System.currentTimeMillis();
}
@Override
public boolean isClosedModeEnabled() {
return true;
}
@Override
public boolean isAutosensModeEnabled() {
return true;
}
@Override
public boolean isAMAModeEnabled() {
return true;
}
@Override
public Double applyBasalConstraints(Double absoluteRate) {
return absoluteRate;
}
@Override
public Integer applyBasalConstraints(Integer percentRate) {
return percentRate;
}
@Override
public Double applyBolusConstraints(Double insulin) {
return insulin;
}
@Override
public Integer applyCarbsConstraints(Integer carbs) {
return carbs;
}
@Override
public Double applyMaxIOBConstraints(Double maxIob) {
return maxIob;
}
}
|
package materialtest.sanjose.venkata.activities;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;
import it.neokree.materialtabs.MaterialTab;
import it.neokree.materialtabs.MaterialTabHost;
import it.neokree.materialtabs.MaterialTabListener;
import static materialtest.sanjose.venkata.constants.ApplicationConstants.RTConstants.*;
import materialtest.sanjose.venkata.fragments.FragmentBoxOffice;
import materialtest.sanjose.venkata.fragments.FragmentSearch;
import materialtest.sanjose.venkata.fragments.FragmentUpcoming;
import materialtest.sanjose.venkata.logging.Logger;
import materialtest.sanjose.venkata.materialtest.R;
public class MovieTabActivity extends ActionBarActivity implements MaterialTabListener, View.OnClickListener{
private Toolbar toolbar;
private MaterialTabHost tabHost;
private ViewPager viewPager;
private ViewPageAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_using_tab_library);
toolbar = (Toolbar) findViewById(R.id.appBar);
//telling to use my own action bar
setSupportActionBar(toolbar);
// go back page if click on arrow
getSupportActionBar().setHomeButtonEnabled(true);
// display back button (arrow)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabHost = (MaterialTabHost) findViewById(R.id.materialTabHost);
viewPager = (ViewPager) findViewById(R.id.viewPager);
adapter = new ViewPageAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// when user do a swipe the selected tab change
tabHost.setSelectedNavigationItem(position);
}
});
// insert all tabs from pagerAdapter data
for (int i = 0; i < adapter.getCount(); i++) {
tabHost.addTab(
tabHost.newTab()
//uncomment below if want to use icons as tab layout
//.setIcon(adapter.getIcon(i))
//the below takes from the get page title beneath
.setIcon(adapter.getIcon(i))
// the this below refers to materialtablistener
.setTabListener(this)
);
}
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_action_new);
FloatingActionButton actionButton = new FloatingActionButton.Builder(this)
.setContentView(imageView)
//setting our own background color to float action
.setBackgroundDrawable(R.drawable.selector_main_float)
//.setBackgroundDrawable(R.color.favBlue)
.build();
//sub menu
//sort by name
ImageView iconSortName = new ImageView(this);
iconSortName.setImageResource(R.drawable.ic_action_alphabets);
//sort by date
ImageView iconSortDate = new ImageView(this);
iconSortDate.setImageResource(R.drawable.ic_action_calendar);
//sort by ratings
ImageView iconSortRatings = new ImageView(this);
iconSortRatings.setImageResource(R.drawable.ic_action_trending_orange);
//sub menu
SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
//add color to sub menu button background
itemBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_sub_float));
//construct the menu using the itembuilder
SubActionButton buttonSortName = itemBuilder.setContentView(iconSortName).build();
SubActionButton buttonSortDate = itemBuilder.setContentView(iconSortDate).build();
SubActionButton buttonSortRatings = itemBuilder.setContentView(iconSortRatings).build();
//perform on click for all the above item
buttonSortDate.setOnClickListener(this);
buttonSortName.setOnClickListener(this);
buttonSortRatings.setOnClickListener(this);
//instead of storing & using instances of the above (3) buttons while using them
//we use tags to identify the corresponding button click in onClick
buttonSortName.setTag(TAG_SORT_NAME);
buttonSortDate.setTag(TAG_SORT_DATE);
buttonSortRatings.setTag(TAG_SORT_RATINGS);
//add actions in the submenu by attaching to the main action button
FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this)
.addSubActionView(buttonSortName)
.addSubActionView(buttonSortDate)
.addSubActionView(buttonSortRatings)
.attachTo(actionButton)
.build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.menu_using_tab_library, menu);
getMenuInflater().inflate(R.menu.menu_using_tab_library, 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
if (id == R.id.action_settings) {
Toast.makeText(this, "Hey you just hit " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
if (id == R.id.navigate) {
startActivity(new Intent(this, SubActivity.class));
}
if(id == R.id.action_about) {
Log.i("hey wow man,", "you want to know about of this?");
}
if(id == R.id.materialTab) {
startActivity(new Intent(this, MainActivity.class));
}
// on the options menu we now have
if(id == R.id.home) {
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(MaterialTab materialTab) {
viewPager.setCurrentItem(materialTab.getPosition());
}
@Override
public void onTabReselected(MaterialTab materialTab) {
}
@Override
public void onTabUnselected(MaterialTab materialTab) {
}
@Override
public void onClick(View v) {
// check which tag was actually triggered
if(v.getTag().equals(TAG_SORT_NAME)){
Logger.showToast(this, "Sorting by name...");
}
if(v.getTag().equals(TAG_SORT_DATE)){
Logger.showToast(this, "Sorting by date...");
}
if(v.getTag().equals(TAG_SORT_RATINGS)){
Logger.showToast(this, "Sorting by ratings...");
}
}
private class ViewPageAdapter extends FragmentStatePagerAdapter{
//uncomment below when want to use icons for tablayout
int icons[] = {R.drawable.ic_action_personal, R.drawable.ic_action_calendar,
R.drawable.ic_action_important, R.drawable.ic_action_trending_orange,
R.drawable.ic_action_home, R.drawable.ic_action_articles,
R.drawable.ic_action_search, R.drawable.ic_action_trending_orange,
R.drawable.ic_action_upcoming, R.drawable.ic_action_trending};
//uncomment below for android svg items
/*int icons[] = {R.drawable.vector_android, R.drawable.vector_android,
R.drawable.vector_android};*/
public ViewPageAdapter(FragmentManager fm) {
super(fm);
}
//return the fragment at that position
@Override
public Fragment getItem(int position) {
//to decide which fragment to instantiate based on the position choosen
Fragment fragment = null;
switch (position){
case MOVIES_SEARCH_RESULTS:
fragment = FragmentSearch.newInstance("", "");
break;
case MOVIES_HITS:
fragment = FragmentBoxOffice.newInstance("", "");
break;
case MOVIES_UPCOMING:
fragment = FragmentUpcoming.newInstance("", "");
break;
}
return fragment;
}
@Override
public int getCount() {
return 3;
}
// now write own implementation for setting text tab headers or icon tab headers
// uncomment below for having text as tab heading
/*@Override
public CharSequence getPageTitle(int position) {
return getResources().getStringArray(R.array.tabs)[position];
}*/
// uncomment below for having icons as tab heading
private Drawable getIcon(int position) {
return getResources().getDrawable(icons[position]);
}
}
}
|
package org.stepic.droid.ui.adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import org.stepic.droid.R;
import org.stepic.droid.base.MainApplication;
import org.stepic.droid.model.Option;
import java.util.Collections;
import java.util.List;
public class MatchingStepEnhancedAdapter extends SortingStepEnhancedAdapter {
protected static final int NOT_DRAGGABLE_VIEW_TYPE = 1;
int optionHeightPx;
public MatchingStepEnhancedAdapter(List<Option> data) {
super(data);
optionHeightPx = (int) MainApplication.getAppContext().getResources().getDimension(R.dimen.option_height);
}
@Override
public OptionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final OptionViewHolder optionViewHolder;
if (viewType == NOT_DRAGGABLE_VIEW_TYPE) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.view_matching_first_option_enhanced, parent, false);
optionViewHolder = new OptionViewHolder(view);
} else if (viewType == DEFAULT_DRAGGABLE_VIEW_TYPE) {
optionViewHolder = super.onCreateViewHolder(parent, viewType);
} else {
throw new IllegalArgumentException("Illegal view type of matching adapter");
}
optionViewHolder.container.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
int localHeight = optionViewHolder.container.getMeasuredHeight();
if (localHeight > optionHeightPx) {
optionViewHolder.container.getLayoutParams().height = localHeight;
optionViewHolder.container.getViewTreeObserver().removeOnPreDrawListener(this);
}
return true;
}
});
return optionViewHolder;
}
@Override
public boolean onCheckCanStartDrag(OptionViewHolder holder, int position, int x, int y) {
return position % 2 != 0 && super.onCheckCanStartDrag(holder, position, x, y);
}
@Override
public void onMoveItem(int fromPosition, int toPosition) {
if (fromPosition == toPosition) {
return;
}
Collections.swap(data, toPosition, fromPosition);
notifyDataSetChanged();
}
@Override
public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
return dropPosition % 2 != 0;
}
@Override
public int getItemViewType(int position) {
if (position % 2 == 0) {
return NOT_DRAGGABLE_VIEW_TYPE;
} else {
return super.getItemViewType(position);
}
}
}
|
package se.toxbee.sleepfighter.utils.math;
import junit.framework.TestCase;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
public class MatrixUtilTest extends TestCase {
public void testComputeDeterminant() {
double[][] matrixData = new double[3][3];
matrixData[0][0] = -2;
matrixData[0][1] = 2;
matrixData[0][2] = 3;
matrixData[1][0] = -1;
matrixData[1][1] = 1;
matrixData[1][2] = 3;
matrixData[2][0] = 2;
matrixData[2][1] = 0;
matrixData[2][2] = -1;
RealMatrix m1 = MatrixUtils.createRealMatrix(matrixData);
assertEquals(6, (int)MatrixUtil.computeDeterminant(m1));
}
public void testIsSingular() {
final RealMatrix m = new Array2DRowRealMatrix(new double[][] {
{1, 0, 0},
{-2, 0, 0},
{4, 6, 1}});
assertTrue(MatrixUtil.isSingular(m));
}
}
|
import com.turn.ttorrent.common.Torrent;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map.Entry;
import java.util.*;
import org.apache.commons.io.IOUtils;
public class App {
private static final String HTTP_ENCODING = "ISO-8859-1";
private static Peer peer;
private static Client client;
public static URL buildAnnounceURL(URI announceURI, Torrent torrent) {
//URL trackerAnnounceURL = this.torrentInfo.TRACKER_URL;
String base = announceURI.toString();
StringBuilder url = new StringBuilder(base);
try {
url.append(base.contains("?") ? "&" : "?");
url.append("info_hash=");
url.append(URLEncoder.encode(new String(torrent.getInfoHash(), HTTP_ENCODING), HTTP_ENCODING)).append("&peer_id=");
url.append(URLEncoder.encode(client.getID(), HTTP_ENCODING));
url.append("&port=");
url.append(53553);
return new URL(url.toString());
}
catch (Exception e) {
return null;
}
}
public static void main(String[] args){
System.out.println("Go go go!");
String id = "-MT0001-" + UUID.randomUUID()
.toString().split("-")[4];
System.out.println(id);
Torrent torrent = null;
try{
torrent = Torrent.load(new File("dsl-4.4.10.iso.torrent"));
client = new Client(InetAddress.getLocalHost(), torrent);
URL announce = buildAnnounceURL(torrent.getAnnounceList().get(0).get(0), torrent);
System.out.println(announce);
//send announce get request
URLConnection connection = announce.openConnection();
//String charset = "UTF-8";
//connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
//int status = connection.getResponseCode();
//System.out.println(status);
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
String encoding = connection.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(response, HTTP_ENCODING);
System.out.println(body);
}
catch (Exception ex){
System.out.println("Aww... why don't you like me, File?");
System.out.println(ex.getMessage());
}
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Stream;
public class StringSplitAndReverse {
public static void main(String[] args) {
String s = " abc.lxu,|fewag'ow$fowajfw#fg-faoi~~|oijgr|freagj!foajg |afewag,/$aaa";
//StringTokenizer
// splitTokenizer(s, "|").stream()
// .forEach(System.out::println);
List<String> result = splitRegExp2(s, " \\.,'
// List<String> result = splitRegExp2(s);
//Collections#reverse
// Collections.reverse(result);
Stream.of("","","","","")
.sorted((a,b) -> -1)
.forEach(System.out::println);
//Stream#sorted
result.stream()
//Comparator-1
.sorted((a,b) -> -1)
.forEach(System.out::println);
}
/**
* StringTokenizer
* @param str
* @param delim
* @return
*/
public static List<String> splitTokenizer(String str, String delim){
List<String> list = new ArrayList<>();
//3true
StringTokenizer st = new StringTokenizer(str, delim, true);
//Iterablefor
while(st.hasMoreTokens()){
list.add(st.nextToken());
}
return list;
}
public static List<String> splitRegExp(String str, String delim){
String[] strs = str.split("((?<=[" + delim + "])|(?=[" + delim + "]))");
return Arrays.asList(strs);
}
public static List<String> splitRegExp2(String str, String delim){
String[] strs = str.split("(?<=[" + delim + "])(?![" + delim + "])|(?<![" + delim + "])(?=[" + delim + "])");
return Arrays.asList(strs);
}
/**
*
* @param str
* @return
*/
public static List<String> splitRegExpBound(String str){
String[] strs = str.split("\\b+");
return Arrays.asList(strs);
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
String[] columnNames = {"String", "Integer", "Boolean"};
Object[][] data = {
{"aaa", 12, true}, {"bbb", 5, false},
{"CCC", 92, true}, {"DDD", 0, false}
};
TableModel model = new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
// ArrayIndexOutOfBoundsException: 0 >= 0
// [JDK-6967479] JTable sorter fires even if the model is empty - Java Bug System
// return getValueAt(0, column).getClass();
switch (column) {
case 0: return String.class;
case 1: return Number.class;
case 2: return Boolean.class;
default: return super.getColumnClass(column);
}
}
};
JTable table = new JTable(model);
table.setAutoCreateRowSorter(true);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
TableColumn col = table.getColumnModel().getColumn(0);
col.setMinWidth(60);
col.setMaxWidth(60);
col.setResizable(false);
JScrollPane scroll = new JScrollPane(table);
scroll.setComponentPopupMenu(new TablePopupMenu());
// scroll.getViewport().setInheritsPopupMenu(true); // 1.5.0
table.setInheritsPopupMenu(true);
// table.setFillsViewportHeight(true);
scroll.getViewport().setOpaque(true);
// scroll.getViewport().setBackground(Color.WHITE);
JCheckBox check = new JCheckBox("viewport setOpaque", true);
check.addActionListener(e -> {
scroll.getViewport().setOpaque(((JCheckBox) e.getSource()).isSelected());
scroll.repaint();
});
JButton button = new JButton("Choose background color");
button.addActionListener(e -> {
Color color = JColorChooser.showDialog(getRootPane(), "background color", scroll.getViewport().getBackground());
scroll.getViewport().setBackground(color);
scroll.repaint();
});
JPanel pnl = new JPanel();
pnl.add(check);
pnl.add(button);
add(scroll);
add(pnl, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class TablePopupMenu extends JPopupMenu {
private final JMenuItem delete;
protected TablePopupMenu() {
super();
add("add").addActionListener(e -> {
JTable table = (JTable) getInvoker();
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[] {"New row", model.getRowCount(), false});
Rectangle r = table.getCellRect(model.getRowCount() - 1, 0, true);
table.scrollRectToVisible(r);
});
addSeparator();
delete = add("delete");
delete.addActionListener(e -> {
JTable table = (JTable) getInvoker();
DefaultTableModel model = (DefaultTableModel) table.getModel();
int[] selection = table.getSelectedRows();
for (int i = selection.length - 1; i >= 0; i
model.removeRow(table.convertRowIndexToModel(selection[i]));
}
});
}
@Override public void show(Component c, int x, int y) {
if (c instanceof JTable) {
delete.setEnabled(((JTable) c).getSelectedRowCount() > 0);
super.show(c, x, y);
}
}
}
|
package io.tetrapod.core;
import static io.tetrapod.protocol.core.Core.*;
import static io.tetrapod.protocol.core.CoreContract.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DecoderException;
import io.netty.util.ReferenceCountUtil;
import io.tetrapod.core.rpc.*;
import io.tetrapod.core.rpc.Error;
import io.tetrapod.core.web.WebRoutes;
import io.tetrapod.protocol.core.*;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import javax.net.ssl.SSLException;
import org.slf4j.*;
/**
* Manages a tetrapod session
*/
abstract public class Session extends ChannelInboundHandlerAdapter {
/**
* Listeners of session life-cycle events
*/
public interface Listener {
public void onSessionStart(Session ses);
public void onSessionStop(Session ses);
}
public static interface Helper {
public Dispatcher getDispatcher();
public Async dispatchRequest(RequestHeader header, Request req, Session fromSession);
public List<SubscriptionAPI> getMessageHandlers(int contractId, int structId);
public int getContractId();
}
public static interface RelayHandler {
public int getAvailableService(int contractid);
public Session getRelaySession(int toId, int contractid);
public void relayMessage(MessageHeader header, ByteBuf buf, boolean isBroadcast) throws IOException;
public WebRoutes getWebRoutes();
public boolean validate(int entityId, long token);
}
protected static final Logger logger = LoggerFactory.getLogger(Session.class);
protected static final Logger commsLog = LoggerFactory.getLogger("comms");
public static final byte DEFAULT_REQUEST_TIMEOUT = 30;
public static final int DEFAULT_OVERLOAD_THRESHOLD = 1024 * 128;
protected static final AtomicInteger sessionCounter = new AtomicInteger();
protected final int sessionNum = sessionCounter.incrementAndGet();
protected final List<Listener> listeners = new LinkedList<Listener>();
protected final Map<Integer, Async> pendingRequests = new ConcurrentHashMap<>();
protected final AtomicInteger requestCounter = new AtomicInteger();
protected final Session.Helper helper;
protected final SocketChannel channel;
protected final AtomicLong lastHeardFrom = new AtomicLong(System.currentTimeMillis());
protected final AtomicLong lastSentTo = new AtomicLong(System.currentTimeMillis());
protected RelayHandler relayHandler;
protected int myId = 0;
protected byte myType = Core.TYPE_ANONYMOUS;
protected int theirId = 0;
protected byte theirType = Core.TYPE_ANONYMOUS;
protected int myContractId;
public Session(SocketChannel channel, Session.Helper helper) {
this.channel = channel;
this.helper = helper;
this.myContractId = helper.getContractId();
}
/**
* Check to see if this session is still alive and close it, if not
*/
// TODO: needs configurable timeouts
public void checkHealth() {
if (isConnected()) {
final long now = System.currentTimeMillis();
if (now - lastHeardFrom.get() > 5000 || now - lastSentTo.get() > 5000) {
if (theirType == TYPE_SERVICE || theirType == TYPE_TETRAPOD)
logger.trace("{} Sending PING ({}/{} ms)", this, now - lastHeardFrom.get(), now - lastSentTo.get());
sendPing();
}
if (now - lastHeardFrom.get() > 20000) {
logger.warn("{} Timeout ({} ms)", this, now - lastHeardFrom.get());
if (theirId == myId && myId != 0) {
logger.error("{} Timeout on LOOPBACK!", this);
} else {
close();
}
}
}
timeoutPendingRequests();
}
public void timeoutPendingRequests() {
for (Entry<Integer, Async> entry : pendingRequests.entrySet()) {
Async a = entry.getValue();
if (a.isTimedout()) {
pendingRequests.remove(entry.getKey());
a.setResponse(ERROR_TIMEOUT);
}
}
}
abstract protected Object makeFrame(Structure header, Structure payload, byte envelope);
abstract protected Object makeFrame(Structure header, ByteBuf payload, byte envelope);
protected void sendPing() {}
protected void sendPong() {}
public Dispatcher getDispatcher() {
return helper.getDispatcher();
}
public int getSessionNum() {
return sessionNum;
}
public long getLastHeardFrom() {
return lastHeardFrom.get();
}
protected void scheduleHealthCheck() {
if (isConnected() || !pendingRequests.isEmpty()) {
getDispatcher().dispatch(1, TimeUnit.SECONDS, new Runnable() {
public void run() {
checkHealth();
scheduleHealthCheck();
}
});
}
}
@Override
public String toString() {
return String.format("%s #%d [0x%08X]", getClass().getSimpleName(), sessionNum, theirId);
}
protected String getStructName(int contractId, int structId) {
Structure s = StructureFactory.make(contractId, structId);
if (s == null) {
return "Struct-" + structId;
}
return s.getClass().getSimpleName();
}
protected void dispatchRequest(final RequestHeader header, final Request req) {
helper.dispatchRequest(header, req, this).handle(new ResponseHandler() {
@Override
public void onResponse(Response res) {
sendResponse(res, header.requestId);
}
});
}
protected void dispatchMessage(final MessageHeader header, final Message msg) {
// we need to hijack this now to prevent a race with dispatching subsequent messages
if (header.structId == EntityMessage.STRUCT_ID) {
if (getTheirEntityType() == Core.TYPE_TETRAPOD) {
EntityMessage m = (EntityMessage) msg;
setMyEntityId(m.entityId);
}
}
// OPTIMIZE: use senderId to queue instead of using this single threaded queue
final MessageContext ctx = new SessionMessageContext(header, this);
getDispatcher().dispatchSequential(new Runnable() {
public void run() {
for (SubscriptionAPI handler : helper.getMessageHandlers(header.contractId, header.structId)) {
msg.dispatch(handler, ctx);
}
}
});
}
public Response sendPendingRequest(final Request req, final int toId, byte timeoutSeconds, final PendingResponseHandler pendingHandler) {
final Async async = sendRequest(req, toId, timeoutSeconds);
async.handle(new ResponseHandler() {
@Override
public void onResponse(Response res) {
Response pendingRes = null;
try {
pendingRes = pendingHandler.onResponse(res);
if (pendingRes == Response.PENDING) {
logger.error("Pending response returned from pending handler for {} @ {}", req.dump(), toId);
return;
}
} catch (ErrorResponseException e1) {
pendingRes = Response.error(e1.errorCode);
} catch (Throwable e) {
logger.error(e.getMessage(), e);
} finally {
// finally return the pending response we were waiting on
if (pendingRes == null) {
pendingRes = new Error(ERROR_UNKNOWN);
}
if (!pendingHandler.sendResponse(pendingRes)) {
sendResponse(pendingRes, pendingHandler.originalRequestId);
}
}
}
});
return Response.PENDING;
}
public Async sendRequest(Request req, int toId) {
return sendRequest(req, toId, DEFAULT_REQUEST_TIMEOUT);
}
public Async sendRequest(Request req, int toId, byte timeoutSeconds) {
final RequestHeader header = new RequestHeader();
header.requestId = requestCounter.incrementAndGet();
header.toId = toId;
header.fromId = myId;
header.timeout = timeoutSeconds;
header.contractId = req.getContractId();
header.structId = req.getStructId();
header.fromType = myType;
return sendRequest(req, header);
}
public Async sendRequest(Request req, final RequestHeader header) {
final Async async = new Async(req, header, this);
if (channel.isActive()) {
pendingRequests.put(header.requestId, async);
if (!commsLogIgnore(req))
commsLog("%s [%d] => %s (to %d)", this, header.requestId, req.dump(), header.toId);
final Object buffer = makeFrame(header, req, ENVELOPE_REQUEST);
if (buffer != null) {
writeFrame(buffer);
} else {
async.setResponse(ERROR_SERIALIZATION);
}
} else {
async.setResponse(ERROR_CONNECTION_CLOSED);
}
return async;
}
public void sendResponse(Response res, int requestId) {
if (res != Response.PENDING) {
if (!commsLogIgnore(res))
commsLog("%s [%d] => %s", this, requestId, res.dump());
final Object buffer = makeFrame(res, requestId);
if (buffer != null) {
writeFrame(buffer);
}
}
}
public Object makeFrame(Response res, int requestId) {
return makeFrame(new ResponseHeader(requestId, res.getContractId(), res.getStructId()), res, ENVELOPE_RESPONSE);
}
public void sendBroadcastMessage(Message msg, byte toType, int toId) {
if (getMyEntityId() != 0) {
if (!commsLogIgnore(msg))
commsLog("%s [B] => %s (to %s:%d)", this, msg.dump(), TO_TYPES[toType], toId);
final Object buffer = makeFrame(new MessageHeader(getMyEntityId(), toType, toId, msg.getContractId(), msg.getStructId()), msg,
ENVELOPE_BROADCAST);
if (buffer != null) {
writeFrame(buffer);
getDispatcher().messagesSentCounter.mark();
}
}
}
public void sendMessage(Message msg, byte toType, int toId) {
if (getMyEntityId() != 0) {
if (!commsLogIgnore(msg))
commsLog("%s [M] => %s (to %s:%d)", this, msg.dump(), TO_TYPES[toType], toId);
final Object buffer = makeFrame(new MessageHeader(getMyEntityId(), toType, toId, msg.getContractId(), msg.getStructId()), msg,
ENVELOPE_MESSAGE);
if (buffer != null) {
writeFrame(buffer);
getDispatcher().messagesSentCounter.mark();
}
}
}
private volatile boolean autoFlush = true;
public void setAutoFlush(boolean val) {
autoFlush = val;
}
public void flush() {
channel.flush();
}
public ChannelFuture writeFrame(Object frame) {
if (frame != null) {
if (channel.isActive()) {
lastSentTo.set(System.currentTimeMillis());
if (autoFlush) {
return channel.writeAndFlush(frame);
} else {
return channel.write(frame);
}
} else {
ReferenceCountUtil.release(frame);
}
}
return null;
}
public static final String[] TO_TYPES = { "Unknown", "Topic", "Entity", "Alt" };
public void sendRelayedMessage(MessageHeader header, ByteBuf payload, boolean broadcast) {
if (!commsLogIgnore(header.structId)) {
commsLog("%s [M] ~> Message:%d %s (to %s:%d)", this, header.structId, getNameFor(header), TO_TYPES[header.toType], header.toId);
}
byte envelope = broadcast ? ENVELOPE_BROADCAST : ENVELOPE_MESSAGE;
writeFrame(makeFrame(header, payload, envelope));
}
public Async sendRelayedRequest(RequestHeader header, ByteBuf payload, Session originator, ResponseHandler handler) {
final Async async = new Async(null, header, originator, handler);
int origRequestId = async.header.requestId;
int newRequestId = addPendingRequest(async);
if (!commsLogIgnore(header.structId))
commsLog("%s [%d/%d] ~> Request:%d", this, newRequestId, origRequestId, header.structId);
// making a new header lets us not worry about synchronizing the change the requestId
RequestHeader newHeader = new RequestHeader(newRequestId, header.fromId, header.toId, header.fromType, header.timeout, header.version,
header.contractId, header.structId);
if (newHeader.toId == UNADDRESSED && theirType != TYPE_TETRAPOD) {
newHeader.toId = theirId;
}
writeFrame(makeFrame(newHeader, payload, ENVELOPE_REQUEST));
return async;
}
public void sendRelayedResponse(ResponseHeader header, ByteBuf payload) {
if (!commsLogIgnore(header.structId))
commsLog("%s [%d] ~> Response:%d", this, header.requestId, header.structId);
writeFrame(makeFrame(header, payload, ENVELOPE_RESPONSE));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
// quieter logging for certain exceptions
if (cause instanceof IOException) {
if (cause instanceof SSLException) {
logger.warn("{} {}", this, cause.getMessage());
return;
} else if (cause.getMessage() != null) {
if (cause.getMessage().equals("Connection reset by peer") || cause.getMessage().equals("Connection timed out")) {
logger.info("{} {}", this, cause.getMessage());
return;
}
}
} else if (cause instanceof DecoderException) {
logger.info("{} {}", this, cause.getMessage());
return;
}
logger.error("{} : {} : {}", this, cause.getClass().getSimpleName(), cause.getMessage());
logger.error(cause.getMessage(), cause);
}
public synchronized boolean isConnected() {
if (channel != null) {
return channel.isActive();
}
return false;
}
public void close() {
channel.close();
}
public void addSessionListener(Listener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
public void removeSessionListener(Listener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
protected void fireSessionStartEvent() {
logger.debug("{} Session Start", this);
for (Listener l : getListeners()) {
l.onSessionStart(this);
}
}
protected void fireSessionStopEvent() {
logger.debug("{} Session Stop", this);
for (Listener l : getListeners()) {
l.onSessionStop(this);
}
}
private Listener[] getListeners() {
synchronized (listeners) {
return listeners.toArray(new Listener[0]);
}
}
public synchronized void setMyEntityId(int entityId) {
if (myId != entityId && isConnected()) {
logger.debug("{} Setting my Entity {}", this, entityId);
}
this.myId = entityId;
}
public synchronized int getMyEntityId() {
return myId;
}
public void setMyEntityType(byte type) {
myType = type;
}
public synchronized void setTheirEntityId(int entityId) {
this.theirId = entityId;
}
public synchronized int getTheirEntityId() {
return theirId;
}
public synchronized byte getTheirEntityType() {
return theirType;
}
public void setTheirEntityType(byte type) {
theirType = type;
}
public int addPendingRequest(Async async) {
int requestId = requestCounter.incrementAndGet();
pendingRequests.put(requestId, async);
return requestId;
}
public void cancelAllPendingRequests() {
for (Async a : pendingRequests.values()) {
a.setResponse(ERROR_CONNECTION_CLOSED);
}
pendingRequests.clear();
}
// /////////////////////////////////// RELAY /////////////////////////////////////
public synchronized void setRelayHandler(RelayHandler relayHandler) {
this.relayHandler = relayHandler;
}
public String getPeerHostname() {
if (channel != null && channel.remoteAddress() != null && channel.remoteAddress().getAddress() != null) {
channel.remoteAddress().getAddress().getHostAddress();
}
return "Unknown";
}
public boolean commsLog(String format, Object... args) {
if (commsLog.isDebugEnabled()) {
for (int i = 0; i < args.length; i++) {
if (args[i] == this) {
args[i] = String.format("%s:%d", getClass().getSimpleName().substring(0, 4), sessionNum);
}
}
commsLog.debug(String.format(format, args));
}
return true;
}
public String getNameFor(MessageHeader header) {
return StructureFactory.getName(header.contractId, header.structId);
}
public boolean commsLogIgnore(Structure struct) {
return commsLogIgnore(struct.getStructId());
}
public boolean commsLogIgnore(int structId) {
if (commsLog.isTraceEnabled())
return false;
switch (structId) {
case ServiceLogsRequest.STRUCT_ID:
case ServiceLogsResponse.STRUCT_ID:
case ServiceStatsMessage.STRUCT_ID:
return true;
}
return !commsLog.isDebugEnabled();
}
}
|
package com.perm.kate.api;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.zip.GZIPInputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.perm.utils.Utils;
import com.perm.utils.WrongResponseCodeException;
import android.util.Log;
public class Api {
static final String TAG="Kate.Api";
public static final String BASE_URL="https://api.vk.com/method/";
public Api(String access_token, String api_id){
this.access_token=access_token;
this.api_id=api_id;
}
String access_token;
String api_id;
//TODO: it's not faster, even slower on slow devices. Maybe we should add an option to disable it. It's only good for paid internet connection.
static boolean enable_compression=true;
/*** utils methods***/
private void checkError(JSONObject root, String url) throws JSONException,KException {
if(!root.isNull("error")){
JSONObject error=root.getJSONObject("error");
int code=error.getInt("error_code");
String message=error.getString("error_msg");
KException e = new KException(code, message, url);
if (code==14) {
e.captcha_img = error.optString("captcha_img");
e.captcha_sid = error.optString("captcha_sid");
}
throw e;
}
}
private JSONObject sendRequest(Params params) throws IOException, MalformedURLException, JSONException, KException {
return sendRequest(params, false);
}
private final static int MAX_TRIES=3;
private JSONObject sendRequest(Params params, boolean is_post) throws IOException, MalformedURLException, JSONException, KException {
String url = getSignedUrl(params, is_post);
String body="";
if(is_post)
body=params.getParamsString(is_post);
Log.i(TAG, "url="+url);
if(body.length()!=0)
Log.i(TAG, "body="+body);
String response="";
for(int i=1;i<=MAX_TRIES;++i){
try{
if(i!=1)
Log.i(TAG, "try "+i);
response = sendRequestInternal(url, body, is_post);
break;
}catch(javax.net.ssl.SSLException ex){
processNetworkException(i, ex);
}catch(java.net.SocketException ex){
processNetworkException(i, ex);
}
}
Log.i(TAG, "response="+response);
JSONObject root=new JSONObject(response);
checkError(root, url);
return root;
}
private void processNetworkException(int i, IOException ex) throws IOException {
ex.printStackTrace();
if(i==MAX_TRIES)
throw ex;
}
private String sendRequestInternal(String url, String body, boolean is_post) throws IOException, MalformedURLException, WrongResponseCodeException {
HttpURLConnection connection=null;
try{
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setUseCaches(false);
connection.setDoOutput(is_post);
connection.setDoInput(true);
connection.setRequestMethod(is_post?"POST":"GET");
if(enable_compression)
connection.setRequestProperty("Accept-Encoding", "gzip");
if(is_post)
connection.getOutputStream().write(body.getBytes("UTF-8"));
int code=connection.getResponseCode();
Log.i(TAG, "code="+code);
if (code==-1)
throw new WrongResponseCodeException("Network error");
//on error can also read error stream from connection.
InputStream is = new BufferedInputStream(connection.getInputStream(), 8192);
String enc=connection.getHeaderField("Content-Encoding");
if(enc!=null && enc.equalsIgnoreCase("gzip"))
is = new GZIPInputStream(is);
String response=Utils.convertStreamToString(is);
return response;
}
finally{
if(connection!=null)
connection.disconnect();
}
}
private String getSignedUrl(Params params, boolean is_post) {
String args = "";
if(!is_post)
args=params.getParamsString(is_post);
//add access_token
if(args.length()!=0)
args+="&";
args+="access_token="+access_token;
return BASE_URL+params.method_name+"?"+args;
}
public static String unescape(String text){
if(text==null)
return null;
return text.replace("&", "&").replace(""", "\"").replace("<br>", "\n").replace(">", ">").replace("<", "<")
.replace("'", "'").replace("<br/>", "\n").replace("–","-").replace("!", "!").trim();
//возможно тут могут быть любые коды после &
}
public static String unescapeWithSmiles(String text){
return unescape(text)
//May be useful to someone
//.replace("\uD83D\uDE0A", ":-)")
//.replace("\uD83D\uDE03", ":D")
//.replace("\uD83D\uDE09", ";-)")
//.replace("\uD83D\uDE06", "xD")
//.replace("\uD83D\uDE1C", ";P")
//.replace("\uD83D\uDE0B", ":p")
//.replace("\uD83D\uDE0D", "8)")
//.replace("\uD83D\uDE0E", "B)")
//.replace("\ud83d\ude12", ":(") //F0 9F 98 92
//.replace("\ud83d\ude0f", ":]") //F0 9F 98 8F
//.replace("\ud83d\ude14", "3(") //F0 9F 98 94
//.replace("\ud83d\ude22", ":'(") //F0 9F 98 A2
//.replace("\ud83d\ude2d", ":_(") //F0 9F 98 AD
//.replace("\ud83d\ude29", ":((") //F0 9F 98 A9
//.replace("\ud83d\ude28", ":o") //F0 9F 98 A8
//.replace("\ud83d\ude10", ":|") //F0 9F 98 90
//.replace("\ud83d\ude0c", "3)") //F0 9F 98 8C
//.replace("\ud83d\ude20", ">(") //F0 9F 98 A0
//.replace("\ud83d\ude21", ">((") //F0 9F 98 A1
//.replace("\ud83d\ude07", "O:)") //F0 9F 98 87
//.replace("\ud83d\ude30", ";o") //F0 9F 98 B0
//.replace("\ud83d\ude32", "8o") //F0 9F 98 B2
//.replace("\ud83d\ude33", "8|") //F0 9F 98 B3
//.replace("\ud83d\ude37", ":X") //F0 9F 98 B7
//.replace("\ud83d\ude1a", ":*") //F0 9F 98 9A
//.replace("\ud83d\ude08", "}:)") //F0 9F 98 88
//.replace("\u2764", "<3") //E2 9D A4
//.replace("\ud83d\udc4d", ":like:") //F0 9F 91 8D
//.replace("\ud83d\udc4e", ":dislike:") //F0 9F 91 8E
//.replace("\u261d", ":up:") //E2 98 9D
//.replace("\u270c", ":v:") //E2 9C 8C
//.replace("\ud83d\udc4c", ":ok:") //F0 9F 91 8C
;
}
/*** API methods ***/
public ArrayList<City> getCitiesByCountry(int country, String q) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("places.getCities");
params.put("country", country);
params.put("q", q);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<City> cities = new ArrayList<City>();
if (array != null) {
for (int i=0; i<array.length(); i++){
JSONObject o = (JSONObject)array.get(i);
City c = City.parse(o);
cities.add(c);
}
}
return cities;
}
public ArrayList<City> getCities(Collection<Long> cids) throws MalformedURLException, IOException, JSONException, KException {
if (cids == null || cids.size() == 0)
return null;
Params params = new Params("places.getCityById");
params.put("cids",arrayToString(cids));
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<City> cities=new ArrayList<City>();
if(array!=null){
for(int i=0; i<array.length(); i++){
JSONObject o = (JSONObject)array.get(i);
City c = City.parse(o);
cities.add(c);
}
}
return cities;
}
<T> String arrayToString(Collection<T> items) {
if(items==null)
return null;
String str_cids = "";
for (Object item:items){
if(str_cids.length()!=0)
str_cids+=',';
str_cids+=item;
}
return str_cids;
}
public ArrayList<Country> getCountriesByCode(Integer need_full, String code) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("places.getCountries");
params.put("need_full", need_full);
params.put("code", code);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
ArrayList<Country> countries = new ArrayList<Country>();
int category_count = array.length();
for (int i=0; i<category_count; i++) {
JSONObject o = (JSONObject)array.get(i);
Country c = Country.parse(o);
countries.add(c);
}
return countries;
}
public ArrayList<Country> getCountries(Collection<Long> cids) throws MalformedURLException, IOException, JSONException, KException {
if (cids == null || cids.size() == 0)
return null;
Params params = new Params("places.getCountryById");
String str_cids = arrayToString(cids);
params.put("cids",str_cids);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Country> countries=new ArrayList<Country>();
int category_count = array.length();
for(int i=0; i<category_count; i++){
JSONObject o = (JSONObject)array.get(i);
Country c = Country.parse(o);
countries.add(c);
}
return countries;
}
//*** methods for users ***//
public ArrayList<User> getProfiles(Collection<Long> uids, Collection<String> domains, String fields, String name_case, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
if (uids == null && domains == null)
return null;
if ((uids != null && uids.size() == 0) || (domains != null && domains.size() == 0))
return null;
Params params = new Params("users.get");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (domains != null && domains.size() > 0)
params.put("uids",arrayToString(domains));
if (fields == null)
params.put("fields","uid,first_name,last_name,nickname,domain,sex,bdate,city,country,timezone,photo,photo_medium_rec,photo_big,has_mobile,rate,contacts,education,online");
else
params.put("fields",fields);
params.put("name_case",name_case);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
/*** methods for friends ***/
public ArrayList<User> getFriends(Long user_id, String fields, Integer lid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.get");
if(fields==null)
fields="first_name,last_name,photo_medium,online";
params.put("fields",fields);
params.put("uid",user_id);
params.put("lid", lid);
if(lid==null)
params.put("order","hints");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
ArrayList<User> users=new ArrayList<User>();
JSONArray array=root.optJSONArray("response");
//if there are no friends "response" will not be array
if(array==null)
return users;
int category_count=array.length();
for(int i=0; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
User u = User.parse(o);
users.add(u);
}
return users;
}
public ArrayList<Long> getOnlineFriends(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getOnline");
params.put("uid",uid);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
public ArrayList<Long> getLikeUsers(String item_type, long item_id, long owner_id, String filter) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.getList");
params.put("type", item_type);
params.put("owner_id", owner_id);
params.put("item_id", item_id);
params.put("filter", filter); //likes - default, copies
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
public ArrayList<Long> getMutual(Long target_uid, Long source_uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getMutual");
params.put("target_uid",target_uid);
params.put("source_uid",source_uid);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
/*** methods for photos ***/
public ArrayList<Album> getAlbums(Long oid, Collection<Long> aids, Integer need_system, Integer need_covers, Integer photo_sizes) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAlbums");
params.put("oid", oid);
params.put("aids", arrayToString(aids));
params.put("need_system", need_system);
params.put("need_covers", need_covers);
params.put("photo_sizes", photo_sizes);
JSONObject root = sendRequest(params);
ArrayList<Album> albums=new ArrayList<Album>();
JSONArray array=root.optJSONArray("response");
if (array == null)
return albums;
int category_count=array.length();
for (int i=0; i<category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
Album a = Album.parse(o);
if (a.title.equals("DELETED"))
continue;
albums.add(a);
}
return albums;
}
public ArrayList<Photo> getPhotos(Long uid, Long aid, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.get");
if(uid>0)
params.put("uid", uid);
else
params.put("gid", -uid);
params.put("aid", aid);
params.put("extended", "1");
params.put("offset",offset);
params.put("limit",count);
params.put("v","4.1");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public ArrayList<Photo> getUserPhotos(Long uid, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getUserPhotos");
params.put("uid", uid);
params.put("sort","0");
params.put("count",count);
params.put("offset",offset);
params.put("extended",1);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public ArrayList<Photo> getAllPhotos(Long owner_id, Integer offset, Integer count, boolean extended) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAll");
params.put("owner_id", owner_id);
params.put("offset", offset);
params.put("count",count);
params.put("extended",extended?1:0);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public CommentList getPhotoComments(Long pid, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getComments");
params.put("pid", pid);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
params.put("sort", "asc");
params.put("v", "4.99");
params.put("need_likes", "1");
JSONObject root = sendRequest(params);
Object x=root.get("response");
CommentList commnets = new CommentList();
//TODO remove later
//parse for v=4.99
if(x instanceof JSONArray){
JSONArray array = (JSONArray)x;
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parse(o);
commnets.comments.add(comment);
}
}
//parse for v=5.0
if(x instanceof JSONObject){
JSONObject y=(JSONObject)x;
JSONArray array = y.getJSONArray("items");
commnets.count=y.getInt("count");
int category_count = array.length();
for(int i = 0; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parse(o);
commnets.comments.add(comment);
}
}
return commnets;
}
public CommentList getNoteComments(Long nid, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.getComments");
params.put("nid", nid);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parseNoteComment(o);
commnets.comments.add(comment);
}
return commnets;
}
public CommentList getVideoComments(long video_id, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getComments");
params.put("vid", video_id);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
params.put("v", "4.99");
params.put("need_likes", "1");
JSONObject root = sendRequest(params);
Object x=root.get("response");
CommentList commnets = new CommentList();
//TODO remove later
//parse for v=4.99
if(x instanceof JSONArray){
JSONArray array = (JSONArray)x;
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parse(o);
commnets.comments.add(comment);
}
}
//parse for v=5.0
if(x instanceof JSONObject){
JSONObject y=(JSONObject)x;
JSONArray array = y.getJSONArray("items");
commnets.count=y.getInt("count");
int category_count = array.length();
for(int i = 0; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parse(o);
commnets.comments.add(comment);
}
}
return commnets;
}
//Not used for now
public ArrayList<Comment> getAllPhotoComments(Long owner_id, Long album_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAllComments");
params.put("owner_id", owner_id);
params.put("album_id", album_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
params.put("need_likes", "1");
ArrayList<Comment> commnets = new ArrayList<Comment>();
@SuppressWarnings("unused")
JSONObject root = sendRequest(params);
//JSONArray array = root.getJSONArray("response");
//int category_count = array.length();
//for(int i = 0; i<category_count; ++i) {
// JSONObject o = (JSONObject)array.get(i);
// Comment comment = new Comment();
// comment.cid = Long.parseLong(o.getString("cid"));
// comment.from_id = Long.parseLong(o.getString("from_id"));
// comment.date = Long.parseLong(o.getString("date"));
// comment.message = unescape(o.getString("message"));
// commnets.add(comment);
return commnets;
}
public long createPhotoComment(Long pid, Long owner_id, String message, Long reply_to_cid, Collection<String> attachments, boolean from_group, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.createComment");
params.put("pid",pid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
params.put("reply_to_cid", reply_to_cid);
params.put("attachments", arrayToString(attachments));
if (from_group)
params.put("from_group", "1");
JSONObject root = sendRequest(params, true);
long message_id = root.optLong("response");
return message_id;
}
public boolean editPhotoComment(long cid, long pid, Long owner_id, String message, Collection<String> attachments, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.editComment");
params.put("cid", cid);
params.put("pid", pid);
params.put("owner_id", owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message", message);
params.put("attachments", arrayToString(attachments));
JSONObject root = sendRequest(params, true);
int response = root.optInt("response");
return response == 1;
}
public long createNoteComment(Long nid, Long owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.createComment");
params.put("nid",nid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
//if (reply_to != null && !reply_to.equals(""))
// params.put("reply_to", reply_to);
JSONObject root = sendRequest(params, true);
long message_id = root.optLong("response");
return message_id;
}
public boolean editNoteComment(long cid, Long owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.editComment");
params.put("cid", cid);
params.put("owner_id", owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message", message);
JSONObject root = sendRequest(params, true);
int response = root.optInt("response");
return response == 1;
}
public long createVideoComment(Long video_id, Long owner_id, String message, Collection<String> attachments, boolean from_group, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.createComment");
params.put("vid",video_id);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
params.put("attachments", arrayToString(attachments));
if (from_group)
params.put("from_group", "1");
JSONObject root = sendRequest(params, true);
long message_id = root.optLong("response");
return message_id;
}
public boolean editVideoComment(long cid, Long owner_id, String message, Collection<String> attachments, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.editComment");
params.put("cid", cid);
params.put("owner_id", owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message", message);
params.put("attachments", arrayToString(attachments));
JSONObject root = sendRequest(params, true);
int response = root.optInt("response");
return response == 1;
}
private void addCaptchaParams(String captcha_key, String captcha_sid, Params params) {
params.put("captcha_sid",captcha_sid);
params.put("captcha_key",captcha_key);
}
public ArrayList<Message> getMessages(long time_offset, boolean is_out, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.get");
if (is_out)
params.put("out","1");
if (time_offset!=0)
params.put("time_offset", time_offset);
if (count != 0)
params.put("count", count);
params.put("preview_length","0");
params.put("v","4.2");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
public ArrayList<Message> getMessagesHistory(long uid, long chat_id, long me, Long offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getHistory");
if(chat_id<=0)
params.put("uid",uid);
else
params.put("chat_id",chat_id);
params.put("offset", offset);
if (count != 0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, chat_id<=0, uid, chat_id>0, me);
return messages;
}
public ArrayList<Message> getMessagesDialogs(long offset, int count, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getDialogs");
if (offset!=0)
params.put("offset", offset);
if (count != 0)
params.put("count", count);
params.put("preview_length","0");
params.put("v","4.2");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false ,0);
return messages;
}
private ArrayList<Message> parseMessages(JSONArray array, boolean from_history, long history_uid, boolean from_chat, long me) throws JSONException {
ArrayList<Message> messages = new ArrayList<Message>();
if (array != null) {
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
Message m = Message.parse(o, from_history, history_uid, from_chat, me);
messages.add(m);
}
}
return messages;
}
public String sendMessage(Long uid, long chat_id, String message, String title, String type, Collection<String> attachments, ArrayList<Long> forward_messages, String lat, String lon, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.send");
if(chat_id<=0)
params.put("uid", uid);
else
params.put("chat_id", chat_id);
params.put("message", message);
params.put("title", title);
params.put("type", type);
params.put("attachment", arrayToString(attachments));
params.put("forward_messages", arrayToString(forward_messages));
params.put("lat", lat);
params.put("long", lon);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
Object message_id = root.opt("response");
if (message_id != null)
return String.valueOf(message_id);
return null;
}
public String markAsNewOrAsRead(ArrayList<Long> mids, boolean as_read) throws MalformedURLException, IOException, JSONException, KException{
if (mids == null || mids.size() == 0)
return null;
Params params;
if (as_read)
params = new Params("messages.markAsRead");
else
params = new Params("messages.markAsNew");
params.put("mids", arrayToString(mids));
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String deleteMessage(Long mid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.delete");
params.put("mid", mid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** for status***/
public VkStatus getStatus(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("status.get");
params.put("uid", uid);
JSONObject root = sendRequest(params);
JSONObject obj = root.optJSONObject("response");
VkStatus status = new VkStatus();
if (obj != null) {
status.text = unescape(obj.getString("text"));
JSONObject jaudio = obj.optJSONObject("audio");
if (jaudio != null)
status.audio = Audio.parse(jaudio);
}
return status;
}
public String setStatus(String status_text, String audio) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("status.set");
params.put("text", status_text);
params.put("audio", audio); //oid_aid
JSONObject root = sendRequest(params);
Object response_id = root.opt("response");
if (response_id != null)
return String.valueOf(response_id);
return null;
}
public ArrayList<WallMessage> getWallMessages(Long owner_id, int count, int offset, String filter) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.get");
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
params.put("offset", offset);
params.put("filter", filter); //owner, others, all - default
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
ArrayList<WallMessage> wmessages = new ArrayList<WallMessage>();
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
WallMessage wm = WallMessage.parse(o);
wmessages.add(wm);
}
return wmessages;
}
//always returns about 33-35 items
public Newsfeed getNews(Long start_time, long count, Long end_time, Integer offset, String from, String source_ids, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("newsfeed.get");
params.put("filters","post,photo,photo_tag,friend,note");
params.put("start_time",start_time);
params.put("end_time",end_time);
if(count!=0)
params.put("count",count);
params.put("offset",offset);
params.put("from",from);
params.put("source_ids",source_ids);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
return Newsfeed.parse(root, false);
}
public Newsfeed getNewsComments() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("newsfeed.getComments");
params.put("last_comments","1");
params.put("count","50");
params.put("v","4.4");
JSONObject root = sendRequest(params);
return Newsfeed.parse(root, true);
}
/*** for audio ***/
public ArrayList<Audio> getAudio(Long uid, Long gid, Long album_id, Collection<Long> aids) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.get");
params.put("uid", uid);
params.put("gid", gid);
params.put("aids", arrayToString(aids));
params.put("album_id", album_id);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
public ArrayList<Audio> getAudioById(String audios, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getById");
params.put("audios", audios);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
public String getLyrics(Long id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getLyrics");
params.put("lyrics_id", id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optString("text");
}
/*** for video ***/
public ArrayList<Video> getVideo(String videos, Long owner_id, Long album_id, String width, Long count, Long offset, String access_key) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.get");
params.put("videos", videos);
if (owner_id != null){
if(owner_id>0)
params.put("uid", owner_id);
else
params.put("gid", -owner_id);
}
params.put("width", width);
params.put("count", count);
params.put("offset", offset);
params.put("aid", album_id);
params.put("access_key", access_key);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videoss = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videoss.add(video);
}
}
return videoss;
}
public ArrayList<Video> getUserVideo(Long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getUserVideos");
params.put("uid", user_id);
params.put("count", "50");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videos = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
videos.add(Video.parse(o));
}
}
return videos;
}
/*** for crate album ***/
public Album createAlbum(String title, Long gid, String privacy, String comment_privacy, String description) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.createAlbum");
params.put("title", title);
params.put("gid", gid);
params.put("privacy", privacy);
params.put("comment_privacy", comment_privacy);
params.put("description", description);
JSONObject root = sendRequest(params);
JSONObject o = root.optJSONObject("response");
if (o == null)
return null;
return Album.parse(o);
}
public String editAlbum(long aid, Long oid, String title, String privacy, String comment_privacy, String description) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.editAlbum");
params.put("aid", String.valueOf(aid));
params.put("oid", oid);
params.put("title", title);
params.put("privacy", privacy);
params.put("comment_privacy", comment_privacy);
params.put("description", description);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** for notes ***/
public ArrayList<Note> getNotes(Long uid, Collection<Long> nids, String sort, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notes.get");
params.put("uid", uid);
params.put("nids", arrayToString(nids));
params.put("sort", sort);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Note> notes = new ArrayList<Note>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Note note = Note.parse(o, true);
notes.add(note);
}
}
return notes;
}
public String deleteNote(Long nid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.delete");
params.put("nid", nid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String photosGetUploadServer(long album_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getUploadServer");
params.put("aid",album_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String photosGetWallUploadServer(Long user_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getWallUploadServer");
params.put("uid",user_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String getAudioUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("getAudioUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String photosGetMessagesUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getMessagesUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String photosGetProfileUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getProfileUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public ArrayList<Photo> photosSave(String server, String photos_list, Long aid, Long group_id, String hash, String caption) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.save");
params.put("server",server);
params.put("photos_list",photos_list);
params.put("aid",aid);
params.put("gid",group_id);
params.put("hash",hash);
params.put("caption",caption);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public ArrayList<Photo> saveWallPhoto(String server, String photo, String hash, Long user_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveWallPhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
params.put("uid",user_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public Audio saveAudio(String server, String audio, String hash, String artist, String title) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.save");
params.put("server",server);
params.put("audio",audio);
params.put("hash",hash);
params.put("artist",artist);
params.put("title",title);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
return Audio.parse(response);
}
public ArrayList<Photo> saveMessagesPhoto(String server, String photo, String hash) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveMessagesPhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public String[] saveProfilePhoto(String server, String photo, String hash) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveProfilePhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
String src = response.optString("photo_src");
String hash1 = response.optString("photo_hash");
String[] res=new String[]{src, hash1};
return res;
}
private ArrayList<Photo> parsePhotos(JSONArray array) throws JSONException {
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count=array.length();
for(int i=0; i<category_count; ++i){
//in getUserPhotos first element is integer
if(array.get(i) instanceof JSONObject == false)
continue;
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
/*public long createGraffitiComment(String gid, String owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("graffiti.createComment");
params.put("gid",gid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}*/
public long createWallComment(Long owner_id, Long post_id, String text, Long reply_to_cid, Collection<String> attachments, boolean from_group, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.addComment");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("text", text);
params.put("reply_to_cid", reply_to_cid);
params.put("attachments", arrayToString(attachments));
if (from_group)
params.put("from_group","1");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
JSONObject response = root.getJSONObject("response");
long cid = response.optLong("cid");
return cid;
}
//no documentation
public boolean editWallComment(long cid, Long owner_id, Long post_id, String text, Collection<String> attachments, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.editComment");
params.put("cid", cid);
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("text", text);
params.put("attachments", arrayToString(attachments));
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
int response = root.optInt("response");
return response == 1;
}
public long createWallPost(long owner_id, String text, Collection<String> attachments, String export, boolean only_friends, boolean from_group, boolean signed, String lat, String lon, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.post");
params.put("owner_id", owner_id);
params.put("attachments", arrayToString(attachments));
params.put("lat", lat);
params.put("long", lon);
params.put("message", text);
if(export!=null && export.length()!=0)
params.put("services",export);
if (from_group)
params.put("from_group","1");
if (only_friends)
params.put("friends_only","1");
if (signed)
params.put("signed","1");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
JSONObject response = root.getJSONObject("response");
long post_id = response.optLong("post_id");
return post_id;
}
public long repostWallPost(String object, String message, long gid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.repost");
params.put("gid", gid);
params.put("message", message);
params.put("object", object);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
long post_id = response.optLong("post_id");
return post_id;
}
public CommentList getWallComments(Long owner_id, Long post_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.getComments");
params.put("post_id", post_id);
params.put("owner_id", owner_id);
if (offset > 0)
params.put("offset", offset);
if (count > 0)
params.put("count", count);
params.put("preview_length", "0");
params.put("need_likes", "1");
params.put("v", "4.4");
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) //get(0) is integer, it is comments count
commnets.comments.add(Comment.parse((JSONObject)array.get(i)));
return commnets;
}
public ArrayList<Audio> searchAudio(String q, String sort, String lyrics, Long count, Long offset, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.search");
params.put("q", q);
params.put("sort", sort);
params.put("lyrics", lyrics);
params.put("count", count);
params.put("offset", offset);
params.put("auto_complete", "1");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 1);
}
private ArrayList<Audio> parseAudioList(JSONArray array, int type_array) //type_array must be 0 or 1
throws JSONException {
ArrayList<Audio> audios = new ArrayList<Audio>();
if (array != null) {
for(int i = type_array; i<array.length(); ++i) { //get(0) is integer, it is audio count
JSONObject o = (JSONObject)array.get(i);
audios.add(Audio.parse(o));
}
}
return audios;
}
public String deleteAudio(Long aid, Long oid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.delete");
params.put("aid", aid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String addAudio(Long aid, Long oid, Long gid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.add");
params.put("aid", aid);
params.put("oid", oid);
params.put("gid", gid);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public Long wallAddLike(Long owner_id, Long post_id, boolean need_publish, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.addLike");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("need_publish", need_publish?"1":"0");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
public Long wallDeleteLike(Long owner_id, Long post_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.deleteLike");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
public Long addLike(Long owner_id, Long item_id, String type, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.add");
params.put("owner_id", owner_id);
params.put("item_id", item_id);
params.put("type", type);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
public Long deleteLike(Long owner_id, Long item_id, String type) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.delete");
params.put("owner_id", owner_id);
params.put("item_id", item_id);
params.put("type", type);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
public Long addLike(Long owner_id, String type, Long item_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.add");
params.put("owner_id", owner_id);
params.put("type", type);
params.put("item_id", item_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optLong("likes", -1);
}
public Long deleteLike(Long owner_id, String type, Long item_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.delete");
params.put("owner_id", owner_id);
params.put("type", type);
params.put("item_id", item_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optLong("likes", -1);
}
public ArrayList<Photo> getPhotosById(String photos) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getById");
params.put("photos", photos);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos1 = parsePhotos(array);
return photos1;
}
public ArrayList<Group> getUserGroups(Long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("groups.get");
params.put("extended","1");
params.put("uid",user_id);
JSONObject root = sendRequest(params);
ArrayList<Group> groups=new ArrayList<Group>();
JSONArray array=root.optJSONArray("response");
//if there are no groups "response" will not be array
if(array==null)
return groups;
groups = Group.parseGroups(array);
return groups;
}
public Boolean removeWallPost(Long post_id, long wall_owner_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("wall.delete");
params.put("owner_id", wall_owner_id);
params.put("post_id", post_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deleteWallComment(Long wall_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("wall.deleteComment");
params.put("owner_id", wall_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deleteNoteComment(Long note_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notes.deleteComment");
params.put("owner_id", note_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deleteVideoComment(Long video_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.deleteComment");
params.put("owner_id", video_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deletePhotoComment(long photo_id, Long photo_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.deleteComment");
params.put("owner_id", photo_owner_id);
params.put("cid", comment_id);
params.put("pid", photo_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public ArrayList<Video> searchVideo(String q, String sort, String hd, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.search");
params.put("q", q);
params.put("sort", sort);
params.put("hd", hd);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videoss = new ArrayList<Video>();
if (array != null) {
for(int i = 0; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videoss.add(video);
}
}
return videoss;
}
public ArrayList<User> searchUser(String q, String fields, Long count, Long offset, Integer sort,
Integer city, Integer country, String hometown, Integer university_country, Integer university, Integer university_year,
Integer sex, Integer age_from, Integer age_to, Integer birth_day, Integer birth_month, Integer birth_year,
Integer online, Integer has_photo, Integer school_country, Integer school_city, Integer school, Integer school_year,
String religion, String interests, String company, String position, Long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("users.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
params.put("fields", fields);
if (sort != null && sort > 0)
params.put("sort", sort);
if (city != null && city > 0)
params.put("city", city);
if (country != null && country > 0)
params.put("country", country);
if (hometown != null && hometown.length() > 0)
params.put("hometown", hometown);
if (university_country != null && university_country > 0)
params.put("university_country", university_country);
if (university != null && university > 0)
params.put("university", university);
if (university_year != null && university_year > 0)
params.put("university_year", university_year);
if (sex != null && sex > 0)
params.put("sex", sex);
if (age_from != null && age_from > 0)
params.put("age_from", age_from);
if (age_to != null && age_to > 0)
params.put("age_to", age_to);
if (birth_day != null && birth_day > 0)
params.put("birth_day", birth_day);
if (birth_month != null && birth_month > 0)
params.put("birth_month", birth_month);
if (birth_year != null && birth_year > 0)
params.put("birth_year", birth_year);
if (online != null && online > 0)
params.put("online", online);
if (has_photo != null && has_photo > 0)
params.put("has_photo", has_photo);
if (school_country != null && school_country > 0)
params.put("school_country", school_country);
if (school_city != null && school_city > 0)
params.put("school_city", school_city);
if (school != null && school > 0)
params.put("school", school);
if (school_year != null && school_year > 0)
params.put("school_year", school_year);
if (religion != null && religion.length() > 0)
params.put("religion", religion);
if (interests != null && interests.length() > 0)
params.put("interests", interests);
if (company != null && company.length() > 0)
params.put("company", company);
if (position != null && position.length() > 0)
params.put("position", position);
if (gid != null && gid > 0)
params.put("gid", gid);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
public ArrayList<User> searchUserExtended(String q, String fields, Long count, Long offset, Integer sort,
Integer city, Integer country, String hometown, Integer university_country, Integer university, Integer university_year,
Integer sex, Integer age_from, Integer age_to, Integer birth_day, Integer birth_month, Integer birth_year,
Integer online, Integer has_photo, Integer school_country, Integer school_city, Integer school, Integer school_year,
String religion, String interests, String company, String position, Long gid) throws MalformedURLException, IOException, JSONException, KException {
String uids = Utils.parseProfileId(q);
if (uids != null && uids.length() > 0 && (offset == null || offset == 0)) {
Log.i(TAG, "Search with uid = " + uids);
String code = "var a=API.users.search({\"q\":\"" + q + "\",\"count\":" + count + ",\"count\":" + offset + ",\"fields\":\"" + fields + "\"});";
code += "var b=API.getProfiles({\"uids\":" + uids +",\"fields\":\"" + fields + "\"});";
code += "return b+a;";
Params params = new Params("execute");
params.put("code", code);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
} else
return searchUser(q, fields, count, offset, sort,
city, country, hometown, university_country, university, university_year,
sex, age_from, age_to, birth_day, birth_month, birth_year,
online, has_photo, school_country, school_city, school, school_year,
religion, interests, company, position, gid);
}
public String deleteVideo(Long vid, Long oid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.delete");
params.put("vid", vid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String addVideo(Long vid, Long oid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.add");
params.put("video_id", vid);
params.put("owner_id", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public long createNote(String title, String text) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.add");
params.put("title", title);
params.put("text", text);
params.put("privacy", "0");
params.put("comment_privacy", "0");
JSONObject root = sendRequest(params, true);
JSONObject response = root.getJSONObject("response");
long note_id = response.optLong("nid");
return note_id;
}
public Object[] getLongPollServer(String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getLongPollServer");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
String key=response.getString("key");
String server=response.getString("server");
Long ts = response.getLong("ts");
return new Object[]{key, server, ts};
}
public void setOnline(String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("activity.online");
addCaptchaParams(captcha_key, captcha_sid, params);
sendRequest(params);
}
public long addFriend(Long uid, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.add");
params.put("uid", uid);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
public long deleteFriend(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.delete");
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
public ArrayList<Object[]> getRequestsFriends(Integer out) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getRequests");
params.put("need_messages", "1");
params.put("out", out);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Object[]> users=new ArrayList<Object[]>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i) {
JSONObject item = array.optJSONObject(i);
if (item != null) {
Long id = item.optLong("uid", -1);
if (id!=-1) {
Object[] u = new Object[2];
u[0] = id;
u[1] = item.optString("message");
users.add(u);
}
}
}
}
return users;
}
public String followUser(Long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("subscriptions.follow");
params.put("uid", uid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public String unfollowUser(Long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("subscriptions.unfollow");
params.put("uid", uid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public ArrayList<Long> getSubscriptions(Long uid, int offset, int count, Integer extended) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("users.getSubscriptions");
params.put("uid", uid);
//params.put("extended", extended); //TODO
if (offset>0)
params.put("offset", offset);
if (count>0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
JSONObject jusers = response.optJSONObject("users");
JSONArray array=jusers.optJSONArray("items");
ArrayList<Long> users = new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i) {
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
public ArrayList<User> getFollowers(Long uid, int offset, int count, String fields, String name_case) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("users.getFollowers");
params.put("uid", uid);
if (offset > 0)
params.put("offset", offset);
if (count > 0)
params.put("count", count);
if (fields == null)
fields = "first_name,last_name,photo_medium_rec,online";
params.put("fields", fields);
params.put("name_case", name_case);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("items");
return User.parseUsers(array);
}
public int deleteMessageThread(Long uid, Long chatId) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.deleteDialog");
params.put("uid", uid);
params.put("chat_id", chatId);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
public void execute(String code) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("execute");
params.put("code", code);
sendRequest(params);
}
public boolean deletePhoto(Long owner_id, Long photo_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.delete");
params.put("oid", owner_id);
params.put("pid", photo_id);
JSONObject root = sendRequest(params);
long response = root.optLong("response", -1);
return response==1;
}
public VkPoll getPoll(long poll_id, long owner_id, long topic_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.getById");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
if(topic_id!=0)
params.put("board", topic_id);
params.put("v", "4.6");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return VkPoll.parse(response);
}
public int addPollVote(long poll_id, long answer_id, long owner_id, long topic_id, String captcha_key, String captcha_sid) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.addVote");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
if(topic_id!=0)
params.put("board", topic_id);
params.put("answer_id", answer_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
public int deletePollVote(long poll_id, long answer_id, long owner_id, long topic_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.deleteVote");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
if(topic_id!=0)
params.put("board", topic_id);
params.put("answer_id", answer_id);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
public ArrayList<User> getPollVoters(long poll_id, long owner_id, Collection<Long> answer_ids, Long count, Long offset, String fields, long topic_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.getVoters");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
if(topic_id!=0)
params.put("board", topic_id);
params.put("answer_ids", arrayToString(answer_ids));
params.put("count", count);
params.put("offset", offset);
params.put("fields", fields);
params.put("v", "4.6");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
JSONObject object = (JSONObject)array.get(0);
JSONArray array2 = object.optJSONArray("users");
//TODO for others answer_ids
return User.parseUsers(array2);
}
public ArrayList<FriendsList> friendsLists() throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("friends.getLists");
JSONObject root = sendRequest(params);
ArrayList<FriendsList> result = new ArrayList<FriendsList>();
JSONArray list = root.optJSONArray("response");
if (list != null) {
for (int i=0; i<list.length(); ++i) {
JSONObject o = list.getJSONObject(i);
FriendsList fl = FriendsList.parse(o);
result.add(fl);
}
}
return result;
}
public String saveVideo(String name, String description, Long gid, int privacy_view, int privacy_comment) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.save");
params.put("name", name);
params.put("description", description);
params.put("gid", gid);
if (privacy_view > 0)
params.put("privacy_view", privacy_view);
if (privacy_comment > 0)
params.put("privacy_comment", privacy_comment);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public String deleteAlbum(Long aid, Long gid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.deleteAlbum");
params.put("aid", aid);
params.put("gid", gid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
public ArrayList<PhotoTag> getPhotoTagsById(Long pid, Long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getTags");
params.put("owner_id", owner_id);
params.put("pid", pid);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<PhotoTag>();
ArrayList<PhotoTag> photo_tags = parsePhotoTags(array, pid, owner_id);
return photo_tags;
}
private ArrayList<PhotoTag> parsePhotoTags(JSONArray array, Long pid, Long owner_id) throws JSONException {
ArrayList<PhotoTag> photo_tags=new ArrayList<PhotoTag>();
int category_count=array.length();
for(int i=0; i<category_count; ++i){
//in getUserPhotos first element is integer
if(array.get(i) instanceof JSONObject == false)
continue;
JSONObject o = (JSONObject)array.get(i);
PhotoTag p = PhotoTag.parse(o);
photo_tags.add(p);
if (pid != null)
p.pid = pid;
if (owner_id != null)
p.owner_id = owner_id;
}
return photo_tags;
}
public String putPhotoTag(PhotoTag ptag, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
if (ptag == null)
return null;
Params params = new Params("photos.putTag");
params.put("owner_id", ptag.owner_id);
params.put("pid", ptag.pid);
params.put("uid", ptag.uid);
params.putDouble("x", ptag.x);
params.putDouble("x2", ptag.x2);
params.putDouble("y", ptag.y);
params.putDouble("y2", ptag.y2);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** topics region ***/
public ArrayList<GroupTopic> getGroupTopics(long gid, Integer order, int extended, int count, int offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.getTopics");
params.put("gid", gid);
params.put("order", order);
if (extended == 1)
params.put("extended", "1"); //for profiles
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<GroupTopic> result = new ArrayList<GroupTopic>();
JSONObject response = root.optJSONObject("response");
if (response != null) {
JSONArray topics = response.optJSONArray("topics");
if (topics != null) {
for (int i=1; i<topics.length(); ++i) {
JSONObject o = topics.getJSONObject(i);
GroupTopic gt = GroupTopic.parse(o);
gt.gid = gid;
result.add(gt);
}
}
}
return result;
}
public CommentList getGroupTopicComments(long gid, long tid, int photo_sizes, int extended, int count, int offset, boolean reverse_order) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("board.getComments");
params.put("gid", gid);
params.put("tid", tid);
if (photo_sizes == 1)
params.put("photo_sizes", "1");
if (extended == 1)
params.put("extended", "1");
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
if(reverse_order)
params.put("sort", "desc");
params.put("need_likes", "1");
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
CommentList result = new CommentList();
if (response != null) {
JSONArray comments = response.optJSONArray("comments");
int category_count = comments.length();
result.count=comments.getInt(0);
for (int i=1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = comments.getJSONObject(i);
Comment c = Comment.parseTopicComment(o);
result.comments.add(c);
}
//topic poll parsed separately
if(offset==0){
JSONObject poll_json=response.optJSONObject("poll");
if(poll_json!=null){
VkPoll poll=VkPoll.parse(poll_json);
poll.topic_id=tid;
Attachment attachment=new Attachment();
attachment.poll=poll;
attachment.type="poll";
if(result.comments.size()>0)
result.comments.get(0).attachments.add(attachment);
}
}
}
return result;
}
public long createGroupTopicComment(long gid, long tid, String text, Collection<String> attachments, boolean from_group, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.addComment");
params.put("gid", gid);
params.put("tid", tid);
params.put("text", text);
params.put("attachments", arrayToString(attachments));
if (from_group)
params.put("from_group", "1");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
long message_id = root.optLong("response");
return message_id;
}
public boolean editGroupTopicComment(long cid, long gid, long tid, String text, Collection<String> attachments, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.editComment");
params.put("cid", cid);
params.put("gid", gid);
params.put("tid", tid);
params.put("text", text);
params.put("attachments", arrayToString(attachments));
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
int response = root.optInt("response");
return response == 1;
}
public Boolean deleteGroupTopicComment(long gid, long tid, long cid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.deleteComment");
params.put("gid", gid);
params.put("tid", tid);
params.put("cid", cid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public long createGroupTopic(long gid, String title, String text, boolean from_group, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.addTopic");
params.put("gid", gid);
params.put("title", title);
params.put("text", text);
if (from_group)
params.put("from_group", "1");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
long topic_id = root.optLong("response");
return topic_id;
}
public Boolean deleteGroupTopic(long gid, long tid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.deleteTopic");
params.put("gid", gid);
params.put("tid", tid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
/*** end topics region ***/
public ArrayList<Group> getGroups(Collection<Long> uids, String domain, String fields) throws MalformedURLException, IOException, JSONException, KException{
if (uids == null && domain == null)
return null;
if (uids.size() == 0 && domain == null)
return null;
Params params = new Params("groups.getById");
String str_uids;
if (uids != null && uids.size() > 0)
str_uids=arrayToString(uids);
else
str_uids = domain;
params.put("gids", str_uids);
params.put("fields", fields); //Possible values: place,wiki_page,city,country,description,start_date,finish_date,site,fixed_post
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return Group.parseGroups(array);
}
//no documentation
public String joinGroup(long gid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.join");
params.put("gid", gid);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//no documentation
public String leaveGroup(long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.leave");
params.put("gid", gid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//no documentation
public ArrayList<Group> searchGroup(String q, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Group> groups = new ArrayList<Group>();
//if there are no groups "response" will not be array
if (array==null)
return groups;
groups = Group.parseGroups(array);
return groups;
}
public String registerDevice(String token, String device_model, String system_version, Integer no_text, String subscribe)
throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.registerDevice");
params.put("token", token);
params.put("device_model", device_model);
params.put("system_version", system_version);
params.put("no_text", no_text);
params.put("subscribe", subscribe);
JSONObject root = sendRequest(params);
return root.getString("response");
}
public String unregisterDevice(String token) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.unregisterDevice");
params.put("token", token);
JSONObject root = sendRequest(params);
return root.getString("response");
}
public Notifications getNotifications(String filters, Long start_time, Long end_time, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.get");
params.put("filters", filters);
params.put("start_time", start_time);
params.put("end_time", end_time);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return Notifications.parse(response);
}
public String resetUnreadNotifications() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.markAsViewed");
JSONObject root = sendRequest(params);
return root.getString("response");
}
public ArrayList<Message> getMessagesById(ArrayList<Long> message_ids) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getById");
params.put("mids", arrayToString(message_ids));
params.put("v","4.2");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
public Counters getCounters(String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("getCounters");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response=root.optJSONObject("response");
return Counters.parse(response);
}
/*** faves ***/
public ArrayList<User> getFaveUsers(String fields, Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("fave.getUsers");
if(fields==null)
fields="photo_medium,online";
params.put("fields",fields);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<User> users=new ArrayList<User>();
JSONArray array=root.optJSONArray("response");
//if there are no friends "response" will not be array
if(array==null)
return users;
int category_count=array.length();
for(int i=0; i<category_count; ++i) {
if(array.get(i)==null || ((array.get(i) instanceof JSONObject)==false))
continue;
JSONObject o = (JSONObject)array.get(i);
User u = User.parseFromFave(o);
users.add(u);
}
return users;
}
public ArrayList<Photo> getFavePhotos(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("fave.getPhotos");
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
public ArrayList<Video> getFaveVideos(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("fave.getVideos");
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videos = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videos.add(video);
}
}
return videos;
}
public ArrayList<WallMessage> getFavePosts(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("fave.getPosts");
//params.put("extended", extended);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
//JSONArray array = response.optJSONArray("wall");
//JSONArray profiles_array = response.optJSONArray("profiles");
//JSONArray groups_array = response.optJSONArray("groups");
ArrayList<WallMessage> wmessages = new ArrayList<WallMessage>();
if (array == null)
return wmessages;
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
WallMessage wm = WallMessage.parse(o);
wmessages.add(wm);
}
return wmessages;
}
public ArrayList<Link> getFaveLinks(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("fave.getLinks");
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<Link> groups=new ArrayList<Link>();
JSONArray array=root.optJSONArray("response");
//if there are no groups "response" will not be array
if(array==null)
return groups;
for(int i = 0; i < array.length(); i++) {
if(!(array.get(i) instanceof JSONObject))
continue;
JSONObject jlink = (JSONObject)array.get(i);
Link link = Link.parse(jlink);
groups.add(link);
}
return groups;
}
/*** end faves ***/
/*** chat methods ***/
public Long chatCreate(ArrayList<Long> uids, String title) throws MalformedURLException, IOException, JSONException, KException {
if (uids == null || uids.size() == 0)
return null;
Params params = new Params("messages.createChat");
String str_uids = String.valueOf(uids.get(0));
for (int i=1; i<uids.size(); i++)
str_uids += "," + String.valueOf(uids.get(i));
params.put("uids", str_uids);
params.put("title", title);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
public Integer chatEdit(long chat_id, String title) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.editChat");
params.put("chat_id", chat_id);
params.put("title", title);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
public ArrayList<User> getChatUsers(long chat_id, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.getChatUsers");
params.put("chat_id", chat_id);
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
public Integer addUserToChat(long chat_id, long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.addChatUser");
params.put("chat_id", chat_id);
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
public Integer removeUserFromChat(long chat_id, long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.removeChatUser");
params.put("chat_id", chat_id);
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
/*** end chat methods ***/
public ArrayList<User> getSuggestions(String filter, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("friends.getSuggestions");
params.put("filter", filter); //mutual, contacts, mutual_contacts
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
public Integer importContacts(Collection<String> contacts) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.importContacts");
params.put("contacts", arrayToString(contacts));
JSONObject root = sendRequest(params);
return root.optInt("response");
}
public ArrayList<User> getFriendsByPhones(ArrayList<String> phones, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("friends.getByPhones");
params.put("phones", arrayToString(phones));
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsersForGetByPhones(array);
}
/*** methods for messages search ***/
public ArrayList<Message> searchMessages(String q, int offset, int count, Integer preview_length) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
params.put("preview_length", preview_length);
params.put("v","4.2");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
public ArrayList<SearchDialogItem> searchDialogs(String q, String fields, Integer limit) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.searchDialogs");
params.put("q", q);
params.put("fields", fields);
params.put("limit", limit);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return Message.parseSearchedDialogs(array);
}
public LastActivity getLastActivity(long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getLastActivity");
params.put("uid", user_id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return LastActivity.parse(response);
}
public ArrayList<Long> getGroupsMembers(long gid, Integer count, Integer offset, String sort) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.getMembers");
params.put("gid", gid);
params.put("count", count);
params.put("offset", offset);
params.put("sort", sort); //id_asc, id_desc, time_asc, time_desc
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
public Long getGroupsMembersCount(long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.getMembers");
params.put("gid", gid);
params.put("count", 10);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
return response.optLong("count");
}
public ArrayList<User> getGroupsMembersWithExecute(long gid, Integer count, Integer offset, String sort, String fields) throws MalformedURLException, IOException, JSONException, KException {
//String code = "return API.getProfiles({\"uids\":API.groups.getMembers({\"gid\":" + String.valueOf(gid) + ",\"count\":" + String.valueOf(count) + ",\"offset\":" + String.valueOf(offset) + ",\"sort\":\"id_asc\"}),\"fields\":\"" + fields + "\"});";
String code = "var members=API.groups.getMembers({\"gid\":" + gid + "}); var u=members[1]; return API.getProfiles({\"uids\":u,\"fields\":\"" + fields + "\"});";
Params params = new Params("execute");
params.put("code", code);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
public long getServerTime() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("getServerTime");
JSONObject root = sendRequest(params);
return root.getLong("response");
}
public ArrayList<AudioAlbum> getAudioAlbums(Long uid, Long gid, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getAlbums");
params.put("uid", uid);
params.put("gid", gid);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<AudioAlbum> albums = AudioAlbum.parseAlbums(array);
return albums;
}
public ArrayList<Audio> getAudioRecommendations() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getRecommendations");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
public ArrayList<AudioAlbum> getVideoAlbums(Long uid, Long gid, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getAlbums");
params.put("uid", uid);
params.put("gid", gid);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<AudioAlbum> albums = AudioAlbum.parseAlbums(array);
return albums;
}
public Integer setMessageActivity(Long uid, Long chat_id, boolean typing) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.setActivity");
params.put("uid", uid);
params.put("chat_id", chat_id);
if (typing)
params.put("type", "typing");
JSONObject root = sendRequest(params);
return root.optInt("response");
}
public int editWallPost(long owner_id, long post_id, String text, Collection<String> attachments, String lat, String lon, long place_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.edit");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("message", text);
params.put("attachments", arrayToString(attachments));
params.put("lat", lat);
params.put("long", lon);
params.put("place_id", place_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
return root.optInt("response");
}
public Integer photoEdit(Long owner_id, long pid, String caption) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.edit");
params.put("owner_id", owner_id);
params.put("pid", pid);
params.put("caption", caption);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
public ArrayList<Document> getDocs(Long owner_id, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.get");
params.put("oid", owner_id);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return Document.parseDocs(array);
}
public String docsGetUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.getUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
public Document saveDoc(String file) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.save");
params.put("file", file);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Document> docs = Document.parseDocs(array);
return docs.get(0);
}
public Boolean deleteDoc(Long doc_id, long owner_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.delete");
params.put("oid", owner_id);
params.put("did", doc_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean markNotificationsAsViewed() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.markAsViewed");
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public BannArg getBanned(boolean is_extended, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.getBanned");
if (is_extended)
params.put("extended", "1");
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONObject object = root.optJSONObject("response");
return BannArg.parse(object);
}
public Boolean addBan(Collection<Long> uids, Collection<Long> gids) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.addBan");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (gids != null && gids.size() > 0)
params.put("gids",arrayToString(gids));
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deleteBan(Collection<Long> uids, Collection<Long> gids) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.deleteBan");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (gids != null && gids.size() > 0)
params.put("gids",arrayToString(gids));
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//gets status of broadcasting user current audio to his page
public boolean audioGetBroadcast() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.getBroadcast");
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optInt("enabled")==1;
}
//enables broadcasting user current audio to his page
public boolean audioSetBroadcast(boolean enabled) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.setBroadcast");
params.put("enabled",enabled?"1":"0");
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optInt("enabled")==1;
}
public Long addAudioAlbum(String title, Long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.addAlbum");
params.put("title", title);
params.put("gid", gid);
JSONObject root = sendRequest(params);
JSONObject obj = root.getJSONObject("response");
return obj.optLong("album_id");
}
public Integer editAudioAlbum(String title, long album_id, Long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.editAlbum");
params.put("title", title);
params.put("album_id", album_id);
params.put("gid", gid);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
public Integer deleteAudioAlbum(long album_id, Long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.deleteAlbum");
params.put("album_id", album_id);
params.put("gid", gid);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
public Integer moveToAudioAlbum(Collection<Long> aids, long album_id, Long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.moveToAlbum");
params.put("aids", arrayToString(aids));
params.put("album_id", album_id);
params.put("gid", gid);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
public ArrayList<WallMessage> getWallMessage(ArrayList<String> posts) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.getById");
params.put("posts", arrayToString(posts));
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
ArrayList<WallMessage> wmessages = new ArrayList<WallMessage>();
int category_count = array.length();
for(int i = 0; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
WallMessage wm = WallMessage.parse(o);
wmessages.add(wm);
}
return wmessages;
}
public Integer newsfeedUnsubscribe(String type, Long owner_id, Long item_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.unsubscribe");
params.put("type", type);
params.put("owner_id", owner_id);
params.put("item_id", item_id);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
public ArrayList<User> getBlackList(Long offset, Long count) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.getBanned");
String fields="first_name,last_name,photo_medium,online";
params.put("fields", fields);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return User.parseUsers(array);
}
public Boolean addToBlackList(long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.banUser");
params.put("uid", uid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Boolean deleteFromBlackList(long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.unbanUser");
params.put("uid", uid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public Long docsAdd(long owner_id, long document_id, String access_key) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.add");
params.put("did", document_id);
params.put("oid", owner_id);
params.put("access_key", access_key);
JSONObject root = sendRequest(params);
//returns new document_id
return root.optLong("response");
}
public Newsfeed searchNews(String q, String start_id, int extended, Long start_time, Long end_time, long count, Long offset, double latitude, double longitude, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.search");
params.put("q", q);
params.put("start_id", start_id);
params.put("extended", extended);
params.put("start_time", start_time);
params.put("end_time", end_time);
if (count != 0)
params.put("count", count);
params.put("offset", offset);
if (latitude != 0)
params.putDouble("latitude", latitude);
if (longitude != 0)
params.putDouble("longitude", longitude);
params.put("v", "4.99");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
return Newsfeed.parseFromSearch(root);
}
}
|
package mockit;
import java.io.*;
import java.util.*;
import junit.framework.*;
@SuppressWarnings({
"WaitWhileNotSynced", "UnconditionalWait", "WaitWithoutCorrespondingNotify", "WaitNotInLoop",
"WaitOrAwaitWithoutTimeout", "UnusedDeclaration"
})
public final class JREMockingTest extends TestCase
{
public void testMockingOfFile()
{
new NonStrictExpectations()
{
File file;
{
file.exists(); result = true;
}
};
File f = new File("...");
assertTrue(f.exists());
}
public void testMockingOfCalendar()
{
final Calendar calCST = new GregorianCalendar(2010, 4, 15);
new NonStrictExpectations(Calendar.class) {{
Calendar.getInstance(TimeZone.getTimeZone("CST")); result = calCST;
}};
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("CST"));
assertSame(calCST, cal);
assertEquals(2010, cal.get(Calendar.YEAR));
assertNotSame(calCST, Calendar.getInstance(TimeZone.getTimeZone("PST")));
}
// Mocking of native methods ///////////////////////////////////////////////////////////////////////////////////////
public void testFirstMockingOfNativeMethods() throws Exception
{
new Expectations()
{
// First mocking: puts mocked class in cache, knowing it has native methods to re-register.
@Mocked("sleep") final Thread unused = null;
};
Thread.sleep(5000);
}
public void testSecondMockingOfNativeMethods(@Mocked("isAlive") final Thread mock)
{
new Expectations()
{{
// Second mocking: retrieves from cache, no longer knowing it has native methods to re-register.
mock.isAlive(); result = true;
}};
assertTrue(mock.isAlive());
}
public void testUnmockedNativeMethods() throws Exception
{
Thread.sleep(10);
assertTrue(System.currentTimeMillis() > 0);
}
public static class InterruptibleThread extends Thread
{
protected final boolean interruptRequested()
{
try {
Thread.sleep(10);
return false;
}
catch (InterruptedException ignore) {
interrupt();
return true;
}
}
}
public void testInterruptibleThreadShouldResetItsInterruptStatusWhenInterrupted() throws Exception
{
final InterruptibleThread t = new InterruptibleThread();
new Expectations() {
@Mocked({"sleep", "interrupt"}) final Thread unused = null;
{
Thread.sleep(anyLong); result = new InterruptedException();
onInstance(t).interrupt();
}
};
assertTrue(t.interruptRequested());
}
static class ExampleInterruptibleThread extends InterruptibleThread
{
boolean terminatedCleanly;
@Override
public void run()
{
while (true) {
for (int i = 0; i < 10; i++) {
if (interruptRequested()) break;
}
if (interruptRequested()) break;
}
terminatedCleanly = true;
}
}
public void testInterruptionOfThreadRunningNestedLoops() throws Exception
{
ExampleInterruptibleThread t = new ExampleInterruptibleThread();
t.start();
Thread.sleep(30);
t.interrupt();
t.join();
assertTrue(t.terminatedCleanly);
}
// When a native instance method is called on a regular instance, there is no way to execute its real
// implementation; therefore, dynamic mocking of native methods is not supported.
public void testDynamicMockingOfNativeMethod(@Injectable final Thread t)
{
new NonStrictExpectations()
{
{
t.isAlive();
try {
result = true;
fail();
}
catch (IllegalStateException ignore) {
}
}
};
}
@Injectable FileOutputStream stream;
// This interferes with the test runner if regular mocking is applied.
public void testDynamicMockingOfFileOutputStreamThroughMockField() throws Exception
{
new Expectations()
{
{
stream.write((byte[]) any);
}
};
stream.write("Hello world".getBytes());
}
// Mocking of java.lang.Object methods /////////////////////////////////////////////////////////////////////////////
final Object lock = new Object();
void awaitNotification() throws InterruptedException
{
synchronized (lock) {
lock.wait();
}
}
public void testWaitingWithDynamicPartialMocking() throws Exception
{
final Object mockedLock = new Object();
new Expectations(Object.class)
{
{
mockedLock.wait();
}
};
awaitNotification();
}
public void testWaitingWithLocalMockField() throws Exception
{
new NonStrictExpectations()
{
Object mockedLock;
{
mockedLock.wait(); times = 1;
}
};
awaitNotification();
}
// Un-mockable JRE classes /////////////////////////////////////////////////////////////////////////////////////////
public void testAttemptToMockJREClassThatIsNotMockable()
{
try {
new Expectations() { Class<?> mockClass; };
fail();
}
catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("java.lang.Class"));
}
}
public void testStringBuilder()
{
new NonStrictExpectations() {
StringBuilder builder;
{
builder.length(); result = 20;
builder.toString(); result = "test";
}
};
StringBuilder s = new StringBuilder();
s.append("something");
assertEquals(20, s.length());
assertEquals("test", s.toString());
}
}
|
package com.intellij.ui.jcef;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.util.containers.hash.LinkedHashMap;
import org.cef.CefClient;
import org.cef.CefSettings;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.callback.*;
import org.cef.handler.*;
import org.cef.misc.BoolRef;
import org.cef.network.CefRequest;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* A wrapper over {@link CefClient}.
* <p>
* Provides facilities to add multiple handlers of the same type ({@code CefClient} doesn't).
* All the handlers of the same type are called in the "last-added-last-called" order. When a return value is expected, the last handler's
* return value is returned as the result. When a CEF callback is passed to the handler, it's the responsibility of the client to manage
* the callback calls in case when multiple handlers are added.
*
* @author tav
*/
// [tav]: todo: think if we need some more sophisticated way to handle results of sequence of handles (like foldResults() callback)
@SuppressWarnings({"unused", "UnusedReturnValue"}) // [tav] todo: remove it ( or add*Handler methods not yet used)
@ApiStatus.Experimental
public class JBCefClient implements JBCefDisposable {
private static final Logger LOG = Logger.getInstance(JBCefClient.class);
@NotNull private final CefClient myCefClient;
@NotNull private final DisposeHelper myDisposeHelper = new DisposeHelper();
private final HandlerSupport<CefContextMenuHandler> myContextMenuHandler = new HandlerSupport<>();
private final HandlerSupport<CefDialogHandler> myDialogHandler = new HandlerSupport<>();
private final HandlerSupport<CefDisplayHandler> myDisplayHandler = new HandlerSupport<>();
private final HandlerSupport<CefDownloadHandler> myDownloadHandler = new HandlerSupport<>();
private final HandlerSupport<CefDragHandler> myDragHandler = new HandlerSupport<>();
private final HandlerSupport<CefFocusHandler> myFocusHandler = new HandlerSupport<>();
private final HandlerSupport<CefJSDialogHandler> myJSDialogHandler = new HandlerSupport<>();
private final HandlerSupport<CefKeyboardHandler> myKeyboardHandler = new HandlerSupport<>();
private final HandlerSupport<CefLifeSpanHandler> myLifeSpanHandler = new HandlerSupport<>();
private final HandlerSupport<CefLoadHandler> myLoadHandler = new HandlerSupport<>();
private final HandlerSupport<CefRequestHandler> myRequestHandler = new HandlerSupport<>();
JBCefClient(@NotNull CefClient client) {
myCefClient = client;
Disposer.register(JBCefApp.getInstance().getDisposable(), this);
}
@NotNull
public CefClient getCefClient() {
return myCefClient;
}
@Override
public void dispose() {
myDisposeHelper.dispose(() -> {
try {
myCefClient.dispose();
}
catch (Exception e) {
LOG.warn(e);
}
});
}
@Override
public boolean isDisposed() {
return myDisposeHelper.isDisposed();
}
public JBCefClient addContextMenuHandler(@NotNull CefContextMenuHandler handler, @NotNull CefBrowser browser) {
return myContextMenuHandler.add(handler, browser, () -> {
myCefClient.addContextMenuHandler(new CefContextMenuHandler() {
@Override
public void onBeforeContextMenu(CefBrowser browser, CefFrame frame, CefContextMenuParams params, CefMenuModel model) {
myContextMenuHandler.handle(browser, handler -> {
handler.onBeforeContextMenu(browser, frame, params, model);
});
}
@Override
public boolean onContextMenuCommand(CefBrowser browser,
CefFrame frame,
CefContextMenuParams params,
int commandId,
int eventFlags) {
return myContextMenuHandler.handleNotNull(browser, handler -> {
return handler.onContextMenuCommand(browser, frame, params, commandId, eventFlags);
});
}
@Override
public void onContextMenuDismissed(CefBrowser browser, CefFrame frame) {
myContextMenuHandler.handle(browser, handler -> {
handler.onContextMenuDismissed(browser, frame);
});
}
});
});
}
public void removeContextMenuHandler(@NotNull CefContextMenuHandler handler, @NotNull CefBrowser browser) {
myContextMenuHandler.remove(handler, browser, () -> myCefClient.removeContextMenuHandler());
}
public JBCefClient addDialogHandler(@NotNull CefDialogHandler handler, @NotNull CefBrowser browser) {
return myDialogHandler.add(handler, browser, () -> {
myCefClient.addDialogHandler(new CefDialogHandler() {
@Override
public boolean onFileDialog(CefBrowser browser,
FileDialogMode mode,
String title,
String defaultFilePath,
Vector<String> acceptFilters,
int selectedAcceptFilter,
CefFileDialogCallback callback) {
return myDialogHandler.handleNotNull(browser, handler -> {
return handler.onFileDialog(browser, mode, title, defaultFilePath, acceptFilters, selectedAcceptFilter, callback);
});
}
});
});
}
public void removeDialogHandler(@NotNull CefDialogHandler handler, @NotNull CefBrowser browser) {
myDialogHandler.remove(handler, browser, () -> myCefClient.removeDialogHandler());
}
public JBCefClient addDisplayHandler(@NotNull CefDisplayHandler handler, @NotNull CefBrowser browser) {
return myDisplayHandler.add(handler, browser, () -> {
myCefClient.addDisplayHandler(new CefDisplayHandler() {
@Override
public void onAddressChange(CefBrowser browser, CefFrame frame, String url) {
myDisplayHandler.handle(browser, handler -> {
handler.onAddressChange(browser, frame, url);
});
}
@Override
public void onTitleChange(CefBrowser browser, String title) {
myDisplayHandler.handle(browser, handler -> {
handler.onTitleChange(browser, title);
});
}
@Override
public boolean onTooltip(CefBrowser browser, String text) {
return myDisplayHandler.handleNotNull(browser, handler -> {
return handler.onTooltip(browser, text);
});
}
@Override
public void onStatusMessage(CefBrowser browser, String value) {
myDisplayHandler.handle(browser, handler -> {
handler.onStatusMessage(browser, value);
});
}
@Override
public boolean onConsoleMessage(CefBrowser browser, CefSettings.LogSeverity level, String message, String source, int line) {
return myDisplayHandler.handleNotNull(browser, handler -> {
return handler.onConsoleMessage(browser, level, message, source, line);
});
}
});
});
}
public void removeDisplayHandler(@NotNull CefDisplayHandler handler, @NotNull CefBrowser browser) {
myDisplayHandler.remove(handler, browser, () -> myCefClient.removeDisplayHandler());
}
public JBCefClient addDownloadHandler(@NotNull CefDownloadHandler handler, @NotNull CefBrowser browser) {
return myDownloadHandler.add(handler, browser, () -> {
myCefClient.addDownloadHandler(new CefDownloadHandler() {
@Override
public void onBeforeDownload(CefBrowser browser,
CefDownloadItem downloadItem,
String suggestedName,
CefBeforeDownloadCallback callback) {
myDownloadHandler.handle(browser, handler -> {
handler.onBeforeDownload(browser, downloadItem, suggestedName, callback);
});
}
@Override
public void onDownloadUpdated(CefBrowser browser, CefDownloadItem downloadItem, CefDownloadItemCallback callback) {
myDownloadHandler.handle(browser, handler -> {
handler.onDownloadUpdated(browser, downloadItem, callback);
});
}
});
});
}
public void removeDownloadHandle(@NotNull CefDownloadHandler handler, @NotNull CefBrowser browser) {
myDownloadHandler.remove(handler, browser, () -> myCefClient.removeDownloadHandler());
}
public JBCefClient addDragHandler(@NotNull CefDragHandler handler, @NotNull CefBrowser browser) {
return myDragHandler.add(handler, browser, () -> {
myCefClient.addDragHandler(new CefDragHandler() {
@Override
public boolean onDragEnter(CefBrowser browser, CefDragData dragData, int mask) {
return myDragHandler.handleNotNull(browser, handler -> {
return handler.onDragEnter(browser, dragData, mask);
});
}
});
});
}
public void removeDragHandler(@NotNull CefDragHandler handler, @NotNull CefBrowser browser) {
myDragHandler.remove(handler, browser, () -> myCefClient.removeDragHandler());
}
public JBCefClient addFocusHandler(@NotNull CefFocusHandler handler, @NotNull CefBrowser browser) {
return myFocusHandler.add(handler, browser, () -> {
myCefClient.addFocusHandler(new CefFocusHandler() {
@Override
public void onTakeFocus(CefBrowser browser, boolean next) {
myFocusHandler.handle(browser, handler -> {
handler.onTakeFocus(browser, next);
});
}
@Override
public boolean onSetFocus(CefBrowser browser, FocusSource source) {
return myFocusHandler.handleNotNull(browser, handler -> {
return handler.onSetFocus(browser, source);
});
}
@Override
public void onGotFocus(CefBrowser browser) {
myFocusHandler.handle(browser, handler -> {
handler.onGotFocus(browser);
});
}
});
});
}
public void removeFocusHandler(@NotNull CefFocusHandler handler, @NotNull CefBrowser browser) {
myFocusHandler.remove(handler, browser, () -> myCefClient.removeFocusHandler());
}
public JBCefClient addJSDialogHandler(@NotNull CefJSDialogHandler handler, @NotNull CefBrowser browser) {
return myJSDialogHandler.add(handler, browser, () -> {
myCefClient.addJSDialogHandler(new CefJSDialogHandler() {
@Override
public boolean onJSDialog(CefBrowser browser,
String origin_url,
JSDialogType dialog_type,
String message_text,
String default_prompt_text,
CefJSDialogCallback callback,
BoolRef suppress_message) {
return myJSDialogHandler.handleNotNull(browser, handler -> {
return handler.onJSDialog(browser, origin_url, dialog_type, message_text, default_prompt_text, callback, suppress_message);
});
}
@Override
public boolean onBeforeUnloadDialog(CefBrowser browser, String message_text, boolean is_reload, CefJSDialogCallback callback) {
return myJSDialogHandler.handleNotNull(browser, handler -> {
return handler.onBeforeUnloadDialog(browser, message_text, is_reload, callback);
});
}
@Override
public void onResetDialogState(CefBrowser browser) {
myJSDialogHandler.handle(browser, handler -> {
handler.onResetDialogState(browser);
});
}
@Override
public void onDialogClosed(CefBrowser browser) {
myJSDialogHandler.handle(browser, handler -> {
handler.onDialogClosed(browser);
});
}
});
});
}
public void removeJSDialogHandler(@NotNull CefJSDialogHandler handler, @NotNull CefBrowser browser) {
myJSDialogHandler.remove(handler, browser, () -> myCefClient.removeJSDialogHandler());
}
public JBCefClient addKeyboardHandler(@NotNull CefKeyboardHandler handler, @NotNull CefBrowser browser) {
return myKeyboardHandler.add(handler, browser, () -> {
myCefClient.addKeyboardHandler(new CefKeyboardHandler() {
@Override
public boolean onPreKeyEvent(CefBrowser browser, CefKeyEvent event, BoolRef is_keyboard_shortcut) {
return myKeyboardHandler.handleNotNull(browser, handler -> {
return handler.onPreKeyEvent(browser, event, is_keyboard_shortcut);
});
}
@Override
public boolean onKeyEvent(CefBrowser browser, CefKeyEvent event) {
return myKeyboardHandler.handleNotNull(browser, handler -> {
return handler.onKeyEvent(browser, event);
});
}
});
});
}
public void removeKeyboardHandler(@NotNull CefKeyboardHandler handler, @NotNull CefBrowser browser) {
myKeyboardHandler.remove(handler, browser, () -> myCefClient.removeKeyboardHandler());
}
public JBCefClient addLifeSpanHandler(@NotNull CefLifeSpanHandler handler, @NotNull CefBrowser browser) {
return myLifeSpanHandler.add(handler, browser, () -> {
myCefClient.addLifeSpanHandler(new CefLifeSpanHandler() {
@Override
public boolean onBeforePopup(CefBrowser browser, CefFrame frame, String target_url, String target_frame_name) {
return myLifeSpanHandler.handleNotNull(browser, handler -> {
return handler.onBeforePopup(browser, frame, target_url, target_frame_name);
});
}
@Override
public void onAfterCreated(CefBrowser browser) {
myLifeSpanHandler.handle(browser, handler -> {
handler.onAfterCreated(browser);
});
}
@Override
public void onAfterParentChanged(CefBrowser browser) {
myLifeSpanHandler.handle(browser, handler -> {
handler.onAfterParentChanged(browser);
});
}
@Override
public boolean doClose(CefBrowser browser) {
return myLifeSpanHandler.handleNotNull(browser, handler -> {
return handler.doClose(browser);
});
}
@Override
public void onBeforeClose(CefBrowser browser) {
myLifeSpanHandler.handle(browser, handler -> {
handler.onBeforeClose(browser);
});
}
});
});
}
public void removeLifeSpanHandler(@NotNull CefLifeSpanHandler handler, @NotNull CefBrowser browser) {
myLifeSpanHandler.remove(handler, browser, () -> myCefClient.removeLifeSpanHandler());
}
public JBCefClient addLoadHandler(@NotNull CefLoadHandler handler, @NotNull CefBrowser browser) {
return myLoadHandler.add(handler, browser, () -> {
myCefClient.addLoadHandler(new CefLoadHandler() {
@Override
public void onLoadingStateChange(CefBrowser browser, boolean isLoading, boolean canGoBack, boolean canGoForward) {
myLoadHandler.handle(browser, handler -> {
handler.onLoadingStateChange(browser, isLoading, canGoBack, canGoForward);
});
}
@Override
public void onLoadStart(CefBrowser browser, CefFrame frame, CefRequest.TransitionType transitionType) {
myLoadHandler.handle(browser, handler -> {
handler.onLoadStart(browser, frame, transitionType);
});
}
@Override
public void onLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode) {
myLoadHandler.handle(browser, handler -> {
handler.onLoadEnd(browser, frame, httpStatusCode);
});
}
@Override
public void onLoadError(CefBrowser browser, CefFrame frame, ErrorCode errorCode, String errorText, String failedUrl) {
myLoadHandler.handle(browser, handler -> {
handler.onLoadError(browser, frame, errorCode, errorText, failedUrl);
});
}
});
});
}
public void removeLoadHandler(@NotNull CefLoadHandler handler, @NotNull CefBrowser browser) {
myLoadHandler.remove(handler, browser, () -> myCefClient.removeLoadHandler());
}
public JBCefClient addRequestHandler(@NotNull CefRequestHandler handler, @NotNull CefBrowser browser) {
return myRequestHandler.add(handler, browser, () -> {
myCefClient.addRequestHandler(new CefRequestHandler() {
@Override
public boolean onBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest request, boolean user_gesture, boolean is_redirect) {
return myRequestHandler.handleNotNull(browser, handler -> {
return handler.onBeforeBrowse(browser, frame, request, user_gesture, is_redirect);
});
}
@Nullable
@Override
public CefResourceRequestHandler getResourceRequestHandler(CefBrowser browser,
CefFrame frame,
CefRequest request,
boolean isNavigation,
boolean isDownload,
String requestInitiator,
BoolRef disableDefaultHandling)
{
return myRequestHandler.handle(browser, handler -> {
return handler.getResourceRequestHandler(browser, frame, request, isNavigation, isDownload, requestInitiator, disableDefaultHandling);
});
}
@Override
public boolean getAuthCredentials(CefBrowser browser,
String origin_url,
boolean isProxy,
String host,
int port,
String realm,
String scheme,
CefAuthCallback callback)
{
return myRequestHandler.handleNotNull(browser, handler -> {
return handler.getAuthCredentials(browser, origin_url, isProxy, host, port, realm, scheme, callback);
});
}
@Override
public boolean onQuotaRequest(CefBrowser browser, String origin_url, long new_size, CefRequestCallback callback) {
return myRequestHandler.handleNotNull(browser, handler -> {
return handler.onQuotaRequest(browser, origin_url, new_size, callback);
});
}
@Override
public boolean onCertificateError(CefBrowser browser,
CefLoadHandler.ErrorCode cert_error,
String request_url,
CefRequestCallback callback) {
return myRequestHandler.handleNotNull(browser, handler -> {
return handler.onCertificateError(browser, cert_error, request_url, callback);
});
}
@Override
public void onPluginCrashed(CefBrowser browser, String pluginPath) {
myRequestHandler.handle(browser, handler -> {
handler.onPluginCrashed(browser, pluginPath);
});
}
@Override
public void onRenderProcessTerminated(CefBrowser browser, TerminationStatus status) {
myRequestHandler.handle(browser, handler -> {
handler.onRenderProcessTerminated(browser, status);
});
}
});
});
}
public void removeRequestHandler(@NotNull CefRequestHandler handler, @NotNull CefBrowser browser) {
myRequestHandler.remove(handler, browser, () -> myCefClient.removeRequestHandler());
}
private class HandlerSupport<T> {
private volatile Map<CefBrowser, List<T>> myMap;
private synchronized void syncInitMap() {
if (myMap == null) {
myMap = Collections.synchronizedMap(new LinkedHashMap<>());
}
}
private synchronized List<T> syncInitList(@NotNull CefBrowser browser, @NotNull Runnable onInit) {
List<T> list = myMap.get(browser);
if (list == null) {
myMap.put(browser, list = Collections.synchronizedList(new LinkedList<>()));
onInit.run();
}
return list;
}
private synchronized void syncRemoveFromMap(@NotNull List<T> list, @NotNull CefBrowser browser, @NotNull Runnable onClear) {
if (list.isEmpty()) {
myMap.remove(browser);
onClear.run();
}
}
public JBCefClient add(@NotNull T handler, @NotNull CefBrowser browser, @NotNull Runnable onInit) {
if (myMap == null) {
syncInitMap();
}
List<T> list = myMap.get(browser);
if (list == null) {
list = syncInitList(browser, onInit);
}
list.add(handler);
return JBCefClient.this;
}
public void remove(@NotNull T handler, @NotNull CefBrowser browser, @NotNull Runnable onClear) {
if (myMap != null) {
List<T> list = myMap.get(browser);
if (list != null) {
list.remove(handler);
if (list.isEmpty()) {
syncRemoveFromMap(list, browser, onClear);
}
}
}
}
public void clear() {
if (myMap != null) {
myMap.clear();
}
}
@Nullable
public List<T> get(@NotNull CefBrowser browser) {
return myMap != null ? myMap.get(browser) : null;
}
@Nullable
public <R> R handle(@NotNull CefBrowser browser, @NotNull HandlerCallable<T, R> callable) {
List<T> list = get(browser);
assert list != null;
final Ref<R> lastResult = new Ref<>(null);
list.forEach(handler -> lastResult.set(callable.handle(handler)));
return lastResult.get();
}
@NotNull
public <R> R handleNotNull(@NotNull CefBrowser browser, @NotNull HandlerCallableNotNull<T, R> callable) {
return Objects.requireNonNull(handle(browser, callable));
}
public void handle(@NotNull CefBrowser browser, @NotNull HandlerRunnable<T> runnable) {
List<T> list = get(browser);
if (list == null) return;
list.forEach(handler -> runnable.handle(handler));
}
}
private interface HandlerCallable<T, R> {
@Nullable
R handle(T handler);
}
private interface HandlerCallableNotNull<T, R> extends HandlerCallable<T, R> {
@Override
@NotNull
R handle(T handler);
}
private interface HandlerRunnable<T> {
void handle(T handler);
}
}
|
package com.intellij.util;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.content.*;
import com.intellij.ui.content.impl.TabbedContentImpl;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Supplier;
/**
* @author Konstantin Bulenkov
*/
public class ContentUtilEx extends ContentsUtil {
public static void addTabbedContent(@NotNull ContentManager manager,
@NotNull JComponent contentComponent,
@NotNull @NonNls String groupPrefix,
@NotNull @Nls String tabName,
boolean select,
@Nullable Disposable childDisposable) {
addTabbedContent(manager, new TabGroupId(groupPrefix, groupPrefix),
new TabDescriptor(contentComponent, () -> tabName, childDisposable), select);
}
public static void addTabbedContent(@NotNull ContentManager manager,
@NotNull JComponent contentComponent,
@NotNull @NonNls String groupId,
@NotNull Supplier<@Nls String> groupDisplayName,
@NotNull Supplier<@Nls String> tabDisplayName,
boolean select,
@Nullable Disposable childDisposable) {
addTabbedContent(manager, new TabGroupId(groupId, groupDisplayName),
new TabDescriptor(contentComponent, tabDisplayName, childDisposable), select);
}
public static void addTabbedContent(@NotNull ContentManager manager, @NotNull TabGroupId tabGroupId, @NotNull TabDescriptor tab,
boolean select) {
if (isSplitMode(tabGroupId.getId())) {
addSplitTabbedContent(manager, tabGroupId, tab, select);
}
else {
addMergedTabbedContent(manager, tabGroupId, tab, select);
}
}
public static void addSplitTabbedContent(@NotNull ContentManager manager,
@NotNull TabGroupId tabGroupId,
@NotNull TabDescriptor tab,
boolean select) {
Content content = ContentFactory.SERVICE.getInstance().createContent(tab.getComponent(), tabGroupId.getDisplayName(tab),
true);
content.setTabName(tabGroupId.getDisplayName(tab));
content.putUserData(Content.TABBED_CONTENT_KEY, Boolean.TRUE);
content.putUserData(Content.TAB_GROUP_ID_KEY, tabGroupId);
content.putUserData(Content.TAB_GROUP_NAME_KEY, tabGroupId.getId()); // for backward compatibility
content.putUserData(Content.TAB_DESCRIPTOR_KEY, tab);
Disposer.register(content, tab);
addContent(manager, content, select);
}
private static void addMergedTabbedContent(@NotNull ContentManager manager,
@NotNull TabGroupId tabGroupId,
@NotNull TabDescriptor tab,
boolean select) {
TabbedContent tabbedContent = findTabbedContent(manager, tabGroupId.getId());
if (tabbedContent != null) {
if (select) {
manager.setSelectedContent(tabbedContent, true, true);
}
tabbedContent.addContent(tab, true);
return;
}
createMergedTabbedContent(manager, tabGroupId, Collections.singletonList(tab), tab, select);
}
private static void createMergedTabbedContent(@NotNull ContentManager manager,
@NotNull TabGroupId tabGroupId,
@NotNull List<TabDescriptor> tabs,
@Nullable TabDescriptor tabToSelect,
boolean selectContent) {
Iterator<TabDescriptor> iterator = tabs.iterator();
TabbedContent tabbedContent = new TabbedContentImpl(tabGroupId, iterator.next(), true);
addContent(manager, tabbedContent, selectContent);
while (iterator.hasNext()) {
TabDescriptor tab = iterator.next();
tabbedContent.addContent(tab, tab == tabToSelect);
}
}
@Nullable
public static TabbedContent findTabbedContent(@NotNull ContentManager manager, @NotNull @NonNls String id) {
for (Content content : manager.getContents()) {
if (content instanceof TabbedContent) {
if (((TabbedContent)content).getId().getId().equals(id)) {
return (TabbedContent)content;
}
}
}
return null;
}
@NotNull
public static String getFullName(@NotNull String groupPrefix, @NotNull String tabName) {
return groupPrefix + ": " + tabName;
}
/**
* Searches through all {@link Content simple} and {@link TabbedContent tabbed} contents of the given ContentManager,
* and selects the one which holds the specified {@code contentComponent}.
*
* @return true if the necessary content was found (and thus selected) among content components of the given ContentManager.
*/
public static boolean selectContent(@NotNull ContentManager manager, @NotNull final JComponent contentComponent, boolean requestFocus) {
for (Content content : manager.getContents()) {
if (content instanceof TabbedContentImpl) {
boolean found = ((TabbedContentImpl)content).findAndSelectContent(contentComponent);
if (found) {
manager.setSelectedContent(content, requestFocus);
return true;
}
}
else if (Comparing.equal(content.getComponent(), contentComponent)) {
manager.setSelectedContent(content, requestFocus);
return true;
}
}
return false;
}
/**
* Searches through all {@link Content simple} and {@link TabbedContent tabbed} contents of the given ContentManager,
* trying to find the first one which matches the given condition.
*/
@Nullable
public static JComponent findContentComponent(@NotNull ContentManager manager, @NotNull Condition<? super JComponent> condition) {
for (Content content : manager.getContents()) {
if (content instanceof TabbedContentImpl) {
List<Pair<String, JComponent>> tabs = ((TabbedContentImpl)content).getTabs();
for (Pair<String, JComponent> tab : tabs) {
if (condition.value(tab.second)) {
return tab.second;
}
}
}
else if (condition.value(content.getComponent())) {
return content.getComponent();
}
}
return null;
}
@Nullable
private static JComponent findContentComponent(@NotNull TabbedContent tabbedContent, @NotNull Condition<? super JComponent> condition) {
for (Pair<String, JComponent> tab : tabbedContent.getTabs()) {
if (condition.value(tab.second)) {
return tab.second;
}
}
return null;
}
/**
* Closes content with component that matches specified condition.
*
* @return true if content was found and closed
*/
public static boolean closeContentTab(@NotNull ContentManager manager, @NotNull Condition<? super JComponent> condition) {
for (Content content : manager.getContents()) {
if (content instanceof TabbedContent && ((TabbedContent)content).hasMultipleTabs()) {
TabbedContent tabbedContent = (TabbedContent)content;
JComponent component = findContentComponent(tabbedContent, condition);
if (component != null) {
tabbedContent.removeContent(component);
return true;
}
}
else if (condition.value(content.getComponent())) {
manager.removeContent(content, true);
return true;
}
}
return false;
}
public static int getSelectedTab(@NotNull TabbedContent content) {
int selectedIndex = content.getSelectedIndex();
if (selectedIndex != -1) return selectedIndex;
final JComponent current = content.getComponent();
int index = 0;
for (Pair<String, JComponent> tab : content.getTabs()) {
if (tab.second == current) {
return index;
}
index++;
}
return -1;
}
public static void updateTabbedContentDisplayName(@NotNull ContentManager manager, @NotNull JComponent contentComponent) {
for (Content content : manager.getContents()) {
if (Comparing.equal(content.getComponent(), contentComponent)) {
TabGroupId groupId = content.getUserData(Content.TAB_GROUP_ID_KEY);
TabDescriptor tab = content.getUserData(Content.TAB_DESCRIPTOR_KEY);
if (groupId != null && tab != null) {
content.setDisplayName(groupId.getDisplayName(tab));
return;
}
}
}
}
public static void mergeTabs(@NotNull ContentManager manager, @NotNull TabGroupId groupId) {
List<TabDescriptor> tabs = new ArrayList<>();
Content selectedContent = manager.getSelectedContent();
TabDescriptor selectedTab = null;
List<Content> mergedContent = new ArrayList<>();
for (Content content : manager.getContents()) {
if (groupId.equals(content.getUserData(Content.TAB_GROUP_ID_KEY))) {
TabDescriptor tab = content.getUserData(Content.TAB_DESCRIPTOR_KEY);
if (tab == null) {
tab = new TabDescriptor(content.getComponent(), content.getDisplayName().substring(groupId.getDisplayName().length() + 2));
}
if (content == selectedContent) {
selectedTab = tab;
}
tabs.add(tab);
manager.removeContent(content, false);
content.setComponent(null);
content.setShouldDisposeContent(false);
mergedContent.add(content);
}
}
setSplitMode(groupId.getId(), false);
createMergedTabbedContent(manager, groupId, tabs, selectedTab, selectedTab != null);
mergedContent.forEach(Disposer::dispose);
}
public static boolean isSplitMode(@NonNls @NotNull String groupId) {
return PropertiesComponent.getInstance().getBoolean(TabbedContent.SPLIT_PROPERTY_PREFIX + groupId, false);
}
public static void setSplitMode(@NonNls @NotNull String groupId, boolean value) {
if (value) {
PropertiesComponent.getInstance().setValue(TabbedContent.SPLIT_PROPERTY_PREFIX + groupId, Boolean.TRUE.toString());
}
else {
PropertiesComponent.getInstance().unsetValue(TabbedContent.SPLIT_PROPERTY_PREFIX + groupId);
}
}
}
|
package won.owner.web.rest;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.jena.query.Dataset;
import org.apache.jena.rdf.model.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import won.protocol.agreement.AgreementProtocolState;
import won.protocol.agreement.AgreementProtocolUris;
import won.protocol.agreement.IncompleteConversationDataException;
import won.protocol.rest.LinkedDataFetchingException;
import won.protocol.util.AuthenticationThreadLocal;
import won.protocol.util.linkeddata.CachingLinkedDataSource;
import won.protocol.util.linkeddata.LinkedDataSource;
import won.protocol.util.linkeddata.WonLinkedDataUtils;
@Controller
@RequestMapping("/rest/agreement")
public class AgreementProtocolController {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private LinkedDataSource linkedDataSourceOnBehalfOfNeed;
public void setLinkedDataSource(LinkedDataSource linkedDataSource) {
this.linkedDataSourceOnBehalfOfNeed = linkedDataSource;
}
@RequestMapping(value = "/getAgreementProtocolUris", method = RequestMethod.GET)
public ResponseEntity<AgreementProtocolUris> getHighlevelProtocolUris(URI connectionUri) {
return new ResponseEntity<AgreementProtocolUris>(
getAgreementProtocolState(connectionUri).getAgreementProtocolUris(), HttpStatus.OK);
}
@RequestMapping(value = "/getRetractedUris", method = RequestMethod.GET)
public ResponseEntity<Set<URI>> getRetractedUris(URI connectionUri) {
Set<URI> uris = getAgreementProtocolState(connectionUri).getRetractedUris();
return new ResponseEntity<>(uris, HttpStatus.OK);
}
@RequestMapping(value = "/getAgreements", method = RequestMethod.GET)
public ResponseEntity<Dataset> getAgreements(URI connectionUri) {
Dataset agreements = getAgreementProtocolState(connectionUri).getAgreements();
return new ResponseEntity<>(agreements, HttpStatus.OK);
}
@RequestMapping(value = "/getAgreementUris", method = RequestMethod.GET)
public ResponseEntity<Set<URI>> getAgreementUris(URI connectionUri) {
Set<URI> uris = getAgreementProtocolState(connectionUri).getAgreementUris();
return new ResponseEntity<>(uris, HttpStatus.OK);
}
@RequestMapping(value = "/getAgreement", method = RequestMethod.GET)
public ResponseEntity<Model> getAgreement(URI connectionUri, String agreementUri) {
Model agreement = getAgreementProtocolState(connectionUri).getAgreement(URI.create(agreementUri));
return new ResponseEntity<>(agreement, HttpStatus.OK);
}
@RequestMapping(value = "/getPendingProposals", method = RequestMethod.GET)
public ResponseEntity<Dataset> getProposals(URI connectionUri) {
Dataset proposals = getAgreementProtocolState(connectionUri).getPendingProposals();
return new ResponseEntity<>(proposals, HttpStatus.OK);
}
@RequestMapping(value = "/getPendingProposalUris", method = RequestMethod.GET)
public ResponseEntity<Set<URI>> getProposalUris(URI connectionUri) {
Set<URI> uris = getAgreementProtocolState(connectionUri).getPendingProposalUris();
return new ResponseEntity<>(uris, HttpStatus.OK);
}
@RequestMapping(value = "/getPendingProposal", method = RequestMethod.GET)
public ResponseEntity<Model> getProposal(URI connectionUri, String proposalUri) {
Model proposal = getAgreementProtocolState(connectionUri).getPendingProposal(URI.create(proposalUri));
return new ResponseEntity<>(proposal, HttpStatus.OK);
}
@RequestMapping(value = "/getCancellationPendingAgreementUris", method = RequestMethod.GET)
public ResponseEntity<Set<URI>> getAgreementsProposedToBeCancelledUris(URI connectionUri) {
Set<URI> uris = getAgreementProtocolState(connectionUri).getCancellationPendingAgreementUris();
return new ResponseEntity<>(uris, HttpStatus.OK);
}
@RequestMapping(value = "/getCancelledAgreementUris", method = RequestMethod.GET)
public ResponseEntity<Set<URI>> getCancelledAgreementUris(URI connectionUri) {
Set<URI> uris = getAgreementProtocolState(connectionUri).getCancelledAreementUris();
return new ResponseEntity<>(uris, HttpStatus.OK);
}
@RequestMapping(value = "/getRejectedUris", method = RequestMethod.GET)
public ResponseEntity<Set<URI>> getRejectedProposalUris(URI connectionUri) {
Set<URI> uris = getAgreementProtocolState(connectionUri).getRejectedUris();
return new ResponseEntity<>(uris, HttpStatus.OK);
}
private Dataset getConversationDataset(URI connectionUri) {
try {
AuthenticationThreadLocal.setAuthentication(SecurityContextHolder.getContext().getAuthentication());
return WonLinkedDataUtils.getConversationAndNeedsDataset(connectionUri, linkedDataSourceOnBehalfOfNeed);
} finally {
// be sure to remove the principal from the threadlocal
AuthenticationThreadLocal.remove();
}
}
private AgreementProtocolState getAgreementProtocolState(URI connectionUri) {
Set<URI> recrawled = new HashSet<>();
while(true) {
//we leave the loop either with a runtime exception or with the result
try {
Dataset conversationDataset = getConversationDataset(connectionUri);
return AgreementProtocolState.of(conversationDataset);
} catch (IncompleteConversationDataException e) {
// we may have tried to crawl a conversation dataset of which messages
// were still in-flight. we allow one re-crawl attempt per exception before
// we throw the exception on:
URI connectionContainerUri = WonLinkedDataUtils.getEventContainerURIforConnectionURI(connectionUri, linkedDataSourceOnBehalfOfNeed);
URI remoteConnectionUri = WonLinkedDataUtils.getRemoteConnectionURIforConnectionURI(connectionUri, linkedDataSourceOnBehalfOfNeed);
if (!recrawl(recrawled, connectionUri, e.getMissingMessageUri(), e.getReferringMessageUri(), connectionContainerUri, connectionUri, remoteConnectionUri)){
throw e;
}
} catch (LinkedDataFetchingException e) {
if (!recrawl(recrawled, connectionUri, e.getResourceUri())){
throw e;
}
}
}
}
private boolean recrawl(Set<URI> recrawled, URI connectionUri, URI... uris) {
Set<URI> urisToCrawl = new HashSet<URI>();
Arrays.stream(uris)
.filter(x -> ! recrawled.contains(x))
.forEach(urisToCrawl::add);
if (urisToCrawl.isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("connection {}: not recrawling again: {}", connectionUri, Arrays.toString(uris));
}
return false;
}
if (logger.isDebugEnabled()) {
logger.debug("connection {}, recrawling: {}", connectionUri, urisToCrawl);
}
if (linkedDataSourceOnBehalfOfNeed instanceof CachingLinkedDataSource) {
urisToCrawl.stream().forEach(((CachingLinkedDataSource)linkedDataSourceOnBehalfOfNeed)::invalidate);
}
recrawled.addAll(urisToCrawl);
return true;
}
}
|
package mondrian.rolap;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import mondrian.olap.*;
import mondrian.rolap.RolapConnection.NonEmptyResult;
import mondrian.rolap.RolapNative.Listener;
import mondrian.rolap.RolapNative.NativeEvent;
import mondrian.rolap.RolapNative.TupleEvent;
import mondrian.rolap.cache.HardSmartCache;
import mondrian.rolap.sql.MemberChildrenConstraint;
import mondrian.rolap.sql.TupleConstraint;
import mondrian.test.SqlPattern;
import mondrian.test.TestContext;
import mondrian.util.Bug;
import mondrian.spi.Dialect;
import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.eigenbase.util.property.BooleanProperty;
import org.eigenbase.util.property.StringProperty;
/**
* Tests for NON EMPTY Optimization, includes SqlConstraint type hierarchy and
* RolapNative classes.
*
* @author av
* @since Nov 21, 2005
* @version $Id$
*/
public class NonEmptyTest extends BatchTestCase {
private static Logger logger = Logger.getLogger(NonEmptyTest.class);
SqlConstraintFactory scf = SqlConstraintFactory.instance();
TestContext localTestContext;
public NonEmptyTest() {
super();
}
public NonEmptyTest(String name) {
super(name);
}
@Override
public TestContext getTestContext() {
return localTestContext != null
? localTestContext : super.getTestContext();
}
public void setTestContext(TestContext testContext) {
localTestContext = testContext;
}
public void testBugMondrian584EnumOrder() {
// The interpreter results include males before females, which is
// correct because it is consistent with the explicit order present
// in the query. Native evaluation returns the females before males,
// which is probably a reflection of the database ordering.
if (Bug.BugMondrian584Fixed) {
checkNative(
4,
4,
"SELECT non empty { CrossJoin( "
+ " {Gender.M, Gender.F}, "
+ " { [Marital Status].[Marital Status].members } "
+ ") } on 0 from sales");
}
}
public void testBugCantRestrictSlicerToCalcMember() throws Exception {
TestContext ctx = getTestContext();
ctx.assertQueryReturns(
"WITH MEMBER [Time].[Aggr] AS 'Aggregate({[Time].[1998].[Q1], [Time].[1998].[Q2]})' "
+ "SELECT {[Measures].[Store Sales]} ON COLUMNS, "
+ "NON EMPTY Order(TopCount([Customers].[Name].Members,3,[Measures].[Store Sales]),[Measures].[Store Sales],BASC) ON ROWS "
+ "FROM [Sales] "
+ "WHERE ([Time].[Aggr])",
"Axis
+ "{[Time].[Aggr]}\n"
+ "Axis
+ "{[Measures].[Store Sales]}\n"
+ "Axis
}
public void testBug1961163() throws Exception {
assertQueryReturns(
"with member [Measures].[AvgRevenue] as 'Avg([Store].[Store Name].Members, [Measures].[Store Sales])' "
+ "select NON EMPTY {[Measures].[Store Sales], [Measures].[AvgRevenue]} ON COLUMNS, "
+ "NON EMPTY Filter([Store].[Store Name].Members, ([Measures].[AvgRevenue] < [Measures].[Store Sales])) ON ROWS "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Store Sales]}\n"
+ "{[Measures].[AvgRevenue]}\n"
+ "Axis
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n"
+ "Row #0: 45,750.24\n"
+ "Row #0: 43,479.86\n"
+ "Row #1: 54,545.28\n"
+ "Row #1: 43,479.86\n"
+ "Row #2: 54,431.14\n"
+ "Row #2: 43,479.86\n"
+ "Row #3: 55,058.79\n"
+ "Row #3: 43,479.86\n"
+ "Row #4: 87,218.28\n"
+ "Row #4: 43,479.86\n"
+ "Row #5: 52,896.30\n"
+ "Row #5: 43,479.86\n"
+ "Row #6: 52,644.07\n"
+ "Row #6: 43,479.86\n"
+ "Row #7: 49,634.46\n"
+ "Row #7: 43,479.86\n"
+ "Row #8: 74,843.96\n"
+ "Row #8: 43,479.86\n");
}
public void testTopCountWithCalcMemberInSlicer() {
// Internal error: can not restrict SQL to calculated Members
TestContext ctx = getTestContext();
ctx.assertQueryReturns(
"with member [Time].[First Term] as 'Aggregate({[Time].[1997].[Q1], [Time].[1997].[Q2]})' "
+ "select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "TopCount([Product].[Product Subcategory].Members, 3, [Measures].[Unit Sales]) ON ROWS "
+ "from [Sales] "
+ "where ([Time].[First Term]) ",
"Axis
+ "{[Time].[First Term]}\n"
+ "Axis
+ "{[Measures].[Unit Sales]}\n"
+ "Axis
+ "{[Product].[All Products].[Food].[Produce].[Vegetables].[Fresh Vegetables]}\n"
+ "{[Product].[All Products].[Food].[Produce].[Fruit].[Fresh Fruit]}\n"
+ "{[Product].[All Products].[Food].[Canned Foods].[Canned Soup].[Soup]}\n"
+ "Row #0: 10,215\n"
+ "Row #1: 5,711\n"
+ "Row #2: 3,926\n");
}
public void testTopCountCacheKeyMustIncludeCount() {
/**
* When caching topcount results, the number of elements must
* be part of the cache key
*/
TestContext ctx = getTestContext();
// fill cache
ctx.assertQueryReturns(
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "TopCount([Product].[Product Subcategory].Members, 2, [Measures].[Unit Sales]) ON ROWS "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Unit Sales]}\n"
+ "Axis
+ "{[Product].[All Products].[Food].[Produce].[Vegetables].[Fresh Vegetables]}\n"
+ "{[Product].[All Products].[Food].[Produce].[Fruit].[Fresh Fruit]}\n"
+ "Row #0: 20,739\n"
+ "Row #1: 11,767\n");
// run again with different count
ctx.assertQueryReturns(
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "TopCount([Product].[Product Subcategory].Members, 3, [Measures].[Unit Sales]) ON ROWS "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Unit Sales]}\n"
+ "Axis
+ "{[Product].[All Products].[Food].[Produce].[Vegetables].[Fresh Vegetables]}\n"
+ "{[Product].[All Products].[Food].[Produce].[Fruit].[Fresh Fruit]}\n"
+ "{[Product].[All Products].[Food].[Canned Foods].[Canned Soup].[Soup]}\n"
+ "Row #0: 20,739\n"
+ "Row #1: 11,767\n"
+ "Row #2: 8,006\n");
}
public void testStrMeasure() {
TestContext ctx = TestContext.create(
null,
"<Cube name=\"StrMeasure\"> \n"
+ " <Table name=\"promotion\"/> \n"
+ " <Dimension name=\"Promotions\"> \n"
+ " <Hierarchy hasAll=\"true\" > \n"
+ " <Level name=\"Promotion Name\" column=\"promotion_name\" uniqueMembers=\"true\"/> \n"
+ " </Hierarchy> \n"
+ " </Dimension> \n"
+ " <Measure name=\"Media\" column=\"media_type\" aggregator=\"max\" datatype=\"String\"/> \n"
+ "</Cube> \n",
null,
null,
null,
null);
ctx.assertQueryReturns(
"select {[Measures].[Media]} on columns " + "from [StrMeasure]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Media]}\n"
+ "Row #0: TV\n");
}
public void testBug1515302() {
TestContext ctx = TestContext.create(
null,
"<Cube name=\"Bug1515302\"> \n"
+ " <Table name=\"sales_fact_1997\"/> \n"
+ " <Dimension name=\"Promotions\" foreignKey=\"promotion_id\"> \n"
+ " <Hierarchy hasAll=\"false\" primaryKey=\"promotion_id\"> \n"
+ " <Table name=\"promotion\"/> \n"
+ " <Level name=\"Promotion Name\" column=\"promotion_name\" uniqueMembers=\"true\"/> \n"
+ " </Hierarchy> \n"
+ " </Dimension> \n"
+ " <Dimension name=\"Customers\" foreignKey=\"customer_id\"> \n"
+ " <Hierarchy hasAll=\"true\" allMemberName=\"All Customers\" primaryKey=\"customer_id\"> \n"
+ " <Table name=\"customer\"/> \n"
+ " <Level name=\"Country\" column=\"country\" uniqueMembers=\"true\"/> \n"
+ " <Level name=\"State Province\" column=\"state_province\" uniqueMembers=\"true\"/> \n"
+ " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/> \n"
+ " <Level name=\"Name\" column=\"customer_id\" type=\"Numeric\" uniqueMembers=\"true\"/> \n"
+ " </Hierarchy> \n"
+ " </Dimension> \n"
+ " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"/> \n"
+ "</Cube> \n",
null,
null,
null,
null);
ctx.assertQueryReturns(
"select {[Measures].[Unit Sales]} on columns, "
+ "non empty crossjoin({[Promotions].[Big Promo]}, "
+ "Descendants([Customers].[USA], [City], "
+ "SELF_AND_BEFORE)) on rows "
+ "from [Bug1515302]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Unit Sales]}\n"
+ "Axis
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Anacortes]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Ballard]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Bellingham]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Burien]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Everett]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Marysville]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Olympia]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Redmond]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Renton]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Seattle]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n"
+ "{[Promotions].[Big Promo], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n"
+ "Row #0: 1,789\n"
+ "Row #1: 1,789\n"
+ "Row #2: 20\n"
+ "Row #3: 35\n"
+ "Row #4: 15\n"
+ "Row #5: 18\n"
+ "Row #6: 60\n"
+ "Row #7: 42\n"
+ "Row #8: 36\n"
+ "Row #9: 79\n"
+ "Row #10: 58\n"
+ "Row #11: 520\n"
+ "Row #12: 438\n"
+ "Row #13: 14\n"
+ "Row #14: 20\n"
+ "Row #15: 65\n"
+ "Row #16: 3\n"
+ "Row #17: 366\n");
}
/**
* Must not use native sql optimization because it chooses the wrong
* RolapStar in SqlContextConstraint/SqlConstraintUtils. Test ensures that
* no exception is thrown.
*/
public void testVirtualCube() throws Exception {
if (MondrianProperties.instance().TestExpDependencies.get() > 0) {
return;
}
TestCase c = new TestCase(
99,
3,
"select NON EMPTY {[Measures].[Unit Sales], [Measures].[Warehouse Sales]} ON COLUMNS, "
+ "NON EMPTY [Product].[All Products].Children ON ROWS "
+ "from [Warehouse and Sales]");
c.run();
}
public void testVirtualCubeMembers() throws Exception {
if (MondrianProperties.instance().TestExpDependencies.get() > 0) {
return;
}
// ok to use native sql optimization for members on a virtual cube
TestCase c = new TestCase(
6,
3,
"select NON EMPTY {[Measures].[Unit Sales], [Measures].[Warehouse Sales]} ON COLUMNS, "
+ "NON EMPTY {[Product].[Product Family].Members} ON ROWS "
+ "from [Warehouse and Sales]");
c.run();
}
/**
* verifies that redundant set braces do not prevent native evaluation
* for example, {[Store].[Store Name].members} and
* {{[Store Type].[Store Type].members}}
*/
public void testNativeCJWithRedundantSetBraces() {
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
boolean requestFreshConnection = true;
checkNative(
0,
20,
"select non empty {CrossJoin({[Store].[Store Name].members}, "
+ " {{[Store Type].[Store Type].members}})}"
+ " on rows, "
+ "{[Measures].[Store Sqft]} on columns "
+ "from [Store]",
null,
requestFreshConnection);
}
/**
* Verifies that CrossJoins with two non native inputs can be natively
* evaluated.
*/
public void testExpandAllNonNativeInputs() {
// This query will not run natively unless the <Dimension>.Children
// expression is expanded to a member list.
// Note: Both dimensions only have one hierarchy, which has the All
// member. <Dimension>.Children is interpreted as the children of
// the All member.
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
boolean requestFreshConnection = true;
checkNative(
0,
2,
"select "
+ "NonEmptyCrossJoin([Gender].Children, [Store].Children) on columns "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Gender].[All Gender].[F], [Store].[All Stores].[USA]}\n"
+ "{[Gender].[All Gender].[M], [Store].[All Stores].[USA]}\n"
+ "Row #0: 131,558\n"
+ "Row #0: 135,215\n",
requestFreshConnection);
}
/**
* Verifies that CrossJoins with one non native inputs can be natively
* evaluated.
*/
public void testExpandOneNonNativeInput() {
// This query will not be evaluated natively unless the Filter
// expression is expanded to a member list.
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
boolean requestFreshConnection = true;
checkNative(
0, 1,
"With "
+ "Set [*Filtered_Set] as Filter([Product].[Product Name].Members, [Product].CurrentMember IS [Product].[Product Name].[Fast Raisins]) "
+ "Set [*NECJ_Set] as NonEmptyCrossJoin([Store].[Store Country].Members, [*Filtered_Set]) "
+ "select [*NECJ_Set] on columns "
+ "From [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Store].[All Stores].[USA], [Product].[All Products].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Raisins]}\n"
+ "Row #0: 152\n",
requestFreshConnection);
}
/**
* Check that the ExpandNonNative does not create Joins with input lists
* containing large number of members.
*/
public void testExpandNonNativeResourceLimitFailure() {
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
propSaver.set(MondrianProperties.instance().ResultLimit, 2);
try {
executeQuery(
"select "
+ "NonEmptyCrossJoin({[Gender].Children, [Gender].[F]}, {[Store].Children, [Store].[Mexico]}) on columns "
+ "from [Sales]");
fail("Expected error did not occur");
} catch (Throwable e) {
String expectedErrorMsg =
"Mondrian Error:Size of CrossJoin result (3) exceeded limit (2)";
assertEquals(expectedErrorMsg, e.getMessage());
}
}
/**
* Verify that the presence of All member in all the inputs disables native
* evaluation, even when ExpandNonNative is true.
*/
public void testExpandAllMembersInAllInputs() {
// This query will not be evaluated natively, even if the Hierarchize
// expression is expanded to a member list. The reason is that the
// expanded list contains ALL members.
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
checkNotNative(
1, "select NON EMPTY {[Time].[1997]} ON COLUMNS,\n"
+ " NON EMPTY Crossjoin(Hierarchize(Union({[Store].[All Stores]},\n"
+ " [Store].[USA].[CA].[San Francisco].[Store 14].Children)), {[Product].[All Products]}) \n"
+ " ON ROWS\n"
+ " from [Sales]\n"
+ " where [Measures].[Unit Sales]",
"Axis
+ "{[Measures].[Unit Sales]}\n"
+ "Axis
+ "{[Time].[1997]}\n"
+ "Axis
+ "{[Store].[All Stores], [Product].[All Products]}\n"
+ "Row #0: 266,773\n");
}
/**
* Verifies that the presence of calculated member in all the inputs
* disables native evaluation, even when ExpandNonNative is true.
*/
public void testExpandCalcMembersInAllInputs() {
// This query will not be evaluated natively, even if the Hierarchize
// expression is expanded to a member list. The reason is that the
// expanded list contains ALL members.
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
checkNotNative(
1,
"With "
+ "Member [Product].[*CTX_MEMBER_SEL~SUM] as 'Sum({[Product].[Product Family].Members})' "
+ "Member [Gender].[*CTX_MEMBER_SEL~SUM] as 'Sum({[Gender].[All Gender]})' "
+ "Select "
+ "NonEmptyCrossJoin({[Gender].[*CTX_MEMBER_SEL~SUM]},{[Product].[*CTX_MEMBER_SEL~SUM]}) "
+ "on columns "
+ "From [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Gender].[*CTX_MEMBER_SEL~SUM], [Product].[*CTX_MEMBER_SEL~SUM]}\n"
+ "Row #0: 266,773\n");
}
/**
* Check that if both inputs to NECJ are either
* AllMember(currentMember, defaultMember are also AllMember)
* or Calcculated member
* native CJ is not used.
*/
public void testExpandCalcMemberInputNECJ() {
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
checkNotNative(
1,
"With \n"
+ "Member [Product].[All Products].[Food].[CalcSum] as \n"
+ "'Sum({[Product].[All Products].[Food]})', SOLVE_ORDER=-100\n"
+ "Select\n"
+ "{[Measures].[Store Cost]} on columns,\n"
+ "NonEmptyCrossJoin({[Product].[All Products].[Food].[CalcSum]},\n"
+ " {[Education Level].DefaultMember}) on rows\n"
+ "From [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Store Cost]}\n"
+ "Axis
+ "{[Product].[All Products].[Food].[CalcSum], [Education Level].[All Education Levels]}\n"
+ "Row #0: 163,270.72\n");
}
/**
* Native evaluation is no longer possible after the fix to
* {@link #testCjEnumCalcMembersBug()} test.
*/
public void testExpandCalcMembers() {
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
checkNotNative(
9,
"with "
+ "member [Store Type].[All Store Types].[S] as sum({[Store Type].[All Store Types]}) "
+ "set [Enum Store Types] as {"
+ " [Store Type].[All Store Types].[Small Grocery], "
+ " [Store Type].[All Store Types].[Supermarket], "
+ " [Store Type].[All Store Types].[HeadQuarters], "
+ " [Store Type].[All Store Types].[S]} "
+ "set [Filtered Enum Store Types] as Filter([Enum Store Types], [Measures].[Unit Sales] > 0)"
+ "select NonEmptyCrossJoin([Product].[All Products].Children, [Filtered Enum Store Types]) on columns from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Product].[All Products].[Drink], [Store Type].[All Store Types].[Small Grocery]}\n"
+ "{[Product].[All Products].[Drink], [Store Type].[All Store Types].[Supermarket]}\n"
+ "{[Product].[All Products].[Drink], [Store Type].[All Store Types].[S]}\n"
+ "{[Product].[All Products].[Food], [Store Type].[All Store Types].[Small Grocery]}\n"
+ "{[Product].[All Products].[Food], [Store Type].[All Store Types].[Supermarket]}\n"
+ "{[Product].[All Products].[Food], [Store Type].[All Store Types].[S]}\n"
+ "{[Product].[All Products].[Non-Consumable], [Store Type].[All Store Types].[Small Grocery]}\n"
+ "{[Product].[All Products].[Non-Consumable], [Store Type].[All Store Types].[Supermarket]}\n"
+ "{[Product].[All Products].[Non-Consumable], [Store Type].[All Store Types].[S]}\n"
+ "Row #0: 574\n"
+ "Row #0: 14,092\n"
+ "Row #0: 24,597\n"
+ "Row #0: 4,764\n"
+ "Row #0: 108,188\n"
+ "Row #0: 191,940\n"
+ "Row #0: 1,219\n"
+ "Row #0: 28,275\n"
+ "Row #0: 50,236\n");
}
/**
* Verify that evaluation is native for expressions with nested non native
* inputs that preduce MemberList results.
*/
public void testExpandNestedNonNativeInputs() {
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
boolean requestFreshConnection = true;
checkNative(
0,
6,
"select "
+ "NonEmptyCrossJoin("
+ " NonEmptyCrossJoin([Gender].Children, [Store].Children), "
+ " [Product].Children) on columns "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Gender].[All Gender].[F], [Store].[All Stores].[USA], [Product].[All Products].[Drink]}\n"
+ "{[Gender].[All Gender].[F], [Store].[All Stores].[USA], [Product].[All Products].[Food]}\n"
+ "{[Gender].[All Gender].[F], [Store].[All Stores].[USA], [Product].[All Products].[Non-Consumable]}\n"
+ "{[Gender].[All Gender].[M], [Store].[All Stores].[USA], [Product].[All Products].[Drink]}\n"
+ "{[Gender].[All Gender].[M], [Store].[All Stores].[USA], [Product].[All Products].[Food]}\n"
+ "{[Gender].[All Gender].[M], [Store].[All Stores].[USA], [Product].[All Products].[Non-Consumable]}\n"
+ "Row #0: 12,202\n"
+ "Row #0: 94,814\n"
+ "Row #0: 24,542\n"
+ "Row #0: 12,395\n"
+ "Row #0: 97,126\n"
+ "Row #0: 25,694\n",
requestFreshConnection);
}
/**
* Verify that a low value for maxConstraints disables native evaluation,
* even when ExpandNonNative is true.
*/
public void testExpandLowMaxConstraints() {
propSaver.set(MondrianProperties.instance().MaxConstraints, 2);
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
checkNotNative(
12,
"select NonEmptyCrossJoin("
+ " Filter([Store Type].Children, [Measures].[Unit Sales] > 10000), "
+ " [Product].Children) on columns "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Store Type].[All Store Types].[Deluxe Supermarket], [Product].[All Products].[Drink]}\n"
+ "{[Store Type].[All Store Types].[Deluxe Supermarket], [Product].[All Products].[Food]}\n"
+ "{[Store Type].[All Store Types].[Deluxe Supermarket], [Product].[All Products].[Non-Consumable]}\n"
+ "{[Store Type].[All Store Types].[Gourmet Supermarket], [Product].[All Products].[Drink]}\n"
+ "{[Store Type].[All Store Types].[Gourmet Supermarket], [Product].[All Products].[Food]}\n"
+ "{[Store Type].[All Store Types].[Gourmet Supermarket], [Product].[All Products].[Non-Consumable]}\n"
+ "{[Store Type].[All Store Types].[Mid-Size Grocery], [Product].[All Products].[Drink]}\n"
+ "{[Store Type].[All Store Types].[Mid-Size Grocery], [Product].[All Products].[Food]}\n"
+ "{[Store Type].[All Store Types].[Mid-Size Grocery], [Product].[All Products].[Non-Consumable]}\n"
+ "{[Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Drink]}\n"
+ "{[Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Food]}\n"
+ "{[Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Non-Consumable]}\n"
+ "Row #0: 6,827\n"
+ "Row #0: 55,358\n"
+ "Row #0: 14,652\n"
+ "Row #0: 1,945\n"
+ "Row #0: 15,438\n"
+ "Row #0: 3,950\n"
+ "Row #0: 1,159\n"
+ "Row #0: 8,192\n"
+ "Row #0: 2,140\n"
+ "Row #0: 14,092\n"
+ "Row #0: 108,188\n"
+ "Row #0: 28,275\n");
}
/**
* Verify that native evaluation is not enabled if expanded member list will
* contain members from different levels, even if ExpandNonNative is set.
*/
public void testExpandDifferentLevels() {
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
checkNotNative(
278,
"select NonEmptyCrossJoin("
+ " Descendants([Customers].[All Customers].[USA].[WA].[Yakima]), "
+ " [Product].Children) on columns "
+ "from [Sales]",
null);
}
/**
* Verify that native evaluation is turned off for tuple inputs, even if
* ExpandNonNative is set.
*/
public void testExpandTupleInputs1() {
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
checkNotNative(
1,
"with "
+ "set [Tuple Set] as {([Store Type].[All Store Types].[HeadQuarters], [Product].[All Products].[Drink]), ([Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Food])} "
+ "set [Filtered Tuple Set] as Filter([Tuple Set], 1=1) "
+ "set [NECJ] as NonEmptyCrossJoin([Store].Children, [Filtered Tuple Set]) "
+ "select [NECJ] on columns from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Store].[All Stores].[USA], [Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Food]}\n"
+ "Row #0: 108,188\n");
}
/**
* Verify that native evaluation is turned off for tuple inputs, even if
* ExpandNonNative is set.
*/
public void testExpandTupleInputs2() {
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
checkNotNative(
1,
"with "
+ "set [Tuple Set] as {([Store Type].[All Store Types].[HeadQuarters], [Product].[All Products].[Drink]), ([Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Food])} "
+ "set [Filtered Tuple Set] as Filter([Tuple Set], 1=1) "
+ "set [NECJ] as NonEmptyCrossJoin([Filtered Tuple Set], [Store].Children) "
+ "select [NECJ] on columns from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Food], [Store].[All Stores].[USA]}\n"
+ "Row #0: 108,188\n");
}
/**
* Verify that native evaluation is on when ExpendNonNative is set, even if
* the input list is empty.
*/
public void testExpandWithOneEmptyInput() {
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
boolean requestFreshConnection = true;
// Query should return empty result.
checkNative(
0,
0,
"With "
+ "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Gender],[*BASE_MEMBERS_Product])' "
+ "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}' "
+ "Set [*BASE_MEMBERS_Gender] as 'Filter([Gender].[Gender].Members,[Gender].CurrentMember.Name Matches (\"abc\"))' "
+ "Set [*NATIVE_MEMBERS_Gender] as 'Generate([*NATIVE_CJ_SET], {[Gender].CurrentMember})' "
+ "Set [*BASE_MEMBERS_Product] as '[Product].[Product Name].Members' "
+ "Set [*NATIVE_MEMBERS_Product] as 'Generate([*NATIVE_CJ_SET], {[Product].CurrentMember})' "
+ "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = '#,##0', SOLVE_ORDER=400 "
+ "Select "
+ "[*BASE_MEMBERS_Measures] on columns, "
+ "Non Empty Generate([*NATIVE_CJ_SET], {([Gender].CurrentMember,[Product].CurrentMember)}) on rows "
+ "From [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis
requestFreshConnection);
}
public void testExpandWithTwoEmptyInputs() {
getConnection().getCacheControl(null).flushSchemaCache();
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
// Query should return empty result.
checkNotNative(
0,
"With "
+ "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Gender],[*BASE_MEMBERS_Product])' "
+ "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}' "
+ "Set [*BASE_MEMBERS_Gender] as 'Filter([Gender].[Gender].Members,[Gender].CurrentMember.Name Matches (\"abc\"))' "
+ "Set [*NATIVE_MEMBERS_Gender] as 'Generate([*NATIVE_CJ_SET], {[Gender].CurrentMember})' "
+ "Set [*BASE_MEMBERS_Product] as 'Filter([Product].[Product Name].Members, [Product].[Product Name].CurrentMember.Name Matches (\"abc\"))' "
+ "Set [*NATIVE_MEMBERS_Product] as 'Generate([*NATIVE_CJ_SET], {[Product].CurrentMember})' "
+ "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = '#,##0', SOLVE_ORDER=400 "
+ "Select "
+ "[*BASE_MEMBERS_Measures] on columns, "
+ "Non Empty Generate([*NATIVE_CJ_SET], {([Gender].CurrentMember,[Product].CurrentMember)}) on rows "
+ "From [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis
}
/**
* Verify that native MemberLists inputs are subject to SQL constriant
* limitation. If mondrian.rolap.maxConstraints is set too low, native
* evaluations will be turned off.
*/
public void testEnumLowMaxConstraints() {
propSaver.set(MondrianProperties.instance().MaxConstraints, 2);
checkNotNative(
12,
"with "
+ "set [All Store Types] as {"
+ "[Store Type].[All Store Types].[Deluxe Supermarket], "
+ "[Store Type].[All Store Types].[Gourmet Supermarket], "
+ "[Store Type].[All Store Types].[Mid-Size Grocery], "
+ "[Store Type].[All Store Types].[Small Grocery], "
+ "[Store Type].[All Store Types].[Supermarket]} "
+ "set [All Products] as {"
+ "[Product].[All Products].[Drink], "
+ "[Product].[All Products].[Food], "
+ "[Product].[All Products].[Non-Consumable]} "
+ "select "
+ "NonEmptyCrossJoin("
+ "Filter([All Store Types], ([Measures].[Unit Sales] > 10000)), "
+ "[All Products]) on columns "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Store Type].[All Store Types].[Deluxe Supermarket], [Product].[All Products].[Drink]}\n"
+ "{[Store Type].[All Store Types].[Deluxe Supermarket], [Product].[All Products].[Food]}\n"
+ "{[Store Type].[All Store Types].[Deluxe Supermarket], [Product].[All Products].[Non-Consumable]}\n"
+ "{[Store Type].[All Store Types].[Gourmet Supermarket], [Product].[All Products].[Drink]}\n"
+ "{[Store Type].[All Store Types].[Gourmet Supermarket], [Product].[All Products].[Food]}\n"
+ "{[Store Type].[All Store Types].[Gourmet Supermarket], [Product].[All Products].[Non-Consumable]}\n"
+ "{[Store Type].[All Store Types].[Mid-Size Grocery], [Product].[All Products].[Drink]}\n"
+ "{[Store Type].[All Store Types].[Mid-Size Grocery], [Product].[All Products].[Food]}\n"
+ "{[Store Type].[All Store Types].[Mid-Size Grocery], [Product].[All Products].[Non-Consumable]}\n"
+ "{[Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Drink]}\n"
+ "{[Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Food]}\n"
+ "{[Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Non-Consumable]}\n"
+ "Row #0: 6,827\n"
+ "Row #0: 55,358\n"
+ "Row #0: 14,652\n"
+ "Row #0: 1,945\n"
+ "Row #0: 15,438\n"
+ "Row #0: 3,950\n"
+ "Row #0: 1,159\n"
+ "Row #0: 8,192\n"
+ "Row #0: 2,140\n"
+ "Row #0: 14,092\n"
+ "Row #0: 108,188\n"
+ "Row #0: 28,275\n");
}
/**
* Verify that the presence of All member in all the inputs disables native
* evaluation.
*/
public void testAllMembersNECJ1() {
// This query cannot be evaluated natively because of the "All" member.
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
checkNotNative(
1,
"select "
+ "NonEmptyCrossJoin({[Store].[All Stores]}, {[Product].[All Products]}) on columns "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Store].[All Stores], [Product].[All Products]}\n"
+ "Row #0: 266,773\n");
}
/**
* Verify that the native evaluation is possible if one input does not
* contain the All member.
*/
public void testAllMembersNECJ2() {
// This query can be evaluated natively because there is at least one
// non "All" member.
// It can also be rewritten to use
// Filter([Product].[All Products].Children, Is
// NotEmpty([Measures].[Unit Sales]))
// which can be natively evaluated
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
boolean requestFreshConnection = true;
checkNative(
0,
3,
"select "
+ "NonEmptyCrossJoin([Product].[All Products].Children, {[Store].[All Stores]}) on columns "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Product].[All Products].[Drink], [Store].[All Stores]}\n"
+ "{[Product].[All Products].[Food], [Store].[All Stores]}\n"
+ "{[Product].[All Products].[Non-Consumable], [Store].[All Stores]}\n"
+ "Row #0: 24,597\n"
+ "Row #0: 191,940\n"
+ "Row #0: 50,236\n",
requestFreshConnection);
}
/**
* getMembersInLevel where Level = (All)
*/
public void testAllLevelMembers() {
checkNative(
14,
14,
"select {[Measures].[Store Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin([Product].[(All)].Members, [Promotion Media].[All Media].Children) ON ROWS "
+ "from [Sales]");
}
/**
* enum sets {} containing ALL
*/
public void testCjDescendantsEnumAllOnly() {
checkNative(
9,
9,
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin("
+ " Descendants([Customers].[All Customers].[USA], [Customers].[City]), "
+ " {[Product].[All Products]}) ON ROWS " + "from [Sales] "
+ "where ([Promotions].[All Promotions].[Bag Stuffers])");
}
/**
* checks that crossjoin returns a modifiable copy from cache
* because its modified during sort
*/
public void testResultIsModifyableCopy() {
checkNative(
3,
3,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Order("
+ " CrossJoin([Customers].[All Customers].[USA].children, [Promotions].[Promotion Name].Members), "
+ " [Measures].[Store Sales]) ON ROWS"
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
/**
* Checks that TopCount is executed natively unless disabled.
*/
public void testNativeTopCount() {
switch (getTestContext().getDialect().getDatabaseProduct()) {
case INFOBRIGHT:
// Hits same Infobright bug as NamedSetTest.testNamedSetOnMember.
return;
}
String query =
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY TopCount("
+ " CrossJoin([Customers].[All Customers].[USA].children, [Promotions].[Promotion Name].Members), "
+ " 3, (3 * [Measures].[Store Sales]) - 100) ON ROWS"
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])";
propSaver.set(MondrianProperties.instance().EnableNativeTopCount, true);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
boolean requestFreshConnection = true;
checkNative(3, 3, query, null, requestFreshConnection);
}
/**
* Checks that TopCount is executed natively with calculated member.
*/
public void testCmNativeTopCount() {
switch (getTestContext().getDialect().getDatabaseProduct()) {
case INFOBRIGHT:
// Hits same Infobright bug as NamedSetTest.testNamedSetOnMember.
return;
}
String query =
"with member [Measures].[Store Profit Rate] as '([Measures].[Store Sales]-[Measures].[Store Cost])/[Measures].[Store Cost]', format = '
+ "select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY TopCount("
+ " [Customers].[All Customers].[USA].children, "
+ " 3, [Measures].[Store Profit Rate] / 2) ON ROWS"
+ " from [Sales]";
propSaver.set(MondrianProperties.instance().EnableNativeTopCount, true);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
boolean requestFreshConnection = true;
checkNative(3, 3, query, null, requestFreshConnection);
}
public void testMeasureAndAggregateInSlicer() {
assertQueryReturns(
"with member [Store Type].[All Store Types].[All Types] as 'Aggregate({[Store Type].[All Store Types].[Deluxe Supermarket], "
+ "[Store Type].[All Store Types].[Gourmet Supermarket], "
+ "[Store Type].[All Store Types].[HeadQuarters], "
+ "[Store Type].[All Store Types].[Mid-Size Grocery], "
+ "[Store Type].[All Store Types].[Small Grocery], "
+ "[Store Type].[All Store Types].[Supermarket]})' "
+ "select NON EMPTY {[Time].[1997]} ON COLUMNS, "
+ "NON EMPTY [Store].[All Stores].[USA].[CA].Children ON ROWS "
+ "from [Sales] "
+ "where ([Store Type].[All Store Types].[All Types], [Measures].[Unit Sales], [Customers].[All Customers].[USA], [Product].[All Products].[Drink]) ",
"Axis
+ "{[Store Type].[All Store Types].[All Types], [Measures].[Unit Sales], [Customers].[All Customers].[USA], [Product].[All Products].[Drink]}\n"
+ "Axis
+ "{[Time].[1997]}\n"
+ "Axis
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Diego]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 1,945\n"
+ "Row #1: 2,422\n"
+ "Row #2: 2,560\n"
+ "Row #3: 175\n");
}
public void testMeasureInSlicer() {
assertQueryReturns(
"select NON EMPTY {[Time].[1997]} ON COLUMNS, "
+ "NON EMPTY [Store].[All Stores].[USA].[CA].Children ON ROWS "
+ "from [Sales] "
+ "where ([Measures].[Unit Sales], [Customers].[All Customers].[USA], [Product].[All Products].[Drink])",
"Axis
+ "{[Measures].[Unit Sales], [Customers].[All Customers].[USA], [Product].[All Products].[Drink]}\n"
+ "Axis
+ "{[Time].[1997]}\n"
+ "Axis
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Diego]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 1,945\n"
+ "Row #1: 2,422\n"
+ "Row #2: 2,560\n"
+ "Row #3: 175\n");
}
/**
* Calc Member in TopCount: this topcount can not be calculated native
* because its set contains calculated members.
*/
public void testCmInTopCount() {
checkNotNative(
1,
"with member [Time].[Jan] as "
+ "'Aggregate({[Time].[1998].[Q1].[1], [Time].[1997].[Q1].[1]})' "
+ "select NON EMPTY {[Measures].[Unit Sales]} ON columns, "
+ "NON EMPTY TopCount({[Time].[Jan]}, 2) ON rows from [Sales] ");
}
/**
* Calc member in slicer cannot be executed natively.
*/
public void testCmInSlicer() {
checkNotNative(
3,
"with member [Time].[Jan] as "
+ "'Aggregate({[Time].[1998].[Q1].[1], [Time].[1997].[Q1].[1]})' "
+ "select NON EMPTY {[Measures].[Unit Sales]} ON columns, "
+ "NON EMPTY [Product].[All Products].Children ON rows from [Sales] "
+ "where ([Time].[Jan]) ");
}
public void testCjMembersMembersMembers() {
checkNative(
67,
67,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " Crossjoin("
+ " [Customers].[Name].Members,"
+ " [Product].[Product Name].Members), "
+ " [Promotions].[Promotion Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjMembersWithHideIfBlankLeafAndNoAll() {
setTestContext(TestContext.createSubstitutingCube(
"Sales",
"<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n"
+ " <Hierarchy hasAll=\"false\" primaryKey=\"product_id\">\n"
+ " <Table name=\"product\"/>\n"
+ " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n"
+ " <Level name=\"Product Name\" table=\"product\" column=\"product_name\" uniqueMembers=\"true\"\n"
+ " hideMemberIf=\"IfBlankName\""
+ " />\n"
+ " </Hierarchy>\n"
+ "</Dimension>"));
// No 'all' level, and ragged because [Product Name] is hidden if
// blank. Native evaluation should be able to handle this query.
checkNative(
9999, // Don't know why resultLimit needs to be so high.
67,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " Crossjoin("
+ " [Customers].[Name].Members,"
+ " [Product Ragged].[Product Name].Members), "
+ " [Promotions].[Promotion Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjMembersWithHideIfBlankLeaf() {
setTestContext(TestContext.createSubstitutingCube(
"Sales",
"<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n"
+ " <Table name=\"product\"/>\n"
+ " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n"
+ " <Level name=\"Product Name\" table=\"product\" column=\"product_name\" uniqueMembers=\"true\"\n"
+ " hideMemberIf=\"IfBlankName\""
+ " />\n"
+ " </Hierarchy>\n"
+ "</Dimension>"));
// [Product Name] can be hidden if it is blank, but native evaluation
// should be able to handle the query.
checkNative(
67,
67,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " Crossjoin("
+ " [Customers].[Name].Members,"
+ " [Product Ragged].[Product Name].Members), "
+ " [Promotions].[Promotion Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjMembersWithHideIfParentsNameLeaf() {
setTestContext(TestContext.createSubstitutingCube(
"Sales",
"<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n"
+ " <Table name=\"product\"/>\n"
+ " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n"
+ " <Level name=\"Product Name\" table=\"product\" column=\"product_name\" uniqueMembers=\"true\"\n"
+ " hideMemberIf=\"IfParentsName\""
+ " />\n"
+ " </Hierarchy>\n"
+ "</Dimension>"));
// [Product Name] can be hidden if it it matches its parent name, so
// native evaluation can not handle this query.
checkNotNative(
67,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " Crossjoin("
+ " [Customers].[Name].Members,"
+ " [Product Ragged].[Product Name].Members), "
+ " [Promotions].[Promotion Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjMembersWithHideIfBlankNameAncestor() {
setTestContext(TestContext.createSubstitutingCube(
"Sales",
"<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n"
+ " <Table name=\"product\"/>\n"
+ " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\""
+ " hideMemberIf=\"IfBlankName\""
+ " />\n"
+ " <Level name=\"Product Name\" table=\"product\" column=\"product_name\"\n uniqueMembers=\"true\"/>\n"
+ " </Hierarchy>\n"
+ "</Dimension>"));
// Since the parent of [Product Name] can be hidden, native evaluation
// can't handle the query.
checkNative(
67,
67,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " Crossjoin("
+ " [Customers].[Name].Members,"
+ " [Product Ragged].[Product Name].Members), "
+ " [Promotions].[Promotion Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjMembersWithHideIfParentsNameAncestor() {
setTestContext(TestContext.createSubstitutingCube(
"Sales",
"<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n"
+ " <Table name=\"product\"/>\n"
+ " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\""
+ " hideMemberIf=\"IfParentsName\""
+ " />\n"
+ " <Level name=\"Product Name\" table=\"product\" column=\"product_name\"\n uniqueMembers=\"true\"/>\n"
+ " </Hierarchy>\n"
+ "</Dimension>"));
// Since the parent of [Product Name] can be hidden, native evaluation
// can't handle the query.
checkNative(
67,
67,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " Crossjoin("
+ " [Customers].[Name].Members,"
+ " [Product Ragged].[Product Name].Members), "
+ " [Promotions].[Promotion Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjEnumWithHideIfBlankLeaf() {
setTestContext(TestContext.createSubstitutingCube(
"Sales",
"<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n"
+ " <Table name=\"product\"/>\n"
+ " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n"
+ " <Level name=\"Product Name\" table=\"product\" column=\"product_name\" uniqueMembers=\"true\"\n"
+ " hideMemberIf=\"IfBlankName\""
+ " />\n"
+ " </Hierarchy>\n"
+ "</Dimension>"));
// [Product Name] can be hidden if it is blank, but native evaluation
// should be able to handle the query.
// Note there's an existing bug with result ordering in native
// non-empty evaluation of enumerations. This test intentionally
// avoids this bug by explicitly lilsting [High Top Cauliflower]
// before [Sphinx Bagels].
checkNative(
999,
7,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " Crossjoin("
+ " [Customers].[Name].Members,"
+ " { [Product Ragged].[Kiwi].[Kiwi Scallops],"
+ " [Product Ragged].[Fast].[Fast Avocado Dip],"
+ " [Product Ragged].[High Top].[High Top Lemons],"
+ " [Product Ragged].[Moms].[Moms Sliced Turkey],"
+ " [Product Ragged].[High Top].[High Top Cauliflower],"
+ " [Product Ragged].[Sphinx].[Sphinx Bagels]"
+ " }), "
+ " [Promotions].[Promotion Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
/**
* use SQL even when all members are known
*/
public void testCjEnumEnum() {
// Make sure maxConstraint settting is high enough
int minConstraints = 2;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints, minConstraints);
}
checkNative(
4,
4,
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NonEmptyCrossjoin({[Product].[All Products].[Drink].[Beverages], [Product].[All Products].[Drink].[Dairy]}, {[Customers].[All Customers].[USA].[OR].[Portland], [Customers].[All Customers].[USA].[OR].[Salem]}) ON ROWS "
+ "from [Sales] ");
}
/**
* Set containing only null member should not prevent usage of native.
*/
public void testCjNullInEnum() {
propSaver.set(
MondrianProperties.instance().IgnoreInvalidMembersDuringQuery,
true);
checkNative(
20,
0,
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin({[Gender].[All Gender].[emale]}, [Customers].[All Customers].[USA].children) ON ROWS "
+ "from [Sales] ");
}
/**
* enum sets {} containing members from different levels can not be computed
* natively currently.
*/
public void testCjDescendantsEnumAll() {
checkNotNative(
13,
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin("
+ " Descendants([Customers].[All Customers].[USA], [Customers].[City]), "
+ " {[Product].[All Products], [Product].[All Products].[Drink].[Dairy]}) ON ROWS "
+ "from [Sales] "
+ "where ([Promotions].[All Promotions].[Bag Stuffers])");
}
public void testCjDescendantsEnum() {
// Make sure maxConstraint settting is high enough
int minConstraints = 2;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints,
minConstraints);
}
checkNative(
11,
11,
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin("
+ " Descendants([Customers].[All Customers].[USA], [Customers].[City]), "
+ " {[Product].[All Products].[Drink].[Beverages], [Product].[All Products].[Drink].[Dairy]}) ON ROWS "
+ "from [Sales] "
+ "where ([Promotions].[All Promotions].[Bag Stuffers])");
}
public void testCjEnumChildren() {
// Make sure maxConstraint settting is high enough
// Make sure maxConstraint settting is high enough
int minConstraints = 2;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints,
minConstraints);
}
checkNative(
3,
3,
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin("
+ " {[Product].[All Products].[Drink].[Beverages], [Product].[All Products].[Drink].[Dairy]}, "
+ " [Customers].[All Customers].[USA].[WA].Children) ON ROWS "
+ "from [Sales] "
+ "where ([Promotions].[All Promotions].[Bag Stuffers])");
}
/**
* {} contains members from different levels, this can not be handled by
* the current native crossjoin.
*/
public void testCjEnumDifferentLevelsChildren() {
// Don't run the test if we're testing expression dependencies.
// Expression dependencies cause spurious interval calls to
// 'level.getMembers()' which create false negatives in this test.
if (MondrianProperties.instance().TestExpDependencies.get() > 0) {
return;
}
TestCase c = new TestCase(
8, 5, "select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin("
+ " {[Product].[All Products].[Food], [Product].[All Products].[Drink].[Dairy]}, "
+ " [Customers].[All Customers].[USA].[WA].Children) ON ROWS "
+ "from [Sales] "
+ "where ([Promotions].[All Promotions].[Bag Stuffers])");
c.run();
}
public void testCjDescendantsMembers() {
checkNative(
67, 67, "select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " Descendants([Customers].[All Customers].[USA].[CA], [Customers].[Name]),"
+ " [Product].[Product Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjMembersDescendants() {
checkNative(
67,
67,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " [Product].[Product Name].Members,"
+ " Descendants([Customers].[All Customers].[USA].[CA], [Customers].[Name])) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
// testcase for bug MONDRIAN-506
public void testCjMembersDescendantsWithNumericArgument() {
checkNative(
67,
67,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin("
+ " {[Product].[Product Name].Members},"
+ " {Descendants([Customers].[All Customers].[USA].[CA], 2)}) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjChildrenMembers() {
checkNative(
67, 67, "select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin([Customers].[All Customers].[USA].[CA].children,"
+ " [Product].[Product Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjMembersChildren() {
checkNative(
67, 67, "select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin([Product].[Product Name].Members,"
+ " [Customers].[All Customers].[USA].[CA].children) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjMembersMembers() {
checkNative(
67, 67, "select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin([Customers].[Name].Members,"
+ " [Product].[Product Name].Members) ON rows "
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
public void testCjChildrenChildren() {
checkNative(
3,
3,
"select {[Measures].[Store Sales]} on columns, "
+ " NON EMPTY Crossjoin("
+ " [Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Wine].children, "
+ " [Customers].[All Customers].[USA].[CA].CHILDREN) ON rows"
+ " from [Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
/**
* Checks that multi-level member list generates compact form of SQL where
* clause:
* (1) Use IN list if possible
* (2) Group members sharing the same parent
* (3) Only need to compare up to the first unique parent level.
*/
public void testMultiLevelMemberConstraintNonNullParent() {
String query =
"with "
+ "set [Filtered Store City Set] as "
+ "{[Store].[USA].[OR].[Portland], "
+ " [Store].[USA].[OR].[Salem], "
+ " [Store].[USA].[CA].[San Francisco], "
+ " [Store].[USA].[WA].[Tacoma]} "
+ "set [NECJ] as NonEmptyCrossJoin([Filtered Store City Set], {[Product].[Product Family].Food}) "
+ "select [NECJ] on columns from [Sales]";
String necjSqlDerby =
"select "
+ "\"store\".\"store_country\", \"store\".\"store_state\", \"store\".\"store_city\", "
+ "\"product_class\".\"product_family\" "
+ "from "
+ "\"store\" as \"store\", \"sales_fact_1997\" as \"sales_fact_1997\", "
+ "\"product\" as \"product\", \"product_class\" as \"product_class\" "
+ "where "
+ "\"sales_fact_1997\".\"store_id\" = \"store\".\"store_id\" and \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" "
+ "and \"sales_fact_1997\".\"product_id\" = \"product\".\"product_id\" "
+ "and ((\"store\".\"store_state\" = 'OR' and \"store\".\"store_city\" in ('Portland', 'Salem'))"
+ " or (\"store\".\"store_state\" = 'CA' and \"store\".\"store_city\" = 'San Francisco')"
+ " or (\"store\".\"store_state\" = 'WA' and \"store\".\"store_city\" = 'Tacoma')) "
+ "and (\"product_class\".\"product_family\" = 'Food') "
+ "group by \"store\".\"store_country\", \"store\".\"store_state\", \"store\".\"store_city\", \"product_class\".\"product_family\" "
+ "order by \"store\".\"store_country\" ASC, \"store\".\"store_state\" ASC, \"store\".\"store_city\" ASC, \"product_class\".\"product_family\" ASC";
String necjSqlMySql =
"select "
+ "`store`.`store_country` as `c0`, `store`.`store_state` as `c1`, "
+ "`store`.`store_city` as `c2`, `product_class`.`product_family` as `c3` "
+ "from "
+ "`store` as `store`, `sales_fact_1997` as `sales_fact_1997`, "
+ "`product` as `product`, `product_class` as `product_class` "
+ "where "
+ "`sales_fact_1997`.`store_id` = `store`.`store_id` and `product`.`product_class_id` = `product_class`.`product_class_id` "
+ "and `sales_fact_1997`.`product_id` = `product`.`product_id` "
+ "and ((`store`.`store_city`,`store`.`store_state`) in (('Portland','OR'),('Salem','OR'),('San Francisco','CA'),('Tacoma','WA'))) "
+ "and (`product_class`.`product_family` = 'Food') "
+ "group by `store`.`store_country`, `store`.`store_state`, `store`.`store_city`, `product_class`.`product_family` "
+ "order by ISNULL(`store`.`store_country`), `store`.`store_country` ASC, ISNULL(`store`.`store_state`), `store`.`store_state` ASC, "
+ "ISNULL(`store`.`store_city`), `store`.`store_city` ASC, ISNULL(`product_class`.`product_family`), `product_class`.`product_family` ASC";
if (MondrianProperties.instance().UseAggregates.get()
&& MondrianProperties.instance().ReadAggregates.get())
{
// slightly different sql expected, uses agg table now for join
necjSqlMySql = necjSqlMySql.replaceAll(
"sales_fact_1997", "agg_c_14_sales_fact_1997");
necjSqlDerby = necjSqlDerby.replaceAll(
"sales_fact_1997", "agg_c_14_sales_fact_1997");
}
SqlPattern[] patterns = {
new SqlPattern(
Dialect.DatabaseProduct.DERBY, necjSqlDerby, necjSqlDerby),
new SqlPattern(
Dialect.DatabaseProduct.MYSQL, necjSqlMySql, necjSqlMySql)
};
assertQuerySql(query, patterns);
}
/**
* Checks that multi-level member list generates compact form of SQL where
* clause:
* (1) Use IN list if possible(not possible if there are null values because
* NULLs in IN lists do not match)
* (2) Group members sharing the same parent, including parents with NULLs.
* (3) If parent levels include NULLs, comparision includes any unique
* level.
*/
public void testMultiLevelMemberConstraintNullParent() {
if (!isDefaultNullMemberRepresentation()) {
return;
}
String dimension =
"<Dimension name=\"Warehouse2\">\n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"warehouse_id\">\n"
+ " <Table name=\"warehouse\"/>\n"
+ " <Level name=\"address3\" column=\"wa_address3\" uniqueMembers=\"true\"/>\n"
+ " <Level name=\"address2\" column=\"wa_address2\" uniqueMembers=\"true\"/>\n"
+ " <Level name=\"address1\" column=\"wa_address1\" uniqueMembers=\"false\"/>\n"
+ " <Level name=\"name\" column=\"warehouse_name\" uniqueMembers=\"false\"/>\n"
+ " </Hierarchy>\n"
+ "</Dimension>\n";
String cube =
"<Cube name=\"Warehouse2\">\n"
+ " <Table name=\"inventory_fact_1997\"/>\n"
+ " <DimensionUsage name=\"Product\" source=\"Product\" foreignKey=\"product_id\"/>\n"
+ " <DimensionUsage name=\"Warehouse2\" source=\"Warehouse2\" foreignKey=\"warehouse_id\"/>\n"
+ " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" aggregator=\"sum\"/>\n"
+ " <Measure name=\"Warehouse Sales\" column=\"warehouse_sales\" aggregator=\"sum\"/>\n"
+ "</Cube>";
String query =
"with\n"
+ "set [Filtered Warehouse Set] as "
+ "{[Warehouse2].[#null].[#null].[5617 Saclan Terrace].[Arnold and Sons],"
+ " [Warehouse2].[#null].[#null].[3377 Coachman Place].[Jones International]} "
+ "set [NECJ] as NonEmptyCrossJoin([Filtered Warehouse Set], {[Product].[Product Family].Food}) "
+ "select [NECJ] on columns from [Warehouse2]";
String necjSqlDerby =
"select \"warehouse\".\"wa_address3\", \"warehouse\".\"wa_address2\", \"warehouse\".\"wa_address1\", \"warehouse\".\"warehouse_name\", \"product_class\".\"product_family\" "
+ "from \"warehouse\" as \"warehouse\", \"inventory_fact_1997\" as \"inventory_fact_1997\", \"product\" as \"product\", \"product_class\" as \"product_class\" "
+ "where \"inventory_fact_1997\".\"warehouse_id\" = \"warehouse\".\"warehouse_id\" and \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" "
+ "and \"inventory_fact_1997\".\"product_id\" = \"product\".\"product_id\" and "
+ "((\"warehouse\".\"wa_address1\" = '5617 Saclan Terrace' and \"warehouse\".\"wa_address2\" is null and \"warehouse\".\"warehouse_name\" = 'Arnold and Sons') "
+ "or (\"warehouse\".\"wa_address1\" = '3377 Coachman Place' and \"warehouse\".\"wa_address2\" is null and \"warehouse\".\"warehouse_name\" = 'Jones International')) "
+ "and (\"product_class\".\"product_family\" = 'Food') group by \"warehouse\".\"wa_address3\", \"warehouse\".\"wa_address2\", \"warehouse\".\"wa_address1\", "
+ "\"warehouse\".\"warehouse_name\", \"product_class\".\"product_family\" order by \"warehouse\".\"wa_address3\" ASC, \"warehouse\".\"wa_address2\" ASC, "
+ "\"warehouse\".\"wa_address1\" ASC, \"warehouse\".\"warehouse_name\" ASC, \"product_class\".\"product_family\" ASC";
String necjSqlMySql =
"select `warehouse`.`wa_address3` as `c0`, `warehouse`.`wa_address2` as `c1`, `warehouse`.`wa_address1` as `c2`, `warehouse`.`warehouse_name` as `c3`, "
+ "`product_class`.`product_family` as `c4` from `warehouse` as `warehouse`, `inventory_fact_1997` as `inventory_fact_1997`, `product` as `product`, "
+ "`product_class` as `product_class` where `inventory_fact_1997`.`warehouse_id` = `warehouse`.`warehouse_id` and "
+ "`product`.`product_class_id` = `product_class`.`product_class_id` and `inventory_fact_1997`.`product_id` = `product`.`product_id` and "
+ "((`warehouse`.`wa_address2` is null and (`warehouse`.`warehouse_name`,`warehouse`.`wa_address1`) in (('Arnold and Sons','5617 Saclan Terrace'),"
+ "('Jones International','3377 Coachman Place')))) and (`product_class`.`product_family` = 'Food') group by `warehouse`.`wa_address3`, "
+ "`warehouse`.`wa_address2`, `warehouse`.`wa_address1`, `warehouse`.`warehouse_name`, `product_class`.`product_family` "
+ "order by ISNULL(`warehouse`.`wa_address3`), `warehouse`.`wa_address3` ASC, ISNULL(`warehouse`.`wa_address2`), `warehouse`.`wa_address2` ASC, "
+ "ISNULL(`warehouse`.`wa_address1`), `warehouse`.`wa_address1` ASC, ISNULL(`warehouse`.`warehouse_name`), `warehouse`.`warehouse_name` ASC, "
+ "ISNULL(`product_class`.`product_family`), `product_class`.`product_family` ASC";
TestContext testContext =
TestContext.create(
dimension,
cube,
null,
null,
null,
null);
SqlPattern[] patterns = {
new SqlPattern(
Dialect.DatabaseProduct.DERBY, necjSqlDerby, necjSqlDerby),
new SqlPattern(
Dialect.DatabaseProduct.MYSQL, necjSqlMySql, necjSqlMySql)
};
assertQuerySql(testContext, query, patterns);
}
/**
* Check that multi-level member list generates compact form of SQL where
* clause:
* (1) Use IN list if possible(not possible if there are null values because
* NULLs in IN lists do not match)
* (2) Group members sharing the same parent, including parents with NULLs.
* (3) If parent levels include NULLs, comparision includes any unique
* level.
* (4) Can handle predicates correctly if the member list contains both NULL
* and non NULL parent levels.
*/
public void testMultiLevelMemberConstraintMixedNullNonNullParent() {
if (!isDefaultNullMemberRepresentation()) {
return;
}
String dimension =
"<Dimension name=\"Warehouse2\">\n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"warehouse_id\">\n"
+ " <Table name=\"warehouse\"/>\n"
+ " <Level name=\"fax\" column=\"warehouse_fax\" uniqueMembers=\"true\"/>\n"
+ " <Level name=\"address1\" column=\"wa_address1\" uniqueMembers=\"false\"/>\n"
+ " <Level name=\"name\" column=\"warehouse_name\" uniqueMembers=\"false\"/>\n"
+ " </Hierarchy>\n"
+ "</Dimension>\n";
String cube =
"<Cube name=\"Warehouse2\">\n"
+ " <Table name=\"inventory_fact_1997\"/>\n"
+ " <DimensionUsage name=\"Product\" source=\"Product\" foreignKey=\"product_id\"/>\n"
+ " <DimensionUsage name=\"Warehouse2\" source=\"Warehouse2\" foreignKey=\"warehouse_id\"/>\n"
+ " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" aggregator=\"sum\"/>\n"
+ " <Measure name=\"Warehouse Sales\" column=\"warehouse_sales\" aggregator=\"sum\"/>\n"
+ "</Cube>";
String query =
"with\n"
+ "set [Filtered Warehouse Set] as "
+ "{[Warehouse2].[#null].[234 West Covina Pkwy].[Freeman And Co],"
+ " [Warehouse2].[971-555-6213].[3377 Coachman Place].[Jones International]} "
+ "set [NECJ] as NonEmptyCrossJoin([Filtered Warehouse Set], {[Product].[Product Family].Food}) "
+ "select [NECJ] on columns from [Warehouse2]";
String necjSqlDerby =
"select \"warehouse\".\"warehouse_fax\", \"warehouse\".\"wa_address1\", \"warehouse\".\"warehouse_name\", \"product_class\".\"product_family\" "
+ "from \"warehouse\" as \"warehouse\", \"inventory_fact_1997\" as \"inventory_fact_1997\", \"product\" as \"product\", \"product_class\" as \"product_class\" "
+ "where \"inventory_fact_1997\".\"warehouse_id\" = \"warehouse\".\"warehouse_id\" and \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" "
+ "and \"inventory_fact_1997\".\"product_id\" = \"product\".\"product_id\" and "
+ "((\"warehouse\".\"wa_address1\" = '234 West Covina Pkwy' and \"warehouse\".\"warehouse_fax\" is null and \"warehouse\".\"warehouse_name\" = 'Freeman And Co') "
+ "or (\"warehouse\".\"wa_address1\" = '3377 Coachman Place' and \"warehouse\".\"warehouse_fax\" = '971-555-6213' and \"warehouse\".\"warehouse_name\" = 'Jones International')) "
+ "and (\"product_class\".\"product_family\" = 'Food') "
+ "group by \"warehouse\".\"warehouse_fax\", \"warehouse\".\"wa_address1\", \"warehouse\".\"warehouse_name\", \"product_class\".\"product_family\" "
+ "order by \"warehouse\".\"warehouse_fax\" ASC, \"warehouse\".\"wa_address1\" ASC, "
+ "\"warehouse\".\"warehouse_name\" ASC, \"product_class\".\"product_family\" ASC";
String necjSqlMySql =
"select `warehouse`.`warehouse_fax` as `c0`, `warehouse`.`wa_address1` as `c1`, "
+ "`warehouse`.`warehouse_name` as `c2`, `product_class`.`product_family` as `c3` "
+ "from `warehouse` as `warehouse`, `inventory_fact_1997` as `inventory_fact_1997`, "
+ "`product` as `product`, `product_class` as `product_class` "
+ "where `inventory_fact_1997`.`warehouse_id` = `warehouse`.`warehouse_id` and "
+ "`product`.`product_class_id` = `product_class`.`product_class_id` and "
+ "`inventory_fact_1997`.`product_id` = `product`.`product_id` and "
+ "((`warehouse`.`warehouse_name`,`warehouse`.`wa_address1`,`warehouse`.`warehouse_fax`) in (('Jones International','3377 Coachman Place','971-555-6213')) "
+ "or (`warehouse`.`warehouse_fax` is null and "
+ "(`warehouse`.`warehouse_name`,`warehouse`.`wa_address1`) in (('Freeman And Co','234 West Covina Pkwy')))) "
+ "and (`product_class`.`product_family` = 'Food') "
+ "group by `warehouse`.`warehouse_fax`, `warehouse`.`wa_address1`, `warehouse`.`warehouse_name`, `product_class`.`product_family` "
+ "order by ISNULL(`warehouse`.`warehouse_fax`), `warehouse`.`warehouse_fax` ASC, "
+ "ISNULL(`warehouse`.`wa_address1`), `warehouse`.`wa_address1` ASC, ISNULL(`warehouse`.`warehouse_name`), "
+ "`warehouse`.`warehouse_name` ASC, ISNULL(`product_class`.`product_family`), `product_class`.`product_family` ASC";
TestContext testContext =
TestContext.create(
dimension,
cube,
null,
null,
null,
null);
SqlPattern[] patterns = {
new SqlPattern(
Dialect.DatabaseProduct.DERBY, necjSqlDerby, necjSqlDerby),
new SqlPattern(
Dialect.DatabaseProduct.MYSQL, necjSqlMySql, necjSqlMySql)
};
assertQuerySql(testContext, query, patterns);
}
/**
* Check that multi-level member list generates compact form of SQL where
* clause:
* (1) Use IN list if possible(not possible if there are null values because
* NULLs in IN lists do not match)
* (2) Group members sharing the same parent
* (3) Only need to compare up to the first unique parent level.
* (4) Can handle predicates correctly if the member list contains both NULL
* and non NULL child levels.
*/
public void testMultiLevelMemberConstraintWithMixedNullNonNullChild() {
if (!isDefaultNullMemberRepresentation()) {
return;
}
String dimension =
"<Dimension name=\"Warehouse2\">\n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"warehouse_id\">\n"
+ " <Table name=\"warehouse\"/>\n"
+ " <Level name=\"address3\" column=\"wa_address3\" uniqueMembers=\"true\"/>\n"
+ " <Level name=\"address2\" column=\"wa_address2\" uniqueMembers=\"false\"/>\n"
+ " <Level name=\"fax\" column=\"warehouse_fax\" uniqueMembers=\"false\"/>\n"
+ " </Hierarchy>\n"
+ "</Dimension>\n";
String cube =
"<Cube name=\"Warehouse2\">\n"
+ " <Table name=\"inventory_fact_1997\"/>\n"
+ " <DimensionUsage name=\"Product\" source=\"Product\" foreignKey=\"product_id\"/>\n"
+ " <DimensionUsage name=\"Warehouse2\" source=\"Warehouse2\" foreignKey=\"warehouse_id\"/>\n"
+ " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" aggregator=\"sum\"/>\n"
+ " <Measure name=\"Warehouse Sales\" column=\"warehouse_sales\" aggregator=\"sum\"/>\n"
+ "</Cube>";
String query =
"with\n"
+ "set [Filtered Warehouse Set] as "
+ "{[Warehouse2].[#null].[#null].[#null],"
+ " [Warehouse2].[#null].[#null].[971-555-6213]} "
+ "set [NECJ] as NonEmptyCrossJoin([Filtered Warehouse Set], {[Product].[Product Family].Food}) "
+ "select [NECJ] on columns from [Warehouse2]";
String necjSqlDerby =
"select \"warehouse\".\"wa_address3\", \"warehouse\".\"wa_address2\", \"warehouse\".\"warehouse_fax\", \"product_class\".\"product_family\" "
+ "from \"warehouse\" as \"warehouse\", \"inventory_fact_1997\" as \"inventory_fact_1997\", \"product\" as \"product\", \"product_class\" as \"product_class\" "
+ "where \"inventory_fact_1997\".\"warehouse_id\" = \"warehouse\".\"warehouse_id\" and "
+ "\"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" and \"inventory_fact_1997\".\"product_id\" = \"product\".\"product_id\" "
+ "and ((\"warehouse\".\"warehouse_fax\" = '971-555-6213' or \"warehouse\".\"warehouse_fax\" is null) and "
+ "\"warehouse\".\"wa_address2\" is null and \"warehouse\".\"wa_address3\" is null) and "
+ "(\"product_class\".\"product_family\" = 'Food') "
+ "group by \"warehouse\".\"wa_address3\", \"warehouse\".\"wa_address2\", \"warehouse\".\"warehouse_fax\", \"product_class\".\"product_family\" "
+ "order by \"warehouse\".\"wa_address3\" ASC, \"warehouse\".\"wa_address2\" ASC, \"warehouse\".\"warehouse_fax\" ASC, "
+ "\"product_class\".\"product_family\" ASC";
String necjSqlMySql =
"select `warehouse`.`wa_address3` as `c0`, `warehouse`.`wa_address2` as `c1`, `warehouse`.`warehouse_fax` as `c2`, "
+ "`product_class`.`product_family` as `c3` from `warehouse` as `warehouse`, `inventory_fact_1997` as `inventory_fact_1997`, "
+ "`product` as `product`, `product_class` as `product_class` "
+ "where `inventory_fact_1997`.`warehouse_id` = `warehouse`.`warehouse_id` and `product`.`product_class_id` = `product_class`.`product_class_id` and "
+ "`inventory_fact_1997`.`product_id` = `product`.`product_id` and "
+ "((`warehouse`.`warehouse_fax` = '971-555-6213' or `warehouse`.`warehouse_fax` is null) and "
+ "`warehouse`.`wa_address2` is null and `warehouse`.`wa_address3` is null) and "
+ "(`product_class`.`product_family` = 'Food') "
+ "group by `warehouse`.`wa_address3`, `warehouse`.`wa_address2`, `warehouse`.`warehouse_fax`, "
+ "`product_class`.`product_family` "
+ "order by ISNULL(`warehouse`.`wa_address3`), `warehouse`.`wa_address3` ASC, ISNULL(`warehouse`.`wa_address2`), "
+ "`warehouse`.`wa_address2` ASC, ISNULL(`warehouse`.`warehouse_fax`), `warehouse`.`warehouse_fax` ASC, "
+ "ISNULL(`product_class`.`product_family`), `product_class`.`product_family` ASC";
TestContext testContext =
TestContext.create(
dimension,
cube,
null,
null,
null,
null);
SqlPattern[] patterns = {
new SqlPattern(
Dialect.DatabaseProduct.DERBY, necjSqlDerby, necjSqlDerby),
new SqlPattern(
Dialect.DatabaseProduct.MYSQL, necjSqlMySql, necjSqlMySql)
};
assertQuerySql(testContext, query, patterns);
}
public void testNonEmptyUnionQuery() {
Result result = executeQuery(
"select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} on columns,\n"
+ " NON EMPTY Hierarchize(\n"
+ " Union(\n"
+ " Crossjoin(\n"
+ " Crossjoin([Gender].[All Gender].children,\n"
+ " [Marital Status].[All Marital Status].children),\n"
+ " Crossjoin([Customers].[All Customers].children,\n"
+ " [Product].[All Products].children) ),\n"
+ " Crossjoin({([Gender].[All Gender].[M], [Marital Status].[All Marital Status].[M])},\n"
+ " Crossjoin(\n"
+ " [Customers].[All Customers].[USA].children,\n"
+ " [Product].[All Products].children) ) )) on rows\n"
+ "from Sales where ([Time].[1997])");
final Axis rowsAxis = result.getAxes()[1];
Assert.assertEquals(21, rowsAxis.getPositions().size());
}
/**
* when Mondrian parses a string like
* "[Store].[All Stores].[USA].[CA].[San Francisco]"
* it shall not lookup additional members.
*/
public void testLookupMemberCache() {
if (MondrianProperties.instance().TestExpDependencies.get() > 0) {
// Dependency testing causes extra SQL reads, and screws up this
// test.
return;
}
// there currently isn't a cube member to children cache, only
// a shared cache so use the shared smart member reader
SmartMemberReader smr = getSmartMemberReader("Store");
MemberCacheHelper smrch = smr.cacheHelper;
MemberCacheHelper rcsmrch =
((RolapCubeHierarchy.RolapCubeHierarchyMemberReader) smr)
.getRolapCubeMemberCacheHelper();
SmartMemberReader ssmr = getSharedSmartMemberReader("Store");
MemberCacheHelper ssmrch = ssmr.cacheHelper;
clearAndHardenCache(smrch);
clearAndHardenCache(rcsmrch);
clearAndHardenCache(ssmrch);
RolapResult result =
(RolapResult) executeQuery(
"select {[Store].[All Stores].[USA].[CA].[San Francisco]} on columns from [Sales]");
assertTrue(
"no additional members should be read:"
+ ssmrch.mapKeyToMember.size(),
ssmrch.mapKeyToMember.size() <= 5);
RolapMember sf =
(RolapMember) result.getAxes()[0].getPositions().get(0).get(0);
RolapMember ca = sf.getParentMember();
// convert back to shared members
ca = ((RolapCubeMember) ca).getRolapMember();
sf = ((RolapCubeMember) sf).getRolapMember();
List list = ssmrch.mapMemberToChildren.get(
ca, scf.getMemberChildrenConstraint(null));
assertNull("children of [CA] are not in cache", list);
list = ssmrch.mapMemberToChildren.get(
ca, scf.getChildByNameConstraint(
ca,
new Id.Segment("San Francisco", Id.Quoting.QUOTED)));
assertNotNull("child [San Francisco] of [CA] is in cache", list);
assertEquals("[San Francisco] expected", sf, list.get(0));
}
/**
* When looking for [Month] Mondrian generates SQL that tries to find
* 'Month' as a member of the time dimension. This resulted in an
* SQLException because the year level is numeric and the constant 'Month'
* in the WHERE condition is not. Its probably a bug that Mondrian does not
* take into account [Time].[1997] when looking up [Month].
*/
public void testLookupMember() {
// ok if no exception occurs
executeQuery(
"SELECT DESCENDANTS([Time].[1997], [Month]) ON COLUMNS FROM [Sales]");
}
/**
* Non Empty CrossJoin (A,B) gets turned into CrossJoin (Non Empty(A), Non
* Empty(B)). Verify that there is no crash when the length of B could be
* non-zero length before the non empty and 0 after the non empty.
*/
public void testNonEmptyCrossJoinList() {
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, false);
boolean oldEnableNativeNonEmpty =
MondrianProperties.instance().EnableNativeNonEmpty.get();
MondrianProperties.instance().EnableNativeNonEmpty.set(false);
executeQuery(
"select non empty CrossJoin([Customers].[Name].Members, "
+ "{[Promotions].[All Promotions].[Fantastic Discounts]}) "
+ "ON COLUMNS FROM [Sales]");
MondrianProperties.instance().EnableNativeNonEmpty.set(
oldEnableNativeNonEmpty);
}
/**
* SQL Optimization must be turned off in ragged hierarchies.
*/
public void testLookupMember2() {
// ok if no exception occurs
executeQuery(
"select {[Store].[USA].[Washington]} on columns from [Sales Ragged]");
}
/**
* Make sure that the Crossjoin in [Measures].[CustomerCount]
* is not evaluated in NON EMPTY context.
*/
public void testCalcMemberWithNonEmptyCrossJoin() {
getConnection().getCacheControl(null).flushSchemaCache();
Result result = executeQuery(
"with member [Measures].[CustomerCount] as \n"
+ "'Count(CrossJoin({[Product].[All Products]}, [Customers].[Name].Members))'\n"
+ "select \n"
+ "NON EMPTY{[Measures].[CustomerCount]} ON columns,\n"
+ "NON EMPTY{[Product].[All Products]} ON rows\n"
+ "from [Sales]\n"
+ "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])");
Cell c = result.getCell(new int[] {0, 0});
// we expect 10281 customers, although there are only 20 non-empty ones
// @see #testLevelMembers
assertEquals("10,281", c.getFormattedValue());
}
public void testLevelMembers() {
if (MondrianProperties.instance().TestExpDependencies.get() > 0) {
// Dependency testing causes extra SQL reads, and screws up this
// test.
return;
}
SmartMemberReader smr = getSmartMemberReader("Customers");
// use the RolapCubeHierarchy's member cache for levels
MemberCacheHelper smrch =
((RolapCubeHierarchy.CacheRolapCubeHierarchyMemberReader) smr)
.rolapCubeCacheHelper;
clearAndHardenCache(smrch);
MemberCacheHelper smrich = smr.cacheHelper;
clearAndHardenCache(smrich);
// use the shared member cache for mapMemberToChildren
SmartMemberReader ssmr = getSharedSmartMemberReader("Customers");
MemberCacheHelper ssmrch = ssmr.cacheHelper;
clearAndHardenCache(ssmrch);
TestCase c = new TestCase(
50,
21,
"select \n"
+ "{[Measures].[Unit Sales]} ON columns,\n"
+ "NON EMPTY {[Customers].[All Customers], [Customers].[Name].Members} ON rows\n"
+ "from [Sales]\n"
+ "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])");
Result r = c.run();
Level[] levels = smr.getHierarchy().getLevels();
Level nameLevel = levels[levels.length - 1];
// evaluator for [All Customers], [Store 14], [1/1/1997]
Evaluator context = getEvaluator(r, new int[]{0, 0});
// make sure that [Customers].[Name].Members is NOT in cache
TupleConstraint lmc = scf.getLevelMembersConstraint(null);
assertNull(smrch.mapLevelToMembers.get((RolapLevel) nameLevel, lmc));
// make sure that NON EMPTY [Customers].[Name].Members IS in cache
lmc = scf.getLevelMembersConstraint(context.push(true));
List list = smrch.mapLevelToMembers.get((RolapLevel) nameLevel, lmc);
if (MondrianProperties.instance().EnableRolapCubeMemberCache.get()) {
assertNotNull(list);
assertEquals(20, list.size());
}
// make sure that the parent/child for the context are cached
// [Customers].[All Customers].[USA].[CA].[Burlingame].[Peggy Justice]
Member member = r.getAxes()[1].getPositions().get(1).get(0);
Member parent = member.getParentMember();
parent = ((RolapCubeMember) parent).getRolapMember();
member = ((RolapCubeMember) member).getRolapMember();
// lookup all children of [Burlingame] -> not in cache
MemberChildrenConstraint mcc = scf.getMemberChildrenConstraint(null);
assertNull(ssmrch.mapMemberToChildren.get((RolapMember) parent, mcc));
// lookup NON EMPTY children of [Burlingame] -> yes these are in cache
mcc = scf.getMemberChildrenConstraint(context.push(true));
list = smrich.mapMemberToChildren.get((RolapMember) parent, mcc);
assertNotNull(list);
assertTrue(list.contains(member));
}
public void testLevelMembersWithoutNonEmpty() {
SmartMemberReader smr = getSmartMemberReader("Customers");
MemberCacheHelper smrch =
((RolapCubeHierarchy.CacheRolapCubeHierarchyMemberReader) smr)
.rolapCubeCacheHelper;
clearAndHardenCache(smrch);
MemberCacheHelper smrich = smr.cacheHelper;
clearAndHardenCache(smrich);
SmartMemberReader ssmr = getSharedSmartMemberReader("Customers");
MemberCacheHelper ssmrch = ssmr.cacheHelper;
clearAndHardenCache(ssmrch);
Result r = executeQuery(
"select \n"
+ "{[Measures].[Unit Sales]} ON columns,\n"
+ "{[Customers].[All Customers], [Customers].[Name].Members} ON rows\n"
+ "from [Sales]\n"
+ "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])");
Level[] levels = smr.getHierarchy().getLevels();
Level nameLevel = levels[levels.length - 1];
// evaluator for [All Customers], [Store 14], [1/1/1997]
Evaluator context = getEvaluator(r, new int[] {0, 0});
// make sure that [Customers].[Name].Members IS in cache
TupleConstraint lmc = scf.getLevelMembersConstraint(null);
List list = smrch.mapLevelToMembers.get((RolapLevel) nameLevel, lmc);
if (MondrianProperties.instance().EnableRolapCubeMemberCache.get()) {
assertNotNull(list);
assertEquals(10281, list.size());
}
// make sure that NON EMPTY [Customers].[Name].Members is NOT in cache
lmc = scf.getLevelMembersConstraint(context.push(true));
assertNull(smrch.mapLevelToMembers.get((RolapLevel) nameLevel, lmc));
// make sure that the parent/child for the context are cached
// [Customers].[All Customers].[Canada].[BC].[Burnaby]
Member member = r.getAxes()[1].getPositions().get(1).get(0);
Member parent = member.getParentMember();
parent = ((RolapCubeMember) parent).getRolapMember();
member = ((RolapCubeMember) member).getRolapMember();
// lookup all children of [Burnaby] -> yes, found in cache
MemberChildrenConstraint mcc = scf.getMemberChildrenConstraint(null);
list = ssmrch.mapMemberToChildren.get((RolapMember) parent, mcc);
assertNotNull(list);
assertTrue(list.contains(member));
// lookup NON EMPTY children of [Burlingame] -> not in cache
mcc = scf.getMemberChildrenConstraint(context.push(true));
list = ssmrch.mapMemberToChildren.get((RolapMember) parent, mcc);
assertNull(list);
}
/**
* Tests that <Dimension>.Members exploits the same optimization as
* <Level>.Members.
*/
public void testDimensionMembers() {
// No query should return more than 20 rows. (1 row at 'all' level,
// 1 row at nation level, 1 at state level, 20 at city level, and 11
// at customers level = 34.)
TestCase c = new TestCase(
34,
34,
"select \n"
+ "{[Measures].[Unit Sales]} ON columns,\n"
+ "NON EMPTY [Customers].Members ON rows\n"
+ "from [Sales]\n"
+ "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])");
c.run();
}
/**
* Tests non empty children of rolap member
*/
public void testMemberChildrenOfRolapMember() {
TestCase c = new TestCase(
50,
4,
"select \n"
+ "{[Measures].[Unit Sales]} ON columns,\n"
+ "NON EMPTY [Customers].[All Customers].[USA].[CA].[Palo Alto].Children ON rows\n"
+ "from [Sales]\n"
+ "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])");
c.run();
}
/**
* Tests non empty children of All member
*/
public void testMemberChildrenOfAllMember() {
TestCase c = new TestCase(
50, 14, "select {[Measures].[Unit Sales]} ON columns,\n"
+ "NON EMPTY [Promotions].[All Promotions].Children ON rows from [Sales]\n"
+ "where ([Time].[1997].[Q1].[1])");
c.run();
}
/**
* Tests non empty children of All member w/o WHERE clause
*/
public void testMemberChildrenNoWhere() {
// The time dimension is joined because there is no (All) level in the
// Time hierarchy:
// select
// `promotion`.`promotion_name` as `c0`
// from
// `time_by_day` as `time_by_day`,
// `sales_fact_1997` as `sales_fact_1997`,
// `promotion` as `promotion`
// where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`
// and `time_by_day`.`the_year` = 1997
// and `sales_fact_1997`.`promotion_id`
// = `promotion`.`promotion_id`
// group by
// `promotion`.`promotion_name`
// order by
// `promotion`.`promotion_name`
TestCase c =
new TestCase(
50,
48,
"select {[Measures].[Unit Sales]} ON columns,\n"
+ "NON EMPTY [Promotions].[All Promotions].Children ON rows "
+ "from [Sales]\n");
c.run();
}
/**
* Testcase for bug 1379068, which causes no children of [Time].[1997].[Q2]
* to be found, because it incorrectly constrains on the level's key column
* rather than name column.
*/
public void testMemberChildrenNameCol() {
// Expression dependency testing casues false negatives.
if (MondrianProperties.instance().TestExpDependencies.get() > 0) {
return;
}
TestCase c = new TestCase(
3,
1,
"select "
+ " {[Measures].[Count]} ON columns,"
+ " {[Time].[1997].[Q2].[April]} on rows "
+ "from [HR]");
c.run();
}
/**
* When a member is expanded in JPivot with mulitple hierarchies visible it
* generates a
* <code>CrossJoin({[member from left hierarchy]}, [member to
* expand].Children)</code>
*
* <p>This should behave the same as if <code>[member from left
* hierarchy]</code> was put into the slicer.
*/
public void testCrossjoin() {
if (MondrianProperties.instance().TestExpDependencies.get() > 0) {
// Dependency testing causes extra SQL reads, and makes this
// test fail.
return;
}
TestCase c =
new TestCase(
45,
4,
"select \n"
+ "{[Measures].[Unit Sales]} ON columns,\n"
+ "NON EMPTY Crossjoin("
+ "{[Store].[USA].[CA].[San Francisco].[Store 14]},"
+ " [Customers].[USA].[CA].[Palo Alto].Children) ON rows\n"
+ "from [Sales] where ([Time].[1997].[Q1].[1])");
c.run();
}
/**
* Ensures that NON EMPTY Descendants is optimized.
* Ensures that Descendants as a side effect collects MemberChildren that
* may be looked up in the cache.
*/
public void testNonEmptyDescendants() {
// Don't run the test if we're testing expression dependencies.
// Expression dependencies cause spurious interval calls to
// 'level.getMembers()' which create false negatives in this test.
if (MondrianProperties.instance().TestExpDependencies.get() > 0) {
return;
}
Connection con = getTestContext().getFoodMartConnection(false);
SmartMemberReader smr = getSmartMemberReader(con, "Customers");
MemberCacheHelper smrch = smr.cacheHelper;
clearAndHardenCache(smrch);
SmartMemberReader ssmr = getSmartMemberReader(con, "Customers");
MemberCacheHelper ssmrch = ssmr.cacheHelper;
clearAndHardenCache(ssmrch);
TestCase c =
new TestCase(
con,
45,
21,
"select \n"
+ "{[Measures].[Unit Sales]} ON columns, "
+ "NON EMPTY {[Customers].[All Customers], Descendants([Customers].[All Customers].[USA].[CA], [Customers].[Name])} on rows "
+ "from [Sales] "
+ "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])");
Result result = c.run();
// [Customers].[All Customers].[USA].[CA].[Burlingame].[Peggy Justice]
RolapMember peggy =
(RolapMember) result.getAxes()[1].getPositions().get(1).get(0);
RolapMember burlingame = peggy.getParentMember();
peggy = ((RolapCubeMember) peggy).getRolapMember();
burlingame = ((RolapCubeMember) burlingame).getRolapMember();
// all children of burlingame are not in cache
MemberChildrenConstraint mcc = scf.getMemberChildrenConstraint(null);
assertNull(ssmrch.mapMemberToChildren.get(burlingame, mcc));
// but non empty children is
Evaluator evaluator = getEvaluator(result, new int[] {0, 0});
mcc = scf.getMemberChildrenConstraint(evaluator.push(true));
List list = ssmrch.mapMemberToChildren.get(burlingame, mcc);
assertNotNull(list);
assertTrue(list.contains(peggy));
// now we run the same query again, this time everything must come out
// of the cache
RolapNativeRegistry reg = getRegistry(con);
reg.setListener(
new Listener() {
public void foundEvaluator(NativeEvent e) {
}
public void foundInCache(TupleEvent e) {
}
public void executingSql(TupleEvent e) {
fail("expected caching");
}
});
try {
c.run();
} finally {
reg.setListener(null);
}
}
public void testBug1412384() {
// Bug 1412384 causes a NPE in SqlConstraintUtils.
assertQueryReturns(
"select NON EMPTY {[Time].[1997]} ON COLUMNS,\n"
+ "NON EMPTY Hierarchize(Union({[Customers].[All Customers]},\n"
+ "[Customers].[All Customers].Children)) ON ROWS\n"
+ "from [Sales]\n"
+ "where [Measures].[Profit]",
"Axis
+ "{[Measures].[Profit]}\n"
+ "Axis
+ "{[Time].[1997]}\n"
+ "Axis
+ "{[Customers].[All Customers]}\n"
+ "{[Customers].[All Customers].[USA]}\n"
+ "Row #0: $339,610.90\n"
+ "Row #1: $339,610.90\n");
}
public void testVirtualCubeCrossJoin() {
checkNative(
18,
3,
"select "
+ "{[Measures].[Units Ordered], [Measures].[Store Sales]} on columns, "
+ "non empty crossjoin([Product].[All Products].children, "
+ "[Store].[All Stores].children) on rows "
+ "from [Warehouse and Sales]");
}
public void testVirtualCubeNonEmptyCrossJoin() {
checkNative(
18,
3,
"select "
+ "{[Measures].[Units Ordered], [Measures].[Store Sales]} on columns, "
+ "NonEmptyCrossJoin([Product].[All Products].children, "
+ "[Store].[All Stores].children) on rows "
+ "from [Warehouse and Sales]");
}
public void testVirtualCubeNonEmptyCrossJoin3Args() {
checkNative(
3,
3,
"select "
+ "{[Measures].[Store Sales]} on columns, "
+ "nonEmptyCrossJoin([Product].[All Products].children, "
+ "nonEmptyCrossJoin([Customers].[All Customers].children,"
+ "[Store].[All Stores].children)) on rows "
+ "from [Warehouse and Sales]");
}
public void testNotNativeVirtualCubeCrossJoin1() {
switch (getTestContext().getDialect().getDatabaseProduct()) {
case INFOBRIGHT:
// Hits same Infobright bug as NamedSetTest.testNamedSetOnMember.
return;
}
// for this test, verify that no alert is raised even though
// native evaluation isn't supported, because query
// doesn't use explicit NonEmptyCrossJoin
propSaver.set(
MondrianProperties.instance().AlertNativeEvaluationUnsupported,
"ERROR");
// native cross join cannot be used due to AllMembers
checkNotNative(
3,
"select "
+ "{[Measures].AllMembers} on columns, "
+ "non empty crossjoin([Product].[All Products].children, "
+ "[Store].[All Stores].children) on rows "
+ "from [Warehouse and Sales]");
}
public void testNotNativeVirtualCubeCrossJoin2() {
// native cross join cannot be used due to the range operator
checkNotNative(
3,
"select "
+ "{[Measures].[Sales Count] : [Measures].[Unit Sales]} on columns, "
+ "non empty crossjoin([Product].[All Products].children, "
+ "[Store].[All Stores].children) on rows "
+ "from [Warehouse and Sales]");
}
public void testNotNativeVirtualCubeCrossJoinUnsupported() {
switch (getTestContext().getDialect().getDatabaseProduct()) {
case INFOBRIGHT:
// Hits same Infobright bug as NamedSetTest.testNamedSetOnMember.
return;
}
final BooleanProperty enableProperty =
MondrianProperties.instance().EnableNativeCrossJoin;
final StringProperty alertProperty =
MondrianProperties.instance().AlertNativeEvaluationUnsupported;
if (!enableProperty.get()) {
// When native cross joins are explicitly disabled, no alerts
// are supposed to be raised.
return;
}
String mdx =
"select "
+ "{[Measures].AllMembers} on columns, "
+ "NonEmptyCrossJoin([Product].[All Products].children, "
+ "[Store].[All Stores].children) on rows "
+ "from [Warehouse and Sales]";
final List<LoggingEvent> events = new ArrayList<LoggingEvent>();
// set up log4j listener to detect alerts
Appender alertListener = new AppenderSkeleton() {
protected void append(LoggingEvent event) {
events.add(event);
}
public void close() {
}
public boolean requiresLayout() {
return false;
}
};
Logger rolapUtilLogger = Logger.getLogger(RolapUtil.class);
rolapUtilLogger.addAppender(alertListener);
String expectedMessage =
"Unable to use native SQL evaluation for 'NonEmptyCrossJoin'";
// verify that exception is thrown if alerting is set to ERROR
propSaver.set(
alertProperty, org.apache.log4j.Level.ERROR.toString());
try {
checkNotNative(3, mdx);
fail("Expected NativeEvaluationUnsupportedException");
} catch (NativeEvaluationUnsupportedException ex) {
// Expected
} finally {
propSaver.reset();
}
// should have gotten one ERROR
int nEvents = countFilteredEvents(
events, org.apache.log4j.Level.ERROR, expectedMessage);
assertEquals("logged error count check", 1, nEvents);
events.clear();
// verify that exactly one warning is posted but execution succeeds
// if alerting is set to WARN
propSaver.set(
alertProperty, org.apache.log4j.Level.WARN.toString());
try {
checkNotNative(3, mdx);
} finally {
propSaver.reset();
}
// should have gotten one WARN
nEvents = countFilteredEvents(
events, org.apache.log4j.Level.WARN, expectedMessage);
assertEquals("logged warning count check", 1, nEvents);
events.clear();
// verify that no warning is posted if native evaluation is
// explicitly disabled
propSaver.set(
alertProperty, org.apache.log4j.Level.WARN.toString());
propSaver.set(
enableProperty, false);
try {
checkNotNative(3, mdx);
} finally {
propSaver.reset();
}
// should have gotten no WARN
nEvents = countFilteredEvents(
events, org.apache.log4j.Level.WARN, expectedMessage);
assertEquals("logged warning count check", 0, nEvents);
events.clear();
// no biggie if we don't get here for some reason; just being
// half-heartedly clean
rolapUtilLogger.removeAppender(alertListener);
}
private int countFilteredEvents(
List<LoggingEvent> events,
org.apache.log4j.Level level,
String pattern)
{
int filteredEventCount = 0;
for (LoggingEvent event : events) {
if (!event.getLevel().equals(level)) {
continue;
}
if (event.getMessage().toString().indexOf(pattern) == -1) {
continue;
}
filteredEventCount++;
}
return filteredEventCount;
}
public void testVirtualCubeCrossJoinCalculatedMember1() {
// calculated member appears in query
checkNative(
18,
3,
"WITH MEMBER [Measures].[Total Cost] as "
+ "'[Measures].[Store Cost] + [Measures].[Warehouse Cost]' "
+ "select "
+ "{[Measures].[Total Cost]} on columns, "
+ "non empty crossjoin([Product].[All Products].children, "
+ "[Store].[All Stores].children) on rows "
+ "from [Warehouse and Sales]");
}
public void testVirtualCubeCrossJoinCalculatedMember2() {
// calculated member defined in schema
checkNative(
18,
3,
"select "
+ "{[Measures].[Profit Per Unit Shipped]} on columns, "
+ "non empty crossjoin([Product].[All Products].children, "
+ "[Store].[All Stores].children) on rows "
+ "from [Warehouse and Sales]");
}
public void testNotNativeVirtualCubeCrossJoinCalculatedMember() {
// native cross join cannot be used due to CurrentMember in the
// calculated member
checkNotNative(
3,
"WITH MEMBER [Measures].[CurrMember] as "
+ "'[Measures].CurrentMember' "
+ "select "
+ "{[Measures].[CurrMember]} on columns, "
+ "non empty crossjoin([Product].[All Products].children, "
+ "[Store].[All Stores].children) on rows "
+ "from [Warehouse and Sales]");
}
public void testCjEnumCalcMembers() {
// 3 cross joins -- 2 of the 4 arguments to the cross joins are
// enumerated sets with calculated members
// should be non-native due to the fix to testCjEnumCalcMembersBug()
checkNotNative(
30,
"with "
+ "member [Product].[All Products].[Drink].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ " 'sum({[Product].[All Products].[Drink]})' "
+ "member [Product].[All Products].[Non-Consumable].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ " 'sum({[Product].[All Products].[Non-Consumable]})' "
+ "member [Customers].[All Customers].[USA].[CA].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ " 'sum({[Customers].[All Customers].[USA].[CA]})' "
+ "member [Customers].[All Customers].[USA].[OR].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ " 'sum({[Customers].[All Customers].[USA].[OR]})' "
+ "member [Customers].[All Customers].[USA].[WA].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ " 'sum({[Customers].[All Customers].[USA].[WA]})' "
+ "select "
+ "{[Measures].[Unit Sales]} on columns, "
+ "non empty "
+ " crossjoin("
+ " crossjoin("
+ " crossjoin("
+ " {[Product].[All Products].[Drink].[*SUBTOTAL_MEMBER_SEL~SUM], "
+ " [Product].[All Products].[Non-Consumable].[*SUBTOTAL_MEMBER_SEL~SUM]}, "
+ " [Education Level].[Education Level].Members), "
+ " {[Customers].[All Customers].[USA].[CA].[*SUBTOTAL_MEMBER_SEL~SUM], "
+ " [Customers].[All Customers].[USA].[OR].[*SUBTOTAL_MEMBER_SEL~SUM], "
+ " [Customers].[All Customers].[USA].[WA].[*SUBTOTAL_MEMBER_SEL~SUM]}), "
+ " [Time].[Year].members)"
+ " on rows "
+ "from [Sales]");
}
public void testCjEnumCalcMembersBug() {
// make sure NECJ is forced to be non-native
// before the fix, the query is natively evaluated and result
// has empty rows for [Store Type].[All Store Types].[HeadQuarters]
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
propSaver.set(MondrianProperties.instance().ExpandNonNative, true);
checkNotNative(
9,
"with "
+ "member [Store Type].[All Store Types].[S] as sum({[Store Type].[All Store Types]}) "
+ "set [Enum Store Types] as {"
+ " [Store Type].[All Store Types].[HeadQuarters], "
+ " [Store Type].[All Store Types].[Small Grocery], "
+ " [Store Type].[All Store Types].[Supermarket], "
+ " [Store Type].[All Store Types].[S]}"
+ "select [Measures] on columns,\n"
+ " NonEmptyCrossJoin([Product].[All Products].Children, [Enum Store Types]) on rows\n"
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Unit Sales]}\n"
+ "Axis
+ "{[Product].[All Products].[Drink], [Store Type].[All Store Types].[Small Grocery]}\n"
+ "{[Product].[All Products].[Drink], [Store Type].[All Store Types].[Supermarket]}\n"
+ "{[Product].[All Products].[Drink], [Store Type].[All Store Types].[S]}\n"
+ "{[Product].[All Products].[Food], [Store Type].[All Store Types].[Small Grocery]}\n"
+ "{[Product].[All Products].[Food], [Store Type].[All Store Types].[Supermarket]}\n"
+ "{[Product].[All Products].[Food], [Store Type].[All Store Types].[S]}\n"
+ "{[Product].[All Products].[Non-Consumable], [Store Type].[All Store Types].[Small Grocery]}\n"
+ "{[Product].[All Products].[Non-Consumable], [Store Type].[All Store Types].[Supermarket]}\n"
+ "{[Product].[All Products].[Non-Consumable], [Store Type].[All Store Types].[S]}\n"
+ "Row #0: 574\n"
+ "Row #1: 14,092\n"
+ "Row #2: 24,597\n"
+ "Row #3: 4,764\n"
+ "Row #4: 108,188\n"
+ "Row #5: 191,940\n"
+ "Row #6: 1,219\n"
+ "Row #7: 28,275\n"
+ "Row #8: 50,236\n");
}
public void testCjEnumEmptyCalcMembers() {
// Make sure maxConstraint settting is high enough
int minConstraints = 3;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints, minConstraints);
}
// enumerated list of calculated members results in some empty cells
checkNotNative(
5,
"with "
+ "member [Customers].[All Customers].[USA].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ " 'sum({[Customers].[All Customers].[USA]})' "
+ "member [Customers].[All Customers].[Mexico].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ " 'sum({[Customers].[All Customers].[Mexico]})' "
+ "member [Customers].[All Customers].[Canada].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ " 'sum({[Customers].[All Customers].[Canada]})' "
+ "select "
+ "{[Measures].[Unit Sales]} on columns, "
+ "non empty "
+ " crossjoin("
+ " {[Customers].[All Customers].[Mexico].[*SUBTOTAL_MEMBER_SEL~SUM], "
+ " [Customers].[All Customers].[Canada].[*SUBTOTAL_MEMBER_SEL~SUM], "
+ " [Customers].[All Customers].[USA].[*SUBTOTAL_MEMBER_SEL~SUM]}, "
+ " [Education Level].[Education Level].Members) "
+ " on rows "
+ "from [Sales]");
}
public void testCjUnionEnumCalcMembers() {
// non-native due to the fix to testCjEnumCalcMembersBug()
checkNotNative(
46,
"with "
+ "member [Education Level].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ " 'sum({[Education Level].[All Education Levels]})' "
+ "member [Education Level].[*SUBTOTAL_MEMBER_SEL~AVG] as "
+ " 'avg([Education Level].[Education Level].Members)' select "
+ "{[Measures].[Unit Sales]} on columns, "
+ "non empty union (Crossjoin("
+ " [Product].[Product Department].Members, "
+ " {[Education Level].[*SUBTOTAL_MEMBER_SEL~AVG]}), "
+ "crossjoin("
+ " [Product].[Product Department].Members, "
+ " {[Education Level].[*SUBTOTAL_MEMBER_SEL~SUM]})) on rows "
+ "from [Sales]");
}
/**
* Tests the behavior if you have NON EMPTY on both axes, and the default
* member of a hierarchy is not 'all' or the first child.
*/
public void testNonEmptyWithWeirdDefaultMember() {
if (!Bug.BugMondrian229Fixed) {
return;
}
TestContext testContext = TestContext.createSubstitutingCube(
"Sales",
" <Dimension name=\"Time\" type=\"TimeDimension\" foreignKey=\"time_id\">\n"
+ " <Hierarchy hasAll=\"false\" primaryKey=\"time_id\" defaultMember=\"[Time].[1997].[Q1].[1]\" >\n"
+ " <Table name=\"time_by_day\"/>\n"
+ " <Level name=\"Year\" column=\"the_year\" type=\"Numeric\" uniqueMembers=\"true\"\n"
+ " levelType=\"TimeYears\"/>\n"
+ " <Level name=\"Quarter\" column=\"quarter\" uniqueMembers=\"false\"\n"
+ " levelType=\"TimeQuarters\"/>\n"
+ " <Level name=\"Month\" column=\"month_of_year\" uniqueMembers=\"false\" type=\"Numeric\"\n"
+ " levelType=\"TimeMonths\"/>\n"
+ " </Hierarchy>\n"
+ " </Dimension>");
// Check that the grand total is different than when [Time].[1997] is
// the default member.
testContext.assertQueryReturns(
"select from [Sales]",
"Axis
+ "{}\n"
+ "21,628");
// Results of this query agree with MSAS 2000 SP1.
// The query gives the same results if the default member of [Time]
// is [Time].[1997] or [Time].[1997].[Q1].[1].
testContext.assertQueryReturns(
"select\n"
+ "NON EMPTY Crossjoin({[Time].[1997].[Q2].[4]}, [Customers].[Country].members) on columns,\n"
+ "NON EMPTY [Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth].children on rows\n"
+ "from sales",
"Axis
+ "{}\n"
+ "Axis
+ "{[Time].[1997].[Q2].[4], [Customers].[All Customers].[USA]}\n"
+ "Axis
+ "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth].[Portsmouth Imported Beer]}\n"
+ "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth].[Portsmouth Light Beer]}\n"
+ "Row #0: 3\n"
+ "Row #1: 21\n");
}
public void testCrossJoinNamedSets1() {
checkNative(
3,
3,
"with "
+ "SET [ProductChildren] as '[Product].[All Products].children' "
+ "SET [StoreMembers] as '[Store].[Store Country].members' "
+ "select {[Measures].[Store Sales]} on columns, "
+ "non empty crossjoin([ProductChildren], [StoreMembers]) "
+ "on rows from [Sales]");
}
public void testCrossJoinNamedSets2() {
// Make sure maxConstraint settting is high enough
int minConstraints = 3;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints, minConstraints);
}
checkNative(
3, 3,
"with "
+ "SET [ProductChildren] as '{[Product].[All Products].[Drink], "
+ "[Product].[All Products].[Food], "
+ "[Product].[All Products].[Non-Consumable]}' "
+ "SET [StoreChildren] as '[Store].[All Stores].children' "
+ "select {[Measures].[Store Sales]} on columns, "
+ "non empty crossjoin([ProductChildren], [StoreChildren]) on rows from "
+ "[Sales]");
}
public void testCrossJoinSetWithDifferentParents() {
// Verify that only the members explicitly referenced in the set
// are returned. Note that different members are referenced in
// each level in the time dimension.
checkNative(
5,
5,
"select "
+ "{[Measures].[Unit Sales]} on columns, "
+ "NonEmptyCrossJoin([Education Level].[Education Level].Members, "
+ "{[Time].[1997].[Q1], [Time].[1998].[Q2]}) on rows from Sales");
}
public void testCrossJoinSetWithCrossProdMembers() {
// Make sure maxConstraint settting is high enough
int minConstraints = 6;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints, minConstraints);
}
// members in set are a cross product of (1997, 1998) and (Q1, Q2, Q3)
checkNative(
15, 15,
"select "
+ "{[Measures].[Unit Sales]} on columns, "
+ "NonEmptyCrossJoin([Education Level].[Education Level].Members, "
+ "{[Time].[1997].[Q1], [Time].[1997].[Q2], [Time].[1997].[Q3], "
+ "[Time].[1998].[Q1], [Time].[1998].[Q2], [Time].[1998].[Q3]})"
+ "on rows from Sales");
}
public void testCrossJoinSetWithSameParent() {
// Make sure maxConstraint settting is high enough
int minConstraints = 2;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints, minConstraints);
}
// members in set have the same parent
checkNative(
10, 10,
"select "
+ "{[Measures].[Unit Sales]} on columns, "
+ "NonEmptyCrossJoin([Education Level].[Education Level].Members, "
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills], "
+ "[Store].[All Stores].[USA].[CA].[San Francisco]}) "
+ "on rows from Sales");
}
public void testCrossJoinSetWithUniqueLevel() {
// Make sure maxConstraint settting is high enough
int minConstraints = 2;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints, minConstraints);
}
// members in set have different parents but there is a unique level
checkNative(
10, 10,
"select "
+ "{[Measures].[Unit Sales]} on columns, "
+ "NonEmptyCrossJoin([Education Level].[Education Level].Members, "
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6], "
+ "[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}) "
+ "on rows from Sales");
}
public void testCrossJoinMultiInExprAllMember() {
checkNative(
10,
10,
"select "
+ "{[Measures].[Unit Sales]} on columns, "
+ "NonEmptyCrossJoin([Education Level].[Education Level].Members, "
+ "{[Product].[All Products].[Drink].[Alcoholic Beverages], "
+ "[Product].[All Products].[Food].[Breakfast Foods]}) "
+ "on rows from Sales");
}
public void testCrossJoinEvaluatorContext1() {
// This test ensures that the proper measure members context is
// set when evaluating a non-empty cross join. The context should
// not include the calculated measure [*TOP_BOTTOM_SET]. If it
// does, the query will result in an infinite loop because the cross
// join will try evaluating the calculated member (when it shouldn't)
// and the calculated member references the cross join, resulting
// in the loop
assertQueryReturns(
"With "
+ "Set [*NATIVE_CJ_SET] as "
+ "'NonEmptyCrossJoin([*BASE_MEMBERS_Store], [*BASE_MEMBERS_Products])' "
+ "Set [*TOP_BOTTOM_SET] as "
+ "'Order([*GENERATED_MEMBERS_Store], ([Measures].[Unit Sales], "
+ "[Product].[All Products].[*TOP_BOTTOM_MEMBER]), BDESC)' "
+ "Set [*BASE_MEMBERS_Store] as '[Store].members' "
+ "Set [*GENERATED_MEMBERS_Store] as 'Generate([*NATIVE_CJ_SET], {[Store].CurrentMember})' "
+ "Set [*BASE_MEMBERS_Products] as "
+ "'{[Product].[All Products].[Food], [Product].[All Products].[Drink], "
+ "[Product].[All Products].[Non-Consumable]}' "
+ "Set [*GENERATED_MEMBERS_Products] as "
+ "'Generate([*NATIVE_CJ_SET], {[Product].CurrentMember})' "
+ "Member [Product].[All Products].[*TOP_BOTTOM_MEMBER] as "
+ "'Aggregate([*GENERATED_MEMBERS_Products])'"
+ "Member [Measures].[*TOP_BOTTOM_MEMBER] as 'Rank([Store].CurrentMember,[*TOP_BOTTOM_SET])' "
+ "Member [Store].[All Stores].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ "'sum(Filter([*GENERATED_MEMBERS_Store], [Measures].[*TOP_BOTTOM_MEMBER] <= 10))'"
+ "Select {[Measures].[Store Cost]} on columns, "
+ "Non Empty Filter(Generate([*NATIVE_CJ_SET], {([Store].CurrentMember)}), "
+ "[Measures].[*TOP_BOTTOM_MEMBER] <= 10) on rows From [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Store Cost]}\n"
+ "Axis
+ "{[Store].[All Stores]}\n"
+ "{[Store].[All Stores].[USA]}\n"
+ "{[Store].[All Stores].[USA].[CA]}\n"
+ "{[Store].[All Stores].[USA].[OR]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Portland]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Salem]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n"
+ "{[Store].[All Stores].[USA].[WA]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Tacoma]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n"
+ "Row #0: 225,627.23\n"
+ "Row #1: 225,627.23\n"
+ "Row #2: 63,530.43\n"
+ "Row #3: 56,772.50\n"
+ "Row #4: 21,948.94\n"
+ "Row #5: 34,823.56\n"
+ "Row #6: 34,823.56\n"
+ "Row #7: 105,324.31\n"
+ "Row #8: 29,959.28\n"
+ "Row #9: 29,959.28\n");
}
public void testCrossJoinEvaluatorContext2() {
// Make sure maxConstraint settting is high enough
int minConstraints = 2;
if (MondrianProperties.instance().MaxConstraints.get()
< minConstraints)
{
propSaver.set(
MondrianProperties.instance().MaxConstraints, minConstraints);
}
// calculated measure contains a calculated member
assertQueryReturns(
"With Set [*NATIVE_CJ_SET] as "
+ "'NonEmptyCrossJoin([*BASE_MEMBERS_Dates], [*BASE_MEMBERS_Stores])' "
+ "Set [*BASE_MEMBERS_Dates] as '{[Time].[1997].[Q1], [Time].[1997].[Q2]}' "
+ "Set [*GENERATED_MEMBERS_Dates] as "
+ "'Generate([*NATIVE_CJ_SET], {[Time].[Time].CurrentMember})' "
+ "Set [*GENERATED_MEMBERS_Measures] as '{[Measures].[*SUMMARY_METRIC_0]}' "
+ "Set [*BASE_MEMBERS_Stores] as '{[Store].[USA].[CA], [Store].[USA].[WA]}' "
+ "Set [*GENERATED_MEMBERS_Stores] as "
+ "'Generate([*NATIVE_CJ_SET], {[Store].CurrentMember})' "
+ "Member [Time].[*SM_CTX_SEL] as 'Aggregate([*GENERATED_MEMBERS_Dates])' "
+ "Member [Measures].[*SUMMARY_METRIC_0] as "
+ "'[Measures].[Unit Sales]/([Measures].[Unit Sales],[Time].[*SM_CTX_SEL])', "
+ "FORMAT_STRING = '0.00%' "
+ "Member [Time].[*SUBTOTAL_MEMBER_SEL~SUM] as 'sum([*GENERATED_MEMBERS_Dates])' "
+ "Member [Store].[*SUBTOTAL_MEMBER_SEL~SUM] as "
+ "'sum(Filter([*GENERATED_MEMBERS_Stores], "
+ "([Measures].[Unit Sales], [Time].[*SUBTOTAL_MEMBER_SEL~SUM]) > 0.0))' "
+ "Select Union "
+ "(CrossJoin "
+ "(Filter "
+ "(Generate([*NATIVE_CJ_SET], {([Time].[Time].CurrentMember)}), "
+ "Not IsEmpty ([Measures].[Unit Sales])), "
+ "[*GENERATED_MEMBERS_Measures]), "
+ "CrossJoin "
+ "(Filter "
+ "({[Time].[*SUBTOTAL_MEMBER_SEL~SUM]}, "
+ "Not IsEmpty ([Measures].[Unit Sales])), "
+ "[*GENERATED_MEMBERS_Measures])) on columns, "
+ "Non Empty Union "
+ "(Filter "
+ "(Filter "
+ "(Generate([*NATIVE_CJ_SET], "
+ "{([Store].CurrentMember)}), "
+ "([Measures].[Unit Sales], "
+ "[Time].[*SUBTOTAL_MEMBER_SEL~SUM]) > 0.0), "
+ "Not IsEmpty ([Measures].[Unit Sales])), "
+ "Filter("
+ "{[Store].[*SUBTOTAL_MEMBER_SEL~SUM]}, "
+ "Not IsEmpty ([Measures].[Unit Sales]))) on rows "
+ "From [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Time].[1997].[Q1], [Measures].[*SUMMARY_METRIC_0]}\n"
+ "{[Time].[1997].[Q2], [Measures].[*SUMMARY_METRIC_0]}\n"
+ "{[Time].[*SUBTOTAL_MEMBER_SEL~SUM], [Measures].[*SUMMARY_METRIC_0]}\n"
+ "Axis
+ "{[Store].[All Stores].[USA].[CA]}\n"
+ "{[Store].[All Stores].[USA].[WA]}\n"
+ "{[Store].[*SUBTOTAL_MEMBER_SEL~SUM]}\n"
+ "Row #0: 48.34%\n"
+ "Row #0: 51.66%\n"
+ "Row #0: 100.00%\n"
+ "Row #1: 50.53%\n"
+ "Row #1: 49.47%\n"
+ "Row #1: 100.00%\n"
+ "Row #2: 49.72%\n"
+ "Row #2: 50.28%\n"
+ "Row #2: 100.00%\n");
}
public void testVCNativeCJWithIsEmptyOnMeasure() {
// Don't use checkNative method here because in the case where
// native cross join isn't used, the query causes a stack overflow.
// A measures member is referenced in the IsEmpty() function. This
// shouldn't prevent native cross join from being used.
assertQueryReturns(
"with "
+ "set BM_PRODUCT as {[Product].[All Products].[Drink]} "
+ "set BM_EDU as [Education Level].[Education Level].Members "
+ "set BM_GENDER as {[Gender].[Gender].[M]} "
+ "set CJ as NonEmptyCrossJoin(BM_GENDER,NonEmptyCrossJoin(BM_EDU,BM_PRODUCT)) "
+ "set GM_PRODUCT as Generate(CJ, {[Product].CurrentMember}) "
+ "set GM_EDU as Generate(CJ, {[Education Level].CurrentMember}) "
+ "set GM_GENDER as Generate(CJ, {[Gender].CurrentMember}) "
+ "set GM_MEASURE as {[Measures].[Unit Sales]} "
+ "member [Education Level].FILTER1 as Aggregate(GM_EDU) "
+ "member [Gender].FILTER2 as Aggregate(GM_GENDER) "
+ "select "
+ "Filter(GM_PRODUCT, Not IsEmpty([Measures].[Unit Sales])) on rows, "
+ "GM_MEASURE on columns "
+ "from [Warehouse and Sales] "
+ "where ([Education Level].FILTER1, [Gender].FILTER2)",
"Axis
+ "{[Education Level].[FILTER1], [Gender].[FILTER2]}\n"
+ "Axis
+ "{[Measures].[Unit Sales]}\n"
+ "Axis
+ "{[Product].[All Products].[Drink]}\n"
+ "Row #0: 12,395\n");
}
public void testVCNativeCJWithTopPercent() {
// The reference to [Store Sales] inside the topPercent function
// should not prevent native cross joins from being used
checkNative(
92,
1,
"select {topPercent(nonemptycrossjoin([Product].[Product Department].members, "
+ "[Time].[1997].children),10,[Measures].[Store Sales])} on columns, "
+ "{[Measures].[Store Sales]} on rows from "
+ "[Warehouse and Sales]");
}
public void testVCOrdinalExpression() {
// [Customers].[Name] is an ordinal expression. Make sure ordering
// is done on the column corresponding to that expression.
checkNative(
67,
67,
"select {[Measures].[Store Sales]} on columns,"
+ " NON EMPTY Crossjoin([Customers].[Name].Members,"
+ " [Product].[Product Name].Members) ON rows "
+ " from [Warehouse and Sales] where ("
+ " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],"
+ " [Time].[1997].[Q1].[1])");
}
/**
* Test for bug #1696772
* Modified which calculations are tested for non native, non empty joins
*/
public void testNonEmptyWithCalcMeasure() {
checkNative(
15,
6,
"With "
+ "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Store],NonEmptyCrossJoin([*BASE_MEMBERS_Education Level],[*BASE_MEMBERS_Product]))' "
+ "Set [*METRIC_CJ_SET] as 'Filter([*NATIVE_CJ_SET],[Measures].[*Store Sales_SEL~SUM] > 50000.0 And [Measures].[*Unit Sales_SEL~MAX] > 50000.0)' "
+ "Set [*BASE_MEMBERS_Store] as '[Store].[Store Country].Members' "
+ "Set [*NATIVE_MEMBERS_Store] as 'Generate([*NATIVE_CJ_SET], {[Store].CurrentMember})' "
+ "Set [*METRIC_MEMBERS_Store] as 'Generate([*METRIC_CJ_SET], {[Store].CurrentMember})' "
+ "Set [*BASE_MEMBERS_Measures] as '{[Measures].[Store Sales],[Measures].[Unit Sales]}' "
+ "Set [*BASE_MEMBERS_Education Level] as '[Education Level].[Education Level].Members' "
+ "Set [*NATIVE_MEMBERS_Education Level] as 'Generate([*NATIVE_CJ_SET], {[Education Level].CurrentMember})' "
+ "Set [*METRIC_MEMBERS_Education Level] as 'Generate([*METRIC_CJ_SET], {[Education Level].CurrentMember})' "
+ "Set [*BASE_MEMBERS_Product] as '[Product].[Product Family].Members' "
+ "Set [*NATIVE_MEMBERS_Product] as 'Generate([*NATIVE_CJ_SET], {[Product].CurrentMember})' "
+ "Set [*METRIC_MEMBERS_Product] as 'Generate([*METRIC_CJ_SET], {[Product].CurrentMember})' "
+ "Member [Product].[*CTX_METRIC_MEMBER_SEL~SUM] as 'Sum({[Product].[All Products]})' "
+ "Member [Store].[*CTX_METRIC_MEMBER_SEL~SUM] as 'Sum({[Store].[All Stores]})' "
+ "Member [Measures].[*Store Sales_SEL~SUM] as '([Measures].[Store Sales],[Education Level].CurrentMember,[Product].[*CTX_METRIC_MEMBER_SEL~SUM],[Store].[*CTX_METRIC_MEMBER_SEL~SUM])' "
+ "Member [Product].[*CTX_METRIC_MEMBER_SEL~MAX] as 'Max([*NATIVE_MEMBERS_Product])' "
+ "Member [Store].[*CTX_METRIC_MEMBER_SEL~MAX] as 'Max([*NATIVE_MEMBERS_Store])' "
+ "Member [Measures].[*Unit Sales_SEL~MAX] as '([Measures].[Unit Sales],[Education Level].CurrentMember,[Product].[*CTX_METRIC_MEMBER_SEL~MAX],[Store].[*CTX_METRIC_MEMBER_SEL~MAX])' "
+ "Select "
+ "CrossJoin(Generate([*METRIC_CJ_SET], {([Store].CurrentMember)}),[*BASE_MEMBERS_Measures]) on columns, "
+ "Non Empty Generate([*METRIC_CJ_SET], {([Education Level].CurrentMember,[Product].CurrentMember)}) on rows "
+ "From [Sales]");
}
public void testCalculatedSlicerMember() {
// This test verifies that members(the FILTER members in the query
// below) on the slicer are ignored in CrossJoin emptiness check.
// Otherwise, if they are not ignored, stack over flow will occur
// because emptiness check depends on a calculated slicer member
// which references the non-empty set being computed.
// Bcause native evaluation already ignores calculated members on
// the slicer, both native and non-native evaluation should return
// the same result.
checkNative(
20,
1,
"With "
+ "Set BM_PRODUCT as '{[Product].[All Products].[Drink]}' "
+ "Set BM_EDU as '[Education Level].[Education Level].Members' "
+ "Set BM_GENDER as '{[Gender].[Gender].[M]}' "
+ "Set NECJ_SET as 'NonEmptyCrossJoin(BM_GENDER, NonEmptyCrossJoin(BM_EDU,BM_PRODUCT))' "
+ "Set GM_PRODUCT as 'Generate(NECJ_SET, {[Product].CurrentMember})' "
+ "Set GM_EDU as 'Generate(NECJ_SET, {[Education Level].CurrentMember})' "
+ "Set GM_GENDER as 'Generate(NECJ_SET, {[Gender].CurrentMember})' "
+ "Set GM_MEASURE as '{[Measures].[Unit Sales]}' "
+ "Member [Education Level].FILTER1 as 'Aggregate(GM_EDU)' "
+ "Member [Gender].FILTER2 as 'Aggregate(GM_GENDER)' "
+ "Select "
+ "GM_PRODUCT on rows, GM_MEASURE on columns "
+ "From [Sales] Where ([Education Level].FILTER1, [Gender].FILTER2)");
}
// next two verify that when NECJ references dimension from slicer,
// slicer is correctly ignored for purposes of evaluating NECJ emptiness,
// regardless of whether evaluation is native or non-native
public void testIndependentSlicerMemberNonNative() {
checkIndependentSlicerMemberNative(false);
}
public void testIndependentSlicerMemberNative() {
checkIndependentSlicerMemberNative(true);
}
private void checkIndependentSlicerMemberNative(boolean useNative) {
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, useNative);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
Connection conn = getTestContext().getFoodMartConnection(false);
TestContext context = getTestContext(conn);
context.assertQueryReturns(
"with set [p] as '[Product].[Product Family].members' "
+ "set [s] as '[Store].[Store Country].members' "
+ "set [ne] as 'nonemptycrossjoin([p],[s])' "
+ "set [nep] as 'Generate([ne],{[Product].CurrentMember})' "
+ "select [nep] on columns from sales "
+ "where ([Store].[Store Country].[Mexico])",
"Axis
+ "{[Store].[All Stores].[Mexico]}\n"
+ "Axis
+ "{[Product].[All Products].[Drink]}\n"
+ "{[Product].[All Products].[Food]}\n"
+ "{[Product].[All Products].[Non-Consumable]}\n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n");
}
public void testDependentSlicerMemberNonNative() {
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, false);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
Connection conn = getTestContext().getFoodMartConnection(false);
TestContext context = getTestContext(conn);
context.assertQueryReturns(
"with set [p] as '[Product].[Product Family].members' "
+ "set [s] as '[Store].[Store Country].members' "
+ "set [ne] as 'nonemptycrossjoin([p],[s])' "
+ "set [nep] as 'Generate([ne],{[Product].CurrentMember})' "
+ "select [nep] on columns from sales "
+ "where ([Time].[1998])",
"Axis
+ "{[Time].[1998]}\n"
+ "Axis
}
public void testDependentSlicerMemberNative() {
propSaver.set(
MondrianProperties.instance().EnableNativeCrossJoin, true);
// Get a fresh connection; Otherwise the mondrian property setting
// is not refreshed for this parameter.
Connection conn = getTestContext().getFoodMartConnection(false);
TestContext context = getTestContext(conn);
context.assertQueryReturns(
"with set [p] as '[Product].[Product Family].members' "
+ "set [s] as '[Store].[Store Country].members' "
+ "set [ne] as 'nonemptycrossjoin([p],[s])' "
+ "set [nep] as 'Generate([ne],{[Product].CurrentMember})' "
+ "select [nep] on columns from sales "
+ "where ([Time].[1998])",
"Axis
+ "{[Time].[1998]}\n"
+ "Axis
}
/**
* Tests bug 1791609, "CrossJoin non empty optimizer eliminates calculated
* member".
*/
public void testBug1791609NonEmptyCrossJoinEliminatesCalcMember() {
if (!Bug.BugMondrian328Fixed) {
return;
}
// From the bug:
// With NON EMPTY (mondrian.rolap.nonempty) behavior set to true
// the following mdx return no result. The same mdx returns valid
// result when NON EMPTY is turned off.
assertQueryReturns(
"WITH \n"
+ "MEMBER Measures.Calc AS '[Measures].[Profit] * 2', SOLVE_ORDER=1000\n"
+ "MEMBER Product.Conditional as 'Iif (Measures.CurrentMember IS Measures.[Calc], "
+ "Measures.CurrentMember, null)', SOLVE_ORDER=2000\n"
+ "SET [S2] AS '{[Store].MEMBERS}' \n"
+ "SET [S1] AS 'CROSSJOIN({[Customers].[All Customers]},{Product.Conditional})' \n"
+ "SELECT \n"
+ "NON EMPTY GENERATE({Measures.[Calc]}, \n"
+ " CROSSJOIN(HEAD( {([Measures].CURRENTMEMBER)}, \n"
+ " 1\n"
+ " ), \n"
+ " {[S1]}\n"
+ " ), \n"
+ " ALL\n"
+ " ) \n"
+ " ON AXIS(0), \n"
+ "NON EMPTY [S2] ON AXIS(1) \n"
+ "FROM [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Calc], [Customers].[All Customers], [Product].[Conditional]}\n"
+ "Axis
+ "{[Store].[All Stores]}\n"
+ "{[Store].[All Stores].[USA]}\n"
+ "{[Store].[All Stores].[USA].[CA]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Diego]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n"
+ "{[Store].[All Stores].[USA].[OR]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Portland]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Salem]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n"
+ "{[Store].[All Stores].[USA].[WA]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bellingham]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bremerton]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Seattle]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Spokane]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Tacoma]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Walla Walla]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Yakima]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n"
+ "Row #0: $679,221.79\n"
+ "Row #1: $679,221.79\n"
+ "Row #2: $191,274.83\n"
+ "Row #3: $54,967.60\n"
+ "Row #4: $54,967.60\n"
+ "Row #5: $65,547.49\n"
+ "Row #6: $65,547.49\n"
+ "Row #7: $65,435.21\n"
+ "Row #8: $65,435.21\n"
+ "Row #9: $5,324.53\n"
+ "Row #10: $5,324.53\n"
+ "Row #11: $171,009.14\n"
+ "Row #12: $66,219.69\n"
+ "Row #13: $66,219.69\n"
+ "Row #14: $104,789.45\n"
+ "Row #15: $104,789.45\n"
+ "Row #16: $316,937.82\n"
+ "Row #17: $5,685.23\n"
+ "Row #18: $5,685.23\n"
+ "Row #19: $63,548.67\n"
+ "Row #20: $63,548.67\n"
+ "Row #21: $63,374.53\n"
+ "Row #22: $63,374.53\n"
+ "Row #23: $59,677.94\n"
+ "Row #24: $59,677.94\n"
+ "Row #25: $89,769.36\n"
+ "Row #26: $89,769.36\n"
+ "Row #27: $5,651.26\n"
+ "Row #28: $5,651.26\n"
+ "Row #29: $29,230.83\n"
+ "Row #30: $29,230.83\n");
}
/**
* Test that executes <Level>.Members and applies a non-empty
* constraint. Must work regardless of whether
* {@link MondrianProperties#EnableNativeNonEmpty native} is enabled.
* Testcase for bug
* 1722959, "NON EMPTY Level.MEMBERS fails if nonempty.enable=false"
*/
public void testNonEmptyLevelMembers() {
boolean currentNativeNonEmpty =
MondrianProperties.instance().EnableNativeNonEmpty.get();
boolean currentNonEmptyOnAllAxis =
MondrianProperties.instance().EnableNonEmptyOnAllAxis.get();
try {
MondrianProperties.instance().EnableNativeNonEmpty.set(false);
MondrianProperties.instance().EnableNonEmptyOnAllAxis.set(true);
assertQueryReturns(
"WITH MEMBER [Measures].[One] AS '1' "
+ "SELECT "
+ "NON EMPTY {[Measures].[One], [Measures].[Store Sales]} ON rows, "
+ "NON EMPTY [Store].[Store State].MEMBERS on columns "
+ "FROM sales",
"Axis
+ "{}\n"
+ "Axis
+ "{[Store].[All Stores].[Canada].[BC]}\n"
+ "{[Store].[All Stores].[Mexico].[DF]}\n"
+ "{[Store].[All Stores].[Mexico].[Guerrero]}\n"
+ "{[Store].[All Stores].[Mexico].[Jalisco]}\n"
+ "{[Store].[All Stores].[Mexico].[Veracruz]}\n"
+ "{[Store].[All Stores].[Mexico].[Yucatan]}\n"
+ "{[Store].[All Stores].[Mexico].[Zacatecas]}\n"
+ "{[Store].[All Stores].[USA].[CA]}\n"
+ "{[Store].[All Stores].[USA].[OR]}\n"
+ "{[Store].[All Stores].[USA].[WA]}\n"
+ "Axis
+ "{[Measures].[One]}\n"
+ "{[Measures].[Store Sales]}\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: 159,167.84\n"
+ "Row #1: 142,277.07\n"
+ "Row #1: 263,793.22\n");
if (Bug.BugMondrian446Fixed) {
MondrianProperties.instance().EnableNativeNonEmpty.set(true);
assertQueryReturns(
"WITH MEMBER [Measures].[One] AS '1' "
+ "SELECT "
+ "NON EMPTY {[Measures].[One], [Measures].[Store Sales]} ON rows, "
+ "NON EMPTY [Store].[Store State].MEMBERS on columns "
+ "FROM sales",
"Axis
+ "{}\n"
+ "Axis
+ "{[Store].[All Stores].[Canada].[BC]}\n"
+ "{[Store].[All Stores].[Mexico].[DF]}\n"
+ "{[Store].[All Stores].[Mexico].[Guerrero]}\n"
+ "{[Store].[All Stores].[Mexico].[Jalisco]}\n"
+ "{[Store].[All Stores].[Mexico].[Veracruz]}\n"
+ "{[Store].[All Stores].[Mexico].[Yucatan]}\n"
+ "{[Store].[All Stores].[Mexico].[Zacatecas]}\n"
+ "{[Store].[All Stores].[USA].[CA]}\n"
+ "{[Store].[All Stores].[USA].[OR]}\n"
+ "{[Store].[All Stores].[USA].[WA]}\n"
+ "Axis
+ "{[Measures].[One]}\n"
+ "{[Measures].[Store Sales]}\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #0: 1\n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: 159,167.84\n"
+ "Row #1: 142,277.07\n"
+ "Row #1: 263,793.22\n");
}
} finally {
MondrianProperties.instance().EnableNativeNonEmpty.set(
currentNativeNonEmpty);
MondrianProperties.instance().EnableNonEmptyOnAllAxis.set(
currentNonEmptyOnAllAxis);
}
}
public void testNonEmptyResults() {
// This unit test was failing with a NullPointerException in JPivot
// after the highcardinality feature was added, I've included it
// here to make sure it continues to work.
assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales], [Measures].[Store Cost]} ON columns, "
+ "NON EMPTY Filter([Product].[Brand Name].Members, ([Measures].[Unit Sales] > 100000.0)) ON rows "
+ "from [Sales] where [Time].[1997]",
"Axis
+ "{[Time].[1997]}\n"
+ "Axis
+ "Axis
}
public void testBugMondrian412() throws Exception {
TestContext ctx = getTestContext();
ctx.assertQueryReturns(
"with member [Measures].[AvgRevenue] as 'Avg([Store].[Store Name].Members, [Measures].[Store Sales])' "
+ "select NON EMPTY {[Measures].[Store Sales], [Measures].[AvgRevenue]} ON COLUMNS, "
+ "NON EMPTY Filter([Store].[Store Name].Members, ([Measures].[AvgRevenue] < [Measures].[Store Sales])) ON ROWS "
+ "from [Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Measures].[Store Sales]}\n"
+ "{[Measures].[AvgRevenue]}\n"
+ "Axis
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n"
+ "Row #0: 45,750.24\n"
+ "Row #0: 43,479.86\n"
+ "Row #1: 54,545.28\n"
+ "Row #1: 43,479.86\n"
+ "Row #2: 54,431.14\n"
+ "Row #2: 43,479.86\n"
+ "Row #3: 55,058.79\n"
+ "Row #3: 43,479.86\n"
+ "Row #4: 87,218.28\n"
+ "Row #4: 43,479.86\n"
+ "Row #5: 52,896.30\n"
+ "Row #5: 43,479.86\n"
+ "Row #6: 52,644.07\n"
+ "Row #6: 43,479.86\n"
+ "Row #7: 49,634.46\n"
+ "Row #7: 43,479.86\n"
+ "Row #8: 74,843.96\n"
+ "Row #8: 43,479.86\n");
}
public void testNonEmpyOnVirtualCubeWithNonJoiningDimension() {
assertQueryReturns(
"select non empty {[Warehouse].[Warehouse name].members} on 0,"
+ "{[Measures].[Units Shipped],[Measures].[Unit Sales]} on 1"
+ " from [Warehouse and Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Warehouse].[All Warehouses].[USA].[CA].[Beverly Hills].[Big Quality Warehouse]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[CA].[Los Angeles].[Artesia Warehousing, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[CA].[San Diego].[Jorgensen Service Storage]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[CA].[San Francisco].[Food Service Storage, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[OR].[Portland].[Quality Distribution, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[OR].[Salem].[Treehouse Distribution]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Bellingham].[Foster Products]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Bremerton].[Destination, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Seattle].[Quality Warehousing and Trucking]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Spokane].[Jones International]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Tacoma].[Jorge Garcia, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Walla Walla].[Valdez Warehousing]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Yakima].[Maddock Stored Foods]}\n"
+ "Axis
+ "{[Measures].[Units Shipped]}\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Row #0: 10759.0\n"
+ "Row #0: 24587.0\n"
+ "Row #0: 23835.0\n"
+ "Row #0: 1696.0\n"
+ "Row #0: 8515.0\n"
+ "Row #0: 32393.0\n"
+ "Row #0: 2348.0\n"
+ "Row #0: 22734.0\n"
+ "Row #0: 24110.0\n"
+ "Row #0: 11889.0\n"
+ "Row #0: 32411.0\n"
+ "Row #0: 1860.0\n"
+ "Row #0: 10589.0\n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n"
+ "Row #1: \n");
}
public void testNonEmptyOnNonJoiningValidMeasure() {
assertQueryReturns(
"with member [Measures].[vm] as 'ValidMeasure([Measures].[Unit Sales])'"
+ "select non empty {[Warehouse].[Warehouse name].members} on 0,"
+ "{[Measures].[Units Shipped],[Measures].[vm]} on 1"
+ " from [Warehouse and Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Warehouse].[All Warehouses].[USA].[CA].[Beverly Hills].[Big Quality Warehouse]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[CA].[Los Angeles].[Artesia Warehousing, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[CA].[San Diego].[Jorgensen Service Storage]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[CA].[San Francisco].[Food Service Storage, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[OR].[Portland].[Quality Distribution, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[OR].[Salem].[Treehouse Distribution]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Bellingham].[Foster Products]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Bremerton].[Destination, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Seattle].[Quality Warehousing and Trucking]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Spokane].[Jones International]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Tacoma].[Jorge Garcia, Inc.]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Walla Walla].[Valdez Warehousing]}\n"
+ "{[Warehouse].[All Warehouses].[USA].[WA].[Yakima].[Maddock Stored Foods]}\n"
+ "Axis
+ "{[Measures].[Units Shipped]}\n"
+ "{[Measures].[vm]}\n"
+ "Row #0: 10759.0\n"
+ "Row #0: 24587.0\n"
+ "Row #0: 23835.0\n"
+ "Row #0: 1696.0\n"
+ "Row #0: 8515.0\n"
+ "Row #0: 32393.0\n"
+ "Row #0: 2348.0\n"
+ "Row #0: 22734.0\n"
+ "Row #0: 24110.0\n"
+ "Row #0: 11889.0\n"
+ "Row #0: 32411.0\n"
+ "Row #0: 1860.0\n"
+ "Row #0: 10589.0\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #1: 266,773\n");
}
public void testCrossjoinWithTwoDimensionsJoiningToOppositeBaseCubes() {
assertQueryReturns(
"with member [Measures].[vm] as 'ValidMeasure([Measures].[Unit Sales])'\n"
+ "select non empty Crossjoin([Warehouse].[Warehouse Name].members, [Gender].[Gender].members) on 0,\n"
+ "{[Measures].[Units Shipped],[Measures].[vm]} on 1\n"
+ "from [Warehouse and Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "Axis
+ "{[Measures].[Units Shipped]}\n"
+ "{[Measures].[vm]}\n");
}
public void testCrossjoinWithOneDimensionThatDoesNotJoinToBothBaseCubes() {
assertQueryReturns(
"with member [Measures].[vm] as 'ValidMeasure([Measures].[Units Shipped])'"
+ "select non empty Crossjoin([Store].[Store Name].members, [Gender].[Gender].members) on 0,"
+ "{[Measures].[Unit Sales],[Measures].[vm]} on 1"
+ " from [Warehouse and Sales]",
"Axis
+ "{}\n"
+ "Axis
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22], [Gender].[All Gender].[M]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23], [Gender].[All Gender].[F]}\n"
+ "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23], [Gender].[All Gender].[M]}\n"
+ "Axis
+ "{[Measures].[Unit Sales]}\n"
+ "{[Measures].[vm]}\n"
+ "Row #0: 10,771\n"
+ "Row #0: 10,562\n"
+ "Row #0: 12,089\n"
+ "Row #0: 13,574\n"
+ "Row #0: 12,835\n"
+ "Row #0: 12,800\n"
+ "Row #0: 1,064\n"
+ "Row #0: 1,053\n"
+ "Row #0: 12,488\n"
+ "Row #0: 13,591\n"
+ "Row #0: 20,548\n"
+ "Row #0: 21,032\n"
+ "Row #0: 1,096\n"
+ "Row #0: 1,141\n"
+ "Row #0: 11,640\n"
+ "Row #0: 12,936\n"
+ "Row #0: 13,513\n"
+ "Row #0: 11,498\n"
+ "Row #0: 12,068\n"
+ "Row #0: 11,523\n"
+ "Row #0: 17,420\n"
+ "Row #0: 17,837\n"
+ "Row #0: 1,019\n"
+ "Row #0: 1,184\n"
+ "Row #0: 5,007\n"
+ "Row #0: 6,484\n"
+ "Row #1: 10759.0\n"
+ "Row #1: 10759.0\n"
+ "Row #1: 24587.0\n"
+ "Row #1: 24587.0\n"
+ "Row #1: 23835.0\n"
+ "Row #1: 23835.0\n"
+ "Row #1: 1696.0\n"
+ "Row #1: 1696.0\n"
+ "Row #1: 8515.0\n"
+ "Row #1: 8515.0\n"
+ "Row #1: 32393.0\n"
+ "Row #1: 32393.0\n"
+ "Row #1: 2348.0\n"
+ "Row #1: 2348.0\n"
+ "Row #1: 22734.0\n"
+ "Row #1: 22734.0\n"
+ "Row #1: 24110.0\n"
+ "Row #1: 24110.0\n"
+ "Row #1: 11889.0\n"
+ "Row #1: 11889.0\n"
+ "Row #1: 32411.0\n"
+ "Row #1: 32411.0\n"
+ "Row #1: 1860.0\n"
+ "Row #1: 1860.0\n"
+ "Row #1: 10589.0\n"
+ "Row #1: 10589.0\n");
}
public void testLeafMembersOfParentChildDimensionAreNativelyEvaluated() {
final String query = "SELECT"
+ " NON EMPTY "
+ "Crossjoin("
+ "{"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Gabriel Walton],"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Bishop Meastas],"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Paula Duran],"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Margaret Earley],"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Elizabeth Horne]"
+ "},"
+ "[Store].[Store Name].members"
+ ") on 0 from hr";
checkNative(50, 5, query);
}
public void testNonLeafMembersOfPCDimensionAreNotNativelyEvaluated() {
final String query = "SELECT"
+ " NON EMPTY "
+ "Crossjoin("
+ "{"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Beverly Baker],"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Gabriel Walton],"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin],"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays],"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley],"
+ "[Employees].[All Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Elizabeth Horne]"
+ "},"
+ "[Store].[Store Name].members"
+ ") on 0 from hr";
checkNotNative(9, query);
}
public void testNativeWithOverriddenNullMemberRepAndNullConstraint() {
String preMdx = "SELECT FROM [Sales]";
String mdx =
"SELECT \n"
+ " [Gender].[Gender].MEMBERS ON ROWS\n"
+ " ,{[Measures].[Unit Sales]} ON COLUMNS\n"
+ "FROM [Sales]\n"
+ "WHERE \n"
+ " [Store Size in SQFT].[All Store Size in SQFTs].[~Missing ]";
// run an mdx query with the default NullMemberRepresentation
executeQuery(preMdx);
propSaver.set(
MondrianProperties.instance().NullMemberRepresentation,
"~Missing ");
propSaver.set(
MondrianProperties.instance().EnableNonEmptyOnAllAxis,
true);
RolapUtil.reloadNullLiteral();
executeQuery(mdx);
}
public void testBugMondrian321() {
if (true) {
return; // TODO: enable
}
assertQueryReturns(
"WITH SET [#DataSet#] AS 'Crossjoin({Descendants([Customer_2].[All Customers], 2)}, {[Product].[All Products]})' \n"
+ "SELECT {[Measures].[Unit Sales], [Measures].[Store Sales]} on columns, \n"
+ "Hierarchize({[#DataSet#]}) on rows FROM [Sales]",
"x");
}
public void testNativeCrossjoinWillConstrainUsingArgsFromAllAxes() {
String mdx = "select "
+ "non empty Crossjoin({[Gender].[Gender].[F]},{[Measures].[Unit Sales]}) on 0,"
+ "non empty Crossjoin({[Time].[1997]},{[Promotions].[All Promotions].[Bag Stuffers],[Promotions].[All Promotions].[Best Savings]}) on 1"
+ " from [Warehouse and Sales]";
SqlPattern accessPattern = new SqlPattern(
Dialect.DatabaseProduct.ACCESS,
"select `time_by_day`.`the_year` as `c0`, `promotion`.`promotion_name` as `c1` "
+ "from `time_by_day` as `time_by_day`, `sales_fact_1997` as `sales_fact_1997`, `promotion` as `promotion`, `customer` as `customer` "
+ "where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id` "
+ "and `sales_fact_1997`.`promotion_id` = `promotion`.`promotion_id` "
+ "and (`promotion`.`promotion_name` in ('Bag Stuffers', 'Best Savings')) "
+ "and `sales_fact_1997`.`customer_id` = `customer`.`customer_id` "
+ "and (`customer`.`gender` = 'F') "
+ "and (`time_by_day`.`the_year` = 1997) "
+ "group by `time_by_day`.`the_year`, `promotion`.`promotion_name` "
+ "order by 1 ASC, 2 ASC",
623);
SqlPattern oraclePattern = new SqlPattern(
Dialect.DatabaseProduct.ORACLE,
"select \"time_by_day\".\"the_year\" as \"c0\", \"promotion\".\"promotion_name\" as \"c1\" "
+ "from \"time_by_day\" \"time_by_day\", "
+ "\"sales_fact_1997\" \"sales_fact_1997\", "
+ "\"promotion\" \"promotion\", \"customer\" \"customer\" "
+ "where \"sales_fact_1997\".\"time_id\" = \"time_by_day\".\"time_id\" "
+ "and \"sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\" "
+ "and (\"promotion\".\"promotion_name\" in ('Bag Stuffers', 'Best Savings')) "
+ "and \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" "
+ "and (\"customer\".\"gender\" = 'F') and (\"time_by_day\".\"the_year\" = 1997) "
+ "group by \"time_by_day\".\"the_year\", \"promotion\".\"promotion_name\" "
+ "order by 1 ASC, 2 ASC",
611);
assertQuerySql(mdx, new SqlPattern[]{oraclePattern, accessPattern});
}
public void testLevelMembersWillConstrainUsingArgsFromAllAxes() {
String mdx = "select "
+ "non empty Crossjoin({[Gender].[Gender].[F]},{[Measures].[Unit Sales]}) on 0,"
+ "non empty [Promotions].[Promotions].members on 1"
+ " from [Warehouse and Sales]";
SqlPattern accessPattern = new SqlPattern(
Dialect.DatabaseProduct.ACCESS,
"select `promotion`.`promotion_name` as `c0` "
+ "from `promotion` as `promotion`, "
+ "`sales_fact_1997` as `sales_fact_1997`, "
+ "`customer` as `customer` "
+ "where `sales_fact_1997`.`promotion_id` = `promotion`.`promotion_id` "
+ "and `sales_fact_1997`.`customer_id` = `customer`.`customer_id` "
+ "and (`customer`.`gender` = 'F') "
+ "group by `promotion`.`promotion_name` "
+ "order by 1 ASC",
357);
SqlPattern oraclePattern = new SqlPattern(
Dialect.DatabaseProduct.ORACLE,
"select \"promotion\".\"promotion_name\" as \"c0\" "
+ "from \"promotion\" \"promotion\", "
+ "\"sales_fact_1997\" \"sales_fact_1997\", "
+ "\"customer\" \"customer\" "
+ "where \"sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\" "
+ "and \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" "
+ "and (\"customer\".\"gender\" = 'F') "
+ "group by \"promotion\".\"promotion_name\" "
+ "order by 1 ASC",
347);
assertQuerySql(mdx, new SqlPattern[]{oraclePattern, accessPattern});
}
public void testNativeCrossjoinWillExpandFirstLastChild() {
String mdx = "select "
+ "non empty Crossjoin({[Gender].firstChild,[Gender].lastChild},{[Measures].[Unit Sales]}) on 0,"
+ "non empty Crossjoin({[Time].[1997]},{[Promotions].[All Promotions].[Bag Stuffers],[Promotions].[All Promotions].[Best Savings]}) on 1"
+ " from [Warehouse and Sales]";
final SqlPattern pattern = new SqlPattern(
Dialect.DatabaseProduct.ORACLE,
"select \"time_by_day\".\"the_year\" as \"c0\", "
+ "\"promotion\".\"promotion_name\" as \"c1\" "
+ "from \"time_by_day\" \"time_by_day\", \"sales_fact_1997\" \"sales_fact_1997\", \"promotion\" \"promotion\", \"customer\" \"customer\" "
+ "where \"sales_fact_1997\".\"time_id\" = \"time_by_day\".\"time_id\" "
+ "and \"sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\" "
+ "and \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" "
+ "and (\"customer\".\"gender\" in ('F', 'M')) "
+ "and (\"promotion\".\"promotion_name\" in ('Bag Stuffers', 'Best Savings')) "
+ "and (\"time_by_day\".\"the_year\" = 1997) "
+ "group by \"time_by_day\".\"the_year\", \"promotion\".\"promotion_name\" "
+ "order by 1 ASC, 2 ASC",
611);
assertQuerySql(mdx, new SqlPattern[]{pattern});
}
public void testNativeCrossjoinWillExpandLagInNamedSet() {
String mdx =
"with set [blah] as '{[Gender].lastChild.lag(1),[Gender].[M]}' "
+ "select "
+ "non empty Crossjoin([blah],{[Measures].[Unit Sales]}) on 0,"
+ "non empty Crossjoin({[Time].[1997]},{[Promotions].[All Promotions].[Bag Stuffers],[Promotions].[All Promotions].[Best Savings]}) on 1"
+ " from [Warehouse and Sales]";
final SqlPattern pattern = new SqlPattern(
Dialect.DatabaseProduct.ORACLE,
"select \"time_by_day\".\"the_year\" as \"c0\", "
+ "\"promotion\".\"promotion_name\" as \"c1\" "
+ "from \"time_by_day\" \"time_by_day\", \"sales_fact_1997\" \"sales_fact_1997\", \"promotion\" \"promotion\", \"customer\" \"customer\" "
+ "where \"sales_fact_1997\".\"time_id\" = \"time_by_day\".\"time_id\" "
+ "and \"sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\" "
+ "and \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" "
+ "and (\"customer\".\"gender\" in ('F', 'M')) "
+ "and (\"promotion\".\"promotion_name\" in ('Bag Stuffers', 'Best Savings')) "
+ "and (\"time_by_day\".\"the_year\" = 1997) "
+ "group by \"time_by_day\".\"the_year\", \"promotion\".\"promotion_name\" "
+ "order by 1 ASC, 2 ASC",
611);
assertQuerySql(mdx, new SqlPattern[]{pattern});
}
void clearAndHardenCache(MemberCacheHelper helper) {
helper.mapLevelToMembers.setCache(
new HardSmartCache<
SmartMemberListCache.Key2<RolapLevel, Object>,
List<RolapMember>>());
helper.mapMemberToChildren.setCache(
new HardSmartCache<
SmartMemberListCache.Key2<RolapMember, Object>,
List<RolapMember>>());
helper.mapKeyToMember.clear();
}
SmartMemberReader getSmartMemberReader(String hierName) {
Connection con = getTestContext().getFoodMartConnection();
return getSmartMemberReader(con, hierName);
}
SmartMemberReader getSmartMemberReader(Connection con, String hierName) {
RolapCube cube = (RolapCube) con.getSchema().lookupCube("Sales", true);
RolapSchemaReader schemaReader =
(RolapSchemaReader) cube.getSchemaReader();
RolapHierarchy hierarchy =
(RolapHierarchy) cube.lookupHierarchy(
new Id.Segment(hierName, Id.Quoting.UNQUOTED),
false);
assertNotNull(hierarchy);
return (SmartMemberReader)
hierarchy.createMemberReader(schemaReader.getRole());
}
SmartMemberReader getSharedSmartMemberReader(String hierName) {
Connection con = getTestContext().getFoodMartConnection();
return getSharedSmartMemberReader(con, hierName);
}
SmartMemberReader getSharedSmartMemberReader(
Connection con, String hierName)
{
RolapCube cube = (RolapCube) con.getSchema().lookupCube("Sales", true);
RolapSchemaReader schemaReader =
(RolapSchemaReader) cube.getSchemaReader();
RolapCubeHierarchy hierarchy =
(RolapCubeHierarchy) cube.lookupHierarchy(
new Id.Segment(hierName, Id.Quoting.UNQUOTED), false);
assertNotNull(hierarchy);
return (SmartMemberReader) hierarchy.getRolapHierarchy()
.createMemberReader(schemaReader.getRole());
}
RolapEvaluator getEvaluator(Result res, int[] pos) {
while (res instanceof NonEmptyResult) {
res = ((NonEmptyResult) res).underlying;
}
return (RolapEvaluator) ((RolapResult) res).getEvaluator(pos);
}
}
// End NonEmptyTest.java
|
package com.zheng.upms.admin.controller;
import com.zheng.common.util.CookieUtil;
import com.zheng.common.util.RedisUtil;
import com.zheng.upms.admin.util.SystemConstant;
import com.zheng.upms.dao.model.UpmsSystemExample;
import com.zheng.upms.rpc.api.UpmsSystemService;
import com.zheng.upms.rpc.api.UpmsUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@Controller
@RequestMapping("/sso")
public class SSOController {
private final static Logger _log = LoggerFactory.getLogger(SSOController.class);
private final static int TIMEOUT = 2 * 60 * 60;
private final static String ZHENG_UPMS_SERVER_SESSION_ID = "zheng-upms-server-session-id";
@Autowired
UpmsSystemService upmsSystemService;
@Autowired
UpmsUserService upmsUserService;
/**
*
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(HttpServletRequest request, HttpServletResponse response) throws Exception {
String system_name = request.getParameter("system_name");
String backurl = request.getParameter("backurl");
UpmsSystemExample upmsSystemExample = new UpmsSystemExample();
upmsSystemExample.createCriteria()
.andNameEqualTo(system_name);
int count = upmsSystemService.countByExample(upmsSystemExample);
if (StringUtils.isEmpty(system_name) || 0 == count) {
_log.info("{}", system_name);
return "/404";
}
// sessionIdsessionidcookiesession
String sessionId = CookieUtil.getCookie(request, ZHENG_UPMS_SERVER_SESSION_ID);
if (StringUtils.isEmpty(sessionId)) {
sessionId = request.getSession().getId();
CookieUtil.setCookie(response, ZHENG_UPMS_SERVER_SESSION_ID, sessionId);
}
if (StringUtils.isEmpty(RedisUtil.get(sessionId + "_token"))) {
return "redirect:/sso/login?backurl=" + URLEncoder.encode(backurl, "utf-8");
}
String token = RedisUtil.get(sessionId + "_token");
String redirectUrl = backurl;
if (backurl.contains("?")) {
redirectUrl += "&token=" + token;
} else {
redirectUrl += "?token=" + token;
}
_log.info("{}", redirectUrl);
return "redirect:" + redirectUrl;
}
/**
* get
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(HttpServletRequest request) {
String sessionId = CookieUtil.getCookie(request, ZHENG_UPMS_SERVER_SESSION_ID);
_log.info("sessionId={}", sessionId);
String backurl = request.getParameter("backurl");
if (!StringUtils.isEmpty(sessionId) && !StringUtils.isEmpty(backurl)) {
String token = RedisUtil.get(sessionId + "_token");
// token
if (!StringUtils.isEmpty(token)) {
String redirectUrl = backurl;
if (backurl.contains("?")) {
redirectUrl += "&token=" + token;
} else {
redirectUrl += "?token=" + token;
}
_log.info("token{}", redirectUrl);
return "redirect:" + redirectUrl;
}
}
return "/sso/login";
}
/**
* post
* @param request
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Object login(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
String backurl = request.getParameter("backurl");
String username = request.getParameter("username");
String password = request.getParameter("password");
Map result = new HashMap<>();
String data = "";
if (StringUtils.isEmpty(username)) {
result.put("result", false);
result.put("data", SystemConstant.NO_USERNAME);
return result;
}
if (StringUtils.isEmpty(password)) {
result.put("result", false);
result.put("data", SystemConstant.NO_PASSWORD);
return result;
}
// shiro
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
try {
usernamePasswordToken.setRememberMe(false);
subject.login(usernamePasswordToken);
} catch (UnknownAccountException e) {
result.put("result", false);
result.put("data", SystemConstant.ERROR_USERNAME);
return result;
} catch (IncorrectCredentialsException e) {
result.put("result", false);
result.put("data", SystemConstant.ERROR_PASSWORD);
return result;
} catch (LockedAccountException e) {
result.put("result", false);
result.put("data", SystemConstant.INVALID_ACCOUNT);
return result;
}
// sessionIdsessionidcookiesession
String sessionId = CookieUtil.getCookie(request, ZHENG_UPMS_SERVER_SESSION_ID);
if (StringUtils.isEmpty(sessionId)) {
sessionId = request.getSession().getId();
CookieUtil.setCookie(response, ZHENG_UPMS_SERVER_SESSION_ID, sessionId);
}
// token
String token = UUID.randomUUID().toString();
// sessionId
RedisUtil.set(sessionId + "_token", token, TIMEOUT);
// token
RedisUtil.set(token, token, TIMEOUT);
if (StringUtils.isEmpty(backurl)) {
result.put("result", true);
result.put("data", "/");
} else {
String redirectUrl = backurl;
if (backurl.contains("?")) {
redirectUrl += "&token=" + token;
} else {
redirectUrl += "?token=" + token;
}
_log.info("token{}", redirectUrl);
result.put("result", true);
result.put("data", redirectUrl);
}
return result;
}
/**
* token
* @param request
* @return
*/
@RequestMapping(value = "/token", method = RequestMethod.POST)
@ResponseBody
public String token(HttpServletRequest request) {
String tokenParam = request.getParameter("token");
String token = RedisUtil.get(tokenParam);
if (StringUtils.isEmpty(tokenParam) || !tokenParam.equals(token)) {
return "failed";
}
return "success";
}
/**
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpServletRequest request, HttpServletResponse response) {
// shiro
SecurityUtils.getSubject().logout();
// sessionId
CookieUtil.removeCookie(response, ZHENG_UPMS_SERVER_SESSION_ID);
String sessionId = CookieUtil.getCookie(request, ZHENG_UPMS_SERVER_SESSION_ID);
// sessionId
String token = RedisUtil.get(sessionId + "_token");
RedisUtil.remove(sessionId + "_token");
// token
RedisUtil.remove(token);
Jedis jedis = RedisUtil.getJedis();
Set<String> subSessionIds = jedis.smembers(token + "_subSessionIds");
for (String subSessionId : subSessionIds) {
jedis.del(subSessionId + "_token");
jedis.srem(token + "_subSessionIds", subSessionId);
}
_log.info("token={}{}", token, jedis.scard(token + "_subSessionIds"));
String redirectUrl = request.getHeader("Referer");
_log.info("{}", redirectUrl);
return "redirect:" + redirectUrl;
}
}
|
package com.guyj.base;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.util.Linkify;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.TextView;
import com.guyj.listener.EasyOnItemChildCheckChangeListener;
import com.guyj.listener.EasyOnItemChildClickListener;
import com.guyj.listener.EasyOnItemChildLongClickListener;
import com.guyj.listener.EasyOnItemChildTouchListener;
public class ViewHolder extends RecyclerView.ViewHolder
{
private SparseArray<View> mViews;
private View mConvertView;
private Context mContext;
public ViewHolder(Context context, View itemView)
{
super(itemView);
mContext = context;
mConvertView = itemView;
mViews = new SparseArray<View>();
}
public static ViewHolder createViewHolder(Context context, View itemView)
{
ViewHolder holder = new ViewHolder(context, itemView);
return holder;
}
public static ViewHolder createViewHolder(Context context,
ViewGroup parent, int layoutId)
{
View itemView = LayoutInflater.from(context).inflate(layoutId, parent,
false);
ViewHolder holder = new ViewHolder(context, itemView);
return holder;
}
/**
* viewId
*
* @param viewId
* @return
*/
public <T extends View> T getView(int viewId)
{
View view = mViews.get(viewId);
if (view == null)
{
view = mConvertView.findViewById(viewId);
mViews.put(viewId, view);
}
return (T) view;
}
public <T extends ImageView> T getImageView(int viewId) {
View view = mViews.get(viewId);
if (view == null) {
view = mConvertView.findViewById(viewId);
mViews.put(viewId, view);
}
return (T) view;
}
public <T extends CheckBox> T getCheckBox(int viewId) {
View view = mViews.get(viewId);
if (view == null) {
view = mConvertView.findViewById(viewId);
mViews.put(viewId, view);
}
return (T) view;
}
public <T extends RadioButton> T getRadioButton(int viewId) {
View view = mViews.get(viewId);
if (view == null) {
view = mConvertView.findViewById(viewId);
mViews.put(viewId, view);
}
return (T) view;
}
public <T extends ProgressBar> T getProgressBar(int viewId) {
View view = mViews.get(viewId);
if (view == null) {
view = mConvertView.findViewById(viewId);
mViews.put(viewId, view);
}
return (T) view;
}
public <T extends SeekBar> T getSeekBar(int viewId) {
View view = mViews.get(viewId);
if (view == null) {
view = mConvertView.findViewById(viewId);
mViews.put(viewId, view);
}
return (T) view;
}
public View getConvertView()
{
return mConvertView;
}
/**
* ItemViewtruefalse
* @param isVisible
*/
public void setItemViewVisibility(boolean isVisible){
RecyclerView.LayoutParams param = (RecyclerView.LayoutParams)itemView.getLayoutParams();
if (isVisible){
param.height = LinearLayout.LayoutParams.WRAP_CONTENT;
param.width = LinearLayout.LayoutParams.MATCH_PARENT;
itemView.setVisibility(View.VISIBLE);
}else{
itemView.setVisibility(View.GONE);
param.height = 0;
param.width = 0;
}
itemView.setLayoutParams(param);
}
/**
* TextView
*
* @param viewId
* @param text
* @return
*/
public ViewHolder setText(int viewId, String text)
{
TextView tv = getView(viewId);
tv.setText(text);
return this;
}
public ViewHolder setImageResource(int viewId, int resId)
{
ImageView view = getView(viewId);
view.setImageResource(resId);
return this;
}
public ViewHolder setImageBitmap(int viewId, Bitmap bitmap)
{
ImageView view = getView(viewId);
view.setImageBitmap(bitmap);
return this;
}
public ViewHolder setImageDrawable(int viewId, Drawable drawable)
{
ImageView view = getView(viewId);
view.setImageDrawable(drawable);
return this;
}
public ViewHolder setBackgroundColor(int viewId, int color)
{
View view = getView(viewId);
view.setBackgroundColor(color);
return this;
}
public ViewHolder setBackgroundRes(int viewId, int backgroundRes)
{
View view = getView(viewId);
view.setBackgroundResource(backgroundRes);
return this;
}
public ViewHolder setTextColor(int viewId, int textColor)
{
TextView view = getView(viewId);
view.setTextColor(textColor);
return this;
}
public ViewHolder setTextColorRes(int viewId, int textColorRes)
{
TextView view = getView(viewId);
view.setTextColor(mContext.getResources().getColor(textColorRes));
return this;
}
@SuppressLint("NewApi")
public ViewHolder setAlpha(int viewId, float value)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
getView(viewId).setAlpha(value);
} else
{
// Pre-honeycomb hack to set Alpha value
AlphaAnimation alpha = new AlphaAnimation(value, value);
alpha.setDuration(0);
alpha.setFillAfter(true);
getView(viewId).startAnimation(alpha);
}
return this;
}
public ViewHolder setVisible(int viewId, boolean visible)
{
View view = getView(viewId);
view.setVisibility(visible ? View.VISIBLE : View.GONE);
return this;
}
public ViewHolder linkify(int viewId)
{
TextView view = getView(viewId);
Linkify.addLinks(view, Linkify.ALL);
return this;
}
public ViewHolder setTypeface(Typeface typeface, int... viewIds)
{
for (int viewId : viewIds)
{
TextView view = getView(viewId);
view.setTypeface(typeface);
view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
return this;
}
public ViewHolder setProgress(int viewId, int progress)
{
ProgressBar view = getView(viewId);
view.setProgress(progress);
return this;
}
public ViewHolder setProgress(int viewId, int progress, int max)
{
ProgressBar view = getView(viewId);
view.setMax(max);
view.setProgress(progress);
return this;
}
public ViewHolder setMax(int viewId, int max)
{
ProgressBar view = getView(viewId);
view.setMax(max);
return this;
}
public ViewHolder setRating(int viewId, float rating)
{
RatingBar view = getView(viewId);
view.setRating(rating);
return this;
}
public ViewHolder setRating(int viewId, float rating, int max)
{
RatingBar view = getView(viewId);
view.setMax(max);
view.setRating(rating);
return this;
}
public ViewHolder setTag(int viewId, Object tag)
{
View view = getView(viewId);
view.setTag(tag);
return this;
}
public ViewHolder setTag(int viewId, int key, Object tag)
{
View view = getView(viewId);
view.setTag(key, tag);
return this;
}
public ViewHolder setChecked(int viewId, boolean checked)
{
Checkable view = (Checkable) getView(viewId);
view.setChecked(checked);
return this;
}
public ViewHolder setOnClickListener(int viewId,
View.OnClickListener listener)
{
View view = getView(viewId);
view.setOnClickListener(listener);
return this;
}
public ViewHolder setOnTouchListener(int viewId,
View.OnTouchListener listener)
{
View view = getView(viewId);
view.setOnTouchListener(listener);
return this;
}
public ViewHolder setOnLongClickListener(int viewId,
View.OnLongClickListener listener)
{
View view = getView(viewId);
view.setOnLongClickListener(listener);
return this;
}
/**
* itemChild ,
*/
private EasyOnItemChildClickListener easyOnItemChildClickListener;
private EasyOnItemChildLongClickListener easyOnItemChildLongClickListener;
private EasyOnItemChildTouchListener easyOnItemChildTouchListener;
private EasyOnItemChildCheckChangeListener easyOnItemChildCheckChangeListener;
public void zSetEasyOnItemChildClickListener(EasyOnItemChildClickListener easyOnItemChildClickListener){
this.easyOnItemChildClickListener=easyOnItemChildClickListener;
}
public void zSetEasyOnItemChildLongClickListener(EasyOnItemChildLongClickListener easyOnItemChildLongClickListener){
this.easyOnItemChildLongClickListener=easyOnItemChildLongClickListener;
}
public void zSetEasyOnItemChildTouchListener(EasyOnItemChildTouchListener easyOnItemChildTouchListener){
this.easyOnItemChildTouchListener=easyOnItemChildTouchListener;
}
public void zSetEasyOnItemChildCheckChangeListener(EasyOnItemChildCheckChangeListener easyOnItemChildCheckChangeListener){
this.easyOnItemChildCheckChangeListener=easyOnItemChildCheckChangeListener;
}
/**
* holderidview
* @param viewId
* @return
*/
public ViewHolder setOnItemChildClickListener(int viewId){
View view = getView(viewId);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null!=easyOnItemChildClickListener&&getLayoutPosition()==getAdapterPosition()&&getAdapterPosition()!=-1){
easyOnItemChildClickListener.onClick(v,getLayoutPosition());
}
}
});
return this;
}
public ViewHolder setOnItemChildLongClickListener(int viewId){
View view = getView(viewId);
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (null!=easyOnItemChildLongClickListener&&getLayoutPosition()==getAdapterPosition()&&getAdapterPosition()!=-1){
return easyOnItemChildLongClickListener.onLongClick(v,getLayoutPosition());
}
return false;
}
});
return this;
}
public ViewHolder setOnItemChildTouchListener(int viewId){
View view = getView(viewId);
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (null!=easyOnItemChildTouchListener&&getLayoutPosition()==getAdapterPosition()&&getAdapterPosition()!=-1){
return easyOnItemChildTouchListener.onTouch(v,event,getLayoutPosition());
}
return false;
}
});
return this;
}
public ViewHolder setOnItemChildCheckChangeListener(int viewId){
View view = getView(viewId);
if (view instanceof CompoundButton){
((CompoundButton) view).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (null!=easyOnItemChildCheckChangeListener&&getLayoutPosition()==getAdapterPosition()&&getAdapterPosition()!=-1){
easyOnItemChildCheckChangeListener.onCheckedChanged(buttonView,getLayoutPosition(),isChecked);
}
}
});
}
return this;
}
}
|
package com.github.games647.fastlogin.bukkit.hooks;
import com.github.games647.fastlogin.core.hooks.AuthPlugin;
import fr.xephi.authme.api.NewAPI;
import fr.xephi.authme.api.v3.AuthMeApi;
import org.bukkit.entity.Player;
public class AuthMeHook implements AuthPlugin<Player> {
private final boolean v3APIAvailable;
public AuthMeHook() {
boolean apiAvailable = true;
try {
Class.forName("fr.xephi.authme.api.v3.AuthMeApi");
} catch (ClassNotFoundException classNotFoundEx) {
apiAvailable = false;
}
this.v3APIAvailable = apiAvailable;
}
@Override
public boolean forceLogin(Player player) {
if (v3APIAvailable) {
//skips registration and login
if (AuthMeApi.getInstance().isAuthenticated(player)) {
return false;
} else {
AuthMeApi.getInstance().forceLogin(player);
}
} else {
//skips registration and login
if (NewAPI.getInstance().isAuthenticated(player)) {
return false;
} else {
NewAPI.getInstance().forceLogin(player);
}
}
return true;
}
@Override
public boolean isRegistered(String playerName) throws Exception {
if (v3APIAvailable) {
return AuthMeApi.getInstance().isRegistered(playerName);
}
return NewAPI.getInstance().isRegistered(playerName);
}
@Override
public boolean forceRegister(Player player, String password) {
//this automatically registers the player too
if (v3APIAvailable) {
AuthMeApi.getInstance().forceRegister(player, password);
} else {
NewAPI.getInstance().forceRegister(player, password);
}
return true;
}
}
|
package ch.ethz.inf.vs.californium.dtls;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import ch.ethz.inf.vs.californium.coap.EndpointAddress;
import ch.ethz.inf.vs.californium.dtls.AlertMessage.AlertDescription;
import ch.ethz.inf.vs.californium.dtls.AlertMessage.AlertLevel;
import ch.ethz.inf.vs.californium.dtls.CertificateRequest.ClientCertificateType;
import ch.ethz.inf.vs.californium.dtls.CertificateRequest.DistinguishedName;
import ch.ethz.inf.vs.californium.dtls.CertificateRequest.HashAlgorithm;
import ch.ethz.inf.vs.californium.dtls.CertificateRequest.SignatureAlgorithm;
import ch.ethz.inf.vs.californium.dtls.CertificateTypeExtension.CertificateType;
import ch.ethz.inf.vs.californium.dtls.CipherSuite.KeyExchangeAlgorithm;
import ch.ethz.inf.vs.californium.dtls.SupportedPointFormatsExtension.ECPointFormat;
import ch.ethz.inf.vs.californium.util.ByteArrayUtils;
import ch.ethz.inf.vs.californium.util.Properties;
/**
* Server handshaker does the protocol handshaking from the point of view of a
* server. It is message-driven by the parent {@link Handshaker} class.
*
* @author Stefan Jucker
*
*/
public class ServerHandshaker extends Handshaker {
// Members ////////////////////////////////////////////////////////
/** Is the client required to authenticate itself? */
private boolean clientAuthenticationRequired = Properties.std.getBool("CLIENT_AUTHENTICATION");
/**
* The client's public key from its certificate (only sent when
* CertificateRequest sent).
*/
private PublicKey clientPublicKey;
private List<CipherSuite> supportedCipherSuites;
/*
* Store all the the message which can possibly be sent by the client. We
* need these to compute the handshake hash.
*/
/** The client's {@link ClientHello}. Mandatory. */
protected ClientHello clientHello;
/** The client's {@link CertificateMessage}. Optional. */
protected CertificateMessage clientCertificate = null;
/** The client's {@link ClientKeyExchange}. mandatory. */
protected ClientKeyExchange clientKeyExchange;
/** The client's {@link CertificateVerify}. Optional. */
protected CertificateVerify certificateVerify = null;
/** The client's {@link Finished} message. Mandatory. */
protected Finished clientFinished;
// Constructors ///////////////////////////////////////////////////
/**
*
* @param endpointAddress
* the peer's address.
* @param session
* the {@link DTLSSession}.
*/
public ServerHandshaker(EndpointAddress endpointAddress, DTLSSession session) {
super(endpointAddress, false, session);
this.supportedCipherSuites = new ArrayList<CipherSuite>();
this.supportedCipherSuites.add(CipherSuite.SSL_NULL_WITH_NULL_NULL);
this.supportedCipherSuites.add(CipherSuite.TLS_PSK_WITH_AES_128_CCM_8);
this.supportedCipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
}
// Methods ////////////////////////////////////////////////////////
@Override
public synchronized DTLSFlight processMessage(Record record) throws HandshakeException {
if (lastFlight != null) {
// we already sent the last flight, but the client did not receive
// it, since we received its finished message again, so we
// retransmit our last flight
LOG.info("Received client's (" + endpointAddress.toString() + ") finished message again, retransmit the last flight.");
return lastFlight;
}
DTLSFlight flight = null;
if (!processMessageNext(record)) {
return flight;
}
switch (record.getType()) {
case ALERT:
AlertMessage alert = (AlertMessage) record.getFragment();
switch (alert.getDescription()) {
case CLOSE_NOTIFY:
flight = closeConnection();
break;
case HANDSHAKE_FAILURE:
// TODO react accordingly
break;
default:
break;
}
break;
case CHANGE_CIPHER_SPEC:
record.getFragment();
setCurrentReadState();
session.incrementReadEpoch();
break;
case HANDSHAKE:
HandshakeMessage fragment = (HandshakeMessage) record.getFragment();
// check for fragmentation
if (fragment instanceof FragmentedHandshakeMessage) {
fragment = handleFragmentation((FragmentedHandshakeMessage) fragment);
if (fragment == null) {
// fragment could not yet be fully reassembled
break;
}
// continue with the reassembled handshake message
record.setFragment(fragment);
}
switch (fragment.getMessageType()) {
case CLIENT_HELLO:
flight = receivedClientHello((ClientHello) fragment);
break;
case CERTIFICATE:
receivedClientCertificate((CertificateMessage) fragment);
break;
case CLIENT_KEY_EXCHANGE:
byte[] premasterSecret;
switch (keyExchange) {
case PSK:
premasterSecret = receivedClientKeyExchange((PSKClientKeyExchange) fragment);
generateKeys(premasterSecret);
break;
case EC_DIFFIE_HELLMAN:
premasterSecret = receivedClientKeyExchange((ECDHClientKeyExchange) fragment);
generateKeys(premasterSecret);
break;
case NULL:
premasterSecret = receivedClientKeyExchange((NULLClientKeyExchange) fragment);
generateKeys(premasterSecret);
break;
default:
AlertMessage alertMessage = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
throw new HandshakeException("Unknown key exchange algorithm: " + keyExchange, alertMessage);
}
handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, clientKeyExchange.toByteArray());
break;
case CERTIFICATE_VERIFY:
receivedCertificateVerify((CertificateVerify) fragment);
break;
case FINISHED:
flight = receivedClientFinished((Finished) fragment);
break;
default:
AlertMessage alertMessage = new AlertMessage(AlertLevel.FATAL, AlertDescription.UNEXPECTED_MESSAGE);
throw new HandshakeException("Server received unexpected handshake message:\n" + fragment.toString(), alertMessage);
}
break;
default:
AlertMessage alertMessage = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
throw new HandshakeException("Server received not supported record:\n" + record.toString(), alertMessage);
}
if (flight == null) {
Record nextMessage = null;
// check queued message, if it is now their turn
for (Record queuedMessage : queuedMessages) {
if (processMessageNext(queuedMessage)) {
// queuedMessages.remove(queuedMessage);
nextMessage = queuedMessage;
break;
}
}
if (nextMessage != null) {
flight = processMessage(nextMessage);
}
}
LOG.info("DTLS Message processed (" + endpointAddress.toString() + "):\n" + record.toString());
return flight;
}
/**
* If the server requires mutual authentication, the client must send its
* certificate.
*
* @param message
* the client's {@link CertificateMessage}.
* @throws HandshakeException
* if the certificate could not be verified.
*/
private void receivedClientCertificate(CertificateMessage message) throws HandshakeException {
if (clientCertificate != null && (clientCertificate.getMessageSeq() == message.getMessageSeq())) {
// discard duplicate message
return;
}
clientCertificate = message;
clientCertificate.verifyCertificate(loadTrustedCertificates());
clientPublicKey = clientCertificate.getPublicKey();
handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, clientCertificate.toByteArray());
}
/**
* Verifies the clien's CertificateVerify message and if verification fails,
* aborts and sends Alert message.
*
* @param message
* the client's CertificateVerify.
* @return <code>null</code> if the signature can be verified, otherwise a
* flight containing an Alert.
* @throws HandshakeException
*/
private void receivedCertificateVerify(CertificateVerify message) throws HandshakeException {
certificateVerify = message;
message.verifySignature(clientPublicKey, handshakeMessages);
}
/**
* Called, when the server received the client's {@link Finished} message.
* Generate a {@link DTLSFlight} containing the
* {@link ChangeCipherSpecMessage} and {@link Finished} message. This flight
* will not be retransmitted, unless we receive the same finish message in
* the future; then, we retransmit this flight.
*
* @param message
* the client's {@link Finished} message.
* @return the server's last {@link DTLSFlight}.
* @throws HandshakeException
*/
private DTLSFlight receivedClientFinished(Finished message) throws HandshakeException {
if (lastFlight != null) {
return null;
}
// check if client sent all expected messages
// (i.e. ClientCertificate/CertificateVerify when server sent CertificateRequest)
if (keyExchange == CipherSuite.KeyExchangeAlgorithm.EC_DIFFIE_HELLMAN &&
clientAuthenticationRequired &&
(clientCertificate == null || certificateVerify == null)) {
AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
throw new HandshakeException("Client did not send required authentication messages.", alert);
}
DTLSFlight flight = new DTLSFlight();
clientFinished = message;
// create handshake hash
if (clientCertificate != null) { // optional
md.update(clientCertificate.toByteArray());
}
md.update(clientKeyExchange.toByteArray()); // mandatory
if (certificateVerify != null) { // optional
md.update(certificateVerify.toByteArray());
}
MessageDigest mdWithClientFinished = null;
try {
/*
* the handshake_messages for the Finished message sent by the
* client will be different from that for the Finished message sent
* by the server, because the one that is sent second will include
* the prior one.
*/
mdWithClientFinished = (MessageDigest) md.clone();
mdWithClientFinished.update(clientFinished.toByteArray());
} catch (CloneNotSupportedException e) {
LOG.severe("Clone not supported.");
e.printStackTrace();
}
// Verify client's data
byte[] handshakeHash = md.digest();
clientFinished.verifyData(getMasterSecret(), true, handshakeHash);
/*
* First, send ChangeCipherSpec
*/
ChangeCipherSpecMessage changeCipherSpecMessage = new ChangeCipherSpecMessage();
flight.addMessage(wrapMessage(changeCipherSpecMessage));
setCurrentWriteState();
session.incrementWriteEpoch();
/*
* Second, send Finished message
*/
handshakeHash = mdWithClientFinished.digest();
Finished finished = new Finished(getMasterSecret(), isClient, handshakeHash);
flight.addMessage(wrapMessage(finished));
state = HandshakeType.FINISHED.getCode();
session.setActive(true);
flight.setRetransmissionNeeded(false);
// store, if we need to retransmit this flight, see
// http://tools.ietf.org/html/rfc6347#section-4.2.4
lastFlight = flight;
return flight;
}
private DTLSFlight receivedClientHello(ClientHello message) throws HandshakeException {
DTLSFlight flight = new DTLSFlight();
if (message.getCookie().length() > 0 && isValidCookie(message)) {
// client has set a cookie, so it is a response to
// HelloVerifyRequest
// store the message and update the handshake hash
clientHello = message;
md.update(clientHello.toByteArray());
handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, clientHello.toByteArray());
/*
* First, send ServerHello (mandatory)
*/
ProtocolVersion serverVersion = negotiateProtocolVersion(clientHello.getClientVersion());
// store client and server random
clientRandom = message.getRandom();
serverRandom = new Random(new SecureRandom());
SessionId sessionId = new SessionId();
session.setSessionIdentifier(sessionId);
CipherSuite cipherSuite = negotiateCipherSuite(clientHello.getCipherSuites());
setCipherSuite(cipherSuite);
// currently only NULL compression supported, no negotiation needed
CompressionMethod compressionMethod = CompressionMethod.NULL;
setCompressionMethod(compressionMethod);
HelloExtensions extensions = null;
CertificateTypeExtension certificateTypeExtension = clientHello.getCertificateTypeExtension();
if (certificateTypeExtension != null) {
// choose certificate type from client's list
CertificateType certType = negotiateCertificateType(certificateTypeExtension);
extensions = new HelloExtensions();
CertificateTypeExtension ext1 = new CertificateTypeExtension(false);
ext1.addCertificateType(certType);
extensions.addExtension(ext1);
if (certType == CertificateType.RAW_PUBLIC_KEY) {
session.setSendRawPublicKey(true);
session.setReceiveRawPublicKey(true);
}
}
if (keyExchange == CipherSuite.KeyExchangeAlgorithm.EC_DIFFIE_HELLMAN) {
// if we chose a ECC cipher suite, the server should send the supported point formats extension in its ServerHello
List<ECPointFormat> formats = Arrays.asList(ECPointFormat.UNCOMPRESSED);
if (extensions == null) {
extensions = new HelloExtensions();
}
HelloExtension ext2 = new SupportedPointFormatsExtension(formats);
extensions.addExtension(ext2);
}
ServerHello serverHello = new ServerHello(serverVersion, serverRandom, sessionId, cipherSuite, compressionMethod, extensions);
flight.addMessage(wrapMessage(serverHello));
// update the handshake hash
md.update(serverHello.toByteArray());
handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, serverHello.toByteArray());
/*
* Second, send Certificate (if required by key exchange algorithm)
*/
CertificateMessage certificate = null;
switch (keyExchange) {
case EC_DIFFIE_HELLMAN:
certificate = new CertificateMessage(certificates, session.sendRawPublicKey());
break;
default:
// NULL and PSK do not require the Certificate message
// See http://tools.ietf.org/html/rfc4279#section-2
break;
}
if (certificate != null) {
flight.addMessage(wrapMessage(certificate));
md.update(certificate.toByteArray());
handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, certificate.toByteArray());
}
/*
* Third, send ServerKeyExchange (if required by key exchange
* algorithm)
*/
ServerKeyExchange serverKeyExchange = null;
switch (keyExchange) {
case EC_DIFFIE_HELLMAN:
int namedCurveId = negotiateNamedCurve(clientHello.getSupportedEllipticCurvesExtension());
ecdhe = new ECDHECryptography(namedCurveId);
serverKeyExchange = new ECDHServerKeyExchange(ecdhe, privateKey, clientRandom, serverRandom, namedCurveId);
break;
case PSK:
// serverKeyExchange = new PSKServerKeyExchange("TEST");
break;
default:
// NULL does not require the server's key exchange message
break;
}
if (serverKeyExchange != null) {
flight.addMessage(wrapMessage(serverKeyExchange));
md.update(serverKeyExchange.toByteArray());
handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, serverKeyExchange.toByteArray());
}
/*
* Fourth, send CertificateRequest for client (if required)
*/
if (clientAuthenticationRequired && keyExchange != KeyExchangeAlgorithm.PSK) {
CertificateRequest certificateRequest = new CertificateRequest();
// TODO make this variable, reasonable values
certificateRequest.addCertificateType(ClientCertificateType.ECDSA_FIXED_ECDH);
certificateRequest.addSignatureAlgorithm(new SignatureAndHashAlgorithm(HashAlgorithm.SHA1, SignatureAlgorithm.ECDSA));
// TODO DER-encoding of distinguished name
certificateRequest.addCertificateAuthority(new DistinguishedName(new byte[6]));
flight.addMessage(wrapMessage(certificateRequest));
md.update(certificateRequest.toByteArray());
handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, certificateRequest.toByteArray());
}
/*
* Last, send ServerHelloDone (mandatory)
*/
ServerHelloDone serverHelloDone = new ServerHelloDone();
flight.addMessage(wrapMessage(serverHelloDone));
md.update(serverHelloDone.toByteArray());
handshakeMessages = ByteArrayUtils.concatenate(handshakeMessages, serverHelloDone.toByteArray());
} else {
// either first time, or cookies did not match
HelloVerifyRequest helloVerifyRequest = new HelloVerifyRequest(new ProtocolVersion(), generateCookie(message));
flight.addMessage(wrapMessage(helloVerifyRequest));
}
return flight;
}
/**
* Generates the premaster secret by taking the client's public key and
* running the ECDHE key agreement.
*
* @param message
* the client's key exchange message.
* @return the premaster secret
*/
private byte[] receivedClientKeyExchange(ECDHClientKeyExchange message) {
clientKeyExchange = message;
byte[] premasterSecret = ecdhe.getSecret(message.getEncodedPoint()).getEncoded();
return premasterSecret;
}
/**
* Retrieves the preshared key from the identity hint and then generates the
* premaster secret.
*
* @param message
* the client's key exchange message.
* @return the premaster secret
* @throws HandshakeException
* if no specified preshared key available.
*/
private byte[] receivedClientKeyExchange(PSKClientKeyExchange message) throws HandshakeException {
clientKeyExchange = message;
// use the client's PSK identity to get right preshared key
String identity = message.getIdentity();
byte[] psk = sharedKeys.get(identity);
LOG.fine("Received client's (" + endpointAddress.toString() + ") key exchange message for PSK:\nIdentity: " + identity + "\nPreshared Key: " + ByteArrayUtils.toHexString(psk));
if (psk == null) {
AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
throw new HandshakeException("No preshared secret found for identity: " + identity, alert);
}
return generatePremasterSecretFromPSK(psk);
}
/**
* Returns an empty premaster secret.
*
* @param message
* the client's key exchange message.
* @return the premaster secret
*/
private byte[] receivedClientKeyExchange(NULLClientKeyExchange message) {
clientKeyExchange = message;
// by current assumption we take an empty premaster secret
// to compute the master secret and the resulting keys
return new byte[] {};
}
private Cookie generateCookie(ClientHello clientHello) {
MessageDigest md;
byte[] cookie = null;
try {
md = MessageDigest.getInstance("SHA-256");
// Cookie = HMAC(Secret, Client-IP, Client-Parameters)
byte[] secret = "generate cookie".getBytes();
// Client-IP
md.update(endpointAddress.toString().getBytes());
// Client-Parameters
md.update((byte) clientHello.getClientVersion().getMajor());
md.update((byte) clientHello.getClientVersion().getMinor());
md.update(clientHello.getRandom().getRandomBytes());
md.update(clientHello.getSessionId().getSessionId());
md.update(CipherSuite.listToByteArray(clientHello.getCipherSuites()));
md.update(CompressionMethod.listToByteArray(clientHello.getCompressionMethods()));
byte[] data = md.digest();
cookie = Handshaker.doHMAC(md, secret, data);
} catch (NoSuchAlgorithmException e) {
LOG.info("Could not instantiate message digest algorithm.");
e.printStackTrace();
}
if (cookie == null) {
return new Cookie(new Random(new SecureRandom()).getRandomBytes());
} else {
return new Cookie(cookie);
}
}
/**
* Checks whether the Cookie in the client's hello message matches the
* expected cookie generated from the client's parameters.
*
* @param clientHello
* the client's hello message containing the cookie.
* @return <code>true</code> if the cookie matches, <code>false</code>
* otherwise.
*/
private boolean isValidCookie(ClientHello clientHello) {
Cookie expected = generateCookie(clientHello);
Cookie actual = clientHello.getCookie();
boolean valid = Arrays.equals(expected.getCookie(), actual.getCookie());
if (!valid) {
LOG.info("Client's (" + endpointAddress.toString() + ") cookie did not match expected cookie:\n" + "Expected: " + ByteArrayUtils.toHexString(expected.getCookie()) + "\n" + "Actual: " + ByteArrayUtils.toHexString(actual.getCookie()));
}
return valid;
}
@Override
public DTLSFlight getStartHandshakeMessage() {
HelloRequest helloRequest = new HelloRequest();
DTLSFlight flight = new DTLSFlight();
flight.addMessage(wrapMessage(helloRequest));
return flight;
}
/**
* Negotiates the version to be used. It will return the lower of that
* suggested by the client in the client hello and the highest supported by
* the server.
*
* @param clientVersion
* the suggested version by the client.
* @return the version to be used in the handshake.
* @throws HandshakeException
* if the client's version is smaller than DTLS 1.2
*/
private ProtocolVersion negotiateProtocolVersion(ProtocolVersion clientVersion) throws HandshakeException {
ProtocolVersion version = new ProtocolVersion();
if (clientVersion.compareTo(version) >= 0) {
return new ProtocolVersion();
} else {
AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.PROTOCOL_VERSION);
throw new HandshakeException("The server only supports DTLS v1.2", alert);
}
}
/**
* Selects one of the client's proposed cipher suites.
*
* @param cipherSuites
* the client's cipher suites.
* @return The single cipher suite selected by the server from the list
* which will be used after handshake completion.
* @throws HandshakeException
* if no suitable cipher suite can be found.
*/
private CipherSuite negotiateCipherSuite(List<CipherSuite> cipherSuites) throws HandshakeException {
// the client's list is sorted by preference
for (CipherSuite cipherSuite : cipherSuites) {
if (supportedCipherSuites.contains(cipherSuite) && cipherSuite != CipherSuite.SSL_NULL_WITH_NULL_NULL) {
return cipherSuite;
}
}
// if none of the client's proposed cipher suites matches throw exception
AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
throw new HandshakeException("No supported cipher suite proposed by the client", alert);
}
/**
* Chooses a elliptic curve from the client's supported list.
*
* @param extension
* the supported elliptic curves extension.
* @return the chosen elliptic curve identifier.
* @throws HandshakeException
* if no extension present in the ClientHello.
*/
private int negotiateNamedCurve(SupportedEllipticCurvesExtension extension) throws HandshakeException {
if (extension != null) {
for (Integer curveID : extension.getEllipticCurveList()) {
// choose first proposal which is supported
if (ECDHServerKeyExchange.NAMED_CURVE_PARAMETERS.get(curveID) != null) {
return curveID;
}
}
} else {
// extension was not present in ClientHello, we can't continue the handshake
AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
throw new HandshakeException("The client did not provide the supported elliptic curves extension although ECC cipher suite chosen.", alert);
}
AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE);
throw new HandshakeException("No proposed elliptic curve supported.", alert);
}
/**
* Chooses the certificate type which will be used in the rest of the
* handshake.
*
* @param extension
* the certificate type extension.
* @return the certificate type in which the client will send its
* certificate.
*/
private CertificateType negotiateCertificateType(CertificateTypeExtension extension) {
CertificateType certType = CertificateType.X_509;
for (CertificateType type : extension.getCertificateTypes()) {
return type;
}
return certType;
}
}
|
package arez.processor;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
/**
* The class that represents the parsed state of ArezComponent annotated class.
*/
@SuppressWarnings( "Duplicates" )
final class ComponentDescriptor
{
private static final Pattern OBSERVABLE_REF_PATTERN = Pattern.compile( "^get([A-Z].*)Observable$" );
private static final Pattern COMPUTED_VALUE_REF_PATTERN = Pattern.compile( "^get([A-Z].*)ComputedValue$" );
private static final Pattern OBSERVER_REF_PATTERN = Pattern.compile( "^get([A-Z].*)Observer$" );
private static final Pattern SETTER_PATTERN = Pattern.compile( "^set([A-Z].*)$" );
private static final Pattern GETTER_PATTERN = Pattern.compile( "^get([A-Z].*)$" );
private static final Pattern ISSER_PATTERN = Pattern.compile( "^is([A-Z].*)$" );
private static final List<String> OBJECT_METHODS =
Arrays.asList( "hashCode", "equals", "clone", "toString", "finalize", "getClass", "wait", "notifyAll", "notify" );
private static final List<String> AREZ_SPECIAL_METHODS =
Arrays.asList( "observe", "dispose", "isDisposed", "getArezId" );
@Nullable
private List<TypeElement> _repositoryExtensions;
/**
* Flag controlling whether dagger module is created for repository.
*/
private String _repositoryDaggerConfig = "AUTODETECT";
/**
* Flag controlling whether Inject annotation is added to repository constructor.
*/
private String _repositoryInjectConfig = "AUTODETECT";
@Nonnull
private final SourceVersion _sourceVersion;
@Nonnull
private final Elements _elements;
@Nonnull
private final String _type;
private final boolean _nameIncludesId;
private final boolean _allowEmpty;
private final boolean _disposeOnDeactivate;
private final boolean _injectClassesPresent;
private final boolean _inject;
private final boolean _dagger;
/**
* Annotation that indicates whether equals/hashCode should be implemented. See arez.annotations.ArezComponent.requireEquals()
*/
private final boolean _requireEquals;
/**
* Scope annotation that is declared on component and should be transferred to injection providers.
*/
private final AnnotationMirror _scopeAnnotation;
private final boolean _deferSchedule;
private final boolean _generateToString;
@Nonnull
private final PackageElement _packageElement;
@Nonnull
private final TypeElement _element;
@Nullable
private ExecutableElement _postConstruct;
@Nullable
private ExecutableElement _componentId;
@Nullable
private ExecutableType _componentIdMethodType;
@Nullable
private ExecutableElement _componentRef;
@Nullable
private ExecutableElement _contextRef;
@Nullable
private ExecutableElement _componentTypeNameRef;
@Nullable
private ExecutableElement _componentNameRef;
@Nullable
private ExecutableElement _preDispose;
@Nullable
private ExecutableElement _postDispose;
private final Map<String, CandidateMethod> _observerRefs = new LinkedHashMap<>();
private final Map<String, ObservableDescriptor> _observables = new LinkedHashMap<>();
private final Collection<ObservableDescriptor> _roObservables =
Collections.unmodifiableCollection( _observables.values() );
private final Map<String, ActionDescriptor> _actions = new LinkedHashMap<>();
private final Collection<ActionDescriptor> _roActions =
Collections.unmodifiableCollection( _actions.values() );
private final Map<String, ComputedDescriptor> _computeds = new LinkedHashMap<>();
private final Collection<ComputedDescriptor> _roComputeds =
Collections.unmodifiableCollection( _computeds.values() );
private final Map<String, MemoizeDescriptor> _memoizes = new LinkedHashMap<>();
private final Collection<MemoizeDescriptor> _roMemoizes =
Collections.unmodifiableCollection( _memoizes.values() );
private final Map<String, AutorunDescriptor> _autoruns = new LinkedHashMap<>();
private final Collection<AutorunDescriptor> _roAutoruns =
Collections.unmodifiableCollection( _autoruns.values() );
private final Map<String, TrackedDescriptor> _trackeds = new LinkedHashMap<>();
private final Collection<TrackedDescriptor> _roTrackeds =
Collections.unmodifiableCollection( _trackeds.values() );
private final Map<ExecutableElement, DependencyDescriptor> _dependencies = new LinkedHashMap<>();
private final Collection<DependencyDescriptor> _roDependencies =
Collections.unmodifiableCollection( _dependencies.values() );
ComponentDescriptor( @Nonnull final SourceVersion sourceVersion,
@Nonnull final Elements elements,
@Nonnull final String type,
final boolean nameIncludesId,
final boolean allowEmpty,
final boolean disposeOnDeactivate,
final boolean injectClassesPresent,
final boolean inject,
final boolean dagger,
final boolean requireEquals,
@Nullable final AnnotationMirror scopeAnnotation,
final boolean deferSchedule,
final boolean generateToString,
@Nonnull final PackageElement packageElement,
@Nonnull final TypeElement element )
{
_sourceVersion = Objects.requireNonNull( sourceVersion );
_elements = Objects.requireNonNull( elements );
_type = Objects.requireNonNull( type );
_nameIncludesId = nameIncludesId;
_allowEmpty = allowEmpty;
_disposeOnDeactivate = disposeOnDeactivate;
_injectClassesPresent = injectClassesPresent;
_inject = inject;
_dagger = dagger;
_requireEquals = requireEquals;
_scopeAnnotation = scopeAnnotation;
_deferSchedule = deferSchedule;
_generateToString = generateToString;
_packageElement = Objects.requireNonNull( packageElement );
_element = Objects.requireNonNull( element );
}
private boolean hasDeprecatedElements()
{
return isDeprecated( _postConstruct ) ||
_roObservables.stream().anyMatch( e -> ( e.hasSetter() && isDeprecated( e.getSetter() ) ) ||
( e.hasGetter() && isDeprecated( e.getGetter() ) ) ) ||
_roComputeds.stream().anyMatch( e -> ( e.hasComputed() && isDeprecated( e.getComputed() ) ) ||
isDeprecated( e.getOnActivate() ) ||
isDeprecated( e.getOnDeactivate() ) ||
isDeprecated( e.getOnStale() ) ||
isDeprecated( e.getOnDispose() ) ) ||
_roActions.stream().anyMatch( e -> isDeprecated( e.getAction() ) ) ||
_roAutoruns.stream().anyMatch( e -> isDeprecated( e.getAutorun() ) ) ||
_roMemoizes.stream().anyMatch( e -> isDeprecated( e.getMemoize() ) ) ||
_roTrackeds.stream().anyMatch( e -> ( e.hasTrackedMethod() && isDeprecated( e.getTrackedMethod() ) ) ||
( e.hasOnDepsChangedMethod() &&
isDeprecated( e.getOnDepsChangedMethod() ) ) );
}
private boolean isDeprecated( @Nullable final ExecutableElement element )
{
return null != element && null != element.getAnnotation( Deprecated.class );
}
@Nonnull
private DeclaredType asDeclaredType()
{
return (DeclaredType) _element.asType();
}
@Nonnull
TypeElement getElement()
{
return _element;
}
@Nonnull
String getType()
{
return _type;
}
@Nonnull
private ObservableDescriptor findOrCreateObservable( @Nonnull final String name )
{
return _observables.computeIfAbsent( name, n -> new ObservableDescriptor( this, n ) );
}
@Nonnull
private TrackedDescriptor findOrCreateTracked( @Nonnull final String name )
{
return _trackeds.computeIfAbsent( name, n -> new TrackedDescriptor( this, n ) );
}
private void addObservable( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_ANNOTATION_CLASSNAME, method );
final String declaredName = getAnnotationParameter( annotation, "name" );
final boolean expectSetter = getAnnotationParameter( annotation, "expectSetter" );
final Boolean requireInitializer = isInitializerRequired( method );
final TypeMirror returnType = method.getReturnType();
final String methodName = method.getSimpleName().toString();
String name;
final boolean setter;
if ( TypeKind.VOID == returnType.getKind() )
{
setter = true;
//Should be a setter
if ( 1 != method.getParameters().size() )
{
throw new ArezProcessorException( "@Observable target should be a setter or getter", method );
}
name = ProcessorUtil.deriveName( method, SETTER_PATTERN, declaredName );
if ( null == name )
{
name = methodName;
}
}
else
{
setter = false;
//Must be a getter
if ( 0 != method.getParameters().size() )
{
throw new ArezProcessorException( "@Observable target should be a setter or getter", method );
}
name = getPropertyAccessorName( method, declaredName );
}
// Override name if supplied by user
if ( !ProcessorUtil.isSentinelName( declaredName ) )
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Observable target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Observable target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
checkNameUnique( name, method, Constants.OBSERVABLE_ANNOTATION_CLASSNAME );
if ( setter && !expectSetter )
{
throw new ArezProcessorException( "Method annotated with @Observable is a setter but defines " +
"expectSetter = false for observable named " + name, method );
}
final ObservableDescriptor observable = findOrCreateObservable( name );
if ( !expectSetter )
{
observable.setExpectSetter( false );
}
if ( !observable.expectSetter() )
{
if ( observable.hasSetter() )
{
throw new ArezProcessorException( "Method annotated with @Observable defines expectSetter = false but a " +
"setter exists named " + observable.getSetter().getSimpleName() +
"for observable named " + name, method );
}
}
if ( setter )
{
if ( observable.hasSetter() )
{
throw new ArezProcessorException( "Method annotated with @Observable defines duplicate setter for " +
"observable named " + name, method );
}
if ( !observable.expectSetter() )
{
throw new ArezProcessorException( "Method annotated with @Observable defines expectSetter = false but a " +
"setter exists for observable named " + name, method );
}
observable.setSetter( method, methodType );
}
else
{
if ( observable.hasGetter() )
{
throw new ArezProcessorException( "Method annotated with @Observable defines duplicate getter for " +
"observable named " + name, method );
}
observable.setGetter( method, methodType );
}
if ( null != requireInitializer )
{
if ( !method.getModifiers().contains( Modifier.ABSTRACT ) )
{
throw new ArezProcessorException( "@Observable target set initializer parameter to ENABLED but " +
"method is not abstract.", method );
}
final Boolean existing = observable.getInitializer();
if ( null == existing )
{
observable.setInitializer( requireInitializer );
}
else if ( existing != requireInitializer )
{
throw new ArezProcessorException( "@Observable target set initializer parameter to value that differs from " +
"the paired observable method.", method );
}
}
}
private void addObservableRef( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = methodType.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!toRawType( returnType ).toString().equals( "arez.Observable" ) )
{
throw new ArezProcessorException( "Method annotated with @ObservableRef must return an instance of " +
"arez.Observable", method );
}
final String declaredName = getAnnotationParameter( annotation, "name" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
name = ProcessorUtil.deriveName( method, OBSERVABLE_REF_PATTERN, declaredName );
if ( null == name )
{
throw new ArezProcessorException( "Method annotated with @ObservableRef should specify name or be " +
"named according to the convention get[Name]Observable", method );
}
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@ObservableRef target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@ObservableRef target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
final ObservableDescriptor observable = findOrCreateObservable( name );
if ( observable.hasRefMethod() )
{
throw new ArezProcessorException( "Method annotated with @ObservableRef defines duplicate ref accessor for " +
"observable named " + name, method );
}
observable.setRefMethod( method, methodType );
}
@Nonnull
private TypeName toRawType( @Nonnull final TypeMirror type )
{
final TypeName typeName = TypeName.get( type );
if ( typeName instanceof ParameterizedTypeName )
{
return ( (ParameterizedTypeName) typeName ).rawType;
}
else
{
return typeName;
}
}
private void addAction( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeWrappable( getElement(), Constants.ACTION_ANNOTATION_CLASSNAME, method );
final String name = deriveActionName( method, annotation );
checkNameUnique( name, method, Constants.ACTION_ANNOTATION_CLASSNAME );
final boolean mutation = getAnnotationParameter( annotation, "mutation" );
final boolean reportParameters = getAnnotationParameter( annotation, "reportParameters" );
final ActionDescriptor action = new ActionDescriptor( this, name, mutation, reportParameters, method, methodType );
_actions.put( action.getName(), action );
}
@Nonnull
private String deriveActionName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation )
throws ArezProcessorException
{
final String name = getAnnotationParameter( annotation, "name" );
if ( ProcessorUtil.isSentinelName( name ) )
{
return method.getSimpleName().toString();
}
else
{
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Action target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Action target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
return name;
}
}
private void addAutorun( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeWrappable( getElement(), Constants.AUTORUN_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.AUTORUN_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.AUTORUN_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotReturnAnyValue( Constants.AUTORUN_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotBePublic( Constants.AUTORUN_ANNOTATION_CLASSNAME, method );
final String name = deriveAutorunName( method, annotation );
checkNameUnique( name, method, Constants.AUTORUN_ANNOTATION_CLASSNAME );
final boolean mutation = getAnnotationParameter( annotation, "mutation" );
final boolean highPriority = getAnnotationParameter( annotation, "highPriority" );
final AutorunDescriptor autorun = new AutorunDescriptor( this, name, mutation, highPriority, method, methodType );
_autoruns.put( autorun.getName(), autorun );
}
@Nonnull
private String deriveAutorunName( @Nonnull final ExecutableElement method,
@Nonnull final AnnotationMirror annotation )
throws ArezProcessorException
{
final String name = getAnnotationParameter( annotation, "name" );
if ( ProcessorUtil.isSentinelName( name ) )
{
return method.getSimpleName().toString();
}
else
{
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Autorun target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Autorun target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
return name;
}
}
private void addOnDepsChanged( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String name =
deriveHookName( method,
TrackedDescriptor.ON_DEPS_CHANGED_PATTERN,
"DepsChanged",
getAnnotationParameter( annotation, "name" ) );
findOrCreateTracked( name ).setOnDepsChangedMethod( method );
}
private void addTracked( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
final String name = deriveTrackedName( method, annotation );
checkNameUnique( name, method, Constants.TRACK_ANNOTATION_CLASSNAME );
final boolean mutation = getAnnotationParameter( annotation, "mutation" );
final boolean highPriority = getAnnotationParameter( annotation, "highPriority" );
final boolean reportParameters = getAnnotationParameter( annotation, "reportParameters" );
final TrackedDescriptor tracked = findOrCreateTracked( name );
tracked.setTrackedMethod( mutation, highPriority, reportParameters, method, methodType );
}
@Nonnull
private String deriveTrackedName( @Nonnull final ExecutableElement method,
@Nonnull final AnnotationMirror annotation )
throws ArezProcessorException
{
final String name = getAnnotationParameter( annotation, "name" );
if ( ProcessorUtil.isSentinelName( name ) )
{
return method.getSimpleName().toString();
}
else
{
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Track target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Track target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
return name;
}
}
private void addObserverRef( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = method.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!returnType.toString().equals( "arez.Observer" ) )
{
throw new ArezProcessorException( "Method annotated with @ObserverRef must return an instance of " +
"arez.Observer", method );
}
final String declaredName = getAnnotationParameter( annotation, "name" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
name = ProcessorUtil.deriveName( method, OBSERVER_REF_PATTERN, declaredName );
if ( null == name )
{
throw new ArezProcessorException( "Method annotated with @ObserverRef should specify name or be " +
"named according to the convention get[Name]Observer", method );
}
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@ObserverRef target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@ObserverRef target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
if ( _observerRefs.containsKey( name ) )
{
throw new ArezProcessorException( "Method annotated with @ObserverRef defines duplicate ref accessor for " +
"observer named " + name, method );
}
_observerRefs.put( name, new CandidateMethod( method, methodType ) );
}
@Nonnull
private ComputedDescriptor findOrCreateComputed( @Nonnull final String name )
{
return _computeds.computeIfAbsent( name, n -> new ComputedDescriptor( this, n ) );
}
private void addComputed( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType computedType )
throws ArezProcessorException
{
final String name = deriveComputedName( method, annotation );
checkNameUnique( name, method, Constants.COMPUTED_ANNOTATION_CLASSNAME );
final boolean keepAlive = getAnnotationParameter( annotation, "keepAlive" );
final boolean highPriority = getAnnotationParameter( annotation, "highPriority" );
findOrCreateComputed( name ).setComputed( method, computedType, keepAlive, highPriority );
}
private void addComputedValueRef( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = methodType.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!toRawType( returnType ).toString().equals( "arez.ComputedValue" ) )
{
throw new ArezProcessorException( "Method annotated with @ComputedValueRef must return an instance of " +
"arez.ComputedValue", method );
}
final String declaredName = getAnnotationParameter( annotation, "name" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
name = ProcessorUtil.deriveName( method, COMPUTED_VALUE_REF_PATTERN, declaredName );
if ( null == name )
{
throw new ArezProcessorException( "Method annotated with @ComputedValueRef should specify name or be " +
"named according to the convention get[Name]ComputedValue", method );
}
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@ComputedValueRef target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@ComputedValueRef target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
findOrCreateComputed( name ).setRefMethod( method, methodType );
}
@Nonnull
private String deriveComputedName( @Nonnull final ExecutableElement method,
@Nonnull final AnnotationMirror annotation )
throws ArezProcessorException
{
final String name = getAnnotationParameter( annotation, "name" );
if ( ProcessorUtil.isSentinelName( name ) )
{
return getPropertyAccessorName( method, name );
}
else
{
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Computed target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Computed target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
return name;
}
}
private void addMemoize( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
final String name = deriveMemoizeName( method, annotation );
checkNameUnique( name, method, Constants.MEMOIZE_ANNOTATION_CLASSNAME );
_memoizes.computeIfAbsent( name, n -> new MemoizeDescriptor( this, n ) ).setMemoize( method, methodType );
}
@Nonnull
private String deriveMemoizeName( @Nonnull final ExecutableElement method,
@Nonnull final AnnotationMirror annotation )
throws ArezProcessorException
{
final String name = getAnnotationParameter( annotation, "name" );
if ( ProcessorUtil.isSentinelName( name ) )
{
return method.getSimpleName().toString();
}
else
{
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Memoize target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Memoize target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
return name;
}
}
private void addOnActivate( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String name = deriveHookName( method,
ComputedDescriptor.ON_ACTIVATE_PATTERN,
"Activate",
getAnnotationParameter( annotation, "name" ) );
findOrCreateComputed( name ).setOnActivate( method );
}
private void addOnDeactivate( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String name =
deriveHookName( method,
ComputedDescriptor.ON_DEACTIVATE_PATTERN,
"Deactivate",
getAnnotationParameter( annotation, "name" ) );
findOrCreateComputed( name ).setOnDeactivate( method );
}
private void addOnStale( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String name =
deriveHookName( method,
ComputedDescriptor.ON_STALE_PATTERN,
"Stale",
getAnnotationParameter( annotation, "name" ) );
findOrCreateComputed( name ).setOnStale( method );
}
private void addOnDispose( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String name = deriveHookName( method,
ComputedDescriptor.ON_DISPOSE_PATTERN,
"Dispose",
getAnnotationParameter( annotation, "name" ) );
findOrCreateComputed( name ).setOnDispose( method );
}
@Nonnull
private String deriveHookName( @Nonnull final ExecutableElement method,
@Nonnull final Pattern pattern,
@Nonnull final String type,
@Nonnull final String name )
throws ArezProcessorException
{
final String value = ProcessorUtil.deriveName( method, pattern, name );
if ( null == value )
{
throw new ArezProcessorException( "Unable to derive name for @On" + type + " as does not match " +
"on[Name]" + type + " pattern. Please specify name.", method );
}
else if ( !SourceVersion.isIdentifier( value ) )
{
throw new ArezProcessorException( "@On" + type + " target specified an invalid name '" + value + "'. The " +
"name must be a valid java identifier.", _element );
}
else if ( SourceVersion.isKeyword( value ) )
{
throw new ArezProcessorException( "@On" + type + " target specified an invalid name '" + value + "'. The " +
"name must not be a java keyword.", _element );
}
else
{
return value;
}
}
private void setContextRef( @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = method.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!returnType.toString().equals( "arez.ArezContext" ) )
{
throw new ArezProcessorException( "Method annotated with @ContextRef must return an instance of " +
"arez.ArezContext", method );
}
if ( null != _contextRef )
{
throw new ArezProcessorException( "@ContextRef target duplicates existing method named " +
_contextRef.getSimpleName(), method );
}
else
{
_contextRef = Objects.requireNonNull( method );
}
}
private void setComponentRef( @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = method.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!returnType.toString().equals( "arez.Component" ) )
{
throw new ArezProcessorException( "Method annotated with @ComponentRef must return an instance of " +
"arez.Component", method );
}
if ( null != _componentRef )
{
throw new ArezProcessorException( "@ComponentRef target duplicates existing method named " +
_componentRef.getSimpleName(), method );
}
else
{
_componentRef = Objects.requireNonNull( method );
}
}
private void setComponentId( @Nonnull final ExecutableElement componentId,
@Nonnull final ExecutableType componentIdMethodType )
throws ArezProcessorException
{
MethodChecks.mustNotBeAbstract( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustBeSubclassCallable( getElement(), Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustBeFinal( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustReturnAValue( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
if ( null != _componentId )
{
throw new ArezProcessorException( "@ComponentId target duplicates existing method named " +
_componentId.getSimpleName(), componentId );
}
else
{
_componentId = Objects.requireNonNull( componentId );
_componentIdMethodType = componentIdMethodType;
}
}
private void setComponentTypeNameRef( @Nonnull final ExecutableElement componentTypeName )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(),
Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME,
componentTypeName );
MethodChecks.mustBeAbstract( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName );
MethodChecks.mustReturnAValue( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName );
final TypeMirror returnType = componentTypeName.getReturnType();
if ( !( TypeKind.DECLARED == returnType.getKind() &&
returnType.toString().equals( String.class.getName() ) ) )
{
throw new ArezProcessorException( "@ComponentTypeNameRef target must return a String", componentTypeName );
}
if ( null != _componentTypeNameRef )
{
throw new ArezProcessorException( "@ComponentTypeNameRef target duplicates existing method named " +
_componentTypeNameRef.getSimpleName(), componentTypeName );
}
else
{
_componentTypeNameRef = Objects.requireNonNull( componentTypeName );
}
}
private void setComponentNameRef( @Nonnull final ExecutableElement componentName )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
MethodChecks.mustBeAbstract( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
MethodChecks.mustReturnAValue( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
if ( null != _componentNameRef )
{
throw new ArezProcessorException( "@ComponentNameRef target duplicates existing method named " +
_componentNameRef.getSimpleName(), componentName );
}
else
{
_componentNameRef = Objects.requireNonNull( componentName );
}
}
@Nullable
ExecutableElement getPostConstruct()
{
return _postConstruct;
}
void setPostConstruct( @Nonnull final ExecutableElement postConstruct )
throws ArezProcessorException
{
MethodChecks.mustBeLifecycleHook( getElement(), Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME, postConstruct );
if ( null != _postConstruct )
{
throw new ArezProcessorException( "@PostConstruct target duplicates existing method named " +
_postConstruct.getSimpleName(), postConstruct );
}
else
{
_postConstruct = postConstruct;
}
}
private void setPreDispose( @Nonnull final ExecutableElement preDispose )
throws ArezProcessorException
{
MethodChecks.mustBeLifecycleHook( getElement(), Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME, preDispose );
if ( null != _preDispose )
{
throw new ArezProcessorException( "@PreDispose target duplicates existing method named " +
_preDispose.getSimpleName(), preDispose );
}
else
{
_preDispose = preDispose;
}
}
private void setPostDispose( @Nonnull final ExecutableElement postDispose )
throws ArezProcessorException
{
MethodChecks.mustBeLifecycleHook( getElement(), Constants.POST_DISPOSE_ANNOTATION_CLASSNAME, postDispose );
if ( null != _postDispose )
{
throw new ArezProcessorException( "@PostDispose target duplicates existing method named " +
_postDispose.getSimpleName(), postDispose );
}
else
{
_postDispose = postDispose;
}
}
@Nonnull
Collection<ObservableDescriptor> getObservables()
{
return _roObservables;
}
void validate()
throws ArezProcessorException
{
_roObservables.forEach( ObservableDescriptor::validate );
_roComputeds.forEach( ComputedDescriptor::validate );
_roDependencies.forEach( DependencyDescriptor::validate );
if ( !_allowEmpty &&
_roObservables.isEmpty() &&
_roActions.isEmpty() &&
_roComputeds.isEmpty() &&
_roMemoizes.isEmpty() &&
_roTrackeds.isEmpty() &&
_roDependencies.isEmpty() &&
_roAutoruns.isEmpty() )
{
throw new ArezProcessorException( "@ArezComponent target has no methods annotated with @Action, " +
"@Computed, @Memoize, @Observable, @Track or @Autorun", _element );
}
}
private void checkNameUnique( @Nonnull final String name,
@Nonnull final ExecutableElement sourceMethod,
@Nonnull final String sourceAnnotationName )
throws ArezProcessorException
{
final ActionDescriptor action = _actions.get( name );
if ( null != action )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.ACTION_ANNOTATION_CLASSNAME,
action.getAction() );
}
final ComputedDescriptor computed = _computeds.get( name );
if ( null != computed && computed.hasComputed() )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.COMPUTED_ANNOTATION_CLASSNAME,
computed.getComputed() );
}
final MemoizeDescriptor memoize = _memoizes.get( name );
if ( null != memoize )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.MEMOIZE_ANNOTATION_CLASSNAME,
memoize.getMemoize() );
}
final AutorunDescriptor autorun = _autoruns.get( name );
if ( null != autorun )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.AUTORUN_ANNOTATION_CLASSNAME,
autorun.getAutorun() );
}
// Track have pairs so let the caller determine whether a duplicate occurs in that scenario
if ( !sourceAnnotationName.equals( Constants.TRACK_ANNOTATION_CLASSNAME ) )
{
final TrackedDescriptor tracked = _trackeds.get( name );
if ( null != tracked )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.TRACK_ANNOTATION_CLASSNAME,
tracked.getTrackedMethod() );
}
}
// Observables have pairs so let the caller determine whether a duplicate occurs in that scenario
if ( !sourceAnnotationName.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) )
{
final ObservableDescriptor observable = _observables.get( name );
if ( null != observable )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.OBSERVABLE_ANNOTATION_CLASSNAME,
observable.getDefiner() );
}
}
}
@Nonnull
private ArezProcessorException toException( @Nonnull final String name,
@Nonnull final String sourceAnnotationName,
@Nonnull final ExecutableElement sourceMethod,
@Nonnull final String targetAnnotationName,
@Nonnull final ExecutableElement targetElement )
{
return new ArezProcessorException( "Method annotated with @" + ProcessorUtil.toSimpleName( sourceAnnotationName ) +
" specified name " + name + " that duplicates @" +
ProcessorUtil.toSimpleName( targetAnnotationName ) + " defined by method " +
targetElement.getSimpleName(), sourceMethod );
}
void analyzeCandidateMethods( @Nonnull final List<ExecutableElement> methods,
@Nonnull final Types typeUtils )
throws ArezProcessorException
{
for ( final ExecutableElement method : methods )
{
final String methodName = method.getSimpleName().toString();
if ( AREZ_SPECIAL_METHODS.contains( methodName ) && method.getParameters().isEmpty() )
{
throw new ArezProcessorException( "Method defined on a class annotated by @ArezComponent uses a name " +
"reserved by Arez", method );
}
else if ( methodName.startsWith( GeneratorUtil.FIELD_PREFIX ) ||
methodName.startsWith( GeneratorUtil.OBSERVABLE_DATA_FIELD_PREFIX ) ||
methodName.startsWith( GeneratorUtil.FRAMEWORK_PREFIX ) )
{
throw new ArezProcessorException( "Method defined on a class annotated by @ArezComponent uses a name " +
"with a prefix reserved by Arez", method );
}
}
final Map<String, CandidateMethod> getters = new HashMap<>();
final Map<String, CandidateMethod> setters = new HashMap<>();
final Map<String, CandidateMethod> trackeds = new HashMap<>();
final Map<String, CandidateMethod> onDepsChangeds = new HashMap<>();
for ( final ExecutableElement method : methods )
{
final ExecutableType methodType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), method );
if ( !analyzeMethod( method, methodType ) )
{
/*
* If we get here the method was not annotated so we can try to detect if it is a
* candidate arez method in case some arez annotations are implied via naming conventions.
*/
if ( method.getModifiers().contains( Modifier.STATIC ) )
{
continue;
}
final CandidateMethod candidateMethod = new CandidateMethod( method, methodType );
final boolean voidReturn = method.getReturnType().getKind() == TypeKind.VOID;
final int parameterCount = method.getParameters().size();
String name;
if ( !method.getModifiers().contains( Modifier.FINAL ) )
{
name = ProcessorUtil.deriveName( method, SETTER_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( voidReturn && 1 == parameterCount && null != name )
{
setters.put( name, candidateMethod );
continue;
}
name = ProcessorUtil.deriveName( method, ISSER_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( !voidReturn && 0 == parameterCount && null != name )
{
getters.put( name, candidateMethod );
continue;
}
name = ProcessorUtil.deriveName( method, GETTER_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( !voidReturn && 0 == parameterCount && null != name )
{
getters.put( name, candidateMethod );
continue;
}
}
name =
ProcessorUtil.deriveName( method, TrackedDescriptor.ON_DEPS_CHANGED_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( voidReturn && 0 == parameterCount && null != name )
{
onDepsChangeds.put( name, candidateMethod );
continue;
}
final String methodName = method.getSimpleName().toString();
if ( !OBJECT_METHODS.contains( methodName ) )
{
trackeds.put( methodName, candidateMethod );
}
}
}
linkUnAnnotatedObservables( getters, setters );
linkUnAnnotatedTracked( trackeds, onDepsChangeds );
linkObserverRefs();
linkDependencies( getters.values() );
autodetectObservableInitializers();
/*
* ALl of the maps will have called remove() for all matching candidates.
* Thus any left are the non-arez methods.
*/
ensureNoAbstractMethods( getters.values() );
ensureNoAbstractMethods( setters.values() );
ensureNoAbstractMethods( trackeds.values() );
ensureNoAbstractMethods( onDepsChangeds.values() );
}
private void autodetectObservableInitializers()
{
for ( final ObservableDescriptor observable : getObservables() )
{
if ( null == observable.getInitializer() && observable.hasGetter() )
{
if ( observable.hasSetter() )
{
final boolean initializer =
autodetectInitializer( observable.getGetter() ) && autodetectInitializer( observable.getSetter() );
observable.setInitializer( initializer );
}
else
{
final boolean initializer =
autodetectInitializer( observable.getGetter() );
observable.setInitializer( initializer );
}
}
}
}
private void linkDependencies( @Nonnull final Collection<CandidateMethod> candidates )
{
_roObservables
.stream()
.filter( ObservableDescriptor::hasGetter )
.filter( o -> hasDependencyAnnotation( o.getGetter() ) )
.forEach( o -> addOrUpdateDependency( o.getGetter(), o ) );
_roComputeds
.stream()
.filter( ComputedDescriptor::hasComputed )
.map( ComputedDescriptor::getComputed )
.filter( this::hasDependencyAnnotation )
.forEach( this::addDependency );
candidates
.stream()
.map( CandidateMethod::getMethod )
.filter( this::hasDependencyAnnotation )
.forEach( this::addDependency );
}
private boolean hasDependencyAnnotation( @Nonnull final ExecutableElement method )
{
return null != ProcessorUtil.findAnnotationByType( method, Constants.DEPENDENCY_ANNOTATION_CLASSNAME );
}
private void addOrUpdateDependency( @Nonnull final ExecutableElement method,
@Nonnull final ObservableDescriptor observable )
{
final DependencyDescriptor dependencyDescriptor =
_dependencies.computeIfAbsent( method, this::createDependencyDescriptor );
dependencyDescriptor.setObservable( observable );
}
private void addDependency( @Nonnull final ExecutableElement method )
{
_dependencies.put( method, createDependencyDescriptor( method ) );
}
@Nonnull
private DependencyDescriptor createDependencyDescriptor( @Nonnull final ExecutableElement method )
{
MethodChecks.mustNotHaveAnyParameters( Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeSubclassCallable( getElement(), Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method );
if ( TypeKind.DECLARED != method.getReturnType().getKind() )
{
throw new ArezProcessorException( "@Dependency target must return a non-primitive value", method );
}
final boolean cascade = isActionCascade( method );
return new DependencyDescriptor( method, cascade );
}
private boolean isActionCascade( @Nonnull final ExecutableElement method )
{
final VariableElement injectParameter = (VariableElement)
ProcessorUtil.getAnnotationValue( _elements,
method,
Constants.DEPENDENCY_ANNOTATION_CLASSNAME,
"action" ).getValue();
switch ( injectParameter.getSimpleName().toString() )
{
case "CASCADE":
return true;
case "SET_NULL":
default:
return false;
}
}
private void ensureNoAbstractMethods( @Nonnull final Collection<CandidateMethod> candidateMethods )
{
candidateMethods
.stream()
.map( CandidateMethod::getMethod )
.filter( m -> m.getModifiers().contains( Modifier.ABSTRACT ) )
.forEach( m -> {
throw new ArezProcessorException( "@ArezComponent target has an abstract method not implemented by framework",
m );
} );
}
private void linkObserverRefs()
{
for ( final Map.Entry<String, CandidateMethod> entry : _observerRefs.entrySet() )
{
final String key = entry.getKey();
final CandidateMethod method = entry.getValue();
final AutorunDescriptor autorunDescriptor = _autoruns.get( key );
if ( null != autorunDescriptor )
{
autorunDescriptor.setRefMethod( method.getMethod(), method.getMethodType() );
}
else
{
final TrackedDescriptor trackedDescriptor = _trackeds.get( key );
if ( null != trackedDescriptor )
{
trackedDescriptor.setRefMethod( method.getMethod(), method.getMethodType() );
}
else
{
throw new ArezProcessorException( "@ObserverRef target defined observer named '" + key + "' but no " +
"@Autorun or @Track method with that name exists", method.getMethod() );
}
}
}
}
private void linkUnAnnotatedObservables( @Nonnull final Map<String, CandidateMethod> getters,
@Nonnull final Map<String, CandidateMethod> setters )
throws ArezProcessorException
{
for ( final ObservableDescriptor observable : _roObservables )
{
if ( !observable.hasSetter() && !observable.hasGetter() )
{
throw new ArezProcessorException( "@ObservableRef target unable to be associated with an Observable property",
observable.getRefMethod() );
}
else if ( !observable.hasSetter() && observable.expectSetter() )
{
final CandidateMethod candidate = setters.remove( observable.getName() );
if ( null != candidate )
{
MethodChecks.mustBeOverridable( getElement(),
Constants.OBSERVABLE_ANNOTATION_CLASSNAME,
candidate.getMethod() );
observable.setSetter( candidate.getMethod(), candidate.getMethodType() );
}
else if ( observable.hasGetter() )
{
throw new ArezProcessorException( "@Observable target defined getter but no setter was defined and no " +
"setter could be automatically determined", observable.getGetter() );
}
}
else if ( !observable.hasGetter() )
{
final CandidateMethod candidate = getters.remove( observable.getName() );
if ( null != candidate )
{
MethodChecks.mustBeOverridable( getElement(),
Constants.OBSERVABLE_ANNOTATION_CLASSNAME,
candidate.getMethod() );
observable.setGetter( candidate.getMethod(), candidate.getMethodType() );
}
else
{
throw new ArezProcessorException( "@Observable target defined setter but no getter was defined and no " +
"getter could be automatically determined", observable.getSetter() );
}
}
}
}
private void linkUnAnnotatedTracked( @Nonnull final Map<String, CandidateMethod> trackeds,
@Nonnull final Map<String, CandidateMethod> onDepsChangeds )
throws ArezProcessorException
{
for ( final TrackedDescriptor tracked : _roTrackeds )
{
if ( !tracked.hasTrackedMethod() )
{
final CandidateMethod candidate = trackeds.remove( tracked.getName() );
if ( null != candidate )
{
tracked.setTrackedMethod( false, false, true, candidate.getMethod(), candidate.getMethodType() );
}
else
{
throw new ArezProcessorException( "@OnDepsChanged target has no corresponding @Track that could " +
"be automatically determined", tracked.getOnDepsChangedMethod() );
}
}
else if ( !tracked.hasOnDepsChangedMethod() )
{
final CandidateMethod candidate = onDepsChangeds.remove( tracked.getName() );
if ( null != candidate )
{
tracked.setOnDepsChangedMethod( candidate.getMethod() );
}
else
{
throw new ArezProcessorException( "@Track target has no corresponding @OnDepsChanged that could " +
"be automatically determined", tracked.getTrackedMethod() );
}
}
}
}
private boolean analyzeMethod( @Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
verifyNoDuplicateAnnotations( method );
final AnnotationMirror action =
ProcessorUtil.findAnnotationByType( method, Constants.ACTION_ANNOTATION_CLASSNAME );
final AnnotationMirror autorun =
ProcessorUtil.findAnnotationByType( method, Constants.AUTORUN_ANNOTATION_CLASSNAME );
final AnnotationMirror observable =
ProcessorUtil.findAnnotationByType( method, Constants.OBSERVABLE_ANNOTATION_CLASSNAME );
final AnnotationMirror observableRef =
ProcessorUtil.findAnnotationByType( method, Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror computed =
ProcessorUtil.findAnnotationByType( method, Constants.COMPUTED_ANNOTATION_CLASSNAME );
final AnnotationMirror computedValueRef =
ProcessorUtil.findAnnotationByType( method, Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror contextRef =
ProcessorUtil.findAnnotationByType( method, Constants.CONTEXT_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror componentRef =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror componentId =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_ID_ANNOTATION_CLASSNAME );
final AnnotationMirror componentTypeName =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror componentName =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror postConstruct =
ProcessorUtil.findAnnotationByType( method, Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME );
final AnnotationMirror ejbPostConstruct =
ProcessorUtil.findAnnotationByType( method, Constants.EJB_POST_CONSTRUCT_ANNOTATION_CLASSNAME );
final AnnotationMirror preDispose =
ProcessorUtil.findAnnotationByType( method, Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME );
final AnnotationMirror postDispose =
ProcessorUtil.findAnnotationByType( method, Constants.POST_DISPOSE_ANNOTATION_CLASSNAME );
final AnnotationMirror onActivate =
ProcessorUtil.findAnnotationByType( method, Constants.ON_ACTIVATE_ANNOTATION_CLASSNAME );
final AnnotationMirror onDeactivate =
ProcessorUtil.findAnnotationByType( method, Constants.ON_DEACTIVATE_ANNOTATION_CLASSNAME );
final AnnotationMirror onStale =
ProcessorUtil.findAnnotationByType( method, Constants.ON_STALE_ANNOTATION_CLASSNAME );
final AnnotationMirror onDispose =
ProcessorUtil.findAnnotationByType( method, Constants.ON_DISPOSE_ANNOTATION_CLASSNAME );
final AnnotationMirror track =
ProcessorUtil.findAnnotationByType( method, Constants.TRACK_ANNOTATION_CLASSNAME );
final AnnotationMirror onDepsChanged =
ProcessorUtil.findAnnotationByType( method, Constants.ON_DEPS_CHANGED_ANNOTATION_CLASSNAME );
final AnnotationMirror observerRef =
ProcessorUtil.findAnnotationByType( method, Constants.OBSERVER_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror memoize =
ProcessorUtil.findAnnotationByType( method, Constants.MEMOIZE_ANNOTATION_CLASSNAME );
final AnnotationMirror dependency =
ProcessorUtil.findAnnotationByType( method, Constants.DEPENDENCY_ANNOTATION_CLASSNAME );
if ( null != observable )
{
addObservable( observable, method, methodType );
return true;
}
else if ( null != observableRef )
{
addObservableRef( observableRef, method, methodType );
return true;
}
else if ( null != action )
{
addAction( action, method, methodType );
return true;
}
else if ( null != autorun )
{
addAutorun( autorun, method, methodType );
return true;
}
else if ( null != track )
{
addTracked( track, method, methodType );
return true;
}
else if ( null != onDepsChanged )
{
addOnDepsChanged( onDepsChanged, method );
return true;
}
else if ( null != observerRef )
{
addObserverRef( observerRef, method, methodType );
return true;
}
else if ( null != contextRef )
{
setContextRef( method );
return true;
}
else if ( null != computed )
{
addComputed( computed, method, methodType );
return true;
}
else if ( null != computedValueRef )
{
addComputedValueRef( computedValueRef, method, methodType );
return true;
}
else if ( null != memoize )
{
addMemoize( memoize, method, methodType );
return true;
}
else if ( null != componentRef )
{
setComponentRef( method );
return true;
}
else if ( null != componentId )
{
setComponentId( method, methodType );
return true;
}
else if ( null != componentName )
{
setComponentNameRef( method );
return true;
}
else if ( null != componentTypeName )
{
setComponentTypeNameRef( method );
return true;
}
else if ( null != ejbPostConstruct )
{
throw new ArezProcessorException( "@" + Constants.EJB_POST_CONSTRUCT_ANNOTATION_CLASSNAME + " annotation " +
"not supported in components annotated with @ArezComponent, use the @" +
Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME + " annotation instead.",
method );
}
else if ( null != postConstruct )
{
setPostConstruct( method );
return true;
}
else if ( null != preDispose )
{
setPreDispose( method );
return true;
}
else if ( null != postDispose )
{
setPostDispose( method );
return true;
}
else if ( null != onActivate )
{
addOnActivate( onActivate, method );
return true;
}
else if ( null != onDeactivate )
{
addOnDeactivate( onDeactivate, method );
return true;
}
else if ( null != onStale )
{
addOnStale( onStale, method );
return true;
}
else if ( null != onDispose )
{
addOnDispose( onDispose, method );
return true;
}
else if ( null != dependency )
{
addDependency( method );
return false;
}
else
{
return false;
}
}
@Nullable
private Boolean isInitializerRequired( @Nonnull final ExecutableElement element )
{
final AnnotationMirror annotation =
ProcessorUtil.findAnnotationByType( element, Constants.OBSERVABLE_ANNOTATION_CLASSNAME );
final AnnotationValue injectParameter =
null == annotation ?
null :
ProcessorUtil.findAnnotationValueNoDefaults( annotation, "initializer" );
final String value =
null == injectParameter ?
"AUTODETECT" :
( (VariableElement) injectParameter.getValue() ).getSimpleName().toString();
switch ( value )
{
case "ENABLE":
return Boolean.TRUE;
case "DISABLE":
return Boolean.FALSE;
default:
return null;
}
}
private boolean autodetectInitializer( @Nonnull final ExecutableElement element )
{
return element.getModifiers().contains( Modifier.ABSTRACT ) &&
(
(
// Getter
element.getReturnType().getKind() != TypeKind.VOID &&
null != ProcessorUtil.findAnnotationByType( element, Constants.NONNULL_ANNOTATION_CLASSNAME )
) ||
(
// Setter
1 == element.getParameters().size() &&
null != ProcessorUtil.findAnnotationByType( element.getParameters().get( 0 ),
Constants.NONNULL_ANNOTATION_CLASSNAME )
)
);
}
private void verifyNoDuplicateAnnotations( @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String[] annotationTypes =
new String[]{ Constants.ACTION_ANNOTATION_CLASSNAME,
Constants.AUTORUN_ANNOTATION_CLASSNAME,
Constants.TRACK_ANNOTATION_CLASSNAME,
Constants.ON_DEPS_CHANGED_ANNOTATION_CLASSNAME,
Constants.OBSERVER_REF_ANNOTATION_CLASSNAME,
Constants.OBSERVABLE_ANNOTATION_CLASSNAME,
Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME,
Constants.COMPUTED_ANNOTATION_CLASSNAME,
Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME,
Constants.MEMOIZE_ANNOTATION_CLASSNAME,
Constants.COMPONENT_REF_ANNOTATION_CLASSNAME,
Constants.COMPONENT_ID_ANNOTATION_CLASSNAME,
Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME,
Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME,
Constants.CONTEXT_REF_ANNOTATION_CLASSNAME,
Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME,
Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME,
Constants.POST_DISPOSE_ANNOTATION_CLASSNAME,
Constants.ON_ACTIVATE_ANNOTATION_CLASSNAME,
Constants.ON_DEACTIVATE_ANNOTATION_CLASSNAME,
Constants.ON_DISPOSE_ANNOTATION_CLASSNAME,
Constants.ON_STALE_ANNOTATION_CLASSNAME,
Constants.DEPENDENCY_ANNOTATION_CLASSNAME };
for ( int i = 0; i < annotationTypes.length; i++ )
{
final String type1 = annotationTypes[ i ];
final Object annotation1 = ProcessorUtil.findAnnotationByType( method, type1 );
if ( null != annotation1 )
{
for ( int j = i + 1; j < annotationTypes.length; j++ )
{
final String type2 = annotationTypes[ j ];
if ( !type2.equals( Constants.DEPENDENCY_ANNOTATION_CLASSNAME ) ||
!type1.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) &&
!type1.equals( Constants.COMPUTED_ANNOTATION_CLASSNAME ) )
{
final Object annotation2 = ProcessorUtil.findAnnotationByType( method, type2 );
if ( null != annotation2 )
{
final String message =
"Method can not be annotated with both @" + ProcessorUtil.toSimpleName( type1 ) +
" and @" + ProcessorUtil.toSimpleName( type2 );
throw new ArezProcessorException( message, method );
}
}
}
}
}
}
@Nonnull
private String getPropertyAccessorName( @Nonnull final ExecutableElement method, @Nonnull final String specifiedName )
throws ArezProcessorException
{
String name = ProcessorUtil.deriveName( method, GETTER_PATTERN, specifiedName );
if ( null != name )
{
return name;
}
if ( method.getReturnType().getKind() == TypeKind.BOOLEAN )
{
name = ProcessorUtil.deriveName( method, ISSER_PATTERN, specifiedName );
if ( null != name )
{
return name;
}
}
return method.getSimpleName().toString();
}
@Nonnull
private String getNestedClassPrefix()
{
final StringBuilder name = new StringBuilder();
TypeElement t = getElement();
while ( NestingKind.TOP_LEVEL != t.getNestingKind() )
{
t = (TypeElement) t.getEnclosingElement();
name.insert( 0, t.getSimpleName() + "_" );
}
return name.toString();
}
/**
* Build the enhanced class for the component.
*/
@Nonnull
TypeSpec buildType( @Nonnull final Types typeUtils )
throws ArezProcessorException
{
final TypeSpec.Builder builder = TypeSpec.classBuilder( getArezClassName() ).
superclass( TypeName.get( getElement().asType() ) ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) ).
addModifiers( Modifier.FINAL );
addOriginatingTypes( getElement(), builder );
addGeneratedAnnotation( builder );
if ( !_roComputeds.isEmpty() )
{
builder.addAnnotation( AnnotationSpec.builder( SuppressWarnings.class ).
addMember( "value", "$S", "unchecked" ).
build() );
}
final boolean publicType =
ProcessorUtil.getConstructors( getElement() ).
stream().
anyMatch( c -> c.getModifiers().contains( Modifier.PUBLIC ) ) &&
getElement().getModifiers().contains( Modifier.PUBLIC );
if ( publicType )
{
builder.addModifiers( Modifier.PUBLIC );
}
if ( null != _scopeAnnotation )
{
final DeclaredType annotationType = _scopeAnnotation.getAnnotationType();
final TypeElement typeElement = (TypeElement) annotationType.asElement();
builder.addAnnotation( ClassName.get( typeElement ) );
}
builder.addSuperinterface( GeneratorUtil.DISPOSABLE_CLASSNAME );
builder.addSuperinterface( ParameterizedTypeName.get( GeneratorUtil.IDENTIFIABLE_CLASSNAME, getIdType().box() ) );
builder.addSuperinterface( GeneratorUtil.COMPONENT_OBSERVABLE_CLASSNAME );
buildFields( builder );
buildConstructors( builder, typeUtils );
builder.addMethod( buildContextRefMethod() );
if ( null != _componentRef )
{
builder.addMethod( buildComponentRefMethod() );
}
if ( null == _componentId )
{
builder.addMethod( buildComponentIdMethod() );
}
builder.addMethod( buildArezIdMethod() );
builder.addMethod( buildComponentNameMethod() );
final MethodSpec method = buildComponentTypeNameMethod();
if ( null != method )
{
builder.addMethod( method );
}
if ( !getCascadeOnDisposeDependencies().isEmpty() )
{
builder.addMethod( buildCascadeOnDisposeDepsMethod() );
}
if ( !getSetNullOnDisposeDependencies().isEmpty() )
{
builder.addMethod( buildSetNullOnDisposeDepsMethod() );
}
builder.addMethod( buildInternalObserve() );
builder.addMethod( buildObserve() );
builder.addMethod( buildIsDisposed() );
builder.addMethod( buildDispose() );
_roObservables.forEach( e -> e.buildMethods( builder ) );
_roAutoruns.forEach( e -> e.buildMethods( builder ) );
_roActions.forEach( e -> e.buildMethods( builder ) );
_roComputeds.forEach( e -> e.buildMethods( builder ) );
_roMemoizes.forEach( e -> e.buildMethods( builder ) );
_roTrackeds.forEach( e -> e.buildMethods( builder ) );
builder.addMethod( buildHashcodeMethod() );
builder.addMethod( buildEqualsMethod() );
if ( _generateToString )
{
builder.addMethod( buildToStringMethod() );
}
return builder.build();
}
@Nonnull
private MethodSpec buildSetNullOnDisposeDepsMethod()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( GeneratorUtil.SET_NULL_ON_DISPOSE_METHOD_NAME );
builder.addModifiers( Modifier.PRIVATE, Modifier.FINAL );
final AtomicInteger count = new AtomicInteger( 1 );
getSetNullOnDisposeDependencies().forEach( d -> {
final String varName = "dependency" + count.get();
count.incrementAndGet();
builder.addStatement( "final $T $N = $N()",
d.getMethod().getReturnType(),
varName,
d.getMethod().getSimpleName().toString() );
final CodeBlock.Builder codeBlock = CodeBlock.builder();
codeBlock.beginControlFlow( "if ( !$T.observe( $N ) ) ", GeneratorUtil.COMPONENT_OBSERVABLE_CLASSNAME, varName );
codeBlock.addStatement( "$N( null )", d.getObservable().getSetter().getSimpleName().toString() );
codeBlock.endControlFlow( "" );
builder.addCode( codeBlock.build() );
} );
return builder.build();
}
@Nonnull
private MethodSpec buildCascadeOnDisposeDepsMethod()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( GeneratorUtil.GET_CASCADE_ON_DISPOSE_DEPS_METHOD_NAME );
builder.addModifiers( Modifier.PRIVATE, Modifier.FINAL );
builder.returns( ParameterizedTypeName.get( ClassName.get( Stream.class ),
ParameterizedTypeName.get( GeneratorUtil.SAFE_FUNCTION_CLASSNAME,
ClassName.OBJECT ) ) );
final ArrayList<Object> params = new ArrayList<>();
params.add( Stream.class );
getCascadeOnDisposeDependencies().forEach( d -> params.add( d.getMethod().getSimpleName().toString() ) );
builder.addStatement( "return $T.of(" +
getCascadeOnDisposeDependencies().stream()
.map( d -> "() -> $N()" )
.collect( Collectors.joining( ", " ) ) +
")",
params.toArray() );
return builder.build();
}
@Nonnull
private MethodSpec buildToStringMethod()
throws ArezProcessorException
{
assert _generateToString;
final MethodSpec.Builder method =
MethodSpec.methodBuilder( "toString" ).
addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
addAnnotation( Override.class ).
returns( TypeName.get( String.class ) );
final CodeBlock.Builder codeBlock = CodeBlock.builder();
codeBlock.beginControlFlow( "if ( $T.areNamesEnabled() )", GeneratorUtil.AREZ_CLASSNAME );
codeBlock.addStatement( "return $S + $N() + $S", "ArezComponent[", getComponentNameMethodName(), "]" );
codeBlock.nextControlFlow( "else" );
codeBlock.addStatement( "return super.toString()" );
codeBlock.endControlFlow();
method.addCode( codeBlock.build() );
return method.build();
}
@Nonnull
private MethodSpec buildEqualsMethod()
throws ArezProcessorException
{
final String idMethod = getIdMethodName();
final MethodSpec.Builder method =
MethodSpec.methodBuilder( "equals" ).
addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
addAnnotation( Override.class ).
addParameter( Object.class, "o", Modifier.FINAL ).
returns( TypeName.BOOLEAN );
final ClassName generatedClass = ClassName.get( getPackageName(), getArezClassName() );
final CodeBlock.Builder codeBlock = CodeBlock.builder();
codeBlock.beginControlFlow( "if ( this == o )" );
codeBlock.addStatement( "return true" );
codeBlock.nextControlFlow( "else if ( null == o || !(o instanceof $T) )", generatedClass );
codeBlock.addStatement( "return false" );
codeBlock.nextControlFlow( "else" );
codeBlock.addStatement( "final $T that = ($T) o;", generatedClass, generatedClass );
final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : TypeKind.LONG;
if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR )
{
codeBlock.addStatement( "return null != $N() && $N().equals( that.$N() )", idMethod, idMethod, idMethod );
}
else
{
codeBlock.addStatement( "return $N() == that.$N()", idMethod, idMethod );
}
codeBlock.endControlFlow();
if ( _requireEquals )
{
method.addCode( codeBlock.build() );
}
else
{
final CodeBlock.Builder guardBlock = CodeBlock.builder();
guardBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME );
guardBlock.add( codeBlock.build() );
guardBlock.nextControlFlow( "else" );
guardBlock.addStatement( "return super.equals( o )" );
guardBlock.endControlFlow();
method.addCode( guardBlock.build() );
}
return method.build();
}
@Nonnull
private MethodSpec buildHashcodeMethod()
throws ArezProcessorException
{
final String idMethod = getIdMethodName();
final MethodSpec.Builder method =
MethodSpec.methodBuilder( "hashCode" ).
addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
addAnnotation( Override.class ).
returns( TypeName.INT );
final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : TypeKind.LONG;
if ( _requireEquals )
{
if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR )
{
method.addStatement( "return null != $N() ? $N().hashCode() : $T.identityHashCode( this )",
idMethod,
idMethod,
System.class );
}
else if ( kind == TypeKind.BYTE )
{
method.addStatement( "return $T.hashCode( $N() )", Byte.class, idMethod );
}
else if ( kind == TypeKind.CHAR )
{
method.addStatement( "return $T.hashCode( $N() )", Character.class, idMethod );
}
else if ( kind == TypeKind.SHORT )
{
method.addStatement( "return $T.hashCode( $N() )", Short.class, idMethod );
}
else if ( kind == TypeKind.INT )
{
method.addStatement( "return $T.hashCode( $N() )", Integer.class, idMethod );
}
else if ( kind == TypeKind.LONG )
{
method.addStatement( "return $T.hashCode( $N() )", Long.class, idMethod );
}
else if ( kind == TypeKind.FLOAT )
{
method.addStatement( "return $T.hashCode( $N() )", Float.class, idMethod );
}
else if ( kind == TypeKind.DOUBLE )
{
method.addStatement( "return $T.hashCode( $N() )", Double.class, idMethod );
}
else
{
// So very unlikely but will cover it for completeness
assert kind == TypeKind.BOOLEAN;
method.addStatement( "return $T.hashCode( $N() )", Boolean.class, idMethod );
}
}
else
{
final CodeBlock.Builder guardBlock = CodeBlock.builder();
guardBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME );
if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR )
{
guardBlock.addStatement( "return null != $N() ? $N().hashCode() : $T.identityHashCode( this )",
idMethod,
idMethod,
System.class );
}
else if ( kind == TypeKind.BYTE )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Byte.class, idMethod );
}
else if ( kind == TypeKind.CHAR )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Character.class, idMethod );
}
else if ( kind == TypeKind.SHORT )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Short.class, idMethod );
}
else if ( kind == TypeKind.INT )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Integer.class, idMethod );
}
else if ( kind == TypeKind.LONG )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Long.class, idMethod );
}
else if ( kind == TypeKind.FLOAT )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Float.class, idMethod );
}
else if ( kind == TypeKind.DOUBLE )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Double.class, idMethod );
}
else
{
// So very unlikely but will cover it for completeness
assert kind == TypeKind.BOOLEAN;
guardBlock.addStatement( "return $T.hashCode( $N() )", Boolean.class, idMethod );
}
guardBlock.nextControlFlow( "else" );
guardBlock.addStatement( "return super.hashCode()" );
guardBlock.endControlFlow();
method.addCode( guardBlock.build() );
}
return method.build();
}
@Nonnull
String getComponentNameMethodName()
{
return null == _componentNameRef ? GeneratorUtil.NAME_METHOD_NAME : _componentNameRef.getSimpleName().toString();
}
@Nonnull
private MethodSpec buildContextRefMethod()
throws ArezProcessorException
{
final String methodName = getContextMethodName();
final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ).
addModifiers( Modifier.FINAL ).
returns( GeneratorUtil.AREZ_CONTEXT_CLASSNAME );
GeneratorUtil.generateNotInitializedInvariant( this, method, methodName );
method.addStatement( "return $T.areZonesEnabled() ? this.$N : $T.context()",
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.CONTEXT_FIELD_NAME,
GeneratorUtil.AREZ_CLASSNAME );
if ( null != _contextRef )
{
method.addAnnotation( Override.class );
ProcessorUtil.copyDocumentedAnnotations( _contextRef, method );
ProcessorUtil.copyAccessModifiers( _contextRef, method );
}
return method.build();
}
@Nonnull
String getContextMethodName()
{
return null != _contextRef ? _contextRef.getSimpleName().toString() : GeneratorUtil.CONTEXT_FIELD_NAME;
}
@Nonnull
private MethodSpec buildComponentRefMethod()
throws ArezProcessorException
{
assert null != _componentRef;
final String methodName = _componentRef.getSimpleName().toString();
final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ).
addModifiers( Modifier.FINAL ).
returns( GeneratorUtil.COMPONENT_CLASSNAME );
GeneratorUtil.generateNotInitializedInvariant( this, method, methodName );
GeneratorUtil.generateNotConstructedInvariant( this, method, methodName );
GeneratorUtil.generateNotCompleteInvariant( this, method, methodName );
GeneratorUtil.generateNotDisposedInvariant( this, method, methodName );
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( $T.shouldCheckInvariants() )", GeneratorUtil.AREZ_CLASSNAME );
block.addStatement( "$T.invariant( () -> $T.areNativeComponentsEnabled(), () -> \"Invoked @ComponentRef " +
"method '$N' but Arez.areNativeComponentsEnabled() returned false.\" )",
GeneratorUtil.GUARDS_CLASSNAME,
GeneratorUtil.AREZ_CLASSNAME,
methodName );
block.endControlFlow();
method.addCode( block.build() );
method.addStatement( "return this.$N", GeneratorUtil.COMPONENT_FIELD_NAME );
ProcessorUtil.copyDocumentedAnnotations( _componentRef, method );
ProcessorUtil.copyAccessModifiers( _componentRef, method );
return method.build();
}
@Nonnull
private MethodSpec buildArezIdMethod()
throws ArezProcessorException
{
return MethodSpec.methodBuilder( "getArezId" ).
addAnnotation( Override.class ).
addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
addModifiers( Modifier.PUBLIC ).
addModifiers( Modifier.FINAL ).
returns( getIdType().box() ).
addStatement( "return $N()", getIdMethodName() ).build();
}
@Nonnull
private MethodSpec buildComponentIdMethod()
throws ArezProcessorException
{
assert null == _componentId;
final MethodSpec.Builder method = MethodSpec.methodBuilder( GeneratorUtil.ID_FIELD_NAME ).
addModifiers( Modifier.FINAL ).
returns( TypeName.LONG );
if ( !hasRepository() )
{
final CodeBlock.Builder block = CodeBlock.builder();
if ( _nameIncludesId )
{
block.beginControlFlow(
"if ( $T.shouldCheckInvariants() && !$T.areNamesEnabled() && !$T.areNativeComponentsEnabled() )",
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.AREZ_CLASSNAME );
}
else
{
block.beginControlFlow( "if ( $T.shouldCheckInvariants() && !$T.areNativeComponentsEnabled() )",
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.AREZ_CLASSNAME );
}
block.addStatement( "$T.fail( () -> \"Method invoked to access id when id not expected.\" )",
GeneratorUtil.GUARDS_CLASSNAME );
block.endControlFlow();
method.addCode( block.build() );
}
return method.addStatement( "return this.$N", GeneratorUtil.ID_FIELD_NAME ).build();
}
/**
* Generate the getter for component name.
*/
@Nonnull
private MethodSpec buildComponentNameMethod()
throws ArezProcessorException
{
final MethodSpec.Builder builder;
final String methodName;
if ( null == _componentNameRef )
{
methodName = GeneratorUtil.NAME_METHOD_NAME;
builder = MethodSpec.methodBuilder( methodName );
}
else
{
methodName = _componentNameRef.getSimpleName().toString();
builder = MethodSpec.methodBuilder( methodName );
ProcessorUtil.copyDocumentedAnnotations( _componentNameRef, builder );
ProcessorUtil.copyAccessModifiers( _componentNameRef, builder );
builder.addModifiers( Modifier.FINAL );
}
builder.returns( TypeName.get( String.class ) );
GeneratorUtil.generateNotInitializedInvariant( this, builder, methodName );
if ( _nameIncludesId )
{
builder.addStatement( "return $S + $N()", _type.isEmpty() ? "" : _type + ".", getIdMethodName() );
}
else
{
builder.addStatement( "return $S", _type );
}
return builder.build();
}
@Nullable
private MethodSpec buildComponentTypeNameMethod()
throws ArezProcessorException
{
if ( null == _componentTypeNameRef )
{
return null;
}
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( _componentTypeNameRef.getSimpleName().toString() );
ProcessorUtil.copyAccessModifiers( _componentTypeNameRef, builder );
builder.addModifiers( Modifier.FINAL );
builder.addAnnotation( GeneratorUtil.NONNULL_CLASSNAME );
builder.returns( TypeName.get( String.class ) );
builder.addStatement( "return $S", _type );
return builder.build();
}
/**
* Generate the dispose method.
*/
@Nonnull
private MethodSpec buildDispose()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "dispose" ).
addModifiers( Modifier.PUBLIC ).
addAnnotation( Override.class );
final CodeBlock.Builder codeBlock = CodeBlock.builder();
codeBlock.beginControlFlow( "if ( !$T.isDisposingOrDisposed( this.$N ) )",
GeneratorUtil.COMPONENT_STATE_CLASSNAME,
GeneratorUtil.STATE_FIELD_NAME );
codeBlock.addStatement( "this.$N = $T.COMPONENT_DISPOSING",
GeneratorUtil.STATE_FIELD_NAME,
GeneratorUtil.COMPONENT_STATE_CLASSNAME );
final CodeBlock.Builder nativeComponentBlock = CodeBlock.builder();
nativeComponentBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME );
nativeComponentBlock.addStatement( "this.$N.dispose()", GeneratorUtil.COMPONENT_FIELD_NAME );
nativeComponentBlock.nextControlFlow( "else" );
final CodeBlock.Builder actionBlock = CodeBlock.builder();
actionBlock.beginControlFlow( "$N().dispose( $T.areNamesEnabled() ? $N() : null, () -> {",
getContextMethodName(),
GeneratorUtil.AREZ_CLASSNAME,
getComponentNameMethodName() );
if ( null != _preDispose )
{
actionBlock.addStatement( "super.$N()", _preDispose.getSimpleName() );
}
actionBlock.addStatement( "this.$N.dispose()", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME );
if ( !getCascadeOnDisposeDependencies().isEmpty() )
{
actionBlock.addStatement( "this.$N.dispose()", GeneratorUtil.CASCADE_ON_DISPOSE_FIELD_NAME );
}
if ( !getSetNullOnDisposeDependencies().isEmpty() )
{
actionBlock.addStatement( "this.$N.dispose()", GeneratorUtil.SET_NULL_ON_DISPOSE_FIELD_NAME );
}
_roAutoruns.forEach( autorun -> autorun.buildDisposer( actionBlock ) );
_roTrackeds.forEach( tracked -> tracked.buildDisposer( actionBlock ) );
_roComputeds.forEach( computed -> computed.buildDisposer( actionBlock ) );
_roMemoizes.forEach( computed -> computed.buildDisposer( actionBlock ) );
_roObservables.forEach( observable -> observable.buildDisposer( actionBlock ) );
if ( null != _postDispose )
{
actionBlock.addStatement( "super.$N()", _postDispose.getSimpleName() );
}
actionBlock.endControlFlow( "} )" );
nativeComponentBlock.add( actionBlock.build() );
nativeComponentBlock.endControlFlow();
codeBlock.add( nativeComponentBlock.build() );
codeBlock.addStatement( "this.$N = $T.COMPONENT_DISPOSED",
GeneratorUtil.STATE_FIELD_NAME,
GeneratorUtil.COMPONENT_STATE_CLASSNAME );
codeBlock.endControlFlow();
builder.addCode( codeBlock.build() );
return builder.build();
}
/**
* Generate the isDisposed method.
*/
@Nonnull
private MethodSpec buildIsDisposed()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "isDisposed" ).
addModifiers( Modifier.PUBLIC ).
addAnnotation( Override.class ).
returns( TypeName.BOOLEAN );
builder.addStatement( "return $T.isDisposingOrDisposed( this.$N )",
GeneratorUtil.COMPONENT_STATE_CLASSNAME,
GeneratorUtil.STATE_FIELD_NAME );
return builder.build();
}
/**
* Generate the observe method.
*/
@Nonnull
private MethodSpec buildInternalObserve()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( GeneratorUtil.INTERNAL_OBSERVE_METHOD_NAME ).
addModifiers( Modifier.PRIVATE ).
returns( TypeName.BOOLEAN );
builder.addStatement( "final boolean isDisposed = isDisposed()" );
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( !isDisposed ) ", getContextMethodName() );
block.addStatement( "this.$N.reportObserved()", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME );
block.endControlFlow();
builder.addCode( block.build() );
builder.addStatement( "return !isDisposed",
GeneratorUtil.COMPONENT_STATE_CLASSNAME,
GeneratorUtil.STATE_FIELD_NAME );
return builder.build();
}
/**
* Generate the observe method.
*/
@Nonnull
private MethodSpec buildObserve()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "observe" ).
addModifiers( Modifier.PUBLIC ).
addAnnotation( Override.class ).
returns( TypeName.BOOLEAN );
if ( _disposeOnDeactivate )
{
builder.addStatement( "return $N.get()", GeneratorUtil.DISPOSE_ON_DEACTIVATE_FIELD_NAME );
}
else
{
builder.addStatement( "return $N()", GeneratorUtil.INTERNAL_OBSERVE_METHOD_NAME );
}
return builder.build();
}
/**
* Build the fields required to make class Observable. This involves;
* <ul>
* <li>the context field if there is any @Action methods.</li>
* <li>the observable object for every @Observable.</li>
* <li>the ComputedValue object for every @Computed method.</li>
* </ul>
*/
private void buildFields( @Nonnull final TypeSpec.Builder builder )
{
// If we don't have a method for object id but we need one then synthesize it
if ( null == _componentId )
{
final FieldSpec.Builder nextIdField =
FieldSpec.builder( TypeName.LONG,
GeneratorUtil.NEXT_ID_FIELD_NAME,
Modifier.VOLATILE,
Modifier.STATIC,
Modifier.PRIVATE );
builder.addField( nextIdField.build() );
final FieldSpec.Builder idField =
FieldSpec.builder( TypeName.LONG, GeneratorUtil.ID_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE );
builder.addField( idField.build() );
}
final FieldSpec.Builder disposableField =
FieldSpec.builder( TypeName.BYTE, GeneratorUtil.STATE_FIELD_NAME, Modifier.PRIVATE );
builder.addField( disposableField.build() );
// Create the field that contains the context
{
final FieldSpec.Builder field =
FieldSpec.builder( GeneratorUtil.AREZ_CONTEXT_CLASSNAME,
GeneratorUtil.CONTEXT_FIELD_NAME,
Modifier.FINAL,
Modifier.PRIVATE ).
addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME );
builder.addField( field.build() );
}
//Create the field that contains the component
{
final FieldSpec.Builder field =
FieldSpec.builder( GeneratorUtil.COMPONENT_CLASSNAME,
GeneratorUtil.COMPONENT_FIELD_NAME,
Modifier.FINAL,
Modifier.PRIVATE );
builder.addField( field.build() );
}
{
final ParameterizedTypeName typeName =
ParameterizedTypeName.get( GeneratorUtil.OBSERVABLE_CLASSNAME, TypeName.BOOLEAN.box() );
final FieldSpec.Builder field =
FieldSpec.builder( typeName,
GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME,
Modifier.FINAL,
Modifier.PRIVATE );
builder.addField( field.build() );
}
_roObservables.forEach( observable -> observable.buildFields( builder ) );
_roComputeds.forEach( computed -> computed.buildFields( builder ) );
_roMemoizes.forEach( e -> e.buildFields( builder ) );
_roAutoruns.forEach( autorun -> autorun.buildFields( builder ) );
_roTrackeds.forEach( tracked -> tracked.buildFields( builder ) );
if ( !getCascadeOnDisposeDependencies().isEmpty() )
{
final FieldSpec.Builder field =
FieldSpec.builder( GeneratorUtil.OBSERVER_CLASSNAME,
GeneratorUtil.CASCADE_ON_DISPOSE_FIELD_NAME,
Modifier.FINAL,
Modifier.PRIVATE ).
addAnnotation( GeneratorUtil.NONNULL_CLASSNAME );
builder.addField( field.build() );
}
if ( !getSetNullOnDisposeDependencies().isEmpty() )
{
final FieldSpec.Builder field =
FieldSpec.builder( GeneratorUtil.OBSERVER_CLASSNAME,
GeneratorUtil.SET_NULL_ON_DISPOSE_FIELD_NAME,
Modifier.FINAL,
Modifier.PRIVATE ).
addAnnotation( GeneratorUtil.NONNULL_CLASSNAME );
builder.addField( field.build() );
}
if ( _disposeOnDeactivate )
{
final FieldSpec.Builder field =
FieldSpec.builder( ParameterizedTypeName.get( GeneratorUtil.COMPUTED_VALUE_CLASSNAME, TypeName.BOOLEAN.box() ),
GeneratorUtil.DISPOSE_ON_DEACTIVATE_FIELD_NAME,
Modifier.FINAL,
Modifier.PRIVATE ).
addAnnotation( GeneratorUtil.NONNULL_CLASSNAME );
builder.addField( field.build() );
}
}
private List<DependencyDescriptor> getCascadeOnDisposeDependencies()
{
return _roDependencies.stream().filter( DependencyDescriptor::shouldCascadeDispose ).collect( Collectors.toList() );
}
private List<DependencyDescriptor> getSetNullOnDisposeDependencies()
{
return _roDependencies.stream().filter( d -> !d.shouldCascadeDispose() ).collect( Collectors.toList() );
}
/**
* Build all constructors as they appear on the ArezComponent class.
* Arez Observable fields are populated as required and parameters are passed up to superclass.
*/
private void buildConstructors( @Nonnull final TypeSpec.Builder builder,
@Nonnull final Types typeUtils )
{
final boolean requiresDeprecatedSuppress = hasDeprecatedElements();
for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( getElement() ) )
{
final ExecutableType methodType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), constructor );
builder.addMethod( buildConstructor( constructor, methodType, requiresDeprecatedSuppress ) );
}
}
/**
* Build a constructor based on the supplied constructor
*/
@Nonnull
private MethodSpec buildConstructor( @Nonnull final ExecutableElement constructor,
@Nonnull final ExecutableType constructorType,
final boolean requiresDeprecatedSuppress )
{
final MethodSpec.Builder builder = MethodSpec.constructorBuilder();
ProcessorUtil.copyAccessModifiers( constructor, builder );
ProcessorUtil.copyExceptions( constructorType, builder );
ProcessorUtil.copyTypeParameters( constructorType, builder );
if ( requiresDeprecatedSuppress )
{
builder.addAnnotation( AnnotationSpec.builder( SuppressWarnings.class )
.addMember( "value", "$S", "deprecation" )
.build() );
}
if ( _inject )
{
builder.addAnnotation( GeneratorUtil.INJECT_CLASSNAME );
}
final StringBuilder superCall = new StringBuilder();
superCall.append( "super(" );
final ArrayList<String> parameterNames = new ArrayList<>();
boolean firstParam = true;
for ( final VariableElement element : constructor.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
superCall.append( "," );
}
firstParam = false;
superCall.append( "$N" );
}
superCall.append( ")" );
builder.addStatement( superCall.toString(), parameterNames.toArray() );
final List<ObservableDescriptor> initializers =
getObservables()
.stream()
.filter( ObservableDescriptor::requireInitializer )
.collect( Collectors.toList() );
for ( final ObservableDescriptor observable : initializers )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( observable.getGetterType().getReturnType() ),
observable.getName(),
Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( observable.getGetter(), param );
builder.addParameter( param.build() );
final boolean isPrimitive = TypeName.get( observable.getGetterType().getReturnType() ).isPrimitive();
if ( isPrimitive )
{
builder.addStatement( "this.$N = $N", observable.getDataFieldName(), observable.getName() );
}
else
{
builder.addStatement( "this.$N = $T.requireNonNull( $N )",
observable.getDataFieldName(),
Objects.class,
observable.getName() );
}
}
builder.addStatement( "this.$N = $T.areZonesEnabled() ? $T.context() : null",
GeneratorUtil.CONTEXT_FIELD_NAME,
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.AREZ_CLASSNAME );
// Synthesize Id if required
if ( null == _componentId )
{
if ( _nameIncludesId )
{
if ( hasRepository() )
{
builder.addStatement( "this.$N = $N++", GeneratorUtil.ID_FIELD_NAME, GeneratorUtil.NEXT_ID_FIELD_NAME );
}
else
{
builder.addStatement(
"this.$N = ( $T.areNativeComponentsEnabled() || $T.areNativeComponentsEnabled() ) ? $N++ : 0L",
GeneratorUtil.ID_FIELD_NAME,
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.NEXT_ID_FIELD_NAME );
}
}
else
{
builder.addStatement( "this.$N = $T.areNativeComponentsEnabled() ? $N++ : 0L",
GeneratorUtil.ID_FIELD_NAME,
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.NEXT_ID_FIELD_NAME );
}
}
builder.addStatement( "this.$N = $T.COMPONENT_INITIALIZED",
GeneratorUtil.STATE_FIELD_NAME,
GeneratorUtil.COMPONENT_STATE_CLASSNAME );
// Create component representation if required
{
final StringBuilder sb = new StringBuilder();
final ArrayList<Object> params = new ArrayList<>();
sb.append( "this.$N = $T.areNativeComponentsEnabled() ? " +
"$N().createComponent( $S, $N(), $T.areNamesEnabled() ? $N() :" +
" null" );
params.add( GeneratorUtil.COMPONENT_FIELD_NAME );
params.add( GeneratorUtil.AREZ_CLASSNAME );
params.add( getContextMethodName() );
params.add( _type );
params.add( getIdMethodName() );
params.add( GeneratorUtil.AREZ_CLASSNAME );
params.add( getComponentNameMethodName() );
if ( null != _preDispose || null != _postDispose )
{
sb.append( ", " );
if ( null != _preDispose )
{
sb.append( "() -> super.$N()" );
params.add( _preDispose.getSimpleName().toString() );
}
if ( null != _postDispose )
{
sb.append( ", () -> super.$N()" );
params.add( _postDispose.getSimpleName().toString() );
}
}
sb.append( " ) : null" );
builder.addStatement( sb.toString(), params.toArray() );
}
{
builder.addStatement( "this.$N = $N().createObservable( " +
"$T.areNativeComponentsEnabled() ? this.$N : null, " +
"$T.areNamesEnabled() ? $N() + $S : null, " +
"$T.arePropertyIntrospectorsEnabled() ? () -> this.$N >= 0 : null )",
GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME,
getContextMethodName(),
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.COMPONENT_FIELD_NAME,
GeneratorUtil.AREZ_CLASSNAME,
getComponentNameMethodName(),
".isDisposed",
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.STATE_FIELD_NAME );
}
if ( _disposeOnDeactivate )
{
builder.addStatement( "this.$N = $N().createComputedValue( " +
"$T.areNativeComponentsEnabled() ? this.$N : null, " +
"$T.areNamesEnabled() ? $N() + $S : null, " +
"() -> $N(), $T.defaultComparator(), null, () -> dispose(), null, null )",
GeneratorUtil.DISPOSE_ON_DEACTIVATE_FIELD_NAME,
getContextMethodName(),
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.COMPONENT_FIELD_NAME,
GeneratorUtil.AREZ_CLASSNAME,
getComponentNameMethodName(),
".disposeOnDeactivate",
GeneratorUtil.INTERNAL_OBSERVE_METHOD_NAME,
GeneratorUtil.EQUALITY_COMPARATOR_CLASSNAME );
}
_roObservables.forEach( observable -> observable.buildInitializer( builder ) );
_roComputeds.forEach( computed -> computed.buildInitializer( builder ) );
_roMemoizes.forEach( e -> e.buildInitializer( builder ) );
_roAutoruns.forEach( autorun -> autorun.buildInitializer( builder ) );
_roTrackeds.forEach( tracked -> tracked.buildInitializer( builder ) );
if ( !getCascadeOnDisposeDependencies().isEmpty() )
{
buildCascadeOnDisposeInitializer( builder );
}
if ( !getSetNullOnDisposeDependencies().isEmpty() )
{
buildSetNullOnDisposeInitializer( builder );
}
builder.addStatement( "this.$N = $T.COMPONENT_CONSTRUCTED",
GeneratorUtil.STATE_FIELD_NAME,
GeneratorUtil.COMPONENT_STATE_CLASSNAME );
final ExecutableElement postConstruct = getPostConstruct();
if ( null != postConstruct )
{
builder.addStatement( "super.$N()", postConstruct.getSimpleName().toString() );
}
final CodeBlock.Builder componentEnabledBlock = CodeBlock.builder();
componentEnabledBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )",
GeneratorUtil.AREZ_CLASSNAME );
componentEnabledBlock.addStatement( "this.$N.complete()", GeneratorUtil.COMPONENT_FIELD_NAME );
componentEnabledBlock.endControlFlow();
builder.addCode( componentEnabledBlock.build() );
if ( !_deferSchedule &&
( !_roAutoruns.isEmpty() ||
!_roDependencies.isEmpty() ||
_computeds.values().stream().anyMatch( ComputedDescriptor::isKeepAlive ) ) )
{
builder.addStatement( "this.$N = $T.COMPONENT_COMPLETE",
GeneratorUtil.STATE_FIELD_NAME,
GeneratorUtil.COMPONENT_STATE_CLASSNAME );
builder.addStatement( "$N().triggerScheduler()", getContextMethodName() );
}
builder.addStatement( "this.$N = $T.COMPONENT_READY",
GeneratorUtil.STATE_FIELD_NAME,
GeneratorUtil.COMPONENT_STATE_CLASSNAME );
return builder.build();
}
private void buildCascadeOnDisposeInitializer( @Nonnull final MethodSpec.Builder builder )
{
builder.addStatement(
"this.$N = $N().when( $T.areNativeComponentsEnabled() ? this.$N : null, $T.areNamesEnabled() ? $N() + $S : null, false, () -> $N().map( $T::call ).peek( $T::observe ).anyMatch( $T::isDisposed ), () -> $T.dispose( this ), true, false )",
GeneratorUtil.CASCADE_ON_DISPOSE_FIELD_NAME,
getContextMethodName(),
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.COMPONENT_FIELD_NAME,
GeneratorUtil.AREZ_CLASSNAME,
getComponentNameMethodName(),
".cascadeOnDispose",
GeneratorUtil.GET_CASCADE_ON_DISPOSE_DEPS_METHOD_NAME,
GeneratorUtil.SAFE_FUNCTION_CLASSNAME,
GeneratorUtil.COMPONENT_OBSERVABLE_CLASSNAME,
GeneratorUtil.DISPOSABLE_CLASSNAME,
GeneratorUtil.DISPOSABLE_CLASSNAME );
}
private void buildSetNullOnDisposeInitializer( @Nonnull final MethodSpec.Builder builder )
{
builder.addStatement(
"this.$N = $N().autorun( $T.areNativeComponentsEnabled() ? this.$N : null, $T.areNamesEnabled() ? $N() + $S : null, true, () -> $N(), true, false )",
GeneratorUtil.SET_NULL_ON_DISPOSE_FIELD_NAME,
getContextMethodName(),
GeneratorUtil.AREZ_CLASSNAME,
GeneratorUtil.COMPONENT_FIELD_NAME,
GeneratorUtil.AREZ_CLASSNAME,
getComponentNameMethodName(),
".setNullOnDispose",
GeneratorUtil.SET_NULL_ON_DISPOSE_METHOD_NAME );
}
boolean shouldGenerateComponentDaggerModule()
{
return _dagger;
}
@Nonnull
TypeSpec buildComponentDaggerModule()
throws ArezProcessorException
{
assert shouldGenerateComponentDaggerModule();
final TypeSpec.Builder builder = TypeSpec.interfaceBuilder( getComponentDaggerModuleName() ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) );
addOriginatingTypes( getElement(), builder );
addGeneratedAnnotation( builder );
builder.addAnnotation( GeneratorUtil.DAGGER_MODULE_CLASSNAME );
builder.addModifiers( Modifier.PUBLIC );
final MethodSpec.Builder method = MethodSpec.methodBuilder( "provideComponent" ).
addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
addAnnotation( GeneratorUtil.DAGGER_PROVIDES_CLASSNAME ).
addModifiers( Modifier.STATIC, Modifier.PUBLIC ).
addParameter( ClassName.get( getPackageName(), getArezClassName() ), "component", Modifier.FINAL ).
addStatement( "return component" ).
returns( ClassName.get( getElement() ) );
if ( null != _scopeAnnotation )
{
final DeclaredType annotationType = _scopeAnnotation.getAnnotationType();
final TypeElement typeElement = (TypeElement) annotationType.asElement();
method.addAnnotation( ClassName.get( typeElement ) );
}
builder.addMethod( method.build() );
return builder.build();
}
boolean hasRepository()
{
return null != _repositoryExtensions;
}
@SuppressWarnings( "ConstantConditions" )
void configureRepository( @Nonnull final String name,
@Nonnull final List<TypeElement> extensions,
@Nonnull final String repositoryInjectConfig,
@Nonnull final String repositoryDaggerConfig )
{
assert null != name;
assert null != extensions;
_repositoryInjectConfig = repositoryInjectConfig;
_repositoryDaggerConfig = repositoryDaggerConfig;
for ( final TypeElement extension : extensions )
{
if ( ElementKind.INTERFACE != extension.getKind() )
{
throw new ArezProcessorException( "Class annotated with @Repository defined an extension that is " +
"not an interface. Extension: " + extension.getQualifiedName(),
getElement() );
}
for ( final Element enclosedElement : extension.getEnclosedElements() )
{
if ( ElementKind.METHOD == enclosedElement.getKind() )
{
final ExecutableElement method = (ExecutableElement) enclosedElement;
if ( !method.isDefault() &&
!( method.getSimpleName().toString().equals( "self" ) && 0 == method.getParameters().size() ) )
{
throw new ArezProcessorException( "Class annotated with @Repository defined an extension that has " +
"a non default method. Extension: " + extension.getQualifiedName() +
" Method: " + method, getElement() );
}
}
}
}
_repositoryExtensions = extensions;
}
/**
* Build the enhanced class for the component.
*/
@Nonnull
TypeSpec buildRepository( @Nonnull final Types typeUtils )
throws ArezProcessorException
{
assert null != _repositoryExtensions;
final TypeElement element = getElement();
final ClassName arezType = ClassName.get( getPackageName(), getArezClassName() );
final TypeSpec.Builder builder = TypeSpec.classBuilder( getRepositoryName() ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) );
addOriginatingTypes( element, builder );
addGeneratedAnnotation( builder );
final boolean addSingletonAnnotation =
"ENABLE".equals( _repositoryInjectConfig ) ||
( "AUTODETECT".equals( _repositoryInjectConfig ) && _injectClassesPresent );
final AnnotationSpec.Builder arezComponent =
AnnotationSpec.builder( ClassName.bestGuess( Constants.COMPONENT_ANNOTATION_CLASSNAME ) );
if ( !addSingletonAnnotation )
{
arezComponent.addMember( "nameIncludesId", "false" );
}
if ( !"AUTODETECT".equals( _repositoryInjectConfig ) )
{
arezComponent.addMember( "inject", "$T.$N", GeneratorUtil.INJECTIBLE_CLASSNAME, _repositoryInjectConfig );
}
if ( !"AUTODETECT".equals( _repositoryDaggerConfig ) )
{
arezComponent.addMember( "dagger", "$T.$N", GeneratorUtil.INJECTIBLE_CLASSNAME, _repositoryDaggerConfig );
}
builder.addAnnotation( arezComponent.build() );
if ( addSingletonAnnotation )
{
builder.addAnnotation( GeneratorUtil.SINGLETON_CLASSNAME );
}
builder.superclass( ParameterizedTypeName.get( GeneratorUtil.ABSTRACT_REPOSITORY_CLASSNAME,
getIdType().box(),
ClassName.get( element ),
ClassName.get( getPackageName(), getRepositoryName() ) ) );
_repositoryExtensions.forEach( e -> builder.addSuperinterface( TypeName.get( e.asType() ) ) );
ProcessorUtil.copyAccessModifiers( element, builder );
builder.addModifiers( Modifier.ABSTRACT );
//Add the default access, no-args constructor
builder.addMethod( MethodSpec.constructorBuilder().build() );
// Add the factory method
builder.addMethod( buildFactoryMethod() );
for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( element ) )
{
final ExecutableType methodType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), constructor );
builder.addMethod( buildRepositoryCreate( constructor, methodType, arezType ) );
}
if ( null != _componentId )
{
builder.addMethod( buildFindByIdMethod() );
builder.addMethod( buildGetByIdMethod() );
}
return builder.build();
}
private void addOriginatingTypes( @Nonnull final TypeElement element, @Nonnull final TypeSpec.Builder builder )
{
builder.addOriginatingElement( element );
ProcessorUtil.getSuperTypes( element ).forEach( builder::addOriginatingElement );
}
@Nonnull
private String getArezClassName()
{
return getNestedClassPrefix() + "Arez_" + getElement().getSimpleName();
}
@Nonnull
private String getComponentDaggerModuleName()
{
return getNestedClassPrefix() + getElement().getSimpleName() + "DaggerModule";
}
@Nonnull
private String getArezRepositoryName()
{
return "Arez_" + getNestedClassPrefix() + getElement().getSimpleName() + "Repository";
}
@Nonnull
private String getRepositoryName()
{
return getNestedClassPrefix() + getElement().getSimpleName() + "Repository";
}
@Nonnull
private MethodSpec buildFindByIdMethod()
{
assert null != _componentId;
final MethodSpec.Builder method = MethodSpec.methodBuilder( "findBy" + getIdName() ).
addModifiers( Modifier.FINAL ).
addParameter( ParameterSpec.builder( getIdType(), "id", Modifier.FINAL ).build() ).
addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME ).
returns( TypeName.get( getElement().asType() ) ).
addStatement( "return findByArezId( id )" );
ProcessorUtil.copyAccessModifiers( getElement(), method );
return method.build();
}
@Nonnull
private MethodSpec buildGetByIdMethod()
{
final TypeName entityType = TypeName.get( getElement().asType() );
final MethodSpec.Builder method = MethodSpec.methodBuilder( "getBy" + getIdName() ).
addModifiers( Modifier.FINAL ).
addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
addParameter( ParameterSpec.builder( getIdType(), "id", Modifier.FINAL ).build() ).
returns( entityType ).
addStatement( "return getByArezId( id )" );
ProcessorUtil.copyAccessModifiers( getElement(), method );
return method.build();
}
@Nonnull
private MethodSpec buildFactoryMethod()
{
final MethodSpec.Builder method = MethodSpec.methodBuilder( "newRepository" ).
addModifiers( Modifier.STATIC ).
addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
returns( ClassName.get( getPackageName(), getRepositoryName() ) ).
addStatement( "return new $T()", ClassName.get( getPackageName(), getArezRepositoryName() ) );
ProcessorUtil.copyAccessModifiers( getElement(), method );
return method.build();
}
@Nonnull
private MethodSpec buildRepositoryCreate( @Nonnull final ExecutableElement constructor,
@Nonnull final ExecutableType methodType,
@Nonnull final ClassName arezType )
{
final String suffix = constructor.getParameters().stream().
map( p -> p.getSimpleName().toString() ).collect( Collectors.joining( "_" ) );
final String actionName = "create" + ( suffix.isEmpty() ? "" : "_" + suffix );
final AnnotationSpec annotationSpec =
AnnotationSpec.builder( ClassName.bestGuess( Constants.ACTION_ANNOTATION_CLASSNAME ) ).
addMember( "name", "$S", actionName ).build();
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "create" ).
addAnnotation( annotationSpec ).
addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
returns( TypeName.get( asDeclaredType() ) );
ProcessorUtil.copyAccessModifiers( getElement(), builder );
ProcessorUtil.copyExceptions( methodType, builder );
ProcessorUtil.copyTypeParameters( methodType, builder );
final StringBuilder newCall = new StringBuilder();
newCall.append( "final $T entity = new $T(" );
final ArrayList<Object> parameters = new ArrayList<>();
parameters.add( arezType );
parameters.add( arezType );
boolean firstParam = true;
for ( final VariableElement element : constructor.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameters.add( element.getSimpleName().toString() );
if ( !firstParam )
{
newCall.append( "," );
}
firstParam = false;
newCall.append( "$N" );
}
newCall.append( ")" );
builder.addStatement( newCall.toString(), parameters.toArray() );
builder.addStatement( "registerEntity( entity )" );
builder.addStatement( "return entity" );
return builder.build();
}
@Nonnull
String getPackageName()
{
return _packageElement.getQualifiedName().toString();
}
@Nonnull
private String getIdMethodName()
{
/*
* Note that it is a deliberate choice to not use getArezId() as that will box Id which for the
* "normal" case involves converting a long to a Long and it was decided that the slight increase in
* code size was worth the slightly reduced memory pressure.
*/
return null != _componentId ? _componentId.getSimpleName().toString() : GeneratorUtil.ID_FIELD_NAME;
}
@Nonnull
private String getIdName()
{
assert null != _componentId;
final String name = ProcessorUtil.deriveName( _componentId, GETTER_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( null != name )
{
return Character.toUpperCase( name.charAt( 0 ) ) + ( name.length() > 1 ? name.substring( 1 ) : "" );
}
else
{
return "Id";
}
}
@Nonnull
private TypeName getIdType()
{
return null == _componentIdMethodType ?
TypeName.LONG :
TypeName.get( _componentIdMethodType.getReturnType() );
}
@SuppressWarnings( "unchecked" )
private <T> T getAnnotationParameter( @Nonnull final AnnotationMirror annotation,
@Nonnull final String parameterName )
{
return (T) ProcessorUtil.getAnnotationValue( _elements,
annotation,
parameterName ).getValue();
}
private void addGeneratedAnnotation( @Nonnull final TypeSpec.Builder builder )
{
builder.addAnnotation( AnnotationSpec.builder( getGeneratedAnnotation() ).
addMember( "value", "$S", ArezProcessor.class.getName() ).
build() );
}
@Nonnull
private Class<?> getGeneratedAnnotation()
{
try
{
return Class.forName( SourceVersion.RELEASE_8.compareTo( _sourceVersion ) < 0 ?
"javax.annotation.processing.Generated" :
"javax.annotation.Generated"
);
}
catch ( final ClassNotFoundException e )
{
throw new ArezProcessorException( "@ArezComponent unable to determine correct @Generated annotation",
getElement() );
}
}
}
|
package konid.soxzz5.fitfood.fitfood_addrecipe_step;
import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import konid.soxzz5.fitfood.R;
import konid.soxzz5.fitfood.fitfood_addrecipe_listview.PrepStep;
import konid.soxzz5.fitfood.fitfood_addrecipe_listview.PrepStepsListAdapter;
import konid.soxzz5.fitfood.utils.utils;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View.OnClickListener;
import android.widget.TextView;
/**
* This application creates a listview where the ordering of the data set
* can be modified in response to user touch events.
*
* An item in the listview is selected via a long press event and is then
* moved around by tracking and following the movement of the user's finger.
* When the item is released, it animates to its new position within the listview.
*/
public class addrecipe_step5 extends Fragment implements OnClickListener, OnItemClickListener {
ListView mListView;
List<PrepStep> prepSteps;
private List<PrepStep> parentList;
String step;
boolean first_item;
PrepStepsListAdapter adapter;
boolean valid_step;
int nbSteps;
Context _context;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.addrecipe_step5, container, false);
nbSteps = 0;
mListView = (ListView) v.findViewById(R.id.step5_listview);
final EditText et_step = (EditText) v.findViewById(R.id.step5_et_step);
final ImageView bt_add = (ImageView) v.findViewById(R.id.step5_bt_add);
final TextView info_error = (TextView) v.findViewById(R.id.info_error);
first_item =false;
valid_step=false;
_context=getContext();
if(parentList != null && parentList.size()>0) {
prepSteps = parentList;
adapter = new PrepStepsListAdapter(_context, prepSteps,this);
mListView.setAdapter(adapter);
if(this.prepSteps.size()==1) {
first_item=true;
} else {
adapter.notifyDataSetChanged();
}
nbSteps = prepSteps.size();
} else prepSteps = new ArrayList<PrepStep>();
et_step.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(utils.findMatch(et_step.getText().toString(),"^[\\s\\w\\.,!\\-'\"\\+*:]{10,100}$")){
step = et_step.getText().toString();
valid_step=true;
info_error.setText("");
} else {
valid_step=false;
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
bt_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(valid_step) {
prepSteps.add(new PrepStep(step,getnbItem()+1));
addToList();
valid_step=false;
et_step.setText("");
} else {
info_error.setText(R.string.step5_invalid_step);
}
}
});
return v;
}
private void addToList()
{
nbSteps++;
if(!first_item)
{
adapter = new PrepStepsListAdapter(getContext(), prepSteps,this);
mListView.setAdapter(adapter);
first_item=true;
}
else
{
adapter.notifyDataSetChanged();
}
}
//Actualisation de la liste
@Override
public void onClick(View v) {
int position = (Integer) v.getTag(R.id.key_position);
if(v.getId() == R.id.handler){
nbSteps
refreshPositions(position);
prepSteps.remove(position);
adapter.notifyDataSetChanged();
}
}
//Allow to refresh steps numbers
private void refreshPositions(int position) {
int i=0;
for (i=position;i<this.prepSteps.size();i++) {
this.prepSteps.get(i).decreasePosition();
}
adapter.notifyDataSetChanged();
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//NOTHING TO DO
}
public List<PrepStep> getPrepSteps() {
return prepSteps;
}
public int getnbItem() {
return nbSteps;
}
public void setParentList(List<PrepStep> parentList) {
this.parentList = parentList;
}
}
|
package com.hubspot.singularity.scheduler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.mesos.client.MesosClient;
import com.hubspot.mesos.json.MesosTaskMonitorObject;
import com.hubspot.singularity.InvalidSingularityTaskIdException;
import com.hubspot.singularity.RequestUtilization;
import com.hubspot.singularity.SingularityClusterUtilization;
import com.hubspot.singularity.SingularityDeleteResult;
import com.hubspot.singularity.SingularityDeploy;
import com.hubspot.singularity.SingularityDeployStatistics;
import com.hubspot.singularity.SingularityRequestWithState;
import com.hubspot.singularity.SingularitySlave;
import com.hubspot.singularity.SingularitySlaveUsage;
import com.hubspot.singularity.SingularitySlaveUsage.ResourceUsageType;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskCurrentUsage;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityTaskUsage;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.DeployManager;
import com.hubspot.singularity.data.RequestManager;
import com.hubspot.singularity.data.TaskManager;
import com.hubspot.singularity.data.UsageManager;
import com.hubspot.singularity.sentry.SingularityExceptionNotifier;
public class SingularityUsagePoller extends SingularityLeaderOnlyPoller {
private static final Logger LOG = LoggerFactory.getLogger(SingularityUsagePoller.class);
private final SingularityConfiguration configuration;
private final MesosClient mesosClient;
private final UsageManager usageManager;
private final SingularityUsageHelper usageHelper;
private final SingularityExceptionNotifier exceptionNotifier;
private final RequestManager requestManager;
private final DeployManager deployManager;
private final TaskManager taskManager;
@Inject
SingularityUsagePoller(SingularityConfiguration configuration,
SingularityUsageHelper usageHelper,
UsageManager usageManager,
MesosClient mesosClient,
SingularityExceptionNotifier exceptionNotifier,
RequestManager requestManager,
DeployManager deployManager,
TaskManager taskManager) {
super(configuration.getCheckUsageEveryMillis(), TimeUnit.MILLISECONDS);
this.configuration = configuration;
this.usageHelper = usageHelper;
this.mesosClient = mesosClient;
this.usageManager = usageManager;
this.exceptionNotifier = exceptionNotifier;
this.requestManager = requestManager;
this.deployManager = deployManager;
this.taskManager = taskManager;
}
@Override
public void runActionOnPoll() {
Map<String, RequestUtilization> utilizationPerRequestId = new HashMap<>();
final long now = System.currentTimeMillis();
long totalMemBytesUsed = 0;
long totalMemBytesAvailable = 0;
double totalCpuUsed = 0.00;
double totalCpuAvailable = 0.00;
long totalDiskBytesUsed = 0;
long totalDiskBytesAvailable = 0;
for (SingularitySlave slave : usageHelper.getSlavesToTrackUsageFor()) {
Map<ResourceUsageType, Number> longRunningTasksUsage = new HashMap<>();
longRunningTasksUsage.put(ResourceUsageType.MEMORY_BYTES_USED, 0);
longRunningTasksUsage.put(ResourceUsageType.CPU_USED, 0);
Optional<Long> memoryMbTotal = Optional.absent();
Optional<Double> cpusTotal = Optional.absent();
Optional<Long> diskMbTotal = Optional.absent();
long memoryMbReservedOnSlave = 0;
double cpuReservedOnSlave = 0;
long diskMbReservedOnSlave = 0;
long memoryBytesUsedOnSlave = 0;
double cpusUsedOnSlave = 0;
long diskMbUsedOnSlave = 0;
try {
List<MesosTaskMonitorObject> allTaskUsage = mesosClient.getSlaveResourceUsage(slave.getHost());
for (MesosTaskMonitorObject taskUsage : allTaskUsage) {
String taskId = taskUsage.getSource();
SingularityTaskId task;
try {
task = SingularityTaskId.valueOf(taskId);
} catch (InvalidSingularityTaskIdException e) {
LOG.error("Couldn't get SingularityTaskId for {}", taskUsage);
continue;
}
SingularityTaskUsage latestUsage = getUsage(taskUsage);
List<SingularityTaskUsage> pastTaskUsages = usageManager.getTaskUsage(taskId);
clearOldUsage(taskId);
usageManager.saveSpecificTaskUsage(taskId, latestUsage);
Optional<SingularityTask> maybeTask = taskManager.getTask(task);
if (maybeTask.isPresent() && maybeTask.get().getTaskRequest().getDeploy().getResources().isPresent()) {
double memoryMbReservedForTask = maybeTask.get().getTaskRequest().getDeploy().getResources().get().getMemoryMb();
double cpuReservedForTask = maybeTask.get().getTaskRequest().getDeploy().getResources().get().getCpus();
double diskMbReservedForTask = maybeTask.get().getTaskRequest().getDeploy().getResources().get().getDiskMb();
memoryMbReservedOnSlave += memoryMbReservedForTask;
cpuReservedOnSlave += cpuReservedForTask;
diskMbReservedOnSlave += diskMbReservedForTask;
updateRequestUtilization(utilizationPerRequestId, pastTaskUsages, latestUsage, task, memoryMbReservedForTask, cpuReservedForTask, diskMbReservedForTask);
}
memoryBytesUsedOnSlave += latestUsage.getMemoryTotalBytes();
diskMbUsedOnSlave += latestUsage.getDiskTotalBytes();
if (!pastTaskUsages.isEmpty()) {
SingularityTaskUsage lastUsage = pastTaskUsages.get(pastTaskUsages.size() - 1);
double taskCpusUsed = ((latestUsage.getCpuSeconds() - lastUsage.getCpuSeconds()) / (latestUsage.getTimestamp() - lastUsage.getTimestamp()));
if (isLongRunning(task) || isConsideredLongRunning(task)) {
updateLongRunningTasksUsage(longRunningTasksUsage, latestUsage.getMemoryTotalBytes(), taskCpusUsed);
}
SingularityTaskCurrentUsage currentUsage = new SingularityTaskCurrentUsage(latestUsage.getMemoryTotalBytes(), now, taskCpusUsed);
usageManager.saveCurrentTaskUsage(taskId, currentUsage);
cpusUsedOnSlave += taskCpusUsed;
}
}
if (!slave.getResources().isPresent() ||
!slave.getResources().get().getMemoryMegaBytes().isPresent() ||
!slave.getResources().get().getNumCpus().isPresent()) {
LOG.debug("Could not find slave or resources for slave {}", slave.getId());
} else {
memoryMbTotal = Optional.of(slave.getResources().get().getMemoryMegaBytes().get().longValue());
cpusTotal = Optional.of(slave.getResources().get().getNumCpus().get().doubleValue());
diskMbTotal = Optional.of(slave.getResources().get().getDiskSpace().get());
}
SingularitySlaveUsage slaveUsage = new SingularitySlaveUsage(cpusUsedOnSlave, cpuReservedOnSlave, cpusTotal, memoryBytesUsedOnSlave, memoryMbReservedOnSlave, memoryMbTotal, diskMbUsedOnSlave, diskMbReservedOnSlave, diskMbTotal, longRunningTasksUsage, allTaskUsage.size(), now);
List<Long> slaveTimestamps = usageManager.getSlaveUsageTimestamps(slave.getId());
if (slaveTimestamps.size() + 1 > configuration.getNumUsageToKeep()) {
usageManager.deleteSpecificSlaveUsage(slave.getId(), slaveTimestamps.get(0));
}
if (slaveUsage.getMemoryBytesTotal().isPresent() && slaveUsage.getCpusTotal().isPresent()) {
totalMemBytesUsed += slaveUsage.getMemoryBytesUsed();
totalCpuUsed += slaveUsage.getCpusUsed();
totalDiskBytesUsed += slaveUsage.getDiskBytesUsed();
totalMemBytesAvailable += slaveUsage.getMemoryBytesTotal().get();
totalCpuAvailable += slaveUsage.getCpusTotal().get();
totalDiskBytesAvailable += slaveUsage.getDiskBytesTotal().get();
}
LOG.debug("Saving slave {} usage {}", slave.getHost(), slaveUsage);
usageManager.saveSpecificSlaveUsageAndSetCurrent(slave.getId(), slaveUsage);
} catch (Exception e) {
String message = String.format("Could not get slave usage for host %s", slave.getHost());
LOG.error(message, e);
exceptionNotifier.notify(message, e);
}
}
usageManager.saveClusterUtilization(getClusterUtilization(utilizationPerRequestId, totalMemBytesUsed, totalMemBytesAvailable, totalCpuUsed, totalCpuAvailable, totalDiskBytesUsed, totalDiskBytesAvailable, now));
}
private SingularityTaskUsage getUsage(MesosTaskMonitorObject taskUsage) {
double cpuSeconds = taskUsage.getStatistics().getCpusSystemTimeSecs() + taskUsage.getStatistics().getCpusUserTimeSecs();
return new SingularityTaskUsage(taskUsage.getStatistics().getMemTotalBytes(), taskUsage.getStatistics().getTimestampSeconds(), cpuSeconds, taskUsage.getStatistics().getDiskUsedBytes());
}
private boolean isLongRunning(SingularityTaskId task) {
Optional<SingularityRequestWithState> request = requestManager.getRequest(task.getRequestId());
if (request.isPresent()) {
return request.get().getRequest().getRequestType().isLongRunning();
}
LOG.warn("Couldn't find request id {} for task {}", task.getRequestId(), task.getId());
return false;
}
private boolean isConsideredLongRunning(SingularityTaskId task) {
final Optional<SingularityDeployStatistics> deployStatistics = deployManager.getDeployStatistics(task.getRequestId(), task.getDeployId());
return deployStatistics.isPresent() && deployStatistics.get().getAverageRuntimeMillis().isPresent() &&
deployStatistics.get().getAverageRuntimeMillis().get() >= configuration.getConsiderNonLongRunningTaskLongRunningAfterRunningForSeconds();
}
private void updateLongRunningTasksUsage(Map<ResourceUsageType, Number> longRunningTasksUsage, long memBytesUsed, double cpuUsed) {
longRunningTasksUsage.compute(ResourceUsageType.MEMORY_BYTES_USED, (k, v) -> (v == null) ? memBytesUsed : v.longValue() + memBytesUsed);
longRunningTasksUsage.compute(ResourceUsageType.CPU_USED, (k, v) -> (v == null) ? cpuUsed : v.doubleValue() + cpuUsed);
}
private void updateRequestUtilization(Map<String, RequestUtilization> utilizationPerRequestId,
List<SingularityTaskUsage> pastTaskUsages,
SingularityTaskUsage latestUsage,
SingularityTaskId task,
double memoryMbReservedForTask,
double cpuReservedForTask,
double diskMbReservedForTask) {
String requestId = task.getRequestId();
RequestUtilization requestUtilization = utilizationPerRequestId.getOrDefault(requestId, new RequestUtilization(requestId, task.getDeployId()));
long curMaxMemBytesUsed = 0;
long curMinMemBytesUsed = Long.MAX_VALUE;
double curMaxCpuUsed = 0;
double curMinCpuUsed = Double.MAX_VALUE;
long curMaxDiskBytesUsed = 0;
long curMinDiskBytesUsed = Long.MAX_VALUE;
if (utilizationPerRequestId.containsKey(requestId)) {
curMaxMemBytesUsed = requestUtilization.getMaxMemBytesUsed();
curMinMemBytesUsed = requestUtilization.getMinMemBytesUsed();
curMaxCpuUsed = requestUtilization.getMaxCpuUsed();
curMinCpuUsed = requestUtilization.getMinCpuUsed();
curMaxDiskBytesUsed = requestUtilization.getMaxDiskBytesUsed();
curMinDiskBytesUsed = requestUtilization.getMinDiskBytesUsed();
}
List<SingularityTaskUsage> pastTaskUsagesCopy = copyUsages(pastTaskUsages, latestUsage, task);
int numTasks = pastTaskUsagesCopy.size() - 1;
for (int i = 0; i < numTasks; i++) {
SingularityTaskUsage olderUsage = pastTaskUsagesCopy.get(i);
SingularityTaskUsage newerUsage = pastTaskUsagesCopy.get(i + 1);
double cpusUsed = (newerUsage.getCpuSeconds() - olderUsage.getCpuSeconds()) / (newerUsage.getTimestamp() - olderUsage.getTimestamp());
curMaxCpuUsed = Math.max(cpusUsed, curMaxCpuUsed);
curMinCpuUsed = Math.min(cpusUsed, curMinCpuUsed);
curMaxMemBytesUsed = Math.max(newerUsage.getMemoryTotalBytes(), curMaxMemBytesUsed);
curMinMemBytesUsed = Math.min(newerUsage.getMemoryTotalBytes(), curMinMemBytesUsed);
curMaxDiskBytesUsed = Math.max(newerUsage.getDiskTotalBytes(), curMaxDiskBytesUsed);
curMinDiskBytesUsed = Math.min(newerUsage.getDiskTotalBytes(), curMinDiskBytesUsed);
requestUtilization
.addCpuUsed(cpusUsed)
.addMemBytesUsed(newerUsage.getMemoryTotalBytes())
.addDiskBytesUsed(newerUsage.getDiskTotalBytes())
.incrementTaskCount();
}
requestUtilization
.addMemBytesReserved((long) (memoryMbReservedForTask * SingularitySlaveUsage.BYTES_PER_MEGABYTE * numTasks))
.addCpuReserved(cpuReservedForTask * numTasks)
.addDiskBytesReserved((long) diskMbReservedForTask * SingularitySlaveUsage.BYTES_PER_MEGABYTE * numTasks)
.setMaxCpuUsed(curMaxCpuUsed)
.setMinCpuUsed(curMinCpuUsed)
.setMaxMemBytesUsed(curMaxMemBytesUsed)
.setMinMemBytesUsed(curMinMemBytesUsed)
.setMaxDiskBytesUsed(curMaxDiskBytesUsed)
.setMinDiskBytesUsed(curMinDiskBytesUsed);
utilizationPerRequestId.put(requestId, requestUtilization);
}
private List<SingularityTaskUsage> copyUsages(List<SingularityTaskUsage> pastTaskUsages, SingularityTaskUsage latestUsage, SingularityTaskId task) {
List<SingularityTaskUsage> pastTaskUsagesCopy = new ArrayList<>();
pastTaskUsagesCopy.add(new SingularityTaskUsage(0, TimeUnit.MILLISECONDS.toSeconds(task.getStartedAt()), 0, 0)); // to calculate oldest cpu usage
pastTaskUsagesCopy.addAll(pastTaskUsages);
pastTaskUsagesCopy.add(latestUsage);
return pastTaskUsagesCopy;
}
private SingularityClusterUtilization getClusterUtilization(Map<String, RequestUtilization> utilizationPerRequestId,
long totalMemBytesUsed,
long totalMemBytesAvailable,
double totalCpuUsed,
double totalCpuAvailable,
long totalDiskBytesUsed,
long totalDiskBytesAvailable,
long now) {
int numRequestsWithUnderUtilizedCpu = 0;
int numRequestsWithOverUtilizedCpu = 0;
int numRequestsWithUnderUtilizedMemBytes = 0;
int numRequestsWithUnderUtilizedDiskBytes = 0;
double totalUnderUtilizedCpu = 0;
double totalOverUtilizedCpu = 0;
long totalUnderUtilizedMemBytes = 0;
long totalUnderUtilizedDiskBytes = 0;
double maxUnderUtilizedCpu = 0;
double maxOverUtilizedCpu = 0;
long maxUnderUtilizedMemBytes = 0;
long maxUnderUtilizedDiskBytes = 0;
String maxUnderUtilizedCpuRequestId = null;
String maxOverUtilizedCpuRequestId = null;
String maxUnderUtilizedMemBytesRequestId = null;
String maxUnderUtilizedDiskBytesRequestId = null;
double minUnderUtilizedCpu = Double.MAX_VALUE;
double minOverUtilizedCpu = Double.MAX_VALUE;
long minUnderUtilizedMemBytes = Long.MAX_VALUE;
long minUnderUtilizedDiskBytes = Long.MAX_VALUE;
for (RequestUtilization utilization : utilizationPerRequestId.values()) {
Optional<SingularityDeploy> maybeDeploy = deployManager.getDeploy(utilization.getRequestId(), utilization.getDeployId());
if (maybeDeploy.isPresent() && maybeDeploy.get().getResources().isPresent()) {
String requestId = utilization.getRequestId();
long memoryBytesReserved = (long) (maybeDeploy.get().getResources().get().getMemoryMb() * SingularitySlaveUsage.BYTES_PER_MEGABYTE);
double cpuReserved = maybeDeploy.get().getResources().get().getCpus();
long diskBytesReserved = (long) maybeDeploy.get().getResources().get().getDiskMb() * SingularitySlaveUsage.BYTES_PER_MEGABYTE;
double unusedCpu = cpuReserved - utilization.getAvgCpuUsed();
long unusedMemBytes = (long) (memoryBytesReserved - utilization.getAvgMemBytesUsed());
long unusedDiskBytes = (long) (diskBytesReserved - utilization.getAvgDiskBytesUsed());
if (unusedCpu > 0) {
numRequestsWithUnderUtilizedCpu++;
totalUnderUtilizedCpu += unusedCpu;
if (unusedCpu > maxUnderUtilizedCpu) {
maxUnderUtilizedCpu = unusedCpu;
maxUnderUtilizedCpuRequestId = requestId;
}
minUnderUtilizedCpu = Math.min(unusedCpu, minUnderUtilizedCpu);
} else if (unusedCpu < 0) {
double overusedCpu = Math.abs(unusedCpu);
numRequestsWithOverUtilizedCpu++;
totalOverUtilizedCpu += overusedCpu;
if (overusedCpu > maxOverUtilizedCpu) {
maxOverUtilizedCpu = overusedCpu;
maxOverUtilizedCpuRequestId = requestId;
}
minOverUtilizedCpu = Math.min(overusedCpu, minOverUtilizedCpu);
}
if (unusedMemBytes > 0) {
numRequestsWithUnderUtilizedMemBytes++;
totalUnderUtilizedMemBytes += unusedMemBytes;
if (unusedMemBytes > maxUnderUtilizedMemBytes) {
maxUnderUtilizedMemBytes = unusedMemBytes;
maxUnderUtilizedMemBytesRequestId = requestId;
}
minUnderUtilizedMemBytes = Math.min(unusedMemBytes, minUnderUtilizedMemBytes);
}
if (unusedDiskBytes > 0) {
numRequestsWithUnderUtilizedDiskBytes++;
totalUnderUtilizedDiskBytes += unusedDiskBytes;
if (unusedDiskBytes > maxUnderUtilizedDiskBytes) {
maxUnderUtilizedDiskBytes = unusedDiskBytes;
maxUnderUtilizedDiskBytesRequestId = requestId;
}
minUnderUtilizedDiskBytes = Math.min(unusedDiskBytes, minUnderUtilizedMemBytes);
}
}
}
double avgUnderUtilizedCpu = numRequestsWithUnderUtilizedCpu != 0 ? totalUnderUtilizedCpu / numRequestsWithUnderUtilizedCpu : 0;
double avgOverUtilizedCpu = numRequestsWithOverUtilizedCpu != 0? totalOverUtilizedCpu / numRequestsWithOverUtilizedCpu : 0;
long avgUnderUtilizedMemBytes = numRequestsWithUnderUtilizedMemBytes != 0 ? totalUnderUtilizedMemBytes / numRequestsWithUnderUtilizedMemBytes : 0;
long avgUnderUtilizedDiskBytes = numRequestsWithUnderUtilizedDiskBytes != 0 ? totalUnderUtilizedDiskBytes / numRequestsWithUnderUtilizedDiskBytes : 0;
return new SingularityClusterUtilization(new ArrayList<>(utilizationPerRequestId.values()), numRequestsWithUnderUtilizedCpu, numRequestsWithOverUtilizedCpu,
numRequestsWithUnderUtilizedMemBytes, numRequestsWithUnderUtilizedDiskBytes, totalUnderUtilizedCpu, totalOverUtilizedCpu, totalUnderUtilizedMemBytes, totalUnderUtilizedDiskBytes, avgUnderUtilizedCpu, avgOverUtilizedCpu,
avgUnderUtilizedMemBytes, avgUnderUtilizedDiskBytes, maxUnderUtilizedCpu, maxOverUtilizedCpu, maxUnderUtilizedMemBytes, maxUnderUtilizedDiskBytes, maxUnderUtilizedCpuRequestId, maxOverUtilizedCpuRequestId,
maxUnderUtilizedMemBytesRequestId, maxUnderUtilizedDiskBytesRequestId, getMin(minUnderUtilizedCpu), getMin(minOverUtilizedCpu), getMin(minUnderUtilizedMemBytes), getMin(minUnderUtilizedDiskBytes), totalMemBytesUsed,
totalMemBytesAvailable, totalDiskBytesUsed, totalDiskBytesAvailable, totalCpuUsed, totalCpuAvailable, now);
}
private double getMin(double value) {
return value == Double.MAX_VALUE ? 0 : value;
}
private long getMin(long value) {
return value == Long.MAX_VALUE ? 0 : value;
}
@VisibleForTesting
void clearOldUsage(String taskId) {
List<Double> pastTaskUsagePaths = usageManager.getTaskUsagePaths(taskId).stream().map(Double::parseDouble).collect(Collectors.toList());
while (pastTaskUsagePaths.size() + 1 > configuration.getNumUsageToKeep()) {
long minSecondsApart = configuration.getUsageIntervalSeconds();
boolean deleted = false;
for (int i = 0; i < pastTaskUsagePaths.size() - 1; i++) {
if (pastTaskUsagePaths.get(i + 1) - pastTaskUsagePaths.get(i) < minSecondsApart) {
SingularityDeleteResult result = usageManager.deleteSpecificTaskUsage(taskId, pastTaskUsagePaths.get(i + 1));
if (result.equals(SingularityDeleteResult.DIDNT_EXIST)) {
LOG.warn("Didn't delete taskUsage {} for taskId {}", pastTaskUsagePaths.get(i + 1).toString(), taskId);
}
deleted = true;
pastTaskUsagePaths.remove(pastTaskUsagePaths.get(i + 1));
break;
}
}
if (!deleted) {
usageManager.deleteSpecificTaskUsage(taskId, pastTaskUsagePaths.get(0));
pastTaskUsagePaths.remove(pastTaskUsagePaths.get(0));
}
}
}
}
|
package com.hubspot.singularity.scheduler;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.mesos.client.MesosClient;
import com.hubspot.mesos.json.MesosTaskMonitorObject;
import com.hubspot.singularity.SingularityDeployStatistics;
import com.hubspot.singularity.SingularityRequestWithState;
import com.hubspot.singularity.SingularitySlave;
import com.hubspot.singularity.SingularitySlaveUsage;
import com.hubspot.singularity.SingularitySlaveUsage.ResourceUsageType;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskCurrentUsage;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityTaskUsage;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.DeployManager;
import com.hubspot.singularity.data.RequestManager;
import com.hubspot.singularity.data.TaskManager;
import com.hubspot.singularity.data.UsageManager;
import com.hubspot.singularity.sentry.SingularityExceptionNotifier;
public class SingularityUsagePoller extends SingularityLeaderOnlyPoller {
private static final Logger LOG = LoggerFactory.getLogger(SingularityUsagePoller.class);
private final SingularityConfiguration configuration;
private final MesosClient mesosClient;
private final UsageManager usageManager;
private final SingularityUsageHelper usageHelper;
private final SingularityExceptionNotifier exceptionNotifier;
private final RequestManager requestManager;
private final DeployManager deployManager;
private final TaskManager taskManager;
@Inject
SingularityUsagePoller(SingularityConfiguration configuration,
SingularityUsageHelper usageHelper,
UsageManager usageManager,
MesosClient mesosClient,
SingularityExceptionNotifier exceptionNotifier,
RequestManager requestManager,
DeployManager deployManager,
TaskManager taskManager) {
super(configuration.getCheckUsageEveryMillis(), TimeUnit.MILLISECONDS);
this.configuration = configuration;
this.usageHelper = usageHelper;
this.mesosClient = mesosClient;
this.usageManager = usageManager;
this.exceptionNotifier = exceptionNotifier;
this.requestManager = requestManager;
this.deployManager = deployManager;
this.taskManager = taskManager;
}
@Override
public void runActionOnPoll() {
final long now = System.currentTimeMillis();
for (SingularitySlave slave : usageHelper.getSlavesToTrackUsageFor()) {
Map<ResourceUsageType, Number> longRunningTasksUsage = new HashMap<>();
longRunningTasksUsage.put(ResourceUsageType.MEMORY_BYTES_USED, 0);
longRunningTasksUsage.put(ResourceUsageType.CPU_USED, 0);
Optional<Long> memoryMbTotal = Optional.absent();
Optional<Double> cpusTotal = Optional.absent();
long memoryMbReserved = 0;
long cpuReserved = 0;
long memoryBytesUsed = 0;
double cpusUsed = 0;
try {
List<MesosTaskMonitorObject> allTaskUsage = mesosClient.getSlaveResourceUsage(slave.getHost());
for (MesosTaskMonitorObject taskUsage : allTaskUsage) {
String taskId = taskUsage.getSource();
SingularityTaskId task = SingularityTaskId.valueOf(taskId);
SingularityTaskUsage usage = getUsage(taskUsage);
List<SingularityTaskUsage> taskUsages = usageManager.getTaskUsage(taskId);
if (taskUsages.size() + 1 > configuration.getNumUsageToKeep()) {
usageManager.deleteSpecificTaskUsage(taskId, taskUsages.get(0).getTimestamp());
}
usageManager.saveSpecificTaskUsage(taskId, usage);
Optional<SingularityTask> maybeTask = taskManager.getTask(task);
if (maybeTask.isPresent() && maybeTask.get().getTaskRequest().getDeploy().getResources().isPresent()) {
memoryMbReserved += maybeTask.get().getTaskRequest().getDeploy().getResources().get().getMemoryMb();
cpuReserved += maybeTask.get().getTaskRequest().getDeploy().getResources().get().getCpus();
}
memoryBytesUsed += usage.getMemoryRssBytes();
if (!taskUsages.isEmpty()) {
SingularityTaskUsage lastUsage = taskUsages.get(taskUsages.size() - 1);
double taskCpusUsed = ((usage.getCpuSeconds() - lastUsage.getCpuSeconds()) / (usage.getTimestamp() - lastUsage.getTimestamp()));
if (isLongRunning(task) || isConsideredLongRunning(task)) {
updateLongRunningTasksUsage(longRunningTasksUsage, usage.getMemoryRssBytes(), taskCpusUsed);
}
SingularityTaskCurrentUsage currentUsage = new SingularityTaskCurrentUsage(usage.getMemoryRssBytes(), now, taskCpusUsed);
usageManager.saveCurrentTaskUsage(taskId, currentUsage);
cpusUsed += taskCpusUsed;
}
}
if (!slave.getResources().isPresent() ||
!slave.getResources().get().getMemoryMegaBytes().isPresent() ||
!slave.getResources().get().getNumCpus().isPresent()) {
LOG.debug("Could not find slave or resources for slave {}", slave.getId());
} else {
memoryMbTotal = Optional.of(slave.getResources().get().getMemoryMegaBytes().get().longValue());
cpusTotal = Optional.of(slave.getResources().get().getNumCpus().get().doubleValue());
}
SingularitySlaveUsage slaveUsage = new SingularitySlaveUsage(memoryBytesUsed, memoryMbReserved, now, cpusUsed, cpuReserved, allTaskUsage.size(), memoryMbTotal, cpusTotal, longRunningTasksUsage);
List<Long> slaveTimestamps = usageManager.getSlaveUsageTimestamps(slave.getId());
if (slaveTimestamps.size() + 1 > configuration.getNumUsageToKeep()) {
usageManager.deleteSpecificSlaveUsage(slave.getId(), slaveTimestamps.get(0));
}
LOG.debug("Saving slave {} usage {}", slave.getHost(), slaveUsage);
usageManager.saveSpecificSlaveUsageAndSetCurrent(slave.getId(), slaveUsage);
} catch (Exception e) {
String message = String.format("Could not get slave usage for host %s", slave.getHost());
LOG.error(message, e);
exceptionNotifier.notify(message, e);
}
}
}
private SingularityTaskUsage getUsage(MesosTaskMonitorObject taskUsage) {
double cpuSeconds = taskUsage.getStatistics().getCpusSystemTimeSecs() + taskUsage.getStatistics().getCpusUserTimeSecs();
return new SingularityTaskUsage(taskUsage.getStatistics().getMemRssBytes(), taskUsage.getStatistics().getTimestamp(), cpuSeconds);
}
private boolean isLongRunning(SingularityTaskId task) {
Optional<SingularityRequestWithState> request = requestManager.getRequest(task.getRequestId());
if (request.isPresent()) {
return request.get().getRequest().getRequestType().isLongRunning();
}
LOG.warn("Couldn't find request id {} for task {}", task.getRequestId(), task.getId());
return false;
}
private boolean isConsideredLongRunning(SingularityTaskId task) {
final Optional<SingularityDeployStatistics> deployStatistics = deployManager.getDeployStatistics(task.getRequestId(), task.getDeployId());
return deployStatistics.isPresent() && deployStatistics.get().getAverageRuntimeMillis().isPresent() &&
deployStatistics.get().getAverageRuntimeMillis().get() >= configuration.getConsiderNonLongRunningTaskLongRunningAfterRunningForSeconds();
}
private void updateLongRunningTasksUsage(Map<ResourceUsageType, Number> longRunningTasksUsage, long memBytesUsed, double cpuUsed) {
longRunningTasksUsage.compute(ResourceUsageType.MEMORY_BYTES_USED, (k, v) -> (v == null) ? memBytesUsed : v.longValue() + memBytesUsed);
longRunningTasksUsage.compute(ResourceUsageType.CPU_USED, (k, v) -> (v == null) ? cpuUsed : v.doubleValue() + cpuUsed);
}
}
|
package org.voovan.http.server.module.annontationRouter.router;
import org.voovan.http.HttpContentType;
import org.voovan.http.message.HttpStatic;
import org.voovan.http.server.*;
import org.voovan.http.server.exception.AnnotationRouterException;
import org.voovan.http.server.module.annontationRouter.AnnotationModule;
import org.voovan.http.server.module.annontationRouter.annotation.*;
import org.voovan.http.websocket.WebSocketRouter;
import org.voovan.tools.TEnv;
import org.voovan.tools.TFile;
import org.voovan.tools.TString;
import org.voovan.tools.json.JSON;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
public class AnnotationRouter implements HttpRouter {
private static Map<Class, Object> singletonObjs = new ConcurrentHashMap<Class, Object>();
private String urlPath;
private String paramPath;
private String path;
private Class clazz;
private Method method;
private String methodName;
private Router classRouter;
private Router methodRoute;
private AnnotationModule annotationModule;
/**
*
* @param clazz Class
* @param method
* @param classRouter Route
* @param methodRoute Route
*/
public AnnotationRouter(AnnotationModule annotationModule, Class clazz, Method method, Router classRouter, Router methodRoute, String urlPath, String paramPath) {
this.annotationModule = annotationModule;
this.clazz = clazz;
this.method = method;
this.methodName = method.getName();
this.classRouter = classRouter;
this.methodRoute = methodRoute;
this.urlPath = urlPath;
this.paramPath = paramPath;
this.path = urlPath + paramPath;
annotationModule.METHOD_URL_MAP.put(method, urlPath);
annotationModule.URL_METHOD_MAP.put(urlPath, method);
if(classRouter.singleton() && !singletonObjs.containsKey(clazz)){
try {
singletonObjs.put(clazz, clazz.newInstance());
} catch (Exception e) {
Logger.error("New a singleton object error", e);
}
}
}
public String getUrlPath() {
return urlPath;
}
public String getParamPath() {
return paramPath;
}
public String getPath() {
return path;
}
public Class getClazz() {
return clazz;
}
public Method getMethod() {
return method;
}
public Router getClassRouter() {
return classRouter;
}
public Router getMethodRoute() {
return methodRoute;
}
public AnnotationModule getAnnotationModule() {
return annotationModule;
}
/**
* Router
*
* @param httpModule AnnotationModule
*/
public static void scanRouterClassAndRegister(AnnotationModule annotationModule) {
int routeMethodNum = 0;
String modulePath = annotationModule.getModuleConfig().getPath();
modulePath = HttpDispatcher.fixRoutePath(modulePath);
WebServer webServer = annotationModule.getWebServer();
try {
// Router
String[] scanRouterPackageArr = annotationModule.getScanRouterPackage().split(";");
for(String scanRouterPackage : scanRouterPackageArr) {
scanRouterPackage = scanRouterPackage.trim();
List<Class> routerClasses = TEnv.searchClassInEnv(scanRouterPackage, new Class[]{Router.class});
for (Class routerClass : routerClasses) {
Method[] methods = routerClass.getMethods();
Router[] annonClassRouters = (Router[]) routerClass.getAnnotationsByType(Router.class);
// Router
for (Router annonClassRouter : annonClassRouters) {
String classRouterPath = annonClassRouter.path().isEmpty() ? annonClassRouter.value() : annonClassRouter.path();
String[] classRouterMethods = annonClassRouter.method();
for (String classRouterMethod : classRouterMethods) {
if (classRouterPath.isEmpty()) {
classRouterPath = routerClass.getSimpleName();
}
classRouterPath = HttpDispatcher.fixRoutePath(classRouterPath);
// if(methods.length > 0) {
// TReflect.register(routerClass);
// Router
for (Method method : methods) {
Router[] annonMethodRouters = (Router[]) method.getAnnotationsByType(Router.class);
if (annonMethodRouters != null) {
// Router ,
for (Router annonMethodRouter : annonMethodRouters) {
String methodRouterPath = annonMethodRouter.path().isEmpty() ? annonMethodRouter.value() : annonMethodRouter.path();
String[] methodRouterMethods = annonMethodRouter.method();
//, Http mehtod
for (String methodRouterMethod : methodRouterMethods) {
if (methodRouterPath.isEmpty()) {
//: index
if (method.getName().equals("index")) {
methodRouterPath = "/";
} else {
methodRouterPath = method.getName();
}
}
methodRouterPath = HttpDispatcher.fixRoutePath(methodRouterPath);
String routePath = classRouterPath + methodRouterPath;
// Method ,
String routeMethod = methodRouterMethod.isEmpty() ? classRouterMethod : methodRouterMethod;
routeMethod = routeMethod.isEmpty() ? HttpStatic.GET_STRING : routeMethod;
String paramPath = "";
Annotation[][] paramAnnotationsArrary = method.getParameterAnnotations();
Class[] paramTypes = method.getParameterTypes();
for (int i = 0; i < paramAnnotationsArrary.length; i++) {
Annotation[] paramAnnotations = paramAnnotationsArrary[i];
if (paramAnnotations.length == 0 &&
paramTypes[i] != HttpRequest.class &&
paramTypes[i] != HttpResponse.class &&
paramTypes[i] != HttpSession.class) {
paramPath = paramPath + "/:param" + (i + 1);
continue;
}
for (Annotation paramAnnotation : paramAnnotations) {
if (paramAnnotation instanceof Param) {
paramPath = TString.assembly(paramPath, "/:", ((Param) paramAnnotation).value());
}
//, BodyParam POST
if ((paramAnnotation instanceof BodyParam || paramAnnotation instanceof Body) && routeMethod.equals(HttpStatic.GET_STRING)) {
routeMethod = HttpStatic.POST_STRING;
}
}
}
if (webServer.getHttpRouters().get(routeMethod) == null) {
webServer.getHttpDispatcher().addRouteMethod(routeMethod);
}
routePath = HttpDispatcher.fixRoutePath(routePath);
// TreeMap containsKey bug
Map routerMaps = new HashMap();
routerMaps.putAll(webServer.getHttpRouters().get(routeMethod));
AnnotationRouter annotationRouter = new AnnotationRouter(annotationModule, routerClass, method,
annonClassRouter, annonMethodRouter, routePath, paramPath);
if (paramPath.isEmpty()) {
routePath = HttpDispatcher.fixRoutePath(routePath);
String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + routePath);
if (!routerMaps.containsKey(moduleRoutePath)) {
annotationModule.otherMethod(routeMethod, routePath, annotationRouter);
Logger.simple("[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() +
"] add Router: " + TString.rightPad(routeMethod, 8, ' ') +
moduleRoutePath);
routeMethodNum++;
}
}
else {
String routeParamPath = null;
routeParamPath = routePath + paramPath;
routeParamPath = HttpDispatcher.fixRoutePath(routeParamPath);
String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + routeParamPath);
if (!routerMaps.containsKey(moduleRoutePath)) {
annotationModule.otherMethod(routeMethod, routeParamPath, annotationRouter);
Logger.simple("[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() +
"] add Router: " + TString.rightPad(routeMethod, 8, ' ') +
moduleRoutePath);
routeMethodNum++;
}
}
}
}
}
}
}
}
}
// WebSocket
List<Class> webSocketClasses = TEnv.searchClassInEnv(annotationModule.getScanRouterPackage(), new Class[]{WebSocket.class});
for (Class webSocketClass : webSocketClasses) {
if (TReflect.isExtendsByClass(webSocketClass, WebSocketRouter.class)) {
WebSocket[] annonClassRouters = (WebSocket[]) webSocketClass.getAnnotationsByType(WebSocket.class);
WebSocket annonClassRouter = annonClassRouters[0];
String classRouterPath = annonClassRouter.path().isEmpty() ? annonClassRouter.value() : annonClassRouter.path();
if (classRouterPath.isEmpty()) {
classRouterPath = webSocketClass.getSimpleName();
}
classRouterPath = HttpDispatcher.fixRoutePath(classRouterPath);
String moduleRoutePath = HttpDispatcher.fixRoutePath(modulePath + classRouterPath);
if (!webServer.getWebSocketRouters().containsKey(moduleRoutePath)) {
annotationModule.socket(classRouterPath, (WebSocketRouter) TReflect.newInstance(webSocketClass));
Logger.simple("[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() +
"] add WebSocket: " + TString.leftPad(moduleRoutePath, 11, ' '));
routeMethodNum++;
}
}
}
if(routeMethodNum>0) {
Logger.simple(TFile.getLineSeparator() + "[SYSTEM] Module [" + annotationModule.getModuleConfig().getName() +
"] Scan some class [" + scanRouterPackage + "] annotation by Router: " + routerClasses.size() +
". Register Router method annotation by route: " + routeMethodNum + ".");
}
}
} catch (Exception e){
Logger.error("Scan router class error.", e);
}
}
// /**
// *
// * @param routePath
// * @return
// */
// private static String fixAnnotationRoutePath(String routePath){
// routePath = routePath.startsWith("/") ? TString.removePrefix(routePath) : routePath;
// routePath = routePath.endsWith("/") ? TString.removeSuffix(routePath) : routePath;
// return routePath;
/**
* Http
* @param request http
* @param response http
* @param clazz Class
* @param method Method
* @return
* @throws Exception
*/
public Object invokeRouterMethod(HttpRequest request, HttpResponse response, Class clazz, Method method) throws Exception {
Object annotationObj = null;
if(this.classRouter.singleton()){
annotationObj = singletonObjs.get(clazz);
} else {
annotationObj = clazz.newInstance();
}
Class[] parameterTypes = method.getParameterTypes();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
String bodyString = "";
Map bodyMap = null;
if(request.body().size() > 0) {
bodyString = request.body().getBodyString();
if(JSON.isJSONMap(bodyString)) {
bodyMap = (Map) JSON.parse(bodyString);
}
}
Object[] params = new Object[parameterTypes.length];
for(int i=0; i < parameterAnnotations.length; i++){
if(parameterTypes[i] == HttpRequest.class){
params[i] = request;
continue;
}
if(parameterTypes[i] == HttpResponse.class){
params[i] = response;
continue;
}
if(parameterTypes[i] == HttpSession.class){
params[i] = request.getSession();
continue;
}
for(Annotation annotation : parameterAnnotations[i]) {
if (annotation instanceof Param) {
String paramName = ((Param) annotation).value();
try {
params[i] = TString.toObject(request.getParameter(paramName), parameterTypes[i], true);
continue;
} catch (Exception e) {
if(((Param) annotation).isRequire()) {
throw new AnnotationRouterException("Router annotation @Param [" + paramName + " = " + params[i] + "] error, data: " + request.getParameters(), e);
}
}
}
if (annotation instanceof BodyParam) {
String paramName = ((BodyParam) annotation).value();
try {
if(bodyMap != null && bodyMap instanceof Map) {
Object bodyParam = bodyMap.get(paramName);
if(TReflect.isBasicType(bodyParam.getClass())) {
params[i] = TString.toObject(bodyParam.toString(), parameterTypes[i], true);
} else if(bodyParam instanceof Map){
params[i] = TReflect.getObjectFromMap(parameterTypes[i], (Map)bodyParam, true);
} else {
params[i] = bodyParam;
}
}
continue;
} catch (Exception e) {
if(((BodyParam) annotation).isRequire()) {
throw new AnnotationRouterException("Router annotation @BodyParam [" + paramName + " = " + params[i] + "] error, data: " + bodyMap.toString(), e);
}
}
}
if (annotation instanceof Head) {
String headName = ((Head) annotation).value();
try {
params[i] = TString.toObject(request.header().get(headName), parameterTypes[i], true);
continue;
} catch (Exception e) {
if(((Head) annotation).isRequire()) {
throw new AnnotationRouterException("Router annotation @Head [" + headName + " = " + params[i] + "] error, data: " + request.header().toString(), e);
}
}
}
// Cookie
if (annotation instanceof Cookie) {
String cookieValue = null;
String cookieName = ((Cookie) annotation).value();
try {
org.voovan.http.message.packet.Cookie cookie = request.getCookie(cookieName);
if (cookie != null) {
cookieValue = cookie.getValue();
}
params[i] = TString.toObject(cookieValue, parameterTypes[i], true);
continue;
} catch (Exception e) {
if(((Cookie) annotation).isRequire()) {
String cookieStr = request.cookies().parallelStream().map(cookie -> cookie.getName() + "=" + cookie.getName()).collect(Collectors.toList()).toString();
throw new AnnotationRouterException("Router annotation @Cookie [" + cookieName + " = " + params[i] + "] error, data: " + cookieStr, e);
}
}
}
// Body
if (annotation instanceof Body) {
try {
params[i] = bodyMap == null ?
TString.toObject(bodyString, parameterTypes[i], true) :
TReflect.getObjectFromMap(parameterTypes[i], bodyMap, true);
continue;
} catch (Exception e) {
if(((Body) annotation).isRequire()) {
throw new AnnotationRouterException("Router annotation @Body error \r\n data: " + bodyString, e);
}
}
}
if (annotation instanceof Attribute) {
String attrName = ((Attribute) annotation).value();
try {
params[i] = TString.toObject(request.getAttributes().get(attrName).toString(), parameterTypes[i], true);
continue;
} catch (Exception e) {
if(((Attribute) annotation).isRequire()) {
throw new AnnotationRouterException("Router annotation @Attribute [" + attrName + " = " + params[i] + "] error, data: " + request.header().toString(), e);
}
}
}
if (annotation instanceof Session) {
String sessionName = ((Session) annotation).value();
HttpSession httpSession = request.getSession();
try {
if (httpSession.getAttribute(sessionName).getClass() == parameterTypes[i]) {
params[i] = httpSession.getAttribute(sessionName);
}
continue;
} catch (Exception e) {
if(((Session) annotation).isRequire()) {
throw new AnnotationRouterException("Router annotation @Session [" + sessionName + " = " + params[i] + "] error, data: " + httpSession.attributes().toString(), e);
}
}
}
}
if(params[i]==null) {
try {
String value = request.getParameter("param" + String.valueOf(i + 1));
params[i] = TString.toObject(value, parameterTypes[i], true);
continue;
} catch (Exception e) {
throw new AnnotationRouterException("Router sequential injection param " + request.getParameters().toString() + " error", e);
}
}
}
return TReflect.invokeMethod(annotationObj, method, params);
}
@Override
public void process(HttpRequest request, HttpResponse response) throws Exception {
AnnotationRouterFilter annotationRouterFilter = annotationModule.getAnnotationRouterFilter();
Object responseObj = null;
Object fliterResult = null;
try {
// Router Content-Type
response.header().put(HttpStatic.CONTENT_TYPE_STRING, HttpContentType.getHttpContentType(methodRoute.contentType()));
if(annotationRouterFilter!=null) {
fliterResult = annotationRouterFilter.beforeInvoke(request, response, this);
}
//null:
// null: http
if(fliterResult == null) {
responseObj = invokeRouterMethod(request, response, clazz, method);
} else {
responseObj = fliterResult;
}
if(annotationRouterFilter!=null) {
fliterResult = annotationRouterFilter.afterInvoke(request, response, this, responseObj);
if(fliterResult!=null) {
responseObj = fliterResult;
}
}
} catch(Exception e) {
if(annotationRouterFilter!=null) {
fliterResult = annotationRouterFilter.exception(request, response, this, e);
}
if(fliterResult !=null) {
responseObj = fliterResult;
} else {
if (e.getCause() != null) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
e = (Exception) cause;
}
}
Logger.error(e);
if (e instanceof AnnotationRouterException) {
throw e;
} else {
throw new AnnotationRouterException("Process annotation router error. URL: " + request.protocol().getPath(), e);
}
}
}
if (responseObj != null) {
if (responseObj instanceof String) {
response.write((String) responseObj);
} else if (responseObj instanceof byte[]) {
response.write((byte[]) responseObj);
} else {
response.header().put(HttpStatic.CONTENT_TYPE_STRING, HttpContentType.getHttpContentType(HttpContentType.JSON));
response.write(JSON.toJSON(responseObj));
}
}
}
}
|
package picoded.struct;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@SuppressWarnings("unchecked")
public class UnsupportedDefaultMap_test {
UnsupportedDefaultMap<String, String> unsupportedDefaultMapForVoidMethod = mock(UnsupportedDefaultMap.class, CALLS_REAL_METHODS);
UnsupportedDefaultMap<String, String> unsupportedDefaultMap = mock(UnsupportedDefaultMap.class);
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test (expected = UnsupportedOperationException.class)
public void getTest() {
when(unsupportedDefaultMap.get("key")).thenCallRealMethod();
unsupportedDefaultMap.get("key");
}
@Test (expected = UnsupportedOperationException.class)
public void putTest() {
when(unsupportedDefaultMap.put("key", "value")).thenCallRealMethod();
unsupportedDefaultMap.put("key", "value");
}
@Test (expected = UnsupportedOperationException.class)
public void removeTest() {
when(unsupportedDefaultMap.remove("key")).thenCallRealMethod();
unsupportedDefaultMap.remove("key");
}
@Test (expected = UnsupportedOperationException.class)
public void keySetTest() {
when(unsupportedDefaultMap.keySet()).thenCallRealMethod();
unsupportedDefaultMap.keySet();
}
@Test (expected = UnsupportedOperationException.class)
public void clearTest() {
unsupportedDefaultMapForVoidMethod.clear();
}
@Test
public void clearValidTest() {
Set<String> set = new HashSet<>();
set.add("key1");
set.add("key2");
when(unsupportedDefaultMap.keySet()).thenReturn(set);
doCallRealMethod().when(unsupportedDefaultMap).clear();
unsupportedDefaultMap.clear();
}
@Test (expected = UnsupportedOperationException.class)
public void containsKeyTest() {
unsupportedDefaultMapForVoidMethod.containsKey("key");
}
@Test
public void containsKeyValidTest() {
when(unsupportedDefaultMap.containsKey("key1")).thenCallRealMethod();
Set<String> set = new HashSet<>();
set.add("key1");
set.add("key2");
when(unsupportedDefaultMap.keySet()).thenReturn(set);
assertTrue(unsupportedDefaultMap.containsKey("key1"));
}
@Test (expected = UnsupportedOperationException.class)
public void containsValueExceptionTest() {
when(unsupportedDefaultMap.containsValue("value")).thenCallRealMethod();
when(unsupportedDefaultMap.entrySet()).thenCallRealMethod();
when(unsupportedDefaultMap.keySet()).thenCallRealMethod();
assertFalse(unsupportedDefaultMap.containsValue("value"));
}
@Test
public void containsValueTest() {
Map<String, String> map = new HashMap<>();
Set<Map.Entry<String, String>> set = new HashSet<>();
when(unsupportedDefaultMap.containsValue(null)).thenCallRealMethod();
when(unsupportedDefaultMap.entrySet()).thenReturn(set);
assertFalse(unsupportedDefaultMap.containsValue(null));
map.put("key1", "abc");
map.put("key2", null);
set.addAll(map.entrySet());
when(unsupportedDefaultMap.entrySet()).thenReturn(set);
assertTrue(unsupportedDefaultMap.containsValue(null));
assertFalse(unsupportedDefaultMap.containsValue(""));
assertFalse(unsupportedDefaultMap.containsValue("abc"));
assertFalse(unsupportedDefaultMap.containsValue("cds"));
// Set<Map.Entry<String, String>> set =null;
// Map<String, String> map = null;
// // set is blank
// set = new HashSet<>();
// when(unsupportedDefaultMap.entrySet()).thenReturn(set);
// assertFalse(unsupportedDefaultMap.containsValue("AQW"));
// // value==null and key-value==null
// set = new HashSet<>();
// map = new HashMap<>();
// map.put("K1", null);
// set.addAll(map.entrySet());
// when(unsupportedDefaultMap.entrySet()).thenReturn(set);
// assertFalse(unsupportedDefaultMap.containsValue(null));
// // value==null and key-value!=null
// set = new HashSet<>();
// map = new HashMap<>();
// String keyValue = new String("V");
// map.put("K", keyValue);
// set.addAll(map.entrySet());
// when(unsupportedDefaultMap.entrySet()).thenReturn(set);
// assertFalse(unsupportedDefaultMap.containsValue(null));
// // value==V2 and key-value==V2
// set = new HashSet<>();
// map = new HashMap<>();
// keyValue = new String("V2");
// map.put("K2", keyValue);
// set.addAll(map.entrySet());
// when(unsupportedDefaultMap.entrySet()).thenReturn(set);
// assertTrue(unsupportedDefaultMap.containsValue(keyValue));
// // value==XYZ and key-value==ABC
// set = new HashSet<>();
// map = new HashMap<>();
// keyValue = new String("ABC");
// map.put("K3", keyValue);
// set.addAll(map.entrySet());
// when(unsupportedDefaultMap.entrySet()).thenReturn(set);
// assertFalse(unsupportedDefaultMap.containsValue(new String("XYZ")));
// // value==XYZ and key-value==ABC
// set = new HashSet<>();
// map = new HashMap<>();
// keyValue = null;
// map.put("K4", keyValue);
// set.addAll(map.entrySet());
// when(unsupportedDefaultMap.entrySet()).thenReturn(set);
// assertFalse(unsupportedDefaultMap.containsValue(new String("VV2")));
}
@Test
public void containsValueValidTest() {
when(unsupportedDefaultMap.containsValue("value1")).thenCallRealMethod();
Set<Map.Entry<String, String>> set = new HashSet<>();
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
set.addAll(map.entrySet());
when(unsupportedDefaultMap.entrySet()).thenReturn(set);
assertTrue(unsupportedDefaultMap.containsValue("value1"));
}
@Test
public void containsValueValidForNullTest() {
when(unsupportedDefaultMap.containsValue(null)).thenCallRealMethod();
Set<Map.Entry<String, String>> set = new HashSet<>();
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", null);
set.addAll(map.entrySet());
when(unsupportedDefaultMap.entrySet()).thenReturn(set);
assertTrue(unsupportedDefaultMap.containsValue(null));
}
@Test (expected = UnsupportedOperationException.class)
public void entrySetTest() {
when(unsupportedDefaultMap.entrySet()).thenCallRealMethod();
when(unsupportedDefaultMap.keySet()).thenCallRealMethod();
unsupportedDefaultMap.entrySet();
}
@Test
public void entrySetValidTest() {
when(unsupportedDefaultMap.entrySet()).thenCallRealMethod();
Set<String> set = new HashSet<>();
set.add("key1");
set.add("key2");
when(unsupportedDefaultMap.keySet()).thenReturn(set);
assertNotNull(unsupportedDefaultMap.entrySet());
}
@Test (expected = UnsupportedOperationException.class)
public void isEmptyTest() {
unsupportedDefaultMapForVoidMethod.isEmpty();
}
@Test
public void isEmptyTrueTest() {
when(unsupportedDefaultMap.isEmpty()).thenCallRealMethod();
Set<String> set = new HashSet<>();
when(unsupportedDefaultMap.keySet()).thenReturn(set);
assertTrue(unsupportedDefaultMap.isEmpty());
}
@Test
public void isEmptyFalseTest() {
when(unsupportedDefaultMap.isEmpty()).thenCallRealMethod();
Set<String> set = new HashSet<>();
set.add("my_entry");
when(unsupportedDefaultMap.keySet()).thenReturn(set);
assertFalse(unsupportedDefaultMap.isEmpty());
}
@Test (expected = java.lang.UnsupportedOperationException.class)
public void putAllTest() {
Map<String, String> map = new HashMap<String, String>();
map.put("my_key", "my_value");
unsupportedDefaultMapForVoidMethod.putAll(map);
}
@Test
public void putAllValidTest() {
Map<String, String> map = new HashMap<String, String>();
map.put("my_key", "my_value");
doCallRealMethod().when(unsupportedDefaultMap).putAll(map);
unsupportedDefaultMap.putAll(map);
}
@Test (expected = UnsupportedOperationException.class)
public void sizeTest() {
unsupportedDefaultMapForVoidMethod.size();
}
@Test
public void sizeValidTest() {
when(unsupportedDefaultMap.size()).thenCallRealMethod();
Set<String> set = new HashSet<>();
set.add("my_entry");
when(unsupportedDefaultMap.keySet()).thenReturn(set);
assertEquals(1, unsupportedDefaultMap.size());
}
@Test (expected = UnsupportedOperationException.class)
public void valuesTest() {
unsupportedDefaultMapForVoidMethod.values();
}
@Test
public void valuesValidTest() {
Set<Map.Entry<String, String>> set = new HashSet<>();
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
set.addAll(map.entrySet());
when(unsupportedDefaultMap.entrySet()).thenReturn(set);
when(unsupportedDefaultMap.values()).thenCallRealMethod();
assertEquals(set.size(), unsupportedDefaultMap.values().size());
}
}
|
package org.mifos.test.acceptance.loan;
import org.joda.time.DateTime;
import org.mifos.test.acceptance.admin.FeeTestHelper;
import org.mifos.test.acceptance.framework.MifosPage;
import org.mifos.test.acceptance.framework.UiTestCaseBase;
import org.mifos.test.acceptance.framework.admin.FeesCreatePage;
import org.mifos.test.acceptance.framework.loan.ChargeParameters;
import org.mifos.test.acceptance.framework.loan.CreateLoanAccountSearchParameters;
import org.mifos.test.acceptance.framework.loan.LoanAccountPage;
import org.mifos.test.acceptance.framework.loanproduct.DefineNewLoanProductPage;
import org.mifos.test.acceptance.framework.office.OfficeParameters;
import org.mifos.test.acceptance.framework.testhelpers.FormParametersHelper;
import org.mifos.test.acceptance.framework.testhelpers.LoanTestHelper;
import org.mifos.test.acceptance.framework.testhelpers.NavigationHelper;
import org.mifos.test.acceptance.loanproduct.LoanProductTestHelper;
import org.mifos.test.acceptance.util.ApplicationDatabaseOperation;
import org.mifos.test.acceptance.util.TestDataSetup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import static org.mifos.test.acceptance.framework.holiday.CreateHolidayEntryPage.CreateHolidaySubmitParameters;
@ContextConfiguration(locations = {"classpath:ui-test-context.xml"})
@Test(sequential = true, groups = {"loanproduct", "acceptance", "ui","smoke"})
public class ViewOriginalLoanScheduleTest extends UiTestCaseBase {
@Autowired
private ApplicationDatabaseOperation applicationDatabaseOperation;
private static final String officeName = "test_office";
private static final String userLoginName = "test_user";
private static final String userName="test user";
private static final String clientName = "test client";
private LoanProductTestHelper loanProductTestHelper;
private String loanProductName;
private LoanTestHelper loanTestHelper;
private DateTime systemDateTime;
private NavigationHelper navigationHelper;
String feeName = "loanWeeklyFee";
boolean isSetUpDone = false;
// @Autowired
// private InitializeApplicationRemoteTestingService initRemote;
// @Autowired
// private DbUnitUtilities dbUnitUtilities;
@AfterMethod
public void logOut() {
(new MifosPage(selenium)).logout();
}
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
@BeforeMethod
public void setUp() throws Exception {
super.setUp();
if (isSetUpDone) {
systemDateTime = new DateTime(2011, 10, 10, 10, 0, 0, 0);
loanTestHelper.setApplicationTime(systemDateTime);
return;
}
// // TODO: please ensure that the database contains Mrs Salutation!
// initRemote.dataLoadAndCacheRefresh(dbUnitUtilities, "acceptance_small_003_dbunit.xml", dataSource, selenium);
loanProductTestHelper = new LoanProductTestHelper(selenium);
navigationHelper = new NavigationHelper(selenium);
systemDateTime = new DateTime(2010, 10, 11, 10, 0, 0, 0);
loanTestHelper = new LoanTestHelper(selenium);
loanTestHelper.setApplicationTime(systemDateTime);
TestDataSetup dataSetup = new TestDataSetup(selenium, applicationDatabaseOperation);
dataSetup.createBranch(OfficeParameters.BRANCH_OFFICE, officeName, "Off");
dataSetup.createUser(userLoginName, userName, officeName);
dataSetup.createClient(clientName, officeName, userName);
systemDateTime = new DateTime(2011, 10, 10, 10, 0, 0, 0);
loanTestHelper.setApplicationTime(systemDateTime);
createHolidays(dataSetup);
new FeeTestHelper(dataSetup).createPeriodicFee(feeName, FeesCreatePage.SubmitFormParameters.LOAN, FeesCreatePage.SubmitFormParameters.WEEKLY_FEE_RECURRENCE, 1, 100);
isSetUpDone=true;
}
private void createHolidays(TestDataSetup dataSetup) throws SQLException {
dataSetup.createHoliday(systemDateTime.plusDays(7), null, CreateHolidaySubmitParameters.NEXT_MEETING_OR_REPAYMENT); //17/10/2011
dataSetup.createHoliday(systemDateTime.plusDays(14), null, CreateHolidaySubmitParameters.NEXT_WORKING_DAY);//24/10/2011
dataSetup.createHoliday(systemDateTime.plusDays(21), null, CreateHolidaySubmitParameters.SAME_DAY);//31/10/2011
dataSetup.createHoliday(systemDateTime.plusDays(15), null, CreateHolidaySubmitParameters.SAME_DAY); //25/10/2011
dataSetup.createHoliday(systemDateTime.plusDays(22), null, CreateHolidaySubmitParameters.NEXT_WORKING_DAY);//01/11/2011
dataSetup.createHoliday(systemDateTime.plusDays(36), null, CreateHolidaySubmitParameters.NEXT_MEETING_OR_REPAYMENT);//15/11/2011
}
@SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
@Test(enabled=true)
public void verifyForFlatLoanEarlyDisbursal() throws Exception {
int interestType = DefineNewLoanProductPage.SubmitFormParameters.FLAT;
applicationDatabaseOperation.updateLSIM(0);
createLoanProduct(interestType);
String accountId = verifyLoanAccountOriginalSchedule(systemDateTime.plusDays(1), systemDateTime, OriginalScheduleData.FLAT_LOAN_SCHEDULE, true, systemDateTime.plusDays(5));
applyChargesAndVerifySchedule(accountId, OriginalScheduleData.FLAT_LOAN_SCHEDULE);
}
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
public void verifyForVariableInstallmentLoanEarlyDisbursal() throws Exception {
int interestType = DefineNewLoanProductPage.SubmitFormParameters.DECLINING_BALANCE;
applicationDatabaseOperation.updateLSIM(1);
DefineNewLoanProductPage.SubmitFormParameters formParameters = defineLoanProductParameters(interestType);
loanProductTestHelper.
navigateToDefineNewLoanPangAndFillMandatoryFields(formParameters).
fillVariableInstalmentOption("30","1","100").
submitAndGotoNewLoanProductPreviewPage().submit();
verifyLoanAccountOriginalSchedule(systemDateTime.plusDays(1), systemDateTime, OriginalScheduleData.VARIABLE_LOAN_EARLY_DISBURSAL_SCHEDULE, false, systemDateTime.plusDays(5));
}
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
public void verifyForVariableInstallmentLoanLateDisbursal() throws Exception {
int interestType = DefineNewLoanProductPage.SubmitFormParameters.DECLINING_BALANCE;
applicationDatabaseOperation.updateLSIM(1);
DefineNewLoanProductPage.SubmitFormParameters formParameters = defineLoanProductParameters(interestType);
loanProductTestHelper.
navigateToDefineNewLoanPangAndFillMandatoryFields(formParameters).
fillVariableInstalmentOption("20","1","100").
submitAndGotoNewLoanProductPreviewPage().submit();
verifyLoanAccountOriginalSchedule(systemDateTime, systemDateTime.plusDays(1), OriginalScheduleData.VARIABLE_LOAN_LATE_DISBURSAL_SCHEDULE, false, systemDateTime.plusDays(15));
}
/**
* early disbursement of loan is not working (interest type doesnt not matter in relation to scheduling of dates.)
*/
@Test(enabled=false)
@SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
public void verifyForDecBalIntReCalcLoanEarlyDisbursalLSIMOn() throws Exception {
int interestType = DefineNewLoanProductPage.SubmitFormParameters.DECLINING_BALANCE_INTEREST_RECALCULATION;
applicationDatabaseOperation.updateLSIM(1);
createLoanProduct(interestType);
String accountId = verifyLoanAccountOriginalSchedule(systemDateTime.plusDays(1), systemDateTime.plusDays(10), OriginalScheduleData.DEC_BAL_INT_RECALC_LOAN_LATE_DISBURSAL_SCHEDULE_ON, true, systemDateTime.plusDays(15));
applyChargesAndVerifySchedule(accountId, OriginalScheduleData.DEC_BAL_INT_RECALC_LOAN_LATE_DISBURSAL_SCHEDULE_ON);
}
private void applyChargesAndVerifySchedule(String accountId, String[][] loanSchedule) {
ChargeParameters feeParameters = new ChargeParameters();
feeParameters.setAmount("10");
feeParameters.setType(ChargeParameters.MISC_FEES);
loanTestHelper.applyCharge(accountId, feeParameters);
feeParameters.setType(ChargeParameters.MISC_PENALTY);
loanTestHelper.applyCharge(accountId, feeParameters);
verifyOriginalSchedule(loanSchedule);
}
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
public void verifyForDecBalIntReCalcLoanEarlyDisbursalLSIMOff() throws Exception {
int interestType = DefineNewLoanProductPage.SubmitFormParameters.DECLINING_BALANCE_INTEREST_RECALCULATION;
applicationDatabaseOperation.updateLSIM(0);
createLoanProduct(interestType);
String accountId = verifyLoanAccountOriginalSchedule(systemDateTime.plusDays(1), systemDateTime, OriginalScheduleData.DEC_BAL_INT_RECALC_LOAN_EARLY_DISBURSAL_SCHEDULE_OFF, true, systemDateTime.plusDays(15));
applyChargesAndVerifySchedule(accountId, OriginalScheduleData.DEC_BAL_INT_RECALC_LOAN_EARLY_DISBURSAL_SCHEDULE_OFF);
}
@Test(enabled=true)
@SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
public void verifyForDecBalIntReCalcLoanLateDisbursalLSIMOff() throws Exception {
int interestType = DefineNewLoanProductPage.SubmitFormParameters.DECLINING_BALANCE_INTEREST_RECALCULATION;
applicationDatabaseOperation.updateLSIM(0);
createLoanProduct(interestType);
String accountId = verifyLoanAccountOriginalSchedule(systemDateTime.plusDays(1), systemDateTime.plusDays(8), OriginalScheduleData.DEC_BAL_INT_RECALC_LOAN_LATE_DISBURSAL_SCHEDULE_OFF, true, systemDateTime.plusDays(15));
applyChargesAndVerifySchedule(accountId, OriginalScheduleData.DEC_BAL_INT_RECALC_LOAN_LATE_DISBURSAL_SCHEDULE_OFF);
}
private String verifyLoanAccountOriginalSchedule(DateTime creationDisbursalDate, DateTime disbursalDate, String[][] tableOnOriginalInstallment, boolean needApplyFee, DateTime paymentDate) throws UnsupportedEncodingException {
String accountId = createLoanAccount(creationDisbursalDate, disbursalDate, needApplyFee);
verifyOriginalSchedule(tableOnOriginalInstallment);
ChargeParameters feeParameters = new ChargeParameters();
feeParameters.setAmount("10");
feeParameters.setType(ChargeParameters.MISC_FEES);
loanTestHelper.applyCharge(accountId, feeParameters);
feeParameters.setType(ChargeParameters.MISC_PENALTY);
loanTestHelper.applyCharge(accountId, feeParameters);
verifyOriginalSchedule(tableOnOriginalInstallment);
loanTestHelper.makePayment(paymentDate, "100");
verifyOriginalSchedule(tableOnOriginalInstallment);
return accountId;
}
private String createLoanAccount(DateTime creationDisbursalDate, DateTime actualDisbursalDate, boolean needApplyFee) throws UnsupportedEncodingException {
navigationHelper.navigateToHomePage();
LoanAccountPage loanAccountPage = loanTestHelper.
navigateToCreateLoanAccountEntryPageWithoutLogout(setLoanSearchParameters()).
setDisbursalDate(creationDisbursalDate).
clickContinue().clickPreviewAndGoToReviewLoanAccountPage().submit().navigateToLoanAccountDetailsPage();
if (needApplyFee) {
ChargeParameters chargeParameters = new ChargeParameters();
chargeParameters.setType(feeName);
new LoanAccountPage(selenium).navigateToApplyCharge().applyFeeAndConfirm(chargeParameters);
}
String accountId = loanAccountPage.getAccountId();
ChargeParameters feeParameters = new ChargeParameters();
feeParameters.setAmount("10");
feeParameters.setType(ChargeParameters.MISC_FEES);
loanTestHelper.applyCharge(accountId, feeParameters);
feeParameters.setType(ChargeParameters.MISC_PENALTY);
loanTestHelper.applyCharge(accountId, feeParameters);
loanTestHelper.approveLoan();
loanTestHelper.disburseLoan(actualDisbursalDate);
return accountId;
}
private LoanAccountPage verifyOriginalSchedule(String[][] tableOnOriginalInstallment) {
return new LoanAccountPage(selenium).
navigateToRepaymentSchedulePage().
navigateToViewOriginalSchedulePage().
verifyScheduleTable(tableOnOriginalInstallment).
returnToRepaymentSchedule().navigateToLoanAccountPage();
}
private void createLoanProduct(int interestType) {
DefineNewLoanProductPage.SubmitFormParameters formParameters = defineLoanProductParameters(interestType);
loanProductTestHelper.
navigateToDefineNewLoanPangAndFillMandatoryFields(formParameters).
submitAndGotoNewLoanProductPreviewPage().submit();
}
private DefineNewLoanProductPage.SubmitFormParameters defineLoanProductParameters(int interestType) {
DefineNewLoanProductPage.SubmitFormParameters formParameters = FormParametersHelper.getWeeklyLoanProductParameters();
formParameters.setDefInstallments(String.valueOf(5));
formParameters.setDefaultLoanAmount(String.valueOf(1000));
formParameters.setInterestTypes(interestType);
formParameters.setDefaultInterestRate(String.valueOf(20));
loanProductName = formParameters.getOfferingName();
return formParameters;
}
private CreateLoanAccountSearchParameters setLoanSearchParameters() {
CreateLoanAccountSearchParameters accountSearchParameters = new CreateLoanAccountSearchParameters();
accountSearchParameters.setLoanProduct(loanProductName);
accountSearchParameters.setSearchString(clientName);
return accountSearchParameters;
}
}
|
package ru.pocket.testcat.addressbook.tests;
import org.hamcrest.CoreMatchers;
import org.testng.annotations.Test;
import ru.pocket.testcat.addressbook.model.GroupData;
import ru.pocket.testcat.addressbook.model.Groups;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class GroupCreationTest extends TestBase {
@Test
public void testGroupCreation() {
app.goTo().groupPage();
Groups before = app.group().all();
GroupData group = new GroupData().withGroupname("test2");
app.group().create(group);
assertThat(app.group().getgroupCount(), equalTo(before.size() + 1));
Groups after = app.group().all();
assertThat(after, equalTo(before
.withAdded(group.withGroupid(after.stream().mapToInt((g) -> g.getGroupid()).max().getAsInt()))));
}
@Test
public void testBadGroupCreation() {
app.goTo().groupPage();
Groups before = app.group().all();
GroupData group = new GroupData().withGroupname("test21'");
app.group().create(group);
assertThat(app.group().getgroupCount (), equalTo(before.size()));
Groups after = app.group().all();
assertThat(after, equalTo(before));
}
}
/* int max = 0;
for(GroupData g: after){
if (g.getGroupid() >max) {
max = g.getGroupid();
}
}*/
// int max1 = after.stream().max((o1, o2) -> Integer.compare(o1.getGroupid(), o2.getGroupid())).get().getGroupid();
/* Comparator<? super GroupData> byId = new Comparator<GroupData>() {
@Override
public int compare(GroupData o1, GroupData o2) {
return Integer.compare(o1.getGroupid(), o2.getGroupid());
}
};*/
/* app.goTo().groupPage();
int before = app.group().getgroupCount ();
app.group().create(new GroupData("newgroup", null, null));
int after = app.group().getgroupCount();
Assert.assertEquals(after, before + 1);*/
|
package ru.stqa.pft.addressbook.generators;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import ru.stqa.pft.addressbook.model.GroupData;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class GroupDataGenetator {
@Parameter(names = "-c", description = "Group count")
public int count;
@Parameter(names = "-f", description = "Target file")
public String file;
public static void main(String[] args) throws IOException {
GroupDataGenetator genetator = new GroupDataGenetator();
JCommander jCommander = new JCommander(genetator);
try {
jCommander.parse(args);
} catch (ParameterException ex) {
jCommander.usage();
return;
}
genetator.run();
}
private void run() throws IOException {
List<GroupData> groups = generateGroups(count);
save(groups, new File(file));
}
private void save(List<GroupData> groups, File file) throws IOException {
System.out.println(new File(".").getAbsolutePath());
Writer writer = new FileWriter(file);
for (GroupData group : groups) {
writer.write(String.format("%s;%s;%s\n", group.getName(), group.getHeader(), group.getFooter()));
}
writer.close();
}
private List<GroupData> generateGroups(int count) {
List<GroupData> groups = new ArrayList<GroupData>();
for (int i = 0; i <count; i++) {
groups.add(new GroupData().withName(String.format("test %s", i))
.withHeader(String.format("header %s", i)).withFooter(String.format("footer %s", i)));
}
return groups;
}
}
|
package org.msf.records.ui.patientcreation;
import android.test.AndroidTestCase;
import com.google.common.base.Optional;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.msf.records.App;
import org.msf.records.FakeAppLocationTreeFactory;
import org.msf.records.R;
import org.msf.records.data.app.AppLocationTree;
import org.msf.records.data.app.AppModel;
import org.msf.records.data.app.AppPatient;
import org.msf.records.data.app.AppPatientDelta;
import org.msf.records.events.data.AppLocationTreeFetchedEvent;
import org.msf.records.events.data.PatientAddFailedEvent;
import org.msf.records.events.data.SingleItemCreatedEvent;
import org.msf.records.model.Zone;
import org.msf.records.ui.FakeEventBus;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.anyVararg;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;
import static org.msf.records.ui.matchers.AppPatientMatchers.matchesPatientDelta;
/**
* Tests for {@link PatientCreationController}.
*/
public class PatientCreationControllerTest extends AndroidTestCase {
private static final String VALID_ID = "123";
private static final String VALID_GIVEN_NAME = "Jane";
private static final String VALID_FAMILY_NAME = "Doe";
private static final String VALID_AGE = "56";
private static final int VALID_AGE_UNITS = PatientCreationController.AGE_YEARS;
private static final int VALID_SEX = PatientCreationController.SEX_FEMALE;
private static final LocalDate VALID_ADMISSION_DATE = LocalDate.now().minusDays(5);
private static final LocalDate VALID_SYMPTOMS_ONSET_DATE = LocalDate.now().minusDays(8);
private static final String VALID_LOCATION_UUID = Zone.SUSPECT_ZONE_UUID;
private PatientCreationController mPatientCreationController;
@Mock private PatientCreationController.Ui mMockUi;
@Mock private AppModel mMockAppModel;
private FakeEventBus mFakeCrudEventBus;
@Override
protected void setUp() {
MockitoAnnotations.initMocks(this);
mFakeCrudEventBus = new FakeEventBus();
mPatientCreationController =
new PatientCreationController(mMockUi, mFakeCrudEventBus, mMockAppModel);
}
/** Tests that initializing the controller fetches a location tree for the location dialog. */
public void testInit_requestsLocationTree() {
// GIVEN an uninitialized controller
// WHEN controller is initialized
mPatientCreationController.init();
// THEN controller requests a location tree
verify(mMockAppModel).fetchLocationTree(any(FakeEventBus.class), anyString());
}
/** Tests that suspending the controller unregisters the controller from the event bus. */
public void testSuspend_unregistersFromEventBus() {
// GIVEN an initialized controller with a location tree
mPatientCreationController.init();
mFakeCrudEventBus.post(new AppLocationTreeFetchedEvent(FakeAppLocationTreeFactory.build()));
// WHEN controller is suspended
mPatientCreationController.suspend();
// THEN controller unregisters from the event bus
assertEquals(0, mFakeCrudEventBus.countRegisteredReceivers());
}
/** Tests that the controller does not crash if it suspends before location tree is present. */
public void testSuspend_handlesNullLocationTree() {
// GIVEN an initialized controller without a location tree
mPatientCreationController.init();
// WHEN controller is suspended
mPatientCreationController.suspend();
// THEN controller doesn't crash
}
/** Tests that the controller passes its location tree to the activity when received. */
public void testEventSubscriber_passesLocationTreeToUi() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN location tree is fetched
AppLocationTree locationTree = FakeAppLocationTreeFactory.build();
mFakeCrudEventBus.post(new AppLocationTreeFetchedEvent(locationTree));
// THEN controller passes the location to the UI
verify(mMockUi).setLocationTree(locationTree);
}
/** Tests that the controller displays an error when the patient was not successfully added. */
public void testEventSubscriber_showsErrorMessageWhenPatientAddFails() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN a patient fails to be added
mFakeCrudEventBus.post(new PatientAddFailedEvent(
PatientAddFailedEvent.REASON_DUPLICATE_ID, null));
// THEN controller reports the error in the UI
verify(mMockUi).showErrorMessage(anyInt());
}
/** Tests that the controller causes the activity to quit when a patient is added. */
public void testEventSubscriber_quitsWhenPatientAddSucceeds() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN a patient is successfully added
AppPatient patient = AppPatient.builder().build();
mFakeCrudEventBus.post(new SingleItemCreatedEvent<>(patient));
// THEN controller tries to quit the activity
verify(mMockUi).quitActivity();
}
/** Tests that all fields are set correctly when adding a fully-populated patient. */
public void testCreatePatient_setsAllFieldsCorrectly() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN patient creation is requested with all fields
AppPatientDelta patientDelta = getValidAppPatientDelta();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller forwards request to model with correct fields
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that clicking 'create patient' clears any existing validation errors. */
public void testCreatePatient_clearsOldValidationErrors() {
// GIVEN an initialized controller with previously-entered incorrect data
mPatientCreationController.init();
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.id = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// WHEN new data is added and 'create' is pressed
patientDelta.id = Optional.of(VALID_ID);
createPatientFromAppPatientDelta(patientDelta);
// THEN controller clears old errors
verify(mMockUi, atLeastOnce()).clearValidationErrors();
}
/** Tests that patient id is treated as a required field. */
public void testCreatePatient_requiresId() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields but id are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.id = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that given name is replaced by a default if not specified. */
public void testCreatePatient_givenNameDefaultsToUnknown() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields but given name are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.givenName = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller adds the patient with a default given name
patientDelta.givenName =
Optional.of(App.getInstance().getString(R.string.unknown_given_name));
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that family name is replaced by a default if not specified. */
public void testCreatePatient_familyNameDefaultsToUnknown() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields but family name are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.familyName = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller adds the patient with a default family name
patientDelta.familyName =
Optional.of(App.getInstance().getString(R.string.unknown_family_name));
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that negative ages are not allowed. */
public void testCreatePatient_rejectsNegativeAge() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields are populated, age is negative (birthdate in future)
mPatientCreationController.createPatient(
VALID_ID,
VALID_GIVEN_NAME,
VALID_FAMILY_NAME,
"-1",
VALID_AGE_UNITS,
VALID_SEX,
VALID_ADMISSION_DATE,
VALID_SYMPTOMS_ONSET_DATE,
VALID_LOCATION_UUID);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that either 'years' or 'months' must be specified for patient age. */
public void testCreatePatient_requiresYearsOrMonthsSet() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields but years/months choice are populated
mPatientCreationController.createPatient(
VALID_ID,
VALID_GIVEN_NAME,
VALID_FAMILY_NAME,
VALID_AGE,
-1,
VALID_SEX,
VALID_ADMISSION_DATE,
VALID_SYMPTOMS_ONSET_DATE,
VALID_LOCATION_UUID);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that gender is a required field (though it shouldn't be). */
public void testCreatePatient_requiresGender() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields but gender are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.gender = Optional.of(-1);
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that admission date must be specified. */
public void testCreatePatient_requiresAdmissionDate() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields but admission date are populated
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.admissionDate = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that admission date cannot be a future date. */
public void testCreatePatient_rejectsFutureAdmissionDate() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields are populated, admission date is in the future
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.admissionDate = Optional.of(LocalDate.now().plusDays(5));
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that admission date can be in the past. */
public void testCreatePatient_allowsPastAdmissionDate() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields are populated, admission date is in the past
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.admissionDate = Optional.of(LocalDate.now().minusDays(5));
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that symptoms onset date can be left blank. */
public void testCreatePatient_doesNotRequireSymptomsOnsetDate() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields are populated except symptoms onset date
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.firstSymptomDate = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation with no symptoms onset date
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that symptoms onset date cannot be in the future. */
public void testCreatePatient_rejectsFutureSymptomsOnsetDate() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields are populated, symptoms onset date is in the future
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.firstSymptomDate = Optional.of(LocalDate.now().plusDays(5));
createPatientFromAppPatientDelta(patientDelta);
// THEN controller fails to add the patient
verify(mMockUi).showValidationError(anyInt(), anyInt(), (String[]) anyVararg());
}
/** Tests that symptoms onset date can be in the past. */
public void testCreatePatient_allowsPastSymptomsOnsetDate() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields are populated, symptoms onset date is in the past
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.firstSymptomDate = Optional.of(LocalDate.now().minusDays(5));
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that location can be left blank. */
public void testCreatePatient_doesNotRequireLocation() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields are populated except location
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.assignedLocationUuid = Optional.absent();
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation, defaulting to Triage
patientDelta.assignedLocationUuid = Optional.of(Zone.TRIAGE_ZONE_UUID);
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
/** Tests that unicode characters can be used in the patient's name. */
public void testCreatePatient_supportsUnicodePatientName() {
// GIVEN an initialized controller
mPatientCreationController.init();
// WHEN all fields are populated and given name contains unicode characters
AppPatientDelta patientDelta = getValidAppPatientDelta();
patientDelta.givenName = Optional.of("ஸ்றீனிவாஸ ராமானுஜன் ஐயங்கார்");
createPatientFromAppPatientDelta(patientDelta);
// THEN controller requests patient creation
verify(mMockAppModel).addPatient(
any(FakeEventBus.class),
argThat(matchesPatientDelta(patientDelta)));
}
private void createPatientFromAppPatientDelta(AppPatientDelta appPatientDelta) {
int age = -1;
int ageUnit = -1;
if (appPatientDelta.birthdate.isPresent()) {
Period agePeriod = new Period(appPatientDelta.birthdate.get(), DateTime.now());
if (agePeriod.getYears() < 1) {
age = agePeriod.getMonths();
ageUnit = PatientCreationController.AGE_MONTHS;
} else {
age = agePeriod.getYears();
ageUnit = PatientCreationController.AGE_YEARS;
}
}
mPatientCreationController.createPatient(
appPatientDelta.id.orNull(),
appPatientDelta.givenName.orNull(),
appPatientDelta.familyName.orNull(),
age == -1 ? null : Integer.toString(age),
ageUnit,
appPatientDelta.gender.get(),
appPatientDelta.admissionDate.orNull(),
appPatientDelta.firstSymptomDate.orNull(),
appPatientDelta.assignedLocationUuid.orNull()
);
}
private AppPatientDelta getValidAppPatientDelta() {
AppPatientDelta appPatientDelta = new AppPatientDelta();
appPatientDelta.id = Optional.of(VALID_ID);
appPatientDelta.givenName = Optional.of(VALID_GIVEN_NAME);
appPatientDelta.familyName = Optional.of(VALID_FAMILY_NAME);
appPatientDelta.birthdate = Optional.of(getBirthdateFromAge(
Integer.parseInt(VALID_AGE), VALID_AGE_UNITS));
appPatientDelta.gender = Optional.of(VALID_SEX);
appPatientDelta.admissionDate = Optional.of(VALID_ADMISSION_DATE);
appPatientDelta.firstSymptomDate = Optional.of(VALID_SYMPTOMS_ONSET_DATE);
appPatientDelta.assignedLocationUuid = Optional.of(VALID_LOCATION_UUID);
return appPatientDelta;
}
private DateTime getBirthdateFromAge(int ageInt, int ageUnits) {
DateTime now = DateTime.now();
switch (ageUnits) {
case PatientCreationController.AGE_YEARS:
return now.minusYears(ageInt);
case PatientCreationController.AGE_MONTHS:
return now.minusMonths(ageInt);
default:
throw new IllegalArgumentException("Unknown age unit");
}
}
}
|
package openfoodfacts.github.scrachx.openfood.views;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import openfoodfacts.github.scrachx.openfood.BuildConfig;
import openfoodfacts.github.scrachx.openfood.R;
import openfoodfacts.github.scrachx.openfood.models.Product;
import openfoodfacts.github.scrachx.openfood.models.Search;
import openfoodfacts.github.scrachx.openfood.network.OpenFoodAPIClient;
import openfoodfacts.github.scrachx.openfood.utils.SearchType;
import openfoodfacts.github.scrachx.openfood.views.adapters.ProductsRecyclerViewAdapter;
import openfoodfacts.github.scrachx.openfood.views.listeners.EndlessRecyclerViewScrollListener;
import openfoodfacts.github.scrachx.openfood.views.listeners.RecyclerItemClickListener;
public class ProductBrowsingListActivity extends BaseActivity {
private static String SEARCH_TYPE = "search_type";
private static String SEARCH_QUERY = "search_query";
private String searchType;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.products_recycler_view)
RecyclerView productsRecyclerView;
@BindView(R.id.textCountProduct)
TextView countProductsView;
@BindView(R.id.offlineCloudLinearLayout)
LinearLayout offlineCloudLayout;
ProgressBar progressBar;
@BindView(R.id.swipe_refresh)
SwipeRefreshLayout swipeRefreshLayout;
private EndlessRecyclerViewScrollListener scrollListener;
private List<Product> mProducts;
private OpenFoodAPIClient api;
private OpenFoodAPIClient apiClient;
private int mCountProducts = 0;
private int pageAddress = 1;
String searchQuery;
public static void startActivity(Context context, String searchQuery, @SearchType String type) {
Intent intent = new Intent(context, ProductBrowsingListActivity.class);
intent.putExtra(SEARCH_QUERY, searchQuery);
intent.putExtra(SEARCH_TYPE, type);
context.startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
searchQuery = query;
newSearchQuery();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat
.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
getSupportActionBar().setTitle(null);
finish();
return true;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brand);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
countProductsView.setVisibility(View.INVISIBLE);
Bundle extras = getIntent().getExtras();
searchType = extras.getString(SEARCH_TYPE);
searchQuery = extras.getString(SEARCH_QUERY);
newSearchQuery();
}
protected void newSearchQuery(){
getSupportActionBar().setTitle(searchQuery);
switch (searchType) {
case SearchType.BRAND: {
toolbar.setSubtitle(R.string.brand_string);
break;
}
case SearchType.COUNTRY: {
toolbar.setSubtitle(R.string.country_string);
break;
}
case SearchType.ADDITIVE: {
toolbar.setSubtitle(R.string.additive_string);
break;
}
case SearchType.SEARCH: {
toolbar.setSubtitle(R.string.search_string);
break;
}
case SearchType.STORE: {
toolbar.setSubtitle(R.string.store_subtitle);
break;
}
case SearchType.PACKAGING: {
toolbar.setSubtitle(R.string.packaging_subtitle);
break;
}
case SearchType.LABEL: {
getSupportActionBar().setSubtitle(getString(R.string.label_string));
break;
}
case SearchType.CATEGORY: {
getSupportActionBar().setSubtitle(getString(R.string.category_string));
break;
}
case SearchType.CONTRIBUTOR: {
getSupportActionBar().setSubtitle(getString(R.string.contributor_string));
break;
}
}
apiClient = new OpenFoodAPIClient(ProductBrowsingListActivity.this, BuildConfig.OFWEBSITE);
api = new OpenFoodAPIClient(ProductBrowsingListActivity.this);
productsRecyclerView = (RecyclerView) findViewById(R.id.products_recycler_view);
progressBar.setVisibility(View.VISIBLE);
setup();
}
@OnClick(R.id.buttonTryAgain)
public void setup() {
offlineCloudLayout.setVisibility(View.INVISIBLE);
countProductsView.setVisibility(View.INVISIBLE);
getDataFromAPI();
}
public void getDataFromAPI() {
switch (searchType) {
case SearchType.BRAND: {
apiClient.getProductsByBrand(searchQuery, pageAddress, new OpenFoodAPIClient.OnBrandCallback() {
@Override
public void onBrandResponse(boolean value, Search brandObject) {
loadData(value, brandObject);
}
});
break;
}
case SearchType.COUNTRY: {
apiClient.getProductsByCountry(searchQuery, pageAddress, new OpenFoodAPIClient.onCountryCallback() {
@Override
public void onCountryResponse(boolean value, Search country) {
loadData(value, country);
}
});
break;
}
case SearchType.ADDITIVE: {
apiClient.getProductsByAdditive(searchQuery, pageAddress, new OpenFoodAPIClient.OnAdditiveCallback() {
@Override
public void onAdditiveResponse(boolean value, Search country) {
loadData(value, country);
}
});
break;
}
case SearchType.STORE: {
apiClient.getProductsByStore(searchQuery, pageAddress, new OpenFoodAPIClient.OnStoreCallback() {
@Override
public void onStoreResponse(boolean value, Search storeObject) {
loadData(value, storeObject);
}
});
break;
}
case SearchType.PACKAGING: {
apiClient.getProductsByPackaging(searchQuery, pageAddress, new OpenFoodAPIClient.OnPackagingCallback() {
@Override
public void onPackagingResponse(boolean value, Search packagingObject) {
loadData(value, packagingObject);
}
});
break;
}
case SearchType.SEARCH: {
api.searchProduct(searchQuery, pageAddress, ProductBrowsingListActivity.this, new OpenFoodAPIClient.OnProductsCallback() {
@Override
public void onProductsResponse(boolean isOk, Search searchResponse, int countProducts) {
loadData(isOk, searchResponse);
}
});
break;
}
case SearchType.LABEL: {
api.getProductsByLabel(searchQuery, pageAddress, new OpenFoodAPIClient.onLabelCallback() {
@Override
public void onLabelResponse(boolean value, Search label) {
loadData(value, label);
}
});
break;
}
case SearchType.CATEGORY: {
api.getProductsByCategory(searchQuery, pageAddress, new OpenFoodAPIClient.onCategoryCallback() {
@Override
public void onCategoryResponse(boolean value, Search category) {
loadData(value, category);
}
});
break;
}
case SearchType.CONTRIBUTOR: {
api.getProductsByContributor(searchQuery, pageAddress, new OpenFoodAPIClient.onContributorCallback() {
@Override
public void onContributorResponse(boolean value, Search contributor) {
loadData(value, contributor);
}
});
break;
}
}
}
private void loadData(boolean isResponseOk, Search response) {
if (isResponseOk) {
mCountProducts = Integer.parseInt(response.getCount());
if (pageAddress == 1) {
countProductsView.append(" " + NumberFormat.getInstance(getResources().getConfiguration().locale).format(Long.parseLong(response.getCount()
)));
mProducts = new ArrayList<>();
mProducts.addAll(response.getProducts());
if (mProducts.size() < mCountProducts) {
mProducts.add(null);
}
setUpRecyclerView();
} else {
if (mProducts.size() - 1 < mCountProducts + 1) {
final int posStart = mProducts.size();
mProducts.remove(mProducts.size() - 1);
mProducts.addAll(response.getProducts());
if (mProducts.size() < mCountProducts) {
mProducts.add(null);
}
productsRecyclerView.getAdapter().notifyItemRangeChanged(posStart - 1, mProducts.size() - 1);
}
}
} else {
swipeRefreshLayout.setRefreshing(false);
productsRecyclerView.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.INVISIBLE);
offlineCloudLayout.setVisibility(View.VISIBLE);
}
}
private void setUpRecyclerView() {
progressBar.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
countProductsView.setVisibility(View.VISIBLE);
offlineCloudLayout.setVisibility(View.INVISIBLE);
productsRecyclerView.setVisibility(View.VISIBLE);
productsRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(ProductBrowsingListActivity.this, LinearLayoutManager.VERTICAL, false);
productsRecyclerView.setLayoutManager(mLayoutManager);
ProductsRecyclerViewAdapter adapter = new ProductsRecyclerViewAdapter(mProducts);
productsRecyclerView.setAdapter(adapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(productsRecyclerView.getContext(),
DividerItemDecoration.VERTICAL);
productsRecyclerView.addItemDecoration(dividerItemDecoration);
// Retain an instance so that you can call `resetState()` for fresh searches
scrollListener = new EndlessRecyclerViewScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
if (mProducts.size() < mCountProducts && !swipeRefreshLayout.isRefreshing()) {
pageAddress = page;
getDataFromAPI();
}
}
};
// Adds the scroll listener to RecyclerView
productsRecyclerView.addOnScrollListener(scrollListener);
productsRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(ProductBrowsingListActivity.this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Product p = ((ProductsRecyclerViewAdapter) productsRecyclerView.getAdapter()).getProduct(position);
if (p != null) {
String barcode = p.getCode();
api.getProduct(barcode, ProductBrowsingListActivity.this);
try {
View view1 = ProductBrowsingListActivity.this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) ProductBrowsingListActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
})
);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
countProductsView.setText(getResources().getString(R.string.number_of_results));
pageAddress = 1;
setup();
}
});
}
}
|
package org.noorganization.instalist.view.fragment;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import org.noorganization.instalist.GlobalApplication;
import org.noorganization.instalist.R;
import org.noorganization.instalist.controller.IListController;
import org.noorganization.instalist.controller.event.ListItemChangedMessage;
import org.noorganization.instalist.controller.implementation.ControllerFactory;
import org.noorganization.instalist.model.ListEntry;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.view.touchlistener.OnRecyclerItemTouchListener;
import org.noorganization.instalist.view.ChangeHandler;
import org.noorganization.instalist.view.MainShoppingListView;
import org.noorganization.instalist.view.customview.AmountPicker;
import org.noorganization.instalist.view.dataholder.SelectableBaseItemListEntryDataHolder;
import org.noorganization.instalist.view.decoration.DividerItemListDecoration;
import org.noorganization.instalist.view.event.ActivityStateMessage;
import org.noorganization.instalist.view.event.ProductSelectMessage;
import org.noorganization.instalist.view.event.ToolbarChangeMessage;
import org.noorganization.instalist.view.interfaces.IBaseActivity;
import org.noorganization.instalist.view.interfaces.IFragment;
import org.noorganization.instalist.view.listadapter.ShoppingItemListAdapter;
import org.noorganization.instalist.view.sorting.shoppingList.AlphabeticalListEntryComparator;
import org.noorganization.instalist.view.sorting.shoppingList.PriorityListEntryComparator;
import org.noorganization.instalist.view.utils.PreferencesManager;
import org.noorganization.instalist.view.utils.ViewUtils;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import de.greenrobot.event.EventBus;
/**
* A ShoppingListOverviewFragment containing a list view.
*/
public class ShoppingListOverviewFragment extends Fragment implements IFragment {
private static final String LOG_TAG = ShoppingListOverviewFragment.class.toString();
private ShoppingList mCurrentShoppingList;
private boolean mHandlingProductSelectedMessages;
private Context mContext;
private FloatingActionButton mAddButton;
private LinearLayoutManager mLayoutManager;
private ShoppingItemListAdapter mShoppingItemListAdapter;
private RecyclerView mRecyclerView;
private IListController mListController;
private IBaseActivity mBaseActivityInterface;
private ActionMode mActionMode; // usage of support.v7.ActionMode!
private static String PREFERENCES_NAME = "SHOPPING_LIST_FRAGMENT";
private static String SORT_MODE = "SORT_MODE";
/**
* Contains the mapping from a Integer to comperators.
*/
private Map<Integer, Comparator> mMapComperable;
private static Integer SORT_BY_NAME = 0;
private static Integer SORT_BY_PRIORITY = 1;
/**
* Used to inflate the actionbar.
*/
private ActionMode.Callback mActionModeCallback;
private View mRootView;
/**
* Listener for Callback of ActionMode when editing an ListEntry.
*/
private class OnShoppingListItemActionModeListener implements ActionMode.Callback {
private Context mContext;
private View mView;
private long mListEntryId;
/**
* Constructor of OnShoppingListItemActionModeListener.
*
* @param _Context the context of the Fragment.
* @param _View the View of the selected element. Used to read the data from it.
* @param _ListEntryId the Id of the clicked ListEntry.
*/
public OnShoppingListItemActionModeListener(Context _Context, View _View, long _ListEntryId) {
mContext = _Context;
mView = _View;
mListEntryId = _ListEntryId;
}
/**
* Checks if any editable field of the editview has a focus.
*
* @return true if a component has focus, false otherwise.
*/
public boolean hasFocus() {
boolean hasFocus = false;
// hasFocus |= mAmountPicker.hasFocus();
return hasFocus;
}
public void clearFocus() {
// mAmountPicker.clearFocus();
}
@Override
public boolean onCreateActionMode(ActionMode _Mode, Menu _Menu) {
mAddButton.setVisibility(View.GONE);
_Menu.clear();
MenuInflater menuInflater = _Mode.getMenuInflater();
menuInflater.inflate(R.menu.menu_contextual_actionmode_options, _Menu);
ListEntry listEntry = getListEntryById(mListEntryId);
_Mode.setTitle(listEntry.mProduct.mName);
return true;
}
// called after onCreateActionMode
@Override
public boolean onPrepareActionMode(ActionMode _Mode, Menu _Menu) {
return true;
}
// called when user selected an item.
@Override
public boolean onActionItemClicked(ActionMode _Mode, MenuItem _Item) {
ListEntry entry = getListEntryById(mListEntryId);
switch (_Item.getItemId()) {
case R.id.menu_add_action:
int position = mShoppingItemListAdapter.getPositionForId(mListEntryId);
View view = mLayoutManager.findViewByPosition(position);
AmountPicker amountPicker = (AmountPicker) view.findViewById(R.id.list_product_shopping_product_amount_edit);
if (amountPicker == null) {
Log.e(LOG_TAG, "mAmountPicker is null.");
return true;
}
float value = amountPicker.getValue();
if (value == 0.0f) {
// TODO: some error messaging
return true;
}
entry.mAmount = value;
// entry.mUnit = unit;
ControllerFactory.getListController().addOrChangeItem(mCurrentShoppingList, entry.mProduct, value);
_Mode.finish();
break;
case R.id.menu_cancel_action:
_Mode.finish();
break;
case R.id.menu_delete_action:
ControllerFactory.getListController().removeItem(ListEntry.findById(ListEntry.class, mListEntryId));
_Mode.finish();
break;
default:
return false;
}
return true;
}
@Override
public void onDestroyActionMode(ActionMode _Mode) {
mShoppingItemListAdapter.resetEditModeView();
mView.setSelected(false);
mActionMode = null;
mAddButton.setVisibility(View.VISIBLE);
}
/**
* Gets the ListEntry by an id. If it is null then an @Link{NullPointerException} will be thrown.
*
* @param _Id the id of the ListEntry.
* @return the ListEntry.
*/
private ListEntry getListEntryById(long _Id) {
ListEntry listEntry = ListEntry.findById(ListEntry.class, _Id);
if (listEntry == null) {
Log.e(LOG_TAG, "ListEntry is not defined.");
throw new NullPointerException("ListEntry is not defined.");
}
return listEntry;
}
}
public ShoppingListOverviewFragment() {
}
/**
* Creates an instance of an ShoppingListOverviewFragment.
*
* @param _ListId id of the @Link{ShoppingList} that should be shown.
* @return the new instance of this fragment.
*/
public static ShoppingListOverviewFragment newInstance(long _ListId) {
ShoppingListOverviewFragment fragment = new ShoppingListOverviewFragment();
Bundle args = new Bundle();
args.putLong(MainShoppingListView.KEY_LISTID, _ListId);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Activity _Activity) {
super.onAttach(_Activity);
mContext = _Activity;
try {
mBaseActivityInterface = (IBaseActivity) _Activity;
} catch (ClassCastException e) {
throw new ClassCastException(_Activity.toString()
+ " has no IBaseActivity interface attached.");
}
mListController = ControllerFactory.getListController();
((ChangeHandler) ((GlobalApplication) getActivity().getApplication()).getChangeHandler()).setCurrentFragment(this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// get bundle args to get the listname that should be shown
Bundle bundle = this.getArguments();
mMapComperable = new WeakHashMap<>();
mMapComperable.put(0, new AlphabeticalListEntryComparator());
mMapComperable.put(1, new PriorityListEntryComparator());
if (bundle == null) {
return;
}
long listId = bundle.getLong(MainShoppingListView.KEY_LISTID);
mCurrentShoppingList = ShoppingList.findById(ShoppingList.class, listId);
// assign other listname if none is assigned
if (mCurrentShoppingList == null) {
List<ShoppingList> mShoppingLists = ShoppingList.listAll(ShoppingList.class);
if (mShoppingLists.size() > 0) {
mCurrentShoppingList = mShoppingLists.get(0);
//mBaseActivityInterface.setToolbarTitle(mCurrentShoppingList.mName);
} else {
//mBaseActivityInterface.setToolbarTitle(mContext.getResources().getString(R.string.shopping_list_overview_fragment_no_list_available));
// do something to show that there are no shoppinglists!
return;
}
}
mHandlingProductSelectedMessages = true;
EventBus.getDefault().register(this);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// swtich which action item was pressed
switch (id) {
case R.id.list_items_sort_by_priority:
mShoppingItemListAdapter.sortByComparator(mMapComperable.get(SORT_BY_PRIORITY));
PreferencesManager.getInstance().setValue(SORT_MODE, SORT_BY_PRIORITY);
break;
case R.id.list_items_sort_by_name:
mShoppingItemListAdapter.sortByComparator(mMapComperable.get(SORT_BY_NAME));
PreferencesManager.getInstance().setValue(SORT_MODE, SORT_BY_NAME);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// set the title in "main" activity so that the current list name is shown on the actionbar
//mBaseActivityInterface.setToolbarTitle(mCurrentShoppingList.mName);
mRootView = getView();
if (mRootView == null) {
throw new NullPointerException("Root view is null. Probably some initialization went wrong.");
}
mRootView.setFocusableInTouchMode(true);
// set focus to this view to get key events.
mRootView.requestFocus();
mRootView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View _View, int _KeyCode, KeyEvent _Event) {
// onKey gets 2 calls when key was pressed ( up and down) only use the up action.
if (_Event.getAction() == MotionEvent.ACTION_UP) {
// only call back button when back button was released
if (_KeyCode == KeyEvent.KEYCODE_BACK) {
if (mActionMode != null) {
mActionMode.finish();
return true;
}
}
}
return false;
}
});
}
@Override
public void onPause() {
super.onPause();
mAddButton.setOnClickListener(null);
mBaseActivityInterface.unregisterFragment(this);
}
@Override
public void onDetach() {
super.onDetach();
((ChangeHandler) ((GlobalApplication) getActivity().getApplication()).getChangeHandler()).setCurrentFragment(null);
EventBus.getDefault().unregister(this);
}
@Override
public void onResume() {
super.onResume();
mBaseActivityInterface.registerFragment(this);
// decl
// init
mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.fragment_shopping_list);
mBaseActivityInterface.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
mShoppingItemListAdapter = new ShoppingItemListAdapter(getActivity(), mCurrentShoppingList.getEntries());
int sortIndex = PreferencesManager.getInstance().getIntValue(SORT_MODE);
if (sortIndex >= 0) {
mShoppingItemListAdapter.sortByComparator(mMapComperable.get(sortIndex));
} else {
// set it by default to sort by name
mShoppingItemListAdapter.sortByComparator(mMapComperable.get(SORT_BY_NAME));
PreferencesManager.getInstance().setValue(SORT_MODE, SORT_BY_NAME);
}
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(mContext);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.addItemDecoration(new DividerItemListDecoration(getResources().getDrawable(R.drawable.list_divider), false, false));
mRecyclerView.setAdapter(mShoppingItemListAdapter);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.addOnItemTouchListener(new OnRecyclerItemTouchListener(mContext, mRecyclerView) {
private void toggleStrike(ListEntry _Entry) {
if (_Entry.mStruck) {
mListController.unstrikeItem(_Entry);
} else {
mListController.strikeItem(_Entry);
}
}
@Override
public void onSwipeRight(View _ChildView, int _Position) {
super.onSwipeRight(_ChildView, _Position);
ListEntry entry = ListEntry.findById(ListEntry.class, mShoppingItemListAdapter.getItemId(_Position));
toggleStrike(entry);
}
@Override
public void onSwipeLeft(View _ChildView, int _Position) {
super.onSwipeLeft(_ChildView, _Position);
ListEntry entry = ListEntry.findById(ListEntry.class, mShoppingItemListAdapter.getItemId(_Position));
toggleStrike(entry);
}
@Override
public void onSingleTap(View _ChildView, int _Position) {
super.onSingleTap(_ChildView, _Position);
if (mActionMode != null) {
if (_Position < 0 || mShoppingItemListAdapter.getItemViewType(_Position) != ShoppingItemListAdapter.ViewType.EDIT_MODE_VIEW) {
// only close edit field when this view is not currently in edit mode or the user clicked not on an listelement
mActionMode.finish();
}
}
// ListEntry entry = ListEntry.findById(ListEntry.class, mShoppingItemListAdapter.getItemId(_Position));
// Toast.makeText(mContext, "Item selected: " + entry.mProduct.mName, Toast.LENGTH_SHORT).show();
}
@Override
public void onLongPress(View _ChildView, int _Position) {
super.onLongPress(_ChildView, _Position);
if (mActionMode != null) {
mActionMode.finish();
}
// return if there was a long press on a position where no listitem is specified.
if (_Position < 0) {
return;
}
mShoppingItemListAdapter.setToEditMode(_Position);
mActionModeCallback = new OnShoppingListItemActionModeListener(mContext, _ChildView, mShoppingItemListAdapter.getItemId(_Position));
// Start the CAB using the Callback defined above
mActionMode = ((AppCompatActivity) getActivity()).startSupportActionMode(mActionModeCallback);
_ChildView.setSelected(true);
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// reset selected items ... (lazy resetting!)
SelectableBaseItemListEntryDataHolder.getInstance().clear();
ViewUtils.addFragment(getActivity(),
ProductListDialogFragment.newInstance());
}
});
String title = (mCurrentShoppingList == null ? "" : mCurrentShoppingList.mName);
EventBus.getDefault().post(new ToolbarChangeMessage(false, title));
}
@Override
public View onCreateView(LayoutInflater _Inflater, ViewGroup _Container, Bundle _SavedInstanceState) {
super.onCreateView(_Inflater, _Container, _SavedInstanceState);
View view = _Inflater.inflate(R.layout.fragment_main_shopping_list_view, _Container, false);
mAddButton = (FloatingActionButton) view.findViewById(R.id.add_item_main_list_view);
return view;
}
public void onEvent(ActivityStateMessage _message) {
if (_message.mActivity == getActivity()) {
mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
}
}
public void onEvent(ProductSelectMessage _message) {
if (mHandlingProductSelectedMessages) {
Map<Product, Float> productAmounts = _message.mProducts;
IListController controller = ControllerFactory.getListController();
for (Product currentProduct : productAmounts.keySet()) {
controller.addOrChangeItem(mCurrentShoppingList, currentProduct,
productAmounts.get(currentProduct), true);
}
}
}
public void onEvent(ListItemChangedMessage _message) {
switch (_message.mChange) {
case CHANGED:
onListItemUpdated(_message.mEntry);
break;
case CREATED:
onListItemAdded(_message.mEntry);
break;
case DELETED:
onListItemDeleted(_message.mEntry);
break;
}
}
/**
* Updates the adapter in the shoppinglistadapter with the given item.
*
* @param _Entry the item that should be deleted.
*/
public void onListItemUpdated(ListEntry _Entry) {
mShoppingItemListAdapter.updateListEntry(_Entry.getId());
}
/**
* Removes the given item from the containing listarray in the shoppinglistadapter.
*
* @param _Entry the item that should be deleted.
*/
public void onListItemDeleted(ListEntry _Entry) {
mShoppingItemListAdapter.removeListEntry(_Entry.getId());
}
/**
* Adds the given listentry to the listentry adapter.
*
* @param _Entry The entry that should be added to the list.
*/
public void onListItemAdded(ListEntry _Entry) {
if (_Entry.mList.getId().equals(mCurrentShoppingList.getId())) {
mShoppingItemListAdapter.addListEntry(_Entry.getId());
}
}
@Override
public void onShoppingListRemoved(ShoppingList _ShoppingList) {
if (mCurrentShoppingList.equals(_ShoppingList)) {
// TODO: set text that there is no shopping list
mBaseActivityInterface.setToolbarTitle(mContext.getResources().getString(R.string.shopping_list_not_choosen));
ViewUtils.removeFragment(getActivity(), this);
}
}
}
|
package de.fau.amos.virtualledger.android.views.contacts;
import org.junit.Test;
import de.fau.amos.virtualledger.dtos.Contact;
import static org.assertj.core.api.Assertions.assertThat;
public class ContactsComperatorTest {
@Test
public void testCompareWithEqualNamesReturnZero() {
ContactsComparator component_under_test = new ContactsComparator();
Contact contact1 = new Contact();
Contact contact2 = new Contact();
final String testFirstName = "Albert";
final String testLastName = "Quack";
contact1.setFirstName(testFirstName);
contact1.setLastName(testLastName);
contact2.setFirstName(testFirstName);
contact2.setLastName(testLastName);
final int expectedValue = 0;
assertThat(component_under_test.compare(contact1, contact2)).isEqualTo(expectedValue);
}
@Test
public void testCompareFirstStringLexicographicallyLess() {
ContactsComparator component_under_test = new ContactsComparator();
Contact contact1 = new Contact();
Contact contact2 = new Contact();
final String testFirstName = "Albert";
final String testLastName = "Quack";
final String testFirstName2 = "Daniel";
final String testLastName2 = "Düsentrieb";
contact1.setFirstName(testFirstName);
contact1.setLastName(testLastName);
contact2.setFirstName(testFirstName2);
contact2.setLastName(testLastName2);
final int referencedValue = 0;
assertThat(component_under_test.compare(contact1, contact2)).isLessThan(referencedValue);
}
@Test
public void testCompareFirstStringLexicographicallyGreater() {
ContactsComparator component_under_test = new ContactsComparator();
Contact contact1 = new Contact();
Contact contact2 = new Contact();
final String testFirstName = "Gundula";
final String testLastName = "Gause";
final String testFirstName2 = "Daisy";
final String testLastName2 = "Duck";
contact1.setFirstName(testFirstName);
contact1.setLastName(testLastName);
contact2.setFirstName(testFirstName2);
contact2.setLastName(testLastName2);
final int referencedValue = 0;
assertThat(component_under_test.compare(contact1, contact2)).isGreaterThan(referencedValue);
}
}
|
package org.ovirt.engine.core.bll;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.network.cluster.DefaultManagementNetworkFinder;
import org.ovirt.engine.core.bll.network.cluster.UpdateClusterNetworkClusterValidator;
import org.ovirt.engine.core.bll.profiles.CpuProfileHelper;
import org.ovirt.engine.core.bll.utils.VersionSupport;
import org.ovirt.engine.core.bll.validator.ClusterValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.ManagementNetworkOnClusterOperationParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.action.VdsActionParameters;
import org.ovirt.engine.core.common.businessentities.ArchitectureType;
import org.ovirt.engine.core.common.businessentities.MigrateOnErrorOptions;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.SupportedAdditionalClusterFeature;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VdsProtocol;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeEntity;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkCluster;
import org.ovirt.engine.core.common.businessentities.network.NetworkStatus;
import org.ovirt.engine.core.common.businessentities.profiles.CpuProfile;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.gluster.GlusterFeatureSupported;
import org.ovirt.engine.core.common.qualifiers.MomPolicyUpdate;
import org.ovirt.engine.core.common.utils.ListUtils;
import org.ovirt.engine.core.common.validation.group.UpdateEntity;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.dao.ClusterFeatureDao;
import org.ovirt.engine.core.dao.SupportedHostFeatureDao;
import org.ovirt.engine.core.dao.network.InterfaceDao;
import org.ovirt.engine.core.dao.network.NetworkDao;
public class UpdateVdsGroupCommand<T extends ManagementNetworkOnClusterOperationParameters> extends
VdsGroupOperationCommandBase<T> implements RenamedEntityInfoProvider{
@Inject
private DefaultManagementNetworkFinder defaultManagementNetworkFinder;
@Inject
private SupportedHostFeatureDao hostFeatureDao;
@Inject
private ClusterFeatureDao clusterFeatureDao;
@Inject
@MomPolicyUpdate
private Event<VDSGroup> momPolicyUpdatedEvent;
@Inject
private InterfaceDao interfaceDao;
@Inject
private NetworkDao networkDao;
private List<VDS> allForVdsGroup;
private VDSGroup oldGroup;
private boolean isAddedToStoragePool = false;
private NetworkCluster managementNetworkCluster;
public UpdateVdsGroupCommand(T parameters) {
this(parameters, null);
}
@Override
protected void init() {
updateMigrateOnError();
}
public UpdateVdsGroupCommand(T parameters, CommandContext commandContext) {
super(parameters, commandContext);
}
protected UpdateVdsGroupCommand(Guid commandId) {
super(commandId);
}
@Override
protected void executeCommand() {
getVdsGroup().setArchitecture(getArchitecture());
// TODO: This code should be revisited and proper compensation logic should be introduced here
checkMaxMemoryOverCommitValue();
if (!Objects.equals(oldGroup.getCompatibilityVersion(), getParameters().getVdsGroup().getCompatibilityVersion())) {
String emulatedMachine = null;
// pick an UP host randomly - all should have latest compat version already if we passed the canDo.
for (VDS vds : allForVdsGroup) {
if (vds.getStatus() == VDSStatus.Up) {
emulatedMachine = getEmulatedMachineOfHostInCluster(vds);
break;
}
}
if (emulatedMachine == null) {
getParameters().getVdsGroup().setDetectEmulatedMachine(true);
} else {
getParameters().getVdsGroup().setEmulatedMachine(emulatedMachine);
}
// create default CPU profile for cluster that is being upgraded.
// and set all attached vms and templates with cpu profile
Guid clusterId = getParameters().getVdsGroupId();
if (!FeatureSupported.cpuQoS(oldGroup.getCompatibilityVersion()) &&
FeatureSupported.cpuQoS(getParameters().getVdsGroup().getCompatibilityVersion()) &&
getCpuProfileDao().getAllForCluster(clusterId).isEmpty()) {
CpuProfile cpuProfile = CpuProfileHelper.createCpuProfile(clusterId,
getParameters().getVdsGroup().getName());
getCpuProfileDao().save(cpuProfile);
getVmStaticDao().updateVmCpuProfileIdForClusterId(clusterId, cpuProfile.getId());
}
}
else if (oldGroup.getArchitecture() != getVdsGroup().getArchitecture()) {
// if architecture was changed, emulated machines must be updated when adding new host.
// At this point the cluster is empty and have changed CPU name
getParameters().getVdsGroup().setDetectEmulatedMachine(true);
getParameters().getVdsGroup().setEmulatedMachine(null);
}
if (getParameters().isForceResetEmulatedMachine()) {
getParameters().getVdsGroup().setDetectEmulatedMachine(true);
}
boolean isKsmPolicyChanged = (getVdsGroup().isKsmMergeAcrossNumaNodes() != getPrevVdsGroup().isKsmMergeAcrossNumaNodes()) ||
(getVdsGroup().isEnableKsm() != getPrevVdsGroup().isEnableKsm());
getVdsGroupDao().update(getParameters().getVdsGroup());
addOrUpdateAddtionalClusterFeatures();
if (isAddedToStoragePool) {
for (VDS vds : allForVdsGroup) {
VdsActionParameters parameters = new VdsActionParameters();
parameters.setVdsId(vds.getId());
VdcReturnValueBase addVdsSpmIdReturn = runInternalAction(VdcActionType.AddVdsSpmId, parameters, cloneContextAndDetachFromParent());
if (!addVdsSpmIdReturn.getSucceeded()) {
setSucceeded(false);
getReturnValue().setFault(addVdsSpmIdReturn.getFault());
return;
}
}
getNetworkClusterDao().save(managementNetworkCluster);
}
alertIfFencingDisabled();
if (isKsmPolicyChanged) {
momPolicyUpdatedEvent.fire(getVdsGroup());
}
setSucceeded(true);
}
private String getEmulatedMachineOfHostInCluster(VDS vds) {
return ListUtils.firstMatch(
Config.<List<String>>getValue(ConfigValues.ClusterEmulatedMachines,
getParameters().getVdsGroup().getCompatibilityVersion().getValue()),
vds.getSupportedEmulatedMachines().split(","));
}
private void addOrUpdateAddtionalClusterFeatures() {
Set<SupportedAdditionalClusterFeature> featuresInDb =
getClusterFeatureDao().getSupportedFeaturesByClusterId(getVdsGroup().getId());
Map<Guid, SupportedAdditionalClusterFeature> featuresEnabled = new HashMap<>();
for (SupportedAdditionalClusterFeature feature : getVdsGroup().getAddtionalFeaturesSupported()) {
featuresEnabled.put(feature.getFeature().getId(), feature);
}
for (SupportedAdditionalClusterFeature featureInDb : featuresInDb) {
if (featureInDb.isEnabled() && !featuresEnabled.containsKey(featureInDb.getFeature().getId())) {
// Disable the features which are not selected in update cluster
featureInDb.setEnabled(false);
getClusterFeatureDao().updateSupportedClusterFeature(featureInDb);
} else if (!featureInDb.isEnabled() && featuresEnabled.containsKey(featureInDb.getFeature().getId())) {
// Enable the features which are selected in update cluster
featureInDb.setEnabled(true);
getClusterFeatureDao().updateSupportedClusterFeature(featureInDb);
}
featuresEnabled.remove(featureInDb.getFeature().getId());
}
// Add the newly add cluster features
if (CollectionUtils.isNotEmpty(featuresEnabled.values())) {
getClusterFeatureDao().addAllSupportedClusterFeature(featuresEnabled.values());
}
}
private NetworkCluster createManagementNetworkCluster(Network managementNetwork) {
final NetworkCluster networkCluster = new NetworkCluster(
getVdsGroup().getId(),
managementNetwork.getId(),
NetworkStatus.OPERATIONAL,
true,
true,
true,
true,
false);
return networkCluster;
}
@Override
public AuditLogType getAuditLogTypeValue() {
if (getParameters().getIsInternalCommand()) {
return getSucceeded() ? AuditLogType.SYSTEM_UPDATE_VDS_GROUP
: AuditLogType.SYSTEM_UPDATE_VDS_GROUP_FAILED;
}
return getSucceeded() ? AuditLogType.USER_UPDATE_VDS_GROUP
: AuditLogType.USER_UPDATE_VDS_GROUP_FAILED;
}
@Override
protected boolean canDoAction() {
boolean result = true;
boolean hasVms = false;
boolean hasVmOrHost = false;
boolean sameCpuNames = false;
boolean allVdssInMaintenance = false;
List<VM> vmList = null;
oldGroup = getVdsGroupDao().get(getVdsGroup().getId());
if (oldGroup == null) {
addCanDoActionMessage(EngineMessage.VDS_CLUSTER_IS_NOT_VALID);
result = false;
}
// if the name was changed then make sure the new name is unique
if (result && !StringUtils.equals(oldGroup.getName(), getVdsGroup().getName())) {
if (!isVdsGroupUnique(getVdsGroup().getName())) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_DO_ACTION_NAME_IN_USE);
result = false;
}
}
if (result && !VersionSupport.checkVersionSupported(getVdsGroup()
.getCompatibilityVersion())) {
addCanDoActionMessage(VersionSupport.getUnsupportedVersionMessage());
result = false;
}
if (result) {
allForVdsGroup = getVdsDao().getAllForVdsGroup(oldGroup.getId());
}
// decreasing of compatibility version is only allowed when no hosts exists, and not beneath the DC version
if (result && getVdsGroup().getCompatibilityVersion().compareTo(oldGroup.getCompatibilityVersion()) < 0) {
if (!allForVdsGroup.isEmpty()) {
result = false;
addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_CANNOT_DECREASE_COMPATIBILITY_VERSION);
}
if (oldGroup.getStoragePoolId() != null) {
ClusterValidator validator = new ClusterValidator(
getDbFacade(), oldGroup, getCpuFlagsManagerHandler());
if (!validate(validator.dataCenterVersionMismatch())) {
result = false;
addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_CANNOT_DECREASE_COMPATIBILITY_VERSION_UNDER_DC);
}
}
}
if (result && oldGroup.getStoragePoolId() != null
&& !oldGroup.getStoragePoolId().equals(getVdsGroup().getStoragePoolId())) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_CHANGE_STORAGE_POOL);
result = false;
}
// If both original Cpu and new Cpu are null, don't check Cpu validity
if (result) {
allVdssInMaintenance = areAllVdssInMaintenance(allForVdsGroup);
}
// Validate the cpu only if the cluster supports Virt
if (result && getVdsGroup().supportsVirtService()
&& (oldGroup.getCpuName() != null || getVdsGroup().getCpuName() != null)) {
// Check that cpu exist
if (!checkIfCpusExist()) {
addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_CPU_NOT_FOUND);
addCanDoActionMessage(EngineMessage.VAR__TYPE__CLUSTER);
result = false;
} else {
// if cpu changed from intel to amd (or backwards) and there are
// vds in this cluster, cannot update
if (!StringUtils.isEmpty(oldGroup.getCpuName())
&& !checkIfCpusSameManufacture(oldGroup)
&& !allVdssInMaintenance) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_UPDATE_CPU_ILLEGAL);
result = false;
}
}
}
if (result) {
vmList = getVmDao().getAllForVdsGroup(oldGroup.getId());
hasVmOrHost = !vmList.isEmpty() || !allForVdsGroup.isEmpty();
}
// cannot change the the processor architecture while there are attached hosts or VMs to the cluster
if (result && getVdsGroup().supportsVirtService()
&& !isArchitectureUpdatable()
&& hasVmOrHost) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_UPDATE_CPU_ARCHITECTURE_ILLEGAL);
result = false;
}
if (result) {
sameCpuNames = StringUtils.equals(oldGroup.getCpuName(), getVdsGroup().getCpuName());
}
if (result) {
boolean isOldCPUEmpty = StringUtils.isEmpty(oldGroup.getCpuName());
if (!isOldCPUEmpty && !sameCpuNames && !isCpuUpdatable(oldGroup) && hasVmOrHost) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CPU_IS_NOT_UPDATABLE);
result = false;
}
}
if (result) {
List<VDS> vdss = new ArrayList<>();
isAddedToStoragePool = oldGroup.getStoragePoolId() == null
&& getVdsGroup().getStoragePoolId() != null;
if (isAddedToStoragePool && !validateManagementNetworkAttachement()) {
return false;
}
for (VDS vds : allForVdsGroup) {
if (vds.getStatus() == VDSStatus.Up) {
if (isAddedToStoragePool) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_UPDATE_VDS_UP);
return false;
} else {
vdss.add(vds);
}
}
}
for (VDS vds : vdss) {
if (!VersionSupport.checkClusterVersionSupported(
getVdsGroup().getCompatibilityVersion(), vds)) {
result = false;
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_UPDATE_COMPATIBILITY_VERSION_WITH_LOWER_HOSTS);
break;
} else if (getVdsGroup().supportsVirtService() && missingServerCpuFlags(vds) != null) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_UPDATE_CPU_WITH_LOWER_HOSTS);
result = false;
break;
}
if (!isSupportedEmulatedMachinesMatchClusterLevel(vds)) {
return failCanDoAction(EngineMessage.VDS_GROUP_CANNOT_UPDATE_COMPATIBILITY_VERSION_WITH_INCOMPATIBLE_EMULATED_MACHINE);
}
}
if (result) {
Set<SupportedAdditionalClusterFeature> additionalClusterFeaturesAdded =
getAdditionalClusterFeaturesAdded();
// New Features cannot be enabled if all up hosts are not supporting the selected feature
if (CollectionUtils.isNotEmpty(additionalClusterFeaturesAdded)
&& !checkClusterFeaturesSupported(vdss, additionalClusterFeaturesAdded)) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_UPDATE_SUPPORTED_FEATURES_WITH_LOWER_HOSTS);
result = false;
}
}
if (result) {
boolean notDownVms = false;
boolean suspendedVms = false;
hasVms = vmList.size() > 0;
if (!sameCpuNames) {
for (VM vm : vmList) {
if (vm.getStatus() == VMStatus.Suspended) {
suspendedVms = true;
break;
} else if (vm.getStatus() != VMStatus.Down) {
notDownVms = true;
break;
}
}
if (suspendedVms) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_UPDATE_CPU_WITH_SUSPENDED_VMS);
result = false;
} else if (notDownVms) {
int compareResult = compareCpuLevels(oldGroup);
if (compareResult > 0) {// Upgrade of CPU in same compability level is allowed if
// there
// are running VMs - but we should warn they
// cannot not be hibernated
AuditLogableBase logable = new AuditLogableBase();
logable.addCustomValue("VdsGroup", getParameters().getVdsGroup().getName());
auditLogDirector.log(logable,
AuditLogType.CANNOT_HIBERNATE_RUNNING_VMS_AFTER_CLUSTER_CPU_UPGRADE);
}
}
}
}
}
if (result && getVdsGroup().getStoragePoolId() != null) {
StoragePool storagePool = getStoragePoolDao().get(getVdsGroup().getStoragePoolId());
if (oldGroup.getStoragePoolId() == null && storagePool.isLocal()) {
// we allow only one cluster in localfs data center
if (!getVdsGroupDao().getAllForStoragePool(getVdsGroup().getStoragePoolId()).isEmpty()) {
getReturnValue()
.getCanDoActionMessages()
.add(EngineMessage.VDS_GROUP_CANNOT_ADD_MORE_THEN_ONE_HOST_TO_LOCAL_STORAGE
.toString());
result = false;
}
else if (Config.getValue(ConfigValues.AutoRegistrationDefaultVdsGroupID).equals(getVdsGroup().getId())) {
addCanDoActionMessage(EngineMessage.DEFAULT_CLUSTER_CANNOT_BE_ON_LOCALFS);
result = false;
}
}
}
if (getVdsGroup().getCompatibilityVersion() != null
&& Version.v3_3.compareTo(getVdsGroup().getCompatibilityVersion()) > 0
&& getVdsGroup().isEnableBallooning()) {
// Members of pre-3.3 clusters don't support ballooning; here we act like a 3.2 engine
addCanDoActionMessage(EngineMessage.QOS_BALLOON_NOT_SUPPORTED);
result = false;
}
if (getVdsGroup().supportsGlusterService()
&& !GlusterFeatureSupported.gluster(getVdsGroup().getCompatibilityVersion())) {
addCanDoActionMessage(EngineMessage.GLUSTER_NOT_SUPPORTED);
addCanDoActionMessageVariable("compatibilityVersion", getVdsGroup().getCompatibilityVersion().getValue());
result = false;
}
if (result) {
if (!(getVdsGroup().supportsGlusterService() || getVdsGroup().supportsVirtService())) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_AT_LEAST_ONE_SERVICE_MUST_BE_ENABLED);
result = false;
}
else if (getVdsGroup().supportsGlusterService() && getVdsGroup().supportsVirtService()
&& !isAllowClusterWithVirtGluster()) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_ENABLING_BOTH_VIRT_AND_GLUSTER_SERVICES_NOT_ALLOWED);
result = false;
}
}
if (result && hasVms && !getVdsGroup().supportsVirtService()) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_DISABLE_VIRT_WHEN_CLUSTER_CONTAINS_VMS);
result = false;
}
if (result && !getVdsGroup().supportsGlusterService()) {
List<GlusterVolumeEntity> volumes = getGlusterVolumeDao().getByClusterId(getVdsGroup().getId());
if (volumes != null && volumes.size() > 0) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_DISABLE_GLUSTER_WHEN_CLUSTER_CONTAINS_VOLUMES);
result = false;
}
}
if (result && getVdsGroup().supportsTrustedService() && Config.<String> getValue(ConfigValues.AttestationServer).equals("")) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_CANNOT_SET_TRUSTED_ATTESTATION_SERVER_NOT_CONFIGURED);
result = false;
}
if (result
&& !FeatureSupported.isMigrationSupported(getArchitecture(), getVdsGroup().getCompatibilityVersion())
&& getVdsGroup().getMigrateOnError() != MigrateOnErrorOptions.NO) {
return failCanDoAction(EngineMessage.MIGRATION_ON_ERROR_IS_NOT_SUPPORTED);
}
if (result) {
result = validateClusterPolicy();
}
// non-empty required sources list and rng-unsupported cluster version
if (result && !getVdsGroup().getRequiredRngSources().isEmpty()
&& !FeatureSupported.virtIoRngSupported(getVdsGroup().getCompatibilityVersion())) {
addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_RNG_SOURCE_NOT_SUPPORTED);
result = false;
}
if (result && getParameters().isForceResetEmulatedMachine()) {
for (VDS vds : allForVdsGroup) {
if (vds.getStatus() == VDSStatus.Up) {
addCanDoActionMessage(EngineMessage.VDS_GROUP_HOSTS_MUST_BE_DOWN);
result = false;
break;
}
}
}
if (result && Version.v3_6.compareTo(getVdsGroup().getCompatibilityVersion()) <= 0) {
List<String> names = new ArrayList<>();
for (VDS host : allForVdsGroup) {
if (VdsProtocol.XML == host.getProtocol()) {
names.add(host.getName());
}
}
if (!names.isEmpty()) {
return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_WRONG_PROTOCOL_FOR_CLUSTER_VERSION);
}
}
return result;
}
protected boolean isSupportedEmulatedMachinesMatchClusterLevel(VDS vds) {
return getEmulatedMachineOfHostInCluster(vds) != null;
}
private Set<SupportedAdditionalClusterFeature> getAdditionalClusterFeaturesAdded() {
// Lets not modify the existing collection. Hence creating a new hashset.
Set<SupportedAdditionalClusterFeature> featuresSupported =
new HashSet<>(getVdsGroup().getAddtionalFeaturesSupported());
featuresSupported.removeAll(getClusterFeatureDao().getSupportedFeaturesByClusterId(getVdsGroup().getId()));
return featuresSupported;
}
private boolean checkClusterFeaturesSupported(List<VDS> vdss,
Set<SupportedAdditionalClusterFeature> newFeaturesEnabled) {
Set<String> featuresNamesEnabled = new HashSet<>();
for (SupportedAdditionalClusterFeature feature : newFeaturesEnabled) {
featuresNamesEnabled.add(feature.getFeature().getName());
}
for (VDS vds : vdss) {
Set<String> featuresSupportedByVds = getHostFeatureDao().getSupportedHostFeaturesByHostId(vds.getId());
if (!featuresSupportedByVds.containsAll(featuresNamesEnabled)) {
return false;
}
}
return true;
}
private boolean validateManagementNetworkAttachement() {
final Network managementNetwork;
final Guid managementNetworkId = getParameters().getManagementNetworkId();
if (managementNetworkId == null) {
managementNetwork =
getDefaultManagementNetworkFinder().findDefaultManagementNetwork(getVdsGroup().getStoragePoolId());
if (managementNetwork == null) {
addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_DEFAULT_MANAGEMENT_NETWORK_NOT_FOUND);
return false;
}
} else {
managementNetwork = getNetworkDao().get(managementNetworkId);
if (managementNetwork == null) {
addCanDoActionMessage(EngineMessage.NETWORK_NOT_EXISTS);
return false;
}
}
managementNetworkCluster = createManagementNetworkCluster(managementNetwork);
final UpdateClusterNetworkClusterValidator networkClusterValidator = createManagementNetworkClusterValidator();
return validate(networkClusterValidator.managementNetworkChange());
}
@Override
protected void setActionMessageParameters() {
super.setActionMessageParameters();
addCanDoActionMessage(EngineMessage.VAR__ACTION__UPDATE);
}
protected boolean isArchitectureUpdatable() {
return oldGroup.getArchitecture() == ArchitectureType.undefined ? true
: getArchitecture() == oldGroup.getArchitecture();
}
protected boolean checkIfCpusSameManufacture(VDSGroup group) {
return getCpuFlagsManagerHandler().checkIfCpusSameManufacture(group.getCpuName(),
getVdsGroup().getCpuName(),
getVdsGroup().getCompatibilityVersion());
}
protected boolean checkIfCpusExist() {
return getCpuFlagsManagerHandler().checkIfCpusExist(getVdsGroup().getCpuName(),
getVdsGroup().getCompatibilityVersion());
}
protected List<String> missingServerCpuFlags(VDS vds) {
return getCpuFlagsManagerHandler().missingServerCpuFlags(
getVdsGroup().getCpuName(),
vds.getCpuFlags(),
getVdsGroup().getCompatibilityVersion());
}
protected boolean isCpuUpdatable(VDSGroup cluster) {
return getCpuFlagsManagerHandler().isCpuUpdatable(cluster.getCpuName(), cluster.getCompatibilityVersion());
}
private boolean areAllVdssInMaintenance(List<VDS> vdss) {
boolean allInMaintenance = true;
for (VDS vds : vdss) {
if (vds.getStatus() != VDSStatus.Maintenance) {
allInMaintenance = false;
break;
}
}
return allInMaintenance;
}
protected int compareCpuLevels(VDSGroup otherGroup) {
return getCpuFlagsManagerHandler().compareCpuLevels(getVdsGroup().getCpuName(),
otherGroup.getCpuName(),
otherGroup.getCompatibilityVersion());
}
@Override
protected List<Class<?>> getValidationGroups() {
addValidationGroup(UpdateEntity.class);
return super.getValidationGroups();
}
@Override
protected NetworkDao getNetworkDao() {
return getDbFacade().getNetworkDao();
}
@Override
public String getEntityType() {
return VdcObjectType.VdsGroups.getVdcObjectTranslation();
}
@Override
public String getEntityOldName() {
return oldGroup.getName();
}
@Override
public String getEntityNewName() {
return getParameters().getVdsGroup().getName();
}
@Override
public void setEntityId(AuditLogableBase logable) {
logable.setVdsGroupId(oldGroup.getId());
}
DefaultManagementNetworkFinder getDefaultManagementNetworkFinder() {
return defaultManagementNetworkFinder;
}
UpdateClusterNetworkClusterValidator createManagementNetworkClusterValidator() {
return new UpdateClusterNetworkClusterValidator(
interfaceDao,
networkDao,
managementNetworkCluster,
getVdsGroup().getCompatibilityVersion());
}
public SupportedHostFeatureDao getHostFeatureDao() {
return hostFeatureDao;
}
public ClusterFeatureDao getClusterFeatureDao() {
return clusterFeatureDao;
}
}
|
package org.ovirt.engine.core.bll;
import java.util.HashMap;
import java.util.Map;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.ovirt.engine.core.common.businessentities.IVdsAsyncCommand;
import org.ovirt.engine.core.common.errors.EngineException;
import org.ovirt.engine.core.common.interfaces.FutureVDSCall;
import org.ovirt.engine.core.common.interfaces.VDSBrokerFrontend;
import org.ovirt.engine.core.common.vdscommands.FutureVDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSParametersBase;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.VdsAndVmIDVDSParametersBase;
import org.ovirt.engine.core.common.vdscommands.VdsIdVDSCommandParametersBase;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.vdsbroker.ResourceManager;
@Singleton
public class VDSBrokerFrontendImpl implements VDSBrokerFrontend {
@Inject
private Instance<ResourceManager> resourceManager;
private Map<Guid, IVdsAsyncCommand> _asyncRunningCommands = new HashMap<>();
@Override
public VDSReturnValue RunVdsCommand(VDSCommandType commandType, VDSParametersBase parameters) {
return VdsHandler.handleVdsResult(getResourceManager().runVdsCommand(commandType, parameters));
}
@Override
public VDSReturnValue RunAsyncVdsCommand(VDSCommandType commandType, VdsAndVmIDVDSParametersBase parameters,
IVdsAsyncCommand command) {
VDSReturnValue result = RunVdsCommand(commandType, parameters);
if (result.getSucceeded()) {
// Add async command to cached commands
IVdsAsyncCommand prevCommand = _asyncRunningCommands.put(parameters.getVmId(), command);
if (prevCommand != null && !prevCommand.equals(command)) {
prevCommand.reportCompleted();
}
} else {
throw new EngineException(result.getVdsError().getCode(), result.getExceptionString());
}
return result;
}
@Override
public IVdsAsyncCommand GetAsyncCommandForVm(Guid vmId) {
IVdsAsyncCommand result = null;
result = _asyncRunningCommands.get(vmId);
return result;
}
@Override
public IVdsAsyncCommand RemoveAsyncRunningCommand(Guid vmId) {
return _asyncRunningCommands.remove(vmId);
}
@Override
public FutureVDSCall<VDSReturnValue> runFutureVdsCommand(FutureVDSCommandType commandType,
VdsIdVDSCommandParametersBase parameters) {
return getResourceManager().runFutureVdsCommand(commandType, parameters);
}
private ResourceManager getResourceManager() {
return resourceManager.get();
}
}
|
package org.iidp.ostmap.batch_processing.areacalc;
import org.apache.flink.api.common.functions.GroupReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
import java.io.Serializable;
import java.util.TreeSet;
public class CoordGroupReduce implements GroupReduceFunction<Tuple2<String, String>, Tuple2<String, String>>, Serializable {
private String user = "";
private String coords = "";
private TreeSet<String> coordSet = new TreeSet<>();
@Override
public void reduce(Iterable<Tuple2<String, String>> values, Collector<Tuple2<String, /*TODO POJO*/String>> out) throws Exception {
for (Tuple2<String,String> entry: values) {
if (coords.equals("")) {
coords += entry.f1;
} else {
coords += "|" + entry.f1;
}
user = entry.f0;
coordSet.add(entry.f1.toString());
}
if(coordSet.size() > 2){
out.collect(new Tuple2<String,String>(user,coords));
}
}
}
|
package com.s2d.bcc.light.controller.core;
public interface LightController
{
void initialize ();
int getLightCount ();
void set ( int lightIndex, boolean on );
void execute ();
void close ();
}
|
package org.intermine.bio.dataconversion;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.bio.util.OrganismRepository;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.StringUtil;
import org.intermine.xml.full.Attribute;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.Reference;
import org.intermine.xml.full.ReferenceList;
/**
* Create items from the modENCODE metadata extensions to the chado schema.
* @author Kim Rutherford,sc,rns
*/
public class ModEncodeMetaDataProcessor extends ChadoProcessor
{
private static final Logger LOG = Logger.getLogger(ModEncodeMetaDataProcessor.class);
private static final String WIKI_URL = "http://wiki.modencode.org/project/index.php?title=";
private static final String FILE_URL = "http://submit.modencode.org/submit/public/get_file/";
private static final Set<String> DB_RECORD_TYPES =
Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(
"GEO_record",
"ArrayExpress_record",
"TraceArchive_record",
"dbEST_record",
"ShortReadArchive_project_ID (SRA)",
"ShortReadArchive_project_ID_list (SRA)")));
// submission maps
private Map<Integer, String> submissionOrganismMap = new HashMap<Integer, String>();
// maps from chado identifier to lab/project details
private Map<Integer, SubmissionDetails> submissionMap =
new HashMap<Integer, SubmissionDetails>();
// chado submission id to list of top level attributes, e.g. dev stage, organism_part
private Map<Integer, String> dccIdMap = new HashMap<Integer, String>();
private Map<Integer, ExperimentalFactor> submissionEFMap =
new HashMap<Integer, ExperimentalFactor>();
// applied_protocol/data/attribute maps
// chado submission id to chado data_id
private Map<Integer, List<Integer>> submissionDataMap = new HashMap<Integer, List<Integer>>();
// chado data id to chado submission id
private Map<Integer, Integer> dataSubmissionMap = new HashMap<Integer, Integer>();
// used when traversing dag of applied protocols
private Map<Integer, AppliedProtocol> appliedProtocolMap =
new HashMap<Integer, AppliedProtocol>();
// used when traversing dag of applied protocols
private Map<Integer, AppliedData> appliedDataMap =
new HashMap<Integer, AppliedData>();
// project/lab/experiment/submission maps
// for projects, the maps link the project name with the identifiers...
private Map<String, Integer> projectIdMap = new HashMap<String, Integer>();
private Map<String, String> projectIdRefMap = new HashMap<String, String>();
// for labs, the maps link the lab name with the identifiers...
private Map<String, Integer> labIdMap = new HashMap<String, Integer>();
private Map<String, String> labIdRefMap = new HashMap<String, String>();
// for experiment, the maps link the exp name (description!) with the identifiers...
private Map<String, Integer> experimentIdMap = new HashMap<String, Integer>();
private Map<String, String> experimentIdRefMap = new HashMap<String, String>();
private Map<String, List<Integer>> expSubMap = new HashMap<String, List<Integer>>();
// ...we need a further map to link to submission
private Map<Integer, String> submissionProjectMap = new HashMap<Integer, String>();
private Map<Integer, String> submissionLabMap = new HashMap<Integer, String>();
// submission/applied_protocol/protocol maps
private Map<String, String> protocolsMap = new HashMap<String, String>();
private Map<Integer, String> protocolItemIds = new HashMap<Integer, String>();
private Map<String, Integer> protocolItemToObjectId = new HashMap<String, Integer>();
// submission chado id to item identifier of Protocol used to generate GFF
private Map<Integer, String> scoreProtocols = new HashMap<Integer, String>();
private Map<Integer, Integer> publicationIdMap = new HashMap<Integer, Integer>();
private Map<Integer, String> publicationIdRefMap = new HashMap<Integer, String>();
private Map<Integer, String> protocolTypesMap = new HashMap<Integer, String>();
private Map<Integer, Integer> appliedProtocolIdMap = new HashMap<Integer, Integer>();
private Map<Integer, String> appliedProtocolIdRefMap = new HashMap<Integer, String>();
// list of firstAppliedProtocols, first level of the DAG linking
// the applied protocols through the data (and giving the flow of data)
private List<Integer> firstAppliedProtocols = new ArrayList<Integer>();
// experimental factor maps
private Map<String, Integer> eFactorIdMap = new HashMap<String, Integer>();
private Map<String, String> eFactorIdRefMap = new HashMap<String, String>();
private Map<Integer, List<String>> submissionEFactorMap = new HashMap<Integer, List<String>>();
// caches
// cache cv term names by id
private Map<String, String> cvtermCache = new HashMap<String, String>();
private Map<String, String> devStageTerms = new HashMap<String, String>();
private Map<String, String> devOntologies = new HashMap<String, String>();
// just for debugging
private Map<String, String> debugMap = new HashMap<String, String>(); // itemIdentifier, type
private Map<String, Item> nonWikiSubmissionProperties = new HashMap<String, Item>();
private Map<String, Item> subItemsMap = new HashMap<String, Item>();
Map<Integer, SubmissionReference> submissionRefs = null;
private IdResolverFactory flyResolverFactory = null;
private IdResolverFactory wormResolverFactory = null;
private Map<String, String> geneToItemIdentifier = new HashMap<String, String>();
private Map<DatabaseRecordKey, String> dbRecords = new HashMap<DatabaseRecordKey, String>();
private static class SubmissionDetails
{
// the identifier assigned to Item eg. "0_23"
private String itemIdentifier;
// the object id of the stored Item
private Integer interMineObjectId;
// the identifier assigned to lab Item for this object
private String labItemIdentifier;
private String title;
}
/**
* AppliedProtocol class to reconstruct the flow of submission data
*/
private static class AppliedProtocol
{
private Integer submissionId; // chado
private Integer protocolId;
private Integer step; // the level in the dag for the AP
// the output data associated to this applied protocol
private List<Integer> outputs = new ArrayList<Integer>();
private List<Integer> inputs = new ArrayList<Integer>();
}
/**
* AppliedData class
* to reconstruct the flow of submission data
*
*/
private static class AppliedData
{
private String itemIdentifier;
private Integer intermineObjectId;
private Integer dataId;
private String value;
private String actualValue;
private String type;
private String name;
// the list of applied protocols for which this data item is an input
private List<Integer> nextAppliedProtocols = new ArrayList<Integer>();
private List<Integer> previousAppliedProtocols = new ArrayList<Integer>();
}
/**
* Experimental Factor class
* to store the couples (type, name/value) of EF
* note that in chado sometime the name is given, other times is the value
*/
private static class ExperimentalFactor
{
private Map<String, String> efTypes = new HashMap<String, String>();
private List<String> efNames = new ArrayList<String>();
}
/**
* Create a new ChadoProcessor object
* @param chadoDBConverter the converter that created this Processor
*/
public ModEncodeMetaDataProcessor(ChadoDBConverter chadoDBConverter) {
super(chadoDBConverter);
}
/**
* {@inheritDoc}
*/
@Override
public void process(Connection connection) throws Exception {
processProjectTable(connection);
processLabTable(connection);
//processLabAttributes(connection);
processSubmissionOrganism(connection);
processSubmission(connection);
processExperimentProps(connection);
processProtocolTable(connection);
processProtocolAttributes(connection);
processAppliedProtocolTable(connection);
processAppliedData(connection);
processAppliedDataAttributes(connection);
processExperiment(connection);
processDag(connection);
findScoreProtocols();
processFeatures(connection, submissionMap);
// set references
setSubmissionRefs(connection);
setSubmissionExperimetRefs(connection);
setDAGRefs(connection);
// create DatabaseRecords where necessary for each submission
createDatabaseRecords(connection);
// create result files per submission
createResultFiles(connection);
// for high level attributes and experimental factors (EF)
// TODO: clean up
processEFactor(connection);
flyResolverFactory = new FlyBaseIdResolverFactory("gene");
wormResolverFactory = new WormBaseChadoIdResolverFactory("gene");
processSubmissionProperties(connection);
createRelatedSubmissions(connection);
setSubmissionProtocolsRefs(connection);
setSubmissionEFactorsRefs(connection);
setSubmissionPublicationRefs(connection);
}
private void processFeatures(Connection connection,
Map<Integer, SubmissionDetails> submissionMap)
throws Exception {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
// hold features that should only be processed once across all submissions, initialise
// processor with this map each time
Map <Integer, FeatureData> commonFeaturesMap = new HashMap<Integer, FeatureData>();
for (Map.Entry<Integer, SubmissionDetails> entry: submissionMap.entrySet()) {
Map<Integer, FeatureData> subFeatureMap = new HashMap<Integer, FeatureData>();
Integer chadoExperimentId = entry.getKey();
SubmissionDetails submissionDetails = entry.getValue();
String submissionItemIdentifier = submissionDetails.itemIdentifier;
String labItemIdentifier = submissionDetails.labItemIdentifier;
String submissionTitle = submissionDetails.title;
List<Integer> thisSubmissionDataIds = submissionDataMap.get(chadoExperimentId);
LOG.info("DATA IDS " + chadoExperimentId + ": " + thisSubmissionDataIds.size());
ModEncodeFeatureProcessor processor =
new ModEncodeFeatureProcessor(getChadoDBConverter(), submissionItemIdentifier,
labItemIdentifier, thisSubmissionDataIds, submissionTitle,
scoreProtocols.get(chadoExperimentId));
processor.initialiseCommonFeatures(commonFeaturesMap);
processor.process(connection);
// all features related to this submission
subFeatureMap.putAll(processor.getFeatureMap());
// features common across many submissions
commonFeaturesMap.putAll(processor.getCommonFeaturesMap());
LOG.info("COMMON FEATURES: " + commonFeaturesMap.size());
if (subFeatureMap.keySet().size() == 0) {
LOG.error("FEATMAP: submission " + chadoExperimentId
+ " has no featureMap keys.");
continue;
}
LOG.info("FEATMAP: submission " + chadoExperimentId + "|"
+ "featureMap: " + subFeatureMap.keySet().size());
String queryList = StringUtil.join(thisSubmissionDataIds, ",");
processDataFeatureTable(connection, subFeatureMap, chadoExperimentId, queryList);
// read any genes that have been created so we can re-use the same item identifiers
// when creating antibody/strain target genes later
extractGenesFromSubFeatureMap(processor, subFeatureMap);
}
LOG.info("PROCESS TIME features: " + (System.currentTimeMillis() - bT));
}
private void extractGenesFromSubFeatureMap(ModEncodeFeatureProcessor processor,
Map<Integer, FeatureData> subFeatureMap) {
for (FeatureData fData : subFeatureMap.values()) {
if (fData.getInterMineType().equals("Gene")) {
String geneIdentifier = processor.fixIdentifier(fData, fData.getUniqueName());
geneToItemIdentifier.put(geneIdentifier, fData.getItemIdentifier());
}
}
}
/**
* @param connection
* @param featureMap
* @throws SQLException
* @throws ObjectStoreException
*/
private void processDataFeatureTable(Connection connection, Map<Integer,
FeatureData> featureMap, Integer chadoExperimentId, String queryList)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getDataFeature(connection, queryList);
ReferenceList collection = null;
String submissionItemId = submissionMap.get(chadoExperimentId).itemIdentifier;
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
Integer featureId = new Integer(res.getInt("feature_id"));
FeatureData featureData = featureMap.get(featureId);
if (featureData == null) {
LOG.debug("Check feature type: no data for feature_id: " + featureId
+ " in processDataFeatureTable(), data_id =" + dataId);
continue;
}
// add submission collection
// using the old setting when the reference was added to the data_ids.
// TODO: it needs correction: here stores only the last submission reference.
Integer featureObjectId = featureData.getIntermineObjectId();
collection = new ReferenceList();
collection.setName("submissions");
collection.addRefId(submissionItemId);
getChadoDBConverter().store(collection, featureObjectId);
}
LOG.info("PROCESS TIME data_feature table: " + (System.currentTimeMillis() - bT));
}
private ResultSet getDataFeature(Connection connection, String queryList)
throws SQLException {
String query =
"SELECT df.data_id, df.feature_id"
+ " FROM data_feature df "
+ " WHERE data_id in (" + queryList + ")";
return doQuery(connection, query, "getDataFeature");
}
private void processDag(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getDAG(connection);
AppliedProtocol node = new AppliedProtocol();
AppliedData branch = null;
Integer count = 0;
Integer actualSubmissionId = 0; // to store the experiment id (see below)
Integer previousAppliedProtocolId = 0;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
Integer protocolId = new Integer(res.getInt("protocol_id"));
Integer appliedProtocolId = new Integer(res.getInt("applied_protocol_id"));
Integer dataId = new Integer(res.getInt("data_id"));
String direction = res.getString("direction");
// build a data node for each iteration
if (appliedDataMap.containsKey(dataId)) {
branch = appliedDataMap.get(dataId);
} else {
branch = new AppliedData();
}
// could use > (order by apid, apdataid, direction)
// NB: using isLast() is expensive
if (!appliedProtocolId.equals(previousAppliedProtocolId) || res.isLast()) {
// the submissionId != null for the first applied protocol
if (submissionId > 0) {
firstAppliedProtocols.add(appliedProtocolId);
// set actual submission id
// we can either be at a first applied protocol (submissionId > 0)..
actualSubmissionId = submissionId;
} else {
// ..or already down the dag, and we use the stored id.
submissionId = actualSubmissionId;
}
// last one: fill the list of outputs
// and add to the general list of data ids for the submission,
// used to fetch features
if (res.isLast()) {
if (direction.equalsIgnoreCase("output")) {
node.outputs.add(dataId);
mapSubmissionAndData(submissionId, dataId);
dataSubmissionMap.put(dataId, submissionId);
}
}
// if it is not the first iteration, let's store it
if (previousAppliedProtocolId > 0) {
appliedProtocolMap.put(previousAppliedProtocolId, node);
}
// new node
AppliedProtocol newNode = new AppliedProtocol();
newNode.protocolId = protocolId;
newNode.submissionId = submissionId;
if (direction.startsWith("in")) {
// add this applied protocol to the list of nextAppliedProtocols
branch.nextAppliedProtocols.add(appliedProtocolId);
// ..and update the map
if (appliedDataMap.containsKey(dataId)) {
appliedDataMap.remove(dataId);
}
appliedDataMap.put(dataId, branch);
// .. and add the dataId to the list of input Data for this applied protocol
newNode.inputs.add(dataId);
} else if (direction.startsWith("out")) {
// add the dataId to the list of output Data for this applied protocol:
// it will be used to link to the next set of applied protocols
newNode.outputs.add(dataId);
if (!previousAppliedProtocolId.equals(0)) {
branch.previousAppliedProtocols.add(previousAppliedProtocolId);
}
} else {
// there is some problem with the strings 'input' or 'output'
throw new IllegalArgumentException("Data direction not valid for dataId: "
+ dataId + "|" + direction + "|");
}
// for the new round..
node = newNode;
previousAppliedProtocolId = appliedProtocolId;
} else {
// keep feeding IN et OUT
if (direction.startsWith("in")) {
node.inputs.add(dataId);
if (submissionId > 0) {
// initial data
mapSubmissionAndData(submissionId, dataId);
}
// as above
branch.nextAppliedProtocols.add(appliedProtocolId);
if (!appliedDataMap.containsKey(dataId)) {
appliedDataMap.put(dataId, branch);
} else {
appliedDataMap.remove(dataId);
appliedDataMap.put(dataId, branch);
}
} else if (direction.startsWith("out")) {
node.outputs.add(dataId);
branch.previousAppliedProtocols.add(previousAppliedProtocolId);
} else {
throw new IllegalArgumentException("Data direction not valid for dataId: "
+ dataId + "|" + direction + "|");
}
}
count++;
}
LOG.info("created " + appliedProtocolMap.size()
+ "(" + count + " applied data points) DAG nodes (= applied protocols) in map");
res.close();
// now traverse the DAG, and associate submission with all the applied protocols
traverseDag();
// set the dag level as an attribute to applied protocol
setAppliedProtocolSteps(connection);
LOG.info("PROCESS TIME DAG: " + (System.currentTimeMillis() - bT));
}
/**
*
* to set the step attribute for the applied protocols
*
*/
private void setAppliedProtocolSteps(Connection connection)
throws ObjectStoreException {
for (Integer appliedProtocolId : appliedProtocolMap.keySet()) {
Integer step = appliedProtocolMap.get(appliedProtocolId).step;
if (step != null) {
Attribute attr = new Attribute("step", step.toString());
getChadoDBConverter().store(attr, appliedProtocolIdMap.get(appliedProtocolId));
} else {
AppliedProtocol ap = appliedProtocolMap.get(appliedProtocolId);
LOG.warn("AppliedProtocol.step not set for chado id: " + appliedProtocolId
+ " sub " + ap.submissionId + " inputs " + ap.inputs + " outputs "
+ ap.outputs);
}
}
}
// Look for protocols that were used to generated GFF files, these are passed to the feature
// processor, if features have a score the protocol is set as the scoreProtocol reference.
// NOTE this could equally be done with data, data_feature and applied_protocol_data
private void findScoreProtocols() {
for (Map.Entry<Integer, AppliedData> entry : appliedDataMap.entrySet()) {
Integer dataId = entry.getKey();
AppliedData aData = entry.getValue();
if (aData.type.equals("Result File")
&& (aData.value.endsWith(".gff") || aData.value.endsWith("gff3"))) {
for (Integer papId : aData.previousAppliedProtocols) {
AppliedProtocol aProtocol = appliedProtocolMap.get(papId);
String protocolItemId = protocolItemIds.get(aProtocol.protocolId);
scoreProtocols.put(dataSubmissionMap.get(dataId), protocolItemId);
}
}
}
}
/**
* Return the rows needed to construct the DAG of the data/protocols.
* The reference to the submission is available only for the first set
* of applied protocols, hence the outer join.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getDAG(Connection connection)
throws SQLException {
String query =
"SELECT eap.experiment_id, ap.protocol_id, apd.applied_protocol_id"
+ " , apd.data_id, apd.applied_protocol_data_id, apd.direction"
+ " FROM applied_protocol ap LEFT JOIN experiment_applied_protocol eap"
+ " ON (eap.first_applied_protocol_id = ap.applied_protocol_id )"
+ " , applied_protocol_data apd"
+ " WHERE apd.applied_protocol_id = ap.applied_protocol_id"
+ " ORDER By 3,5,6";
return doQuery(connection, query, "getDAG");
}
/**
* Applies iteratively buildADaglevel
*
* @throws SQLException
* @throws ObjectStoreException
*/
private void traverseDag()
throws SQLException, ObjectStoreException {
List<Integer> currentIterationAP = firstAppliedProtocols;
List<Integer> nextIterationAP = new ArrayList<Integer>();
Integer step = 1; // DAG level
while (currentIterationAP.size() > 0) {
nextIterationAP = buildADagLevel (currentIterationAP, step);
currentIterationAP = nextIterationAP;
step++;
}
}
/**
* This method is given a set of applied protocols (already associated with a submission)
* and produces the next set of applied protocols. The latter are the protocols attached to the
* output data of the starting set (output data for a applied protocol is the input data for the
* next one).
* It also fills the map linking directly results ('leaf' output data) with submission
*
* @param previousAppliedProtocols
* @return the next batch of appliedProtocolId
* @throws SQLException
* @throws ObjectStoreException
*/
private List<Integer> buildADagLevel(List<Integer> previousAppliedProtocols, Integer step)
throws SQLException, ObjectStoreException {
List<Integer> nextIterationProtocols = new ArrayList<Integer>();
Iterator<Integer> pap = previousAppliedProtocols.iterator();
while (pap.hasNext()) {
List<Integer> outputs = new ArrayList<Integer>();
List<Integer> inputs = new ArrayList<Integer>();
Integer currentId = pap.next();
// add the DAG level here only if these are the first AP
if (step == 1) {
appliedProtocolMap.get(currentId).step = step;
}
outputs.addAll(appliedProtocolMap.get(currentId).outputs);
Integer submissionId = appliedProtocolMap.get(currentId).submissionId;
Iterator<Integer> od = outputs.iterator();
while (od.hasNext()) {
Integer currentOD = od.next();
List<Integer> nextProtocols = new ArrayList<Integer>();
// build map submission-data
mapSubmissionAndData(submissionId, currentOD);
if (appliedDataMap.containsKey(currentOD)) {
// fill the list of next (children) protocols
nextProtocols.addAll(appliedDataMap.get(currentOD).nextAppliedProtocols);
if (appliedDataMap.get(currentOD).nextAppliedProtocols.isEmpty()) {
// this is a leaf!!
}
}
// to fill submission-dataId map
// this is needed, otherwise inputs to AP that are not outputs
// of a previous protocol are not considered
inputs.addAll(appliedProtocolMap.get(currentId).inputs);
Iterator<Integer> in = inputs.iterator();
while (in.hasNext()) {
Integer currentIn = in.next();
// build map submission-data
mapSubmissionAndData(submissionId, currentIn);
}
// build the list of children applied protocols chado identifiers
// as input for the next iteration
Iterator<Integer> nap = nextProtocols.iterator();
while (nap.hasNext()) {
Integer currentAPId = nap.next();
// and fill the map with the chado experiment_id
// and the DAG level
appliedProtocolMap.get(currentAPId).submissionId = submissionId;
appliedProtocolMap.get(currentAPId).step = step + 1;
nextIterationProtocols.add(currentAPId);
// and set the reference from applied protocol to the submission
Reference reference = new Reference();
reference.setName("submission");
reference.setRefId(submissionMap.get(submissionId).itemIdentifier);
getChadoDBConverter().store(reference, appliedProtocolIdMap.get(currentAPId));
}
}
}
return nextIterationProtocols;
}
private void processSubmissionOrganism(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getSubmissionOrganism(connection);
int count = 0;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
String value = res.getString("value");
submissionOrganismMap.put(submissionId, value);
count++;
}
res.close();
LOG.info("found an organism for " + submissionOrganismMap.size() + " submissions.");
LOG.info("PROCESS TIME organisms: " + (System.currentTimeMillis() - bT));
}
/**
* Return the row needed for the organism.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getSubmissionOrganism(Connection connection)
throws SQLException {
String query =
"select distinct eap.experiment_id, a.value "
+ " from experiment_applied_protocol eap, applied_protocol ap, "
+ " protocol_attribute pa, attribute a "
+ " where eap.first_applied_protocol_id = ap.applied_protocol_id "
+ " and ap.protocol_id=pa.protocol_id "
+ " and pa.attribute_id=a.attribute_id "
+ " and a.heading='species' ";
return doQuery(connection, query, "getSubmissionOrganism");
}
private void processProjectTable(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getProjects(connection);
int count = 0;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
String value = res.getString("value");
submissionProjectMap.put(submissionId, value);
count++;
}
res.close();
Set <Integer> exp = submissionProjectMap.keySet();
Iterator <Integer> i = exp.iterator();
while (i.hasNext()) {
Integer thisExp = i.next();
String project = submissionProjectMap.get(thisExp);
if (projectIdMap.containsKey(project)) {
continue;
}
LOG.debug("PROJECT: " + project);
Item pro = getChadoDBConverter().createItem("Project");
pro.setAttribute("surnamePI", project);
Integer intermineObjectId = getChadoDBConverter().store(pro);
storeInProjectMaps(pro, project, intermineObjectId);
}
LOG.info("created " + projectIdMap.size() + " project");
LOG.info("PROCESS TIME projects: " + (System.currentTimeMillis() - bT));
}
/**
* Return the project name.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getProjects(Connection connection)
throws SQLException {
String query =
"SELECT distinct a.experiment_id, a.value "
+ " FROM experiment_prop a "
+ " where a.name = 'Project' "
+ " AND rank=0";
return doQuery(connection, query, "getProjects");
}
private void processLabTable(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getLabs(connection);
int count = 0;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
String value = res.getString("value");
submissionLabMap.put(submissionId, value);
count++;
}
res.close();
Set <Integer> exp = submissionLabMap.keySet();
Iterator <Integer> i = exp.iterator();
while (i.hasNext()) {
Integer thisExp = i.next();
String prov = submissionLabMap.get(thisExp);
String project = submissionProjectMap.get(thisExp);
if (labIdMap.containsKey(prov)) {
continue;
}
LOG.debug("PROV: " + prov);
Item lab = getChadoDBConverter().createItem("Lab");
lab.setAttribute("surname", prov);
lab.setReference("project", projectIdRefMap.get(project));
Integer intermineObjectId = getChadoDBConverter().store(lab);
storeInLabMaps(lab, prov, intermineObjectId);
}
LOG.info("created " + labIdMap.size() + " labs");
LOG.info("PROCESS TIME labs: " + (System.currentTimeMillis() - bT));
}
/**
* Return the lab name.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getLabs(Connection connection)
throws SQLException {
String query =
"SELECT distinct a.experiment_id, a.name, a.value "
+ " FROM experiment_prop a "
+ " where a.name = 'Lab' "
+ " AND a.rank=0";
return doQuery(connection, query, "getLabs");
}
private void processExperiment(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getExperimentTitles(connection);
Map<String, String> expProMap = new HashMap<String, String>();
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
String name = cleanWikiLinks(res.getString("name"));
addToMap(expSubMap, name, submissionId);
expProMap.put(name, submissionProjectMap.get(submissionId));
}
res.close();
Set <String> experiment = expSubMap.keySet();
Iterator <String> i = experiment.iterator();
while (i.hasNext()) {
String name = i.next();
Item exp = getChadoDBConverter().createItem("Experiment");
exp.setAttribute("name", name);
String project = expProMap.get(name);
exp.setReference("project", projectIdRefMap.get(project));
// note: the reference to submission collection is in a separate method
Integer intermineObjectId = getChadoDBConverter().store(exp);
experimentIdMap .put(name, intermineObjectId);
experimentIdRefMap .put(name, exp.getIdentifier());
}
LOG.info("created " + expSubMap.size() + " experiments");
LOG.info("PROCESS TIME experiments: " + (System.currentTimeMillis() - bT));
}
/**
* method to clean a wiki reference (url to a named page) in chado
* @param w the wiki reference
*/
private String cleanWikiLinks(String w) {
String url = "http://wiki.modencode.org/project/index.php?title=";
// we are stripping from first ':', maybe we want to include project suffix
// now: Gene Model Prediction
// maybe? Gene Model Prediction:SC:1
String w1 = StringUtils.replace(w, url, "");
String s1 = null;
if (w1.contains(":")){
s1 = StringUtils.substringBefore(w1, ":");
} else {
// for links missing the : char, e.g.
// MacAlpine Early Origin of Replication Identification&oldid=10464
s1 = StringUtils.substringBefore(w1, "&");
}
String s = s1.replace('"', ' ').trim();
if (s.contains("%E2%80%99")) {
// prime: for the Piano experiment
String s2 = s.replace("%E2%80%99", "'");
return s2;
}
return s;
}
/**
* Return the rows needed for experiment from the experiment_prop table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getExperimentTitles(Connection connection)
throws SQLException {
// TODO use standard SQl and deal with string in java
String query =
"select e.experiment_id, "
+ " translate(x.accession, '_', ' ') as name "
+ " from experiment_prop e, dbxref x "
+ " where e.dbxref_id = x.dbxref_id "
+ " and e.name='Experiment Description' ";
return doQuery(connection, query, "getExperimentTitles");
}
private void processSubmission(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getSubmissions(connection);
int count = 0;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
String name = res.getString("uniquename");
Item submission = getChadoDBConverter().createItem("Submission");
submission.setAttribute("title", name);
String project = submissionProjectMap.get(submissionId);
String projectItemIdentifier = projectIdRefMap.get(project);
submission.setReference("project", projectItemIdentifier);
String labName = submissionLabMap.get(submissionId);
String labItemIdentifier = labIdRefMap.get(labName);
submission.setReference("lab", labItemIdentifier);
String organismName = submissionOrganismMap.get(submissionId);
int divPos = organismName.indexOf(' ');
String genus = organismName.substring(0, divPos);
String species = organismName.substring(divPos + 1);
OrganismRepository or = OrganismRepository.getOrganismRepository();
Integer taxId = Integer.valueOf
(or.getOrganismDataByGenusSpecies(genus, species).getTaxonId());
LOG.debug("SPECIES: " + organismName + "|" + taxId);
String organismItemIdentifier = getChadoDBConverter().getOrganismItem
(or.getOrganismDataByGenusSpecies(genus, species).getTaxonId()).getIdentifier();
submission.setReference("organism", organismItemIdentifier);
// ..store all
Integer intermineObjectId = getChadoDBConverter().store(submission);
// ..and fill the SubmissionDetails object
SubmissionDetails details = new SubmissionDetails();
details.interMineObjectId = intermineObjectId;
details.itemIdentifier = submission.getIdentifier();
details.labItemIdentifier = labItemIdentifier;
details.title = name;
submissionMap.put(submissionId, details);
debugMap .put(details.itemIdentifier, submission.getClassName());
count++;
}
LOG.info("created " + count + " submissions");
res.close();
LOG.info("PROCESS TIME submissions: " + (System.currentTimeMillis() - bT));
}
/**
* Return the rows needed for the submission table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getSubmissions(Connection connection)
throws SQLException {
String query =
"SELECT experiment_id, uniquename"
+ " FROM experiment";
return doQuery(connection, query, "getSubmissions");
}
/**
* submission attributes (table experiment_prop)
*
* @param connection
* @throws SQLException
* @throws ObjectStoreException
*/
private void processExperimentProps(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getExperimentProperties(connection);
int count = 0;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
String heading = res.getString("name");
String value = res.getString("value");
// TODO this is a temporary hack to make sure we get properly matched Experiment.factors
// EF are dealt with separately
if (heading.startsWith("Experimental Factor")) {
continue;
}
String fieldName = FIELD_NAME_MAP.get(heading);
if (fieldName == null) {
LOG.error("NOT FOUND in FIELD_NAME_MAP: " + heading + " [experiment]");
continue;
} else if (fieldName == NOT_TO_BE_LOADED) {
continue;
}
if (fieldName.equals("DCCid")) {
LOG.info("DCC: " + submissionId + ", " + value);
dccIdMap.put(submissionId, value);
}
if (fieldName.equals("pubMedId")) {
// sometime in the form PMID:16938558
if (value.contains(":")) {
value = value.substring(value.indexOf(':') + 1);
}
Item pub = getChadoDBConverter().createItem("Publication");
pub.setAttribute(fieldName, value);
Integer intermineObjectId = getChadoDBConverter().store(pub);
publicationIdMap.put(submissionId, intermineObjectId);
publicationIdRefMap.put(submissionId, pub.getIdentifier());
continue;
}
setAttribute(submissionMap.get(submissionId).interMineObjectId, fieldName, value);
count++;
}
LOG.info("created " + count + " submission properties");
res.close();
LOG.info("PROCESS TIME submission properties: " + (System.currentTimeMillis() - bT));
}
/**
* Return the rows needed for submission from the experiment_prop table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getExperimentProperties(Connection connection)
throws SQLException {
String query =
"SELECT ep.experiment_id, ep.name, ep.value, ep.rank "
+ "from experiment_prop ep ";
return doQuery(connection, query, "getExperimentProperties");
}
private void processEFactor(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getEFactors(connection);
int count = 0;
int prevRank = -1;
int prevSub = -1;
ExperimentalFactor ef = null;
String name = null;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
Integer rank = new Integer(res.getInt("rank"));
String value = res.getString("value");
// the data is alternating between EF types and names, in order.
if (submissionId != prevSub) {
// except for the first record, this is a new EF object
if (!res.isFirst()) {
submissionEFMap.put(prevSub, ef);
}
ef = new ExperimentalFactor();
}
if (rank != prevRank || submissionId != prevSub) {
// this is a name
if (getPreferredSynonym(value) != null) {
value = getPreferredSynonym(value);
}
ef.efNames.add(value);
name = value;
count++;
} else {
// this is a type
ef.efTypes.put(name, value);
name = null;
if (res.isLast()) {
submissionEFMap.put(submissionId, ef);
LOG.debug("EF MAP last: " + submissionId + "|" + rank + "|" + ef.efNames);
}
}
prevRank = rank;
prevSub = submissionId;
}
res.close();
LOG.info("created " + count + " experimental factors");
LOG.info("PROCESS TIME experimental factors: " + (System.currentTimeMillis() - bT));
}
/**
* Return the rows needed for the experimental factors.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getEFactors(Connection connection)
throws SQLException {
String query =
"SELECT ep.experiment_id, ep.name, ep.value, ep.rank "
+ " FROM experiment_prop ep "
+ " where ep.name = 'Experimental Factor Name' "
+ " OR ep.name = 'Experimental Factor Type' "
+ " ORDER BY 1,4,2";
return doQuery(connection, query, "getEFactors");
}
private void processProtocolTable(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getProtocols(connection);
int count = 0;
while (res.next()) {
Integer protocolChadoId = new Integer(res.getInt("protocol_id"));
String name = res.getString("name");
String description = res.getString("description");
String wikiLink = res.getString("accession");
Integer version = res.getInt("version");
// needed: it breaks otherwise
if (description.length() == 0) {
description = "N/A";
}
createProtocol(protocolChadoId, name, description, wikiLink, version);
count++;
}
res.close();
LOG.info("created " + count + " protocols");
LOG.info("PROCESS TIME protocols: " + (System.currentTimeMillis() - bT));
}
private String createProtocol(Integer chadoId, String name, String description, String wikiLink,
Integer version) throws ObjectStoreException {
String protocolItemId = protocolsMap.get(wikiLink);
if (protocolItemId == null) {
Item protocol = getChadoDBConverter().createItem("Protocol");
protocol.setAttribute("name", name);
protocol.setAttribute("description", description);
protocol.setAttribute("wikiLink", wikiLink);
protocol.setAttribute("version", "" + version);
Integer intermineObjectId = getChadoDBConverter().store(protocol);
protocolItemId = protocol.getIdentifier();
protocolItemToObjectId.put(protocolItemId, intermineObjectId);
protocolsMap.put(wikiLink, protocolItemId);
}
protocolItemIds.put(chadoId, protocolItemId);
return protocolItemId;
}
private Integer getProtocolInterMineId(Integer chadoId) {
return protocolItemToObjectId.get(protocolItemIds.get(chadoId));
}
/**
* Return the rows needed from the protocol table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getProtocols(Connection connection) throws SQLException {
String query =
"SELECT protocol_id, name, protocol.description, accession, protocol.version"
+ " FROM protocol, dbxref"
+ " WHERE protocol.dbxref_id = dbxref.dbxref_id";
return doQuery(connection, query, "getProtocols");
}
/**
* to store protocol attributes
*
* @param connection
* @throws SQLException
* @throws ObjectStoreException
*/
private void processProtocolAttributes(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getProtocolAttributes(connection);
int count = 0;
while (res.next()) {
Integer protocolId = new Integer(res.getInt("protocol_id"));
String heading = res.getString("heading");
String value = res.getString("value");
String fieldName = FIELD_NAME_MAP.get(heading);
if (fieldName == null) {
LOG.error("NOT FOUND in FIELD_NAME_MAP: " + heading + " [protocol]");
continue;
} else if (fieldName == NOT_TO_BE_LOADED) {
continue;
}
setAttribute(getProtocolInterMineId(protocolId), fieldName, value);
if (fieldName.equals("type")) {
protocolTypesMap.put(protocolId, value);
}
count++;
}
LOG.info("created " + count + " protocol attributes");
res.close();
LOG.info("PROCESS TIME protocol attributes: " + (System.currentTimeMillis() - bT));
}
/**
* Return the rows needed for protocols from the attribute table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getProtocolAttributes(Connection connection) throws SQLException {
String query =
"SELECT p.protocol_id, a.heading, a.value "
+ "from protocol p, attribute a, protocol_attribute pa "
+ "where pa.attribute_id = a.attribute_id "
+ "and pa.protocol_id = p.protocol_id ";
return doQuery(connection, query, "getProtocolAttributes");
}
private void processAppliedProtocolTable(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getAppliedProtocols(connection);
int count = 0;
while (res.next()) {
Integer appliedProtocolId = new Integer(res.getInt("applied_protocol_id"));
Integer protocolId = new Integer(res.getInt("protocol_id"));
Integer submissionId = new Integer(res.getInt("experiment_id"));
Item appliedProtocol = getChadoDBConverter().createItem("AppliedProtocol");
// setting references to protocols
String protocolItemId = protocolItemIds.get(protocolId);
if (protocolId != null) {
appliedProtocol.setReference("protocol", protocolItemId);
}
if (submissionId > 0) {
// setting reference to submission
// probably to rm (we do it later anyway). TODO: check
appliedProtocol.setReference("submission",
submissionMap.get(submissionId).itemIdentifier);
}
// store it and add to maps
Integer intermineObjectId = getChadoDBConverter().store(appliedProtocol);
appliedProtocolIdMap .put(appliedProtocolId, intermineObjectId);
appliedProtocolIdRefMap .put(appliedProtocolId, appliedProtocol.getIdentifier());
count++;
}
LOG.info("created " + count + " appliedProtocol");
res.close();
LOG.info("PROCESS TIME applied protocols: " + (System.currentTimeMillis() - bT));
}
/**
* Return the rows needed from the appliedProtocol table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedProtocols(Connection connection)
throws SQLException {
String query =
"SELECT eap.experiment_id ,ap.applied_protocol_id, ap.protocol_id"
+ " FROM applied_protocol ap"
+ " LEFT JOIN experiment_applied_protocol eap"
+ " ON (eap.first_applied_protocol_id = ap.applied_protocol_id )";
/* "SELECT ap.applied_protocol_id, ap.protocol_id, apd.data_id, apd.direction"
+ " FROM applied_protocol ap, applied_protocol_data apd"
+ " WHERE apd.applied_protocol_id = ap.applied_protocol_id";
*/
return doQuery(connection, query, "getAppliedProtocols");
}
private void processAppliedData(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getAppliedData(connection);
int count = 0;
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
String name = res.getString("name");
String heading = res.getString("heading");
String value = res.getString("value");
String typeId = res.getString("type_id");
// check if this datum has an official name:
ResultSet oName = getOfficialName(connection, dataId);
String officialName = null;
while (oName.next()) {
officialName = oName.getString(1);
}
// if there is one, use it instead of the value
String datumType = name = getCvterm(connection, typeId);
if (!StringUtils.isEmpty(officialName)
&& doReplaceWithOfficialName(heading, datumType)) {
value = officialName;
}
Item submissionData = getChadoDBConverter().createItem("SubmissionData");
if (name != null && !name.equals("")) {
submissionData.setAttribute("name", name);
}
// if no name for attribute fetch the cvterm of the type
if ((name == null || name.equals("")) && typeId != null) {
name = getCvterm(connection, typeId);
submissionData.setAttribute("name", name);
}
if (!StringUtils.isEmpty(value)) {
submissionData.setAttribute("value", value);
}
submissionData.setAttribute("type", heading);
// store it and add to object and maps
Integer intermineObjectId = getChadoDBConverter().store(submissionData);
AppliedData aData = new AppliedData();
aData.intermineObjectId = intermineObjectId;
aData.itemIdentifier = submissionData.getIdentifier();
aData.value = value;
aData.actualValue = res.getString("value");
aData.dataId = dataId;
aData.type = heading;
aData.name = name;
appliedDataMap.put(dataId, aData);
count++;
}
LOG.info("created " + count + " SubmissionData");
res.close();
LOG.info("PROCESS TIME submission data: " + (System.currentTimeMillis() - bT));
}
// For some data types we don't want to replace with official name - e.g. file names and
// database record ids. It looks like the official name shouldn't actually be present.
private boolean doReplaceWithOfficialName(String heading, String type) {
if (heading.equals("Result File")) {
return false;
}
if (heading.equals("Result Value") && DB_RECORD_TYPES.contains(type)) {
return false;
}
return true;
}
/**
* Return the rows needed for data from the applied_protocol_data table.
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedData(Connection connection)
throws SQLException {
String query =
"SELECT d.data_id,"
+ " d.heading, d.name, d.value, d.type_id"
+ " FROM data d";
return doQuery(connection, query, "getAppliedData");
}
/**
* Return the rows needed for data from the applied_protocol_data table.
*
* @param connection the db connection
* @param dataId the dataId
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getOfficialName(Connection connection, Integer dataId)
throws SQLException {
String query =
"SELECT a.value "
+ " from attribute a, data_attribute da "
+ " where a.attribute_id=da.attribute_id "
+ " and da.data_id=" + dataId
+ " and a.heading='official name'";
return doQuery(connection, query);
}
/**
* Fetch a cvterm by id and cache results in cvtermCache. Returns null if the cv terms isn't
* found.
* @param connection to chado database
* @param cvtermId internal chado id for a cvterm
* @return the cvterm name or null if not found
* @throws SQLException if database access problem
*/
private String getCvterm(Connection connection, String cvtermId) throws SQLException {
String cvTerm = cvtermCache.get(cvtermId);
if (cvTerm == null) {
String query =
"SELECT c.name "
+ " from cvterm c"
+ " where c.cvterm_id=" + cvtermId;
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
while (res.next()) {
cvTerm = res.getString("name");
}
cvtermCache.put(cvtermId, cvTerm);
}
return cvTerm;
}
private void processAppliedDataAttributes(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getAppliedDataAttributes(connection);
int count = 0;
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
String name = res.getString("heading");
String value = res.getString("value");
String type = res.getString("name");
Item dataAttribute = getChadoDBConverter().createItem("SubmissionDataAttribute");
if (name != null && !name.equals("")) {
dataAttribute.setAttribute("name", name);
}
if (!StringUtils.isEmpty(value)) {
dataAttribute.setAttribute("value", value);
}
if (!StringUtils.isEmpty(type)) {
dataAttribute.setAttribute("type", type);
}
// setting references to SubmissionData
dataAttribute.setReference("submissionData", appliedDataMap.get(dataId).itemIdentifier);
getChadoDBConverter().store(dataAttribute);
count++;
}
LOG.info("created " + count + " data attributes");
res.close();
LOG.info("PROCESS TIME data attributes: " + (System.currentTimeMillis() - bT));
}
// first value in the list of synonyms is the 'preferred' value
private static String[][] synonyms = new String[][]{
new String[] {"developmental stage", "stage",
"developmental_stage", "dev stage", "devstage"},
new String[] {"strain", "strain_or_line"},
new String[] {"cell line", "cell_line", "Cell line", "cell id"},
new String[] {"array", "adf"},
new String[] {"compound", "Compound"},
new String[] {"incubation time", "Incubation Time"},
new String[] {"RNAi reagent", "RNAi_reagent", "dsRNA"},
new String[] {"temperature", "temp"}
};
private static List<String> makeLookupList(String initialLookup) {
for (String[] synonymType : synonyms) {
for (String synonym : synonymType) {
if (synonym.equals(initialLookup)) {
return (List<String>) Arrays.asList(synonymType);
}
}
}
return new ArrayList<String>(Collections.singleton(initialLookup));
}
private static String getPreferredSynonym(String initialLookup) {
return makeLookupList(initialLookup).get(0);
}
private static Set<String> unifyFactorNames(Collection<String> original) {
Set<String> unified = new HashSet<String>();
for (String name : original) {
unified.add(getPreferredSynonym(name));
}
return unified;
}
private class SubmissionReference
{
public SubmissionReference(Integer referencedSubmissionId, String dataValue) {
this.referencedSubmissionId = referencedSubmissionId;
this.dataValue = dataValue;
}
private Integer referencedSubmissionId;
private String dataValue;
}
// process new query
// get DCC id
// add antibody to types
private void processSubmissionProperties(Connection connection) throws SQLException,
IOException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getAppliedDataAll(connection);
String comma = ",";
String reportName = getChadoDBConverter().getDatabase().getName() + "_subs_report.csv";
File f = new File(reportName);
FileWriter writer = new FileWriter(f);
writer.write("submission" + comma);
writer.write("data_heading" + comma);
writer.write("data_name" + comma);
writer.write("data_value" + comma);
writer.write("cv_term" + comma);
writer.write("att_heading" + comma);
writer.write("att_name" + comma);
writer.write("att_value" + comma);
writer.write(System.getProperty("line.separator"));
SubmissionProperty buildSubProperty = null;
Integer lastDataId = new Integer(-1);
Map<String, SubmissionProperty> props = new HashMap <String, SubmissionProperty>();
Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes =
new HashMap<Integer, Map<String, List<SubmissionProperty>>>();
submissionRefs = new HashMap<Integer, SubmissionReference>();
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
String dataHeading = res.getString("data_heading");
String dataName = res.getString("data_name");
String wikiPageUrl = res.getString("data_value");
String cvTerm = res.getString("cv_term");
String attHeading = res.getString("att_heading");
String attName = res.getString("att_name");
String attValue = res.getString("att_value");
String attDbxref = res.getString("att_dbxref");
int attRank = res.getInt("att_rank");
Integer submissionId = dataSubmissionMap.get(dataId);
LOG.debug("DCC fetch: " + submissionId + ", " + dccIdMap.get(submissionId));
String dccId = dccIdMap.get(submissionId);
writer.write(dccId + comma + dataHeading + comma + dataName + comma
+ wikiPageUrl + comma + cvTerm + comma + attHeading + comma + attName
+ comma + attValue + comma + attDbxref + System.getProperty("line.separator"));
if (submissionId == null) {
LOG.warn("Failed to find a submission id for data id " + dataId + " - this probably"
+ " means there is a problem with the applied_protocol DAG strucuture.");
continue;
}
// Currently using attValue for referenced submission DCC id, should be dbUrl but seems
// to be filled in incorrectly
if (attHeading != null && attHeading.startsWith("modENCODE Reference")) {
if (attValue.indexOf(":") > 0) {
attValue = attValue.substring(0, attValue.indexOf(":"));
}
Integer referencedSubId = getSubmissionIdFromDccId(attValue);
if (referencedSubId != null) {
SubmissionReference subRef =
new SubmissionReference(referencedSubId, wikiPageUrl);
submissionRefs.put(submissionId, subRef);
LOG.info("Submission " + dccId + " (" + submissionId + ") has reference to "
+ attValue + " (" + referencedSubId + ")");
} else {
LOG.warn("Could not find submission " + attValue + " referenced by " + dccId);
}
}
// we are starting a new data row
if (dataId.intValue() != lastDataId.intValue()) {
// have we seen this modencodewiki entry before?
if (props.containsKey(wikiPageUrl)) {
buildSubProperty = null;
} else {
buildSubProperty =
new SubmissionProperty(getPreferredSynonym(dataName), wikiPageUrl);
props.put(wikiPageUrl, buildSubProperty);
}
// submissionId -> [type -> SubmissionProperty]
addToSubToTypes(subToTypes, submissionId, props.get(wikiPageUrl));
}
if (buildSubProperty != null) {
// we are building a new submission attribute, this is the first time we have
// seen a data.value that points to modencodewiki
buildSubProperty.addDetail(attHeading, attValue, attRank);
}
lastDataId = dataId;
}
writer.flush();
writer.close();
// Characteristics are modelled differently to protocol inputs/outputs, read in extra
// properties here
addSubmissionPropsFromCharacteristics(subToTypes, connection);
// some submissions use reagents created in reference submissions, find the properties
// of the reagents and add to referencing submission
addSubmissionPropsFromReferencedSubmissions(subToTypes, props, submissionRefs);
// create and store properties of submission
for (Integer submissionId : subToTypes.keySet()) {
Integer storedSubmissionId = submissionMap.get(submissionId).interMineObjectId;
Map<String, List<SubmissionProperty>> typeToProp = subToTypes.get(submissionId);
String dccId = dccIdMap.get(submissionId);
ExperimentalFactor ef = submissionEFMap.get(submissionId);
if (ef == null) {
LOG.warn("No experimental factors found for submission: " + dccId);
continue;
}
Set<String> exFactorNames = unifyFactorNames(ef.efNames);
LOG.info("PROPERTIES " + dccId + " typeToProp keys: " + typeToProp.keySet());
List<Item> allPropertyItems = new ArrayList<Item>();
// DEVELOPMENTAL STAGE
List<Item> devStageItems = new ArrayList<Item>();
devStageItems.addAll(createFromWikiPage(dccId, "DevelopmentalStage", typeToProp,
makeLookupList("developmental stage")));
if (devStageItems.isEmpty()) {
devStageItems.addAll(lookForAttributesInOtherWikiPages(dccId, "DevelopmentalStage",
typeToProp, new String[] {
"developmental stage.developmental stage",
"tissue.developmental stage",
"tissue source.developmental stage",
"cell line.developmental stage",
"cell id.developmental stage"
}));
if (!devStageItems.isEmpty()) {
}
}
storeSubmissionCollection(storedSubmissionId, "developmentalStages", devStageItems);
if (!devStageItems.isEmpty() && exFactorNames.contains("developmental stage")) {
createExperimentalFactors(submissionId, "developmental stage", devStageItems);
exFactorNames.remove("developmental stage");
}
allPropertyItems.addAll(devStageItems);
// STRAIN
List<Item> strainItems = new ArrayList<Item>();
strainItems.addAll(createFromWikiPage(
dccId, "Strain", typeToProp, makeLookupList("strain")));
storeSubmissionCollection(storedSubmissionId, "strains", strainItems);
if (!strainItems.isEmpty() && exFactorNames.contains("strain")) {
createExperimentalFactors(submissionId, "strain", strainItems);
exFactorNames.remove("strain");
}
allPropertyItems.addAll(strainItems);
// ARRAY
List<Item> arrayItems = new ArrayList<Item>();
arrayItems.addAll(createFromWikiPage(
dccId, "Array", typeToProp, makeLookupList("array")));
LOG.debug("ARRAY: " + typeToProp.get("array"));
if (arrayItems.isEmpty()) {
arrayItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Array",
typeToProp, new String[] {
"adf.official name"
}));
if (!arrayItems.isEmpty()) {
LOG.debug("Attribute found in other wiki pages: "
+ dccId + " ARRAY ");
}
}
storeSubmissionCollection(storedSubmissionId, "arrays", arrayItems);
if (!arrayItems.isEmpty() && exFactorNames.contains("array")) {
createExperimentalFactors(submissionId, "array", arrayItems);
exFactorNames.remove("array");
}
allPropertyItems.addAll(arrayItems);
// CELL LINE
List<Item> lineItems = new ArrayList<Item>();
lineItems.addAll(createFromWikiPage(dccId, "CellLine", typeToProp,
makeLookupList("cell line")));
storeSubmissionCollection(storedSubmissionId, "cellLines", lineItems);
if (!lineItems.isEmpty() && exFactorNames.contains("cell line")) {
createExperimentalFactors(submissionId, "cell line", lineItems);
exFactorNames.remove("cell line");
}
allPropertyItems.addAll(lineItems);
// RNAi REAGENT
List<Item> reagentItems = new ArrayList<Item>();
reagentItems.addAll(createFromWikiPage(dccId, "SubmissionProperty", typeToProp,
makeLookupList("dsRNA")));
if (!reagentItems.isEmpty() && exFactorNames.contains("RNAi reagent")) {
createExperimentalFactors(submissionId, "RNAi reagent", reagentItems);
exFactorNames.remove("RNAi reagent");
}
allPropertyItems.addAll(reagentItems);
// ANTIBODY
List<Item> antibodyItems = new ArrayList<Item>();
antibodyItems.addAll(createFromWikiPage(dccId, "Antibody", typeToProp,
makeLookupList("antibody")));
if (antibodyItems.isEmpty()) {
LOG.debug("ANTIBODY: " + typeToProp.get("antibody"));
antibodyItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Antibody",
typeToProp, new String[] {
"antibody.official name"
}));
if (!antibodyItems.isEmpty()) {
LOG.debug("Attribute found in other wiki pages: "
+ dccId + " ANTIBODY ");
}
}
storeSubmissionCollection(storedSubmissionId, "antibodies", antibodyItems);
if (!antibodyItems.isEmpty() && exFactorNames.contains("antibody")) {
createExperimentalFactors(submissionId, "antibody", antibodyItems);
exFactorNames.remove("antibody");
}
allPropertyItems.addAll(antibodyItems);
// TISSUE
List<Item> tissueItems = new ArrayList<Item>();
tissueItems.addAll(createFromWikiPage(
dccId, "Tissue", typeToProp, makeLookupList("tissue")));
if (tissueItems.isEmpty()) {
tissueItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Tissue",
typeToProp, new String[] {
"stage.tissue"
, "cell line.tissue"
, "cell id.tissue"
}));
if (!tissueItems.isEmpty()) {
LOG.info("Attribute found in other wiki pages: "
+ dccId + " TISSUE");
}
}
storeSubmissionCollection(storedSubmissionId, "tissues", tissueItems);
if (!tissueItems.isEmpty() && exFactorNames.contains("tissue")) {
createExperimentalFactors(submissionId, "tissue", tissueItems);
exFactorNames.remove("tissue");
}
allPropertyItems.addAll(tissueItems);
// There may be some other experimental factors that require SubmissionProperty objects
// but don't fall into the categories above. Create them here and set experimental
// factors.
ArrayList<String> extraPropNames = new ArrayList<String>(exFactorNames);
for (String exFactor : extraPropNames) {
List<Item> extraPropItems = new ArrayList<Item>();
extraPropItems.addAll(lookForAttributesInOtherWikiPages(dccId, "SubmissionProperty",
typeToProp, new String[] {exFactor}));
allPropertyItems.addAll(extraPropItems);
createExperimentalFactors(submissionId, exFactor, extraPropItems);
exFactorNames.remove(exFactor);
}
// Store Submission.properties/ SubmissionProperty.submissions
storeSubmissionCollection(storedSubmissionId, "properties", allPropertyItems);
// deal with remaining factor names (e.g. the ones for which we did
// not find a corresponding attribute
for (String exFactor : exFactorNames) {
String type = ef.efTypes.get(exFactor);
createEFItem(submissionId, type, exFactor, null);
}
}
LOG.info("PROCESS TIME submission properties: " + (System.currentTimeMillis() - bT));
}
// Traverse DAG following previous applied protocol links to build a list of all AppliedData
private void findAppliedProtocolsAndDataFromEarlierInDag(Integer startDataId,
List<AppliedData> foundAppliedData, List<AppliedProtocol> foundAppliedProtocols) {
AppliedData aData = appliedDataMap.get(startDataId);
if (foundAppliedData != null) {
foundAppliedData.add(aData);
}
for (Integer previousAppliedProtocolId : aData.previousAppliedProtocols) {
AppliedProtocol ap = appliedProtocolMap.get(previousAppliedProtocolId);
if (foundAppliedProtocols != null) {
foundAppliedProtocols.add(ap);
}
for (Integer previousDataId : ap.inputs) {
findAppliedProtocolsAndDataFromEarlierInDag(previousDataId, foundAppliedData,
foundAppliedProtocols);
}
}
}
private void createExperimentalFactors(Integer submissionId, String type,
Collection<Item> items) throws ObjectStoreException {
for (Item item : items) {
createEFItem(submissionId, type, item.getAttribute("name").getValue(),
item.getIdentifier());
}
}
private void createEFItem(Integer current, String type,
String efName, String propertyIdentifier) throws ObjectStoreException {
// create the EF, if not there already
if (!eFactorIdMap.containsKey(efName)) {
Item ef = getChadoDBConverter().createItem("ExperimentalFactor");
String preferredType = getPreferredSynonym(type);
ef.setAttribute ("type", preferredType);
ef.setAttribute ("name", efName);
if (propertyIdentifier != null) {
ef.setReference("property", propertyIdentifier);
}
LOG.debug("ExFactor created for sub " + current + ":" + efName + "|" + type);
Integer intermineObjectId = getChadoDBConverter().store(ef);
eFactorIdMap.put(efName, intermineObjectId);
eFactorIdRefMap.put(efName, ef.getIdentifier());
}
// if pertinent to the current sub, add to the map for the references
addToMap(submissionEFactorMap, current, efName);
}
private void addToSubToTypes(Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes,
Integer submissionId, SubmissionProperty prop) {
// submissionId -> [type -> SubmissionProperty]
if (submissionId == null) {
throw new RuntimeException("Called addToSubToTypes with a null sub id!");
}
Map<String, List<SubmissionProperty>> typeToSubProp = subToTypes.get(submissionId);
if (typeToSubProp == null) {
typeToSubProp = new HashMap<String, List<SubmissionProperty>>();
subToTypes.put(submissionId, typeToSubProp);
}
List<SubmissionProperty> subProps = typeToSubProp.get(prop.type);
if (subProps == null) {
subProps = new ArrayList<SubmissionProperty>();
typeToSubProp.put(prop.type, subProps);
}
subProps.add(prop);
}
private void addSubmissionPropsFromCharacteristics(
Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes,
Connection connection)
throws SQLException {
ResultSet res = getAppliedDataCharacteristics(connection);
Integer lastAttDbXref = new Integer(-1);
Integer lastDataId = new Integer(-1);
Map<Integer, SubmissionProperty> createdProps = new HashMap<Integer, SubmissionProperty>();
SubmissionProperty buildSubProperty = null;
boolean isValidCharacteristic = false;
Integer currentSubId = null; // we need those to attach the property to the correct sub
Integer previousSubId = null;
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
String attHeading = res.getString("att_heading");
String attName = res.getString("att_name");
String attValue = res.getString("att_value");
Integer attDbxref = new Integer(res.getInt("att_dbxref"));
int attRank = res.getInt("att_rank");
currentSubId = dataSubmissionMap.get(dataId);
LOG.info("XXX0 " + currentSubId + ":" + dataId + "|" + attValue
+ "|" +attDbxref);
if (dataId.intValue() != lastDataId.intValue() ||
attDbxref.intValue() != lastAttDbXref.intValue() ||
currentSubId != previousSubId) {
// store the last build property if created, type is set only if we found an
// attHeading of Characteristics
// note: dbxref can remain the same in different subs -> or
// LOG.info("XXX1if changes in dbxref or subid");
if (buildSubProperty != null && buildSubProperty.type != null) {
LOG.info("XXX11if ADD PREVIOUS" + lastAttDbXref + "|"+ buildSubProperty);
createdProps.put(lastAttDbXref, buildSubProperty);
// createdProps.put(lastDataId, buildSubProperty);
addToSubToTypes(subToTypes, previousSubId, buildSubProperty);
}
// set up for next attDbxref
if (createdProps.containsKey(attDbxref) && isValidCharacteristic) {
// if (createdProps.containsKey(dataId) && isValidCharacteristic) {
// LOG.info("XXX12if ADD CURRENT" + attDbxref+"|"+ createdProps.get(attDbxref));
// seen this property before so just add for this submission, don't build again
buildSubProperty = null;
isValidCharacteristic = false;
addToSubToTypes(subToTypes, currentSubId, createdProps.get(attDbxref));
// addToSubToTypes(subToTypes, currentSubId, createdProps.get(dataId));
} else {
// LOG.info("XXX12else NEW SP");
buildSubProperty = new SubmissionProperty();
isValidCharacteristic = false;
}
}
if (attHeading.startsWith("Characteristic")) {
// LOG.info("XXX2if Characteristic");
isValidCharacteristic = true;
}
if (buildSubProperty != null) {
if (attHeading.startsWith("Characteristic")) {
buildSubProperty.type = getPreferredSynonym(attName);
buildSubProperty.wikiPageUrl = attValue;
// add detail here as some Characteristics don't reference a wiki page
// but have all information on single row
buildSubProperty.addDetail(attName, attValue, attRank);
// LOG.info("XXX3if ADD for CHAR"+ getPreferredSynonym(attName) + "|" + attValue + "|"+ attName);
} else {
// LOG.info("XXX3else ADD for OTHER"+ attValue + "|"+ attHeading);
buildSubProperty.addDetail(attHeading, attValue, attRank);
}
}
previousSubId = currentSubId;
lastAttDbXref = attDbxref;
lastDataId = dataId;
}
if (buildSubProperty != null && buildSubProperty.type != null) {
// LOG.info("XXX3end "+ lastAttDbXref + "|"+ buildSubProperty);
// LOG.info("XXX32end " +currentSubId+ "|"+ subToTypes);
createdProps.put(lastAttDbXref, buildSubProperty);
// createdProps.put(lastDataId, buildSubProperty);
addToSubToTypes(subToTypes, currentSubId, buildSubProperty);
}
}
// Some submission mention e.g. an RNA Sample but the details of how that sample was created,
// stage, strain, etc are in a previous submission. There are references to previous submission
// DCC ids where a sample with the corresponding name can be found. We then need to traverse
// backwards along the AppliedProtocol DAG to find the stage, strain, etc wiki pages. These
// should already have been processed so the properties can just be added to the referencing
// submission.
private void addSubmissionPropsFromReferencedSubmissions(
Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes,
Map<String, SubmissionProperty> props,
Map<Integer, SubmissionReference> submissionRefs) {
for (Map.Entry<Integer, SubmissionReference> entry : submissionRefs.entrySet()) {
Integer submissionId = entry.getKey();
SubmissionReference subRef = entry.getValue();
List<AppliedData> refAppliedData = findAppliedDataFromReferencedSubmission(subRef);
for (AppliedData aData : refAppliedData) {
String possibleWikiUrl = aData.actualValue;
if (possibleWikiUrl != null && props.containsKey(possibleWikiUrl)) {
SubmissionProperty propFromReferencedSub = props.get(possibleWikiUrl);
addToSubToTypes(subToTypes, submissionId, propFromReferencedSub);
}
}
}
}
private List<AppliedData> findAppliedDataFromReferencedSubmission(SubmissionReference subRef) {
List<AppliedData> foundAppliedData = new ArrayList<AppliedData>();
findAppliedProtocolsAndDataFromReferencedSubmission(subRef, foundAppliedData, null);
return foundAppliedData;
}
private List<AppliedProtocol> findAppliedProtocolsFromReferencedSubmission(
SubmissionReference subRef) {
List<AppliedProtocol> foundAppliedProtocols = new ArrayList<AppliedProtocol>();
findAppliedProtocolsAndDataFromReferencedSubmission(subRef, null, foundAppliedProtocols);
return foundAppliedProtocols;
}
private void findAppliedProtocolsAndDataFromReferencedSubmission(
SubmissionReference subRef,
List<AppliedData> foundAppliedData,
List<AppliedProtocol> foundAppliedProtocols) {
String refDataValue = subRef.dataValue;
Integer refSubId = subRef.referencedSubmissionId;
for (AppliedData aData : appliedDataMap.values()) {
String currentDataValue = aData.value;
Integer currentDataSubId = dataSubmissionMap.get(aData.dataId);
if (refDataValue.equals(currentDataValue) && refSubId.equals(currentDataSubId)) {
LOG.info("REFSUBS found a matching data value: " + currentDataValue + " in sub "
+ dccIdMap.get(currentDataSubId) + " ref sub = "
+ dccIdMap.get(refSubId));
Integer foundDataId = aData.dataId;
findAppliedProtocolsAndDataFromEarlierInDag(foundDataId, foundAppliedData,
foundAppliedProtocols);
}
}
}
private List<Item> createFromWikiPage(String dccId, String clsName,
Map<String, List<SubmissionProperty>> typeToProp, List<String> types)
throws ObjectStoreException {
List<Item> items = new ArrayList<Item>();
List<SubmissionProperty> props = new ArrayList<SubmissionProperty>();
for (String type : types) {
if (typeToProp.containsKey(type)) {
props.addAll(typeToProp.get(type));
}
}
items.addAll(createItemsForSubmissionProperties(dccId, clsName, props));
return items;
}
private void storeSubmissionCollection(Integer storedSubmissionId, String name,
List<Item> items)
throws ObjectStoreException {
if (!items.isEmpty()) {
ReferenceList refList = new ReferenceList(name, getIdentifiersFromItems(items));
getChadoDBConverter().store(refList, storedSubmissionId);
}
}
private List<String> getIdentifiersFromItems(Collection<Item> items) {
List<String> ids = new ArrayList<String>();
for (Item item : items) {
ids.add(item.getIdentifier());
}
return ids;
}
private List<Item> createItemsForSubmissionProperties(String dccId, String clsName,
List<SubmissionProperty> subProps)
throws ObjectStoreException {
List<Item> items = new ArrayList<Item>();
for (SubmissionProperty subProp : subProps) {
Item item = getItemForSubmissionProperty(clsName, subProp, dccId);
if (item != null) {
items.add(item);
}
}
return items;
}
private Item getItemForSubmissionProperty(String clsName, SubmissionProperty prop, String dccId)
throws ObjectStoreException {
Item propItem = subItemsMap.get(prop.wikiPageUrl);
if (propItem == null) {
if (clsName != null) {
List<String> checkOfficialName = prop.details.get("official name");
if (checkOfficialName == null) {
LOG.warn("No 'official name', using 'name' instead for: " + prop.wikiPageUrl);
checkOfficialName = prop.details.get("name");
}
if (checkOfficialName == null) {
LOG.info("Official name - missing for property: "
+ prop.type + ", " + prop.wikiPageUrl);
return null;
} else if (checkOfficialName.size() != 1) {
LOG.info("Official name - multiple times for property: "
+ prop.type + ", " + prop.wikiPageUrl + ", "
+ checkOfficialName);
}
String officialName = getCorrectedOfficialName(prop);
propItem = createSubmissionProperty(clsName, officialName);
propItem.setAttribute("type", getPreferredSynonym(prop.type));
propItem.setAttribute("wikiLink", WIKI_URL + prop.wikiPageUrl);
if (clsName.equals("DevelopmentalStage")) {
setAttributeOnProp(prop, propItem, "sex", "sex");
List<String> devStageValues = prop.details.get("developmental stage");
if (devStageValues != null) {
for (String devStageValue : devStageValues) {
propItem.addToCollection("ontologyTerms",
getDevStageTerm(devStageValue, dccId));
}
} else {
LOG.error("METADATA FAIL: no 'developmental stage' values for wiki page: "
+ prop.wikiPageUrl);
}
} else if (clsName.equals("Antibody")) {
setAttributeOnProp(prop, propItem, "antigen", "antigen");
setAttributeOnProp(prop, propItem, "host", "hostOrganism");
setAttributeOnProp(prop, propItem, "target name", "targetName");
setGeneItem(dccId, prop, propItem, "Antibody");
} else if (clsName.equals("Array")) {
setAttributeOnProp(prop, propItem, "platform", "platform");
setAttributeOnProp(prop, propItem, "resolution", "resolution");
setAttributeOnProp(prop, propItem, "genome", "genome");
} else if (clsName.equals("CellLine")) {
setAttributeOnProp(prop, propItem, "sex", "sex");
setAttributeOnProp(prop, propItem, "short description",
"description");
setAttributeOnProp(prop, propItem, "species", "species");
setAttributeOnProp(prop, propItem, "tissue", "tissue");
setAttributeOnProp(prop, propItem, "cell type", "cellType");
setAttributeOnProp(prop, propItem, "target name", "targetName");
setGeneItem(dccId, prop, propItem, "CellLine");
} else if (clsName.equals("Strain")) {
setAttributeOnProp(prop, propItem, "species", "species");
setAttributeOnProp(prop, propItem, "source", "source");
// the following 2 should be mutually exclusive
setAttributeOnProp(prop, propItem, "Description", "description");
setAttributeOnProp(prop, propItem, "details", "description");
setAttributeOnProp(prop, propItem, "aliases", "name");
setAttributeOnProp(prop, propItem, "reference", "reference");
setAttributeOnProp(prop, propItem, "target name", "targetName");
setGeneItem(dccId, prop, propItem, "Strain");
} else if (clsName.equals("Tissue")) {
setAttributeOnProp(prop, propItem, "species", "species");
setAttributeOnProp(prop, propItem, "sex", "sex");
setAttributeOnProp(prop, propItem, "organismPart", "organismPart");
}
getChadoDBConverter().store(propItem);
}
subItemsMap.put(prop.wikiPageUrl, propItem);
}
return propItem;
}
private void setGeneItem(String dccId, SubmissionProperty prop, Item propItem, String source)
throws ObjectStoreException {
String targetText = null;
String[] possibleTypes = new String[] {"target id"};
for (String targetType : possibleTypes) {
if (prop.details.containsKey(targetType)) {
if (prop.details.get(targetType).size() != 1) {
// we used to complain if multiple values, now only
// if they don't have the same value
checkIfSameValue(prop, source, targetType);
}
targetText = prop.details.get(targetType).get(0);
break;
}
}
if (targetText != null) {
// if no target name was found use the target id
if (!propItem.hasAttribute("targetName")) {
propItem.setAttribute("targetName", targetText);
}
String geneItemId = getTargetGeneItemIdentfier(targetText, dccId);
if (geneItemId != null) {
propItem.setReference("target", geneItemId);
}
}
}
/**
* @param prop
* @param source
* @param targetType
* @throws RuntimeException
*/
private void checkIfSameValue(SubmissionProperty prop, String source,
String targetType) throws RuntimeException {
String value = prop.details.get(targetType).get(0);
for (int i = 1; i < prop.details.get(targetType).size(); i++) {
String newValue = prop.details.get(targetType).get(i);
if (!newValue.equals(value)) {
throw new RuntimeException(source + " should only have one value for '" + targetType
+ "' field: " + prop.details.get(targetType));
}
}
}
private void setAttributeOnProp(SubmissionProperty subProp, Item item, String metadataName,
String attributeName) {
if (subProp.details.containsKey(metadataName)) {
if (metadataName.equalsIgnoreCase("aliases")) {
for (String s :subProp.details.get(metadataName)) {
if (s.equalsIgnoreCase("yellow cinnabar brown speck")) {
// swapping name with fullName
String full = item.getAttribute("name").getValue();
item.setAttribute("fullName", full);
item.setAttribute(attributeName, s);
break;
}
}
} else if (metadataName.equalsIgnoreCase("description")
|| metadataName.equalsIgnoreCase("details")) {
// description is often split in more than 1 line, details should be correct order
StringBuffer sb = new StringBuffer();
for (String desc : subProp.details.get(metadataName)) {
sb.append(desc);
}
if (sb.length() > 0) {
item.setAttribute(attributeName, sb.toString());
}
} else {
String value = subProp.details.get(metadataName).get(0);
item.setAttribute(attributeName, value);
}
}
}
private String getTargetGeneItemIdentfier(String geneTargetIdText, String dccId)
throws ObjectStoreException {
String taxonId = "";
String originalId = null;
String flyPrefix = "fly_genes:";
String wormPrefix = "worm_genes:";
if (geneTargetIdText.startsWith(flyPrefix)) {
originalId = geneTargetIdText.substring(flyPrefix.length());
taxonId = "7227";
} else if (geneTargetIdText.startsWith(wormPrefix)) {
originalId = geneTargetIdText.substring(wormPrefix.length());
taxonId = "6239";
} else {
// attempt to work out the organism from the submission
taxonId = getTaxonIdForSubmission(dccId);
originalId = geneTargetIdText;
LOG.info("RESOLVER: found taxon " + taxonId + " for submission " + dccId);
}
IdResolver resolver = null;
if (taxonId.equals("7227")) {
resolver = flyResolverFactory.getIdResolver();
} else if (taxonId.equals("6239")) {
resolver = wormResolverFactory.getIdResolver();
} else {
LOG.info("RESOLVER: unable to work out organism for target id text: "
+ geneTargetIdText);
}
String geneItemId = null;
String primaryIdentifier = resolveGene(originalId, taxonId, resolver);
if (primaryIdentifier != null) {
geneItemId = geneToItemIdentifier.get(primaryIdentifier);
if (geneItemId == null) {
Item gene = getChadoDBConverter().createItem("Gene");
geneItemId = gene.getIdentifier();
gene.setAttribute("primaryIdentifier", primaryIdentifier);
getChadoDBConverter().store(gene);
geneToItemIdentifier.put(primaryIdentifier, geneItemId);
} else {
LOG.info("RESOLVER fetched gene from cache: " + primaryIdentifier);
}
}
return geneItemId;
}
private String resolveGene(String originalId, String taxonId, IdResolver resolver) {
String primaryIdentifier = null;
int resCount = resolver.countResolutions(taxonId, originalId);
if (resCount != 1) {
LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring "
+ "gene: " + originalId + " for organism " + taxonId + " count: " + resCount
+ " found ids: " + resolver.resolveId(taxonId, originalId) + ".");
} else {
primaryIdentifier =
resolver.resolveId(taxonId, originalId).iterator().next();
LOG.info("RESOLVER found gene " + primaryIdentifier
+ " for original id: " + originalId);
}
return primaryIdentifier;
}
private List<Item> lookForAttributesInOtherWikiPages(String dccId, String clsName,
Map<String, List<SubmissionProperty>> typeToProp, String[] lookFor)
throws ObjectStoreException {
List<Item> items = new ArrayList<Item>();
for (String typeProp : lookFor) {
if (typeProp.indexOf(".") > 0) {
String[] bits = StringUtils.split(typeProp, '.');
String type = bits[0];
String propName = bits[1];
if (typeToProp.containsKey(type)) {
for (SubmissionProperty subProp : typeToProp.get(type)) {
if (subProp.details.containsKey(propName)) {
for (String value : subProp.details.get(propName)) {
items.add(createNonWikiSubmissionPropertyItem(dccId, clsName,
getPreferredSynonym(propName),
correctAttrValue(value)));
}
}
}
if (!items.isEmpty()) {
break;
}
}
} else {
// no attribute type given so use the data.value (SubmissionProperty.wikiPageUrl)
// which probably won't be a wiki page
if (typeToProp.containsKey(typeProp)) {
for (SubmissionProperty subProp : typeToProp.get(typeProp)) {
String value = subProp.wikiPageUrl;
// This is an ugly special case to deal with 'exposure time/24 hours'
if (subProp.details.containsKey("Unit")) {
String unit = subProp.details.get("Unit").get(0);
value = value + " " + unit + (unit.endsWith("s") ? "" : "s");
}
items.add(createNonWikiSubmissionPropertyItem(dccId, clsName, subProp.type,
correctAttrValue(value)));
}
}
}
}
return items;
}
private String correctAttrValue(String value) {
if (value == null) {
return null;
}
value = value.replace("–", "-");
return value;
}
private Item createNonWikiSubmissionPropertyItem(String dccId, String clsName, String type,
String name)
throws ObjectStoreException {
if (clsName.equals("DevelopmentalStage")) {
name = correctDevStageTerm(name);
}
Item item = nonWikiSubmissionProperties.get(name);
if (item == null) {
item = createSubmissionProperty(clsName, name);
item.setAttribute("type", getPreferredSynonym(type));
if (clsName.equals("DevelopmentalStage")) {
String ontologyTermId = getDevStageTerm(name, dccId);
item.addToCollection("ontologyTerms", ontologyTermId);
}
getChadoDBConverter().store(item);
nonWikiSubmissionProperties.put(name, item);
}
return item;
}
private Item createSubmissionProperty(String clsName, String name) {
Item subProp = getChadoDBConverter().createItem(clsName);
if (name != null) {
subProp.setAttribute("name", name);
}
return subProp;
}
private String getCorrectedOfficialName(SubmissionProperty prop) {
String preferredType = getPreferredSynonym(prop.type);
String name = null;
if (prop.details.containsKey("official name")) {
name = prop.details.get("official name").get(0);
} else if (prop.details.containsKey("name")) {
name = prop.details.get("name").get(0);
} else {
// no official name so maybe there is a key that matches the type - sometimes the
// setup for Characteristics
for (String lookup : makeLookupList(prop.type)) {
if (prop.details.containsKey(lookup)) {
name = prop.details.get(lookup).get(0);
}
}
}
return correctOfficialName(name, preferredType);
}
/**
* Unify variations on similar official names.
* @param name the original 'official name' value
* @param type the treatment depends on the type
* @return a unified official name
*/
protected String correctOfficialName(String name, String type) {
if (name == null) {
return null;
}
if (type.equals("developmental stage")) {
name = name.replace("_", " ");
name = name.replaceFirst("embryo", "Embryo");
name = name.replaceFirst("Embyro", "Embryo");
if (name.matches("E\\d.*")) {
name = name.replaceFirst("^E", "Embryo ");
}
if (name.matches("Embryo.*\\d")) {
name = name + " h";
}
if (name.matches(".*hr")) {
name = name.replace("hr", "h");
}
if (name.matches("Embryo.*\\dh")) {
name = name.replaceFirst("h", " h");
}
if (name.startsWith("DevStage:")) {
name = name.replaceFirst("DevStage:", "").trim();
}
if (name.matches("L\\d")) {
name = name + " stage larvae";
}
if (name.matches(".*L\\d")) {
name = name + " stage larvae";
}
if (name.matches("WPP.*")) {
name = name.replaceFirst("WPP", "White prepupae (WPP)");
}
}
return name;
}
private String getDevStageTerm(String value, String dccId) throws ObjectStoreException {
value = correctDevStageTerm(value);
// there may be duplicate terms for fly and worm, include taxon in key
String taxonId = getTaxonIdForSubmission(dccId);
OrganismRepository or = OrganismRepository.getOrganismRepository();
String genus = or.getOrganismDataByTaxon(Integer.parseInt(taxonId)).getGenus();
String key = value + "_" + genus;
String identifier = devStageTerms.get(key);
if (identifier == null) {
Item term = getChadoDBConverter().createItem("OntologyTerm");
term.setAttribute("name", value);
String ontologyRef = getDevelopmentOntologyByTaxon(taxonId);
if (ontologyRef != null) {
term.setReference("ontology", ontologyRef);
}
getChadoDBConverter().store(term);
devStageTerms.put(key, term.getIdentifier());
identifier = term.getIdentifier();
}
return identifier;
}
private String correctDevStageTerm(String value) {
// some terms are prefixed with ontology namespace
String prefix = "FlyBase development CV:";
if (value.startsWith(prefix)) {
value = value.substring(prefix.length());
}
return value;
}
private String getTaxonIdForSubmission(String dccId) {
Integer subChadoId = getSubmissionIdFromDccId(dccId);
String organism = submissionOrganismMap.get(subChadoId);
OrganismRepository or = OrganismRepository.getOrganismRepository();
return "" + or.getOrganismDataByFullName(organism).getTaxonId();
}
private String getDevelopmentOntologyByTaxon(String taxonId) throws ObjectStoreException {
if (taxonId == null) {
return null;
}
String ontologyName = null;
OrganismRepository or = OrganismRepository.getOrganismRepository();
String genus = or.getOrganismDataByTaxon(Integer.parseInt(taxonId)).getGenus();
if (genus.equals("Drosophila")) {
ontologyName = "Fly Development";
} else {
ontologyName = "Worm Development";
}
String ontologyId = devOntologies.get(ontologyName);
if (ontologyId == null) {
Item ontology = getChadoDBConverter().createItem("Ontology");
ontology.setAttribute("title", ontologyName);
getChadoDBConverter().store(ontology);
ontologyId = ontology.getIdentifier();
devOntologies.put(ontologyName, ontologyId);
}
return ontologyId;
}
private Integer getSubmissionIdFromDccId(String dccId) {
for (Map.Entry<Integer, String> entry : dccIdMap.entrySet()) {
if (entry.getValue().equals(dccId)) {
return entry.getKey();
}
}
return null;
}
/**
* Return the rows needed for data from the applied_protocol_data table.
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedDataAll(Connection connection)
throws SQLException {
String sraAcc = "SRA acc";
String query = "SELECT d.data_id, d.heading as data_heading,"
+ " d.name as data_name, d.value as data_value,"
+ " c.name as cv_term,"
+ " a.attribute_id, a.heading as att_heading, a.name as att_name, a.value as att_value,"
+ " a.dbxref_id as att_dbxref, a.rank as att_rank"
+ " FROM data d"
+ " LEFT JOIN data_attribute da ON (d.data_id = da.data_id)"
+ " LEFT JOIN attribute a ON (da.attribute_id = a.attribute_id)"
+ " LEFT JOIN cvterm c ON (d.type_id = c.cvterm_id)"
+ " LEFT JOIN dbxref as x ON (a.dbxref_id = x.dbxref_id)"
+ " WHERE d.name != '" + sraAcc + "'"
+ " AND d.value != '' "
+ " ORDER BY d.data_id";
return doQuery(connection, query, "getAppliedDataAll");
}
/**
* Return the rows needed for data from the applied_protocol_data table.
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedDataCharacteristics(Connection connection)
throws SQLException {
String query = "select d.data_id, d.heading as data_heading,"
+ " d.name as data_name, d.value as data_value,"
+ " a.attribute_id, a.heading as att_heading, a.name as att_name, a.value as att_value,"
+ " a.dbxref_id as att_dbxref, a.rank as att_rank"
+ " FROM data d, data_attribute da, attribute a, dbxref ax, db"
+ " WHERE d.data_id = da.data_id"
+ " AND da.attribute_id = a.attribute_id"
+ " AND a.dbxref_id = ax.dbxref_id"
+ " AND ax.db_id = db.db_id"
+ " ORDER BY d.data_id, a.dbxref_id ";
return doQuery(connection, query, "getAppliedDataCharacteristics");
}
private class SubmissionProperty
{
protected String type;
protected String wikiPageUrl;
protected Map<String, List<String>> details;
protected SubmissionProperty() {
details = new HashMap<String, List<String>>();
}
public SubmissionProperty(String type, String wikiPageUrl) {
this.type = type;
this.wikiPageUrl = wikiPageUrl;
details = new HashMap<String, List<String>>();
}
public void addDetail(String type, String value, int rank) {
List<String> values = details.get(type);
if (values == null) {
values = new ArrayList<String>();
details.put(type, values);
}
while (values.size() <= rank) {
values.add(null);
}
values.set(rank, value);
}
public String toString() {
return this.type + ": " + this.wikiPageUrl + this.details.entrySet();
}
}
private class DatabaseRecordConfig
{
private String dbName;
private String dbDescrition;
private String dbURL;
private Set<String> types = new HashSet<String>();;
}
private Set<DatabaseRecordConfig> initDatabaseRecordConfigs() {
Set<DatabaseRecordConfig> configs = new HashSet<DatabaseRecordConfig>();
DatabaseRecordConfig geo = new DatabaseRecordConfig();
geo.dbName = "GEO";
geo.dbDescrition = "Gene Expression Omnibus (NCBI)";
geo.dbURL = "http:
geo.types.add("GEO_record");
configs.add(geo);
DatabaseRecordConfig ae = new DatabaseRecordConfig();
ae.dbName = "ArrayExpress";
ae.dbDescrition = "ArrayExpress (EMBL-EBI)";
ae.dbURL = "http:
ae.types.add("ArrayExpress_record");
configs.add(ae);
DatabaseRecordConfig sra = new DatabaseRecordConfig();
sra.dbName = "SRA";
sra.dbDescrition = "Sequence Read Archive (NCBI)";
sra.dbURL =
"http:
sra.types.add("ShortReadArchive_project_ID_list (SRA)");
sra.types.add("ShortReadArchive_project_ID (SRA)");
configs.add(sra);
DatabaseRecordConfig ta = new DatabaseRecordConfig();
ta.dbName = "Trace Archive";
ta.dbDescrition = "Trace Archive (NCBI)";
ta.dbURL = "http:
ta.types.add("TraceArchive_record");
configs.add(ta);
DatabaseRecordConfig de = new DatabaseRecordConfig();
de.dbName = "dbEST";
de.dbDescrition = "Expressed Sequence Tags database (NCBI)";
de.dbURL = "http:
de.types.add("dbEST_record");
configs.add(de);
return configs;
}
/**
* Query to get data attributes
* This is a protected method so that it can be overridden for testing.
*
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedDataAttributes(Connection connection)
throws SQLException {
String query =
"select da.data_id, a.heading, a.value, a.name "
+ " from data_attribute da, attribute a"
+ " where da.attribute_id = a.attribute_id";
return doQuery(connection, query, "getAppliedDataAttributes");
}
private void setSubmissionRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
for (Integer submissionId : submissionDataMap.keySet()) {
for (Integer dataId : submissionDataMap.get(submissionId)) {
if (appliedDataMap.get(dataId).intermineObjectId == null) {
continue;
}
Reference reference = new Reference();
reference.setName("submission");
reference.setRefId(submissionMap.get(submissionId).itemIdentifier);
getChadoDBConverter().store(reference,
appliedDataMap.get(dataId).intermineObjectId);
}
}
LOG.info("TIME setting submission-data references: " + (System.currentTimeMillis() - bT));
}
private void createDatabaseRecords(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
Set<DatabaseRecordConfig> configs = initDatabaseRecordConfigs();
for (Integer submissionId : submissionDataMap.keySet()) {
List<String> submissionDbRecords = new ArrayList<String>();
for (Integer dataId : submissionDataMap.get(submissionId)) {
AppliedData ad = appliedDataMap.get(dataId);
if (ad.type.equalsIgnoreCase("Result Value")) {
for (DatabaseRecordConfig conf : configs) {
for (String type : conf.types) {
if (ad.name.equals(type)) {
submissionDbRecords.addAll(createDatabaseRecords(ad.value, conf));
}
}
}
}
if (!submissionDbRecords.isEmpty()) {
ReferenceList col = new ReferenceList("databaseRecords", submissionDbRecords);
getChadoDBConverter().store(col,
submissionMap.get(submissionId).interMineObjectId);
}
}
}
LOG.info("TIME creating DatabaseRecord objects: " + (System.currentTimeMillis() - bT));
}
private void createResultFiles(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
for (Integer submissionId : submissionDataMap.keySet()) {
for (Integer dataId : submissionDataMap.get(submissionId)) {
AppliedData ad = appliedDataMap.get(dataId);
if (ad.type.equalsIgnoreCase("Result File")) {
if (!StringUtils.isBlank(ad.value)) {
createResultFile(ad.value, ad.name, submissionId);
}
}
}
}
LOG.info("TIME creating ResultFile objects: " + (System.currentTimeMillis() - bT));
}
private List<String> createDatabaseRecords(String accession, DatabaseRecordConfig config)
throws ObjectStoreException {
List<String> dbRecordIds = new ArrayList<String>();
Set<String> cleanAccessions = new HashSet<String>();
// NOTE - this is a special case to deal with a very strange SRA accession format in some
// Celniker submissions. The 'accession' is provided as e.g.
// SRR013492.225322.1;SRR013492.462158.1;...
// We just want the unique SRR ids
if (config.dbName.equals("SRA") && (accession.indexOf(';') != -1
|| accession.indexOf('.') != -1)) {
for (String part : accession.split(";")) {
if (part.indexOf('.') != -1) {
cleanAccessions.add(part.substring(0, part.indexOf('.')));
} else {
cleanAccessions.add(part);
}
}
} else {
cleanAccessions.add(accession);
}
for (String cleanAccession : cleanAccessions) {
dbRecordIds.add(createDatabaseRecord(cleanAccession, config));
}
return dbRecordIds;
}
private String createDatabaseRecord(String accession, DatabaseRecordConfig config)
throws ObjectStoreException {
DatabaseRecordKey key = new DatabaseRecordKey(config.dbName, accession);
String dbRecordId = dbRecords.get(key);
if (dbRecordId == null) {
Item dbRecord = getChadoDBConverter().createItem("DatabaseRecord");
dbRecord.setAttribute("database", config.dbName);
dbRecord.setAttribute("description", config.dbDescrition);
if (StringUtils.isEmpty(accession)) {
dbRecord.setAttribute("accession", "To be confirmed");
} else {
dbRecord.setAttribute("url", config.dbURL + accession);
dbRecord.setAttribute("accession", accession);
}
getChadoDBConverter().store(dbRecord);
dbRecordId = dbRecord.getIdentifier();
dbRecords.put(key, dbRecordId);
}
return dbRecordId;
}
private class DatabaseRecordKey
{
private String db;
private String accession;
/**
* Construct with the database and accession
* @param db database name
* @param accession id in database
*/
public DatabaseRecordKey(String db, String accession) {
this.db = db;
this.accession = accession;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object o) {
if (o instanceof DatabaseRecordKey) {
DatabaseRecordKey otherKey = (DatabaseRecordKey) o;
if (StringUtils.isNotEmpty(accession)
&& StringUtils.isNotEmpty(otherKey.accession)) {
return this.db.equals(otherKey.db)
&& this.accession.equals(otherKey.accession);
}
}
return false;
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return db.hashCode() + 3 * accession.hashCode();
}
}
private void createResultFile(String fileName, String type, Integer submissionId)
throws ObjectStoreException {
Item resultFile = getChadoDBConverter().createItem("ResultFile");
resultFile.setAttribute("name", fileName);
String url = null;
if (fileName.startsWith("http")) {
url = fileName;
} else {
String dccId = dccIdMap.get(submissionId);
url = FILE_URL + dccId + "/extracted/" + fileName;
}
resultFile.setAttribute("url", url);
resultFile.setAttribute("type", type);
resultFile.setReference("submission", submissionMap.get(submissionId).itemIdentifier);
getChadoDBConverter().store(resultFile);
}
private void createRelatedSubmissions(Connection connection) throws ObjectStoreException {
Map<Integer, Set<String>> relatedSubs = new HashMap<Integer, Set<String>>();
for (Map.Entry<Integer, SubmissionReference> entry : submissionRefs.entrySet()) {
Integer submissionId = entry.getKey();
SubmissionReference ref = entry.getValue();
addRelatedSubmissions(relatedSubs, submissionId, ref.referencedSubmissionId);
addRelatedSubmissions(relatedSubs, ref.referencedSubmissionId, submissionId);
}
for (Map.Entry<Integer, Set<String>> entry : relatedSubs.entrySet()) {
ReferenceList related = new ReferenceList("relatedSubmissions",
new ArrayList<String>(entry.getValue()));
getChadoDBConverter().store(related, entry.getKey());
}
}
private void addRelatedSubmissions(Map<Integer, Set<String>> relatedSubs, Integer subId,
Integer relatedId) {
Set<String> itemIds = relatedSubs.get(subId);
if (itemIds == null) {
itemIds = new HashSet<String>();
relatedSubs.put(submissionMap.get(subId).interMineObjectId, itemIds);
}
itemIds.add(submissionMap.get(relatedId).itemIdentifier);
}
//sub -> prot
private void setSubmissionProtocolsRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
Map<Integer, List<Integer>> submissionProtocolMap = new HashMap<Integer, List<Integer>>();
Iterator<Integer> apId = appliedProtocolMap.keySet().iterator();
while (apId.hasNext()) {
Integer thisAP = apId.next();
AppliedProtocol ap = appliedProtocolMap.get(thisAP);
addToMap(submissionProtocolMap, ap.submissionId, ap.protocolId);
}
Iterator<Integer> subs = submissionProtocolMap.keySet().iterator();
while (subs.hasNext()) {
Integer thisSubmissionId = subs.next();
List<Integer> protocolChadoIds = submissionProtocolMap.get(thisSubmissionId);
ReferenceList collection = new ReferenceList();
collection.setName("protocols");
for (Integer protocolChadoId : protocolChadoIds) {
collection.addRefId(protocolItemIds.get(protocolChadoId));
}
Integer storedSubmissionId = submissionMap.get(thisSubmissionId).interMineObjectId;
getChadoDBConverter().store(collection, storedSubmissionId);
// may need protocols from referenced submissions to work out experiment type
protocolChadoIds.addAll(findProtocolIdsFromReferencedSubmissions(thisSubmissionId));
String piName = submissionProjectMap.get(thisSubmissionId);
setSubmissionExperimentType(storedSubmissionId, protocolChadoIds, piName);
}
LOG.info("TIME setting submission-protocol references: "
+ (System.currentTimeMillis() - bT));
}
// store Submission.experimentType if it can be inferred from protocols
private void setSubmissionExperimentType(Integer storedSubId, List<Integer> protocolIds,
String piName) throws ObjectStoreException {
Set<String> protocolTypes = new HashSet<String>();
for (Integer protocolId : protocolIds) {
protocolTypes.add(protocolTypesMap.get(protocolId).trim());
}
String experimentType = inferExperimentType(protocolTypes, piName);
if (experimentType != null) {
Attribute expTypeAtt = new Attribute("experimentType", experimentType);
getChadoDBConverter().store(expTypeAtt, storedSubId);
}
}
// Fetch protocols used to create reagents that are inputs to this submission, these are
// found in referenced submissions
private List<Integer> findProtocolIdsFromReferencedSubmissions(Integer submissionId) {
List<Integer> protocolIds = new ArrayList<Integer>();
if (submissionRefs == null) {
throw new RuntimeException("Attempting to access submissionRefs before it has been"
+ " populated, this method needs to be called after"
+ " processSubmissionProperties");
}
SubmissionReference subRef = submissionRefs.get(submissionId);
if (subRef != null) {
for (AppliedProtocol aProtocol : findAppliedProtocolsFromReferencedSubmission(subRef)) {
protocolIds.add(aProtocol.protocolId);
}
}
return protocolIds;
}
/**
* Work out an experiment type give the combination of protocols used for the
* submussion. e.g. *immunoprecipitation + hybridization = chIP-chip
* @param protocolTypes the protocal types
* @param piName name of PI
* @return a short experiment type
*/
protected String inferExperimentType(Set<String> protocolTypes, String piName) {
// extraction + sequencing + reverse transcription - ChIP = RTPCR
// extraction + sequencing - reverse transcription - ChIP = RNA-seq
if (containsMatch(protocolTypes, "nucleic_acid_extraction|RNA extraction")
&& containsMatch(protocolTypes, "sequencing(_protocol)?")
&& !containsMatch(protocolTypes, "chromatin_immunoprecipitation")) {
if (containsMatch(protocolTypes, "reverse_transcription")) {
return "RTPCR";
} else {
return "RNA-seq";
}
}
// reverse transcription + PCR + RACE = RACE
// reverse transcription + PCR - RACE = RTPCR
if (containsMatch(protocolTypes, "reverse_transcription")
&& containsMatch(protocolTypes, "PCR(_amplification)?")) {
if (containsMatch(protocolTypes, "RACE")) {
return "RACE";
} else {
return "RTPCR";
}
}
// ChIP + hybridization = ChIP-chip
// ChIP - hybridization = ChIP-seq
if (containsMatch(protocolTypes, "(.*)?immunoprecipitation")) {
if (containsMatch(protocolTypes, "hybridization")) {
return "ChIP-chip";
} else {
return "ChIP-seq";
}
}
// hybridization - ChIP =
// Celniker: RNA tiling array
// Henikoff: Chromatin-chip
// otherwise: Tiling array
if (containsMatch(protocolTypes, "hybridization")
&& !containsMatch(protocolTypes, "immunoprecipitation")) {
if (piName.equals("Celniker")) {
return "RNA tiling array";
} else if (piName.equals("Henikoff")) {
return "Chromatin-chip";
} else {
return "Tiling array";
}
}
// annotation = Computational annotation
if (containsMatch(protocolTypes, "annotation")) {
return "Computational annotation";
}
// If we haven't found a type yet, and there is a growth protocol, then
// this is probably an RNA sample creation experiment from Celniker
if (containsMatch(protocolTypes, "grow")) {
return "RNA sample creation";
}
return null;
}
// utility method for looking up in a set by regular expression
private boolean containsMatch(Set<String> testSet, String regex) {
boolean matches = false;
Pattern p = Pattern.compile(regex);
for (String test : testSet) {
Matcher m = p.matcher(test);
if (m.matches()) {
matches = true;
}
}
return matches;
}
//sub -> exp
private void setSubmissionExperimetRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
Iterator<String> exp = expSubMap.keySet().iterator();
while (exp.hasNext()) {
String thisExp = exp.next();
List<Integer> subs = expSubMap.get(thisExp);
Iterator <Integer> s = subs.iterator();
while (s.hasNext()) {
Integer thisSubId = s.next();
Reference reference = new Reference();
reference.setName("experiment");
reference.setRefId(experimentIdRefMap.get(thisExp));
getChadoDBConverter().store(reference,
submissionMap.get(thisSubId).interMineObjectId);
}
}
LOG.info("TIME setting submission-experiment references: "
+ (System.currentTimeMillis() - bT));
}
//sub -> ef
private void setSubmissionEFactorsRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
Iterator<Integer> subs = submissionEFactorMap.keySet().iterator();
while (subs.hasNext()) {
Integer thisSubmissionId = subs.next();
List<String> eFactors = submissionEFactorMap.get(thisSubmissionId);
LOG.debug("EF REFS: " + thisSubmissionId + " (" + eFactors + ")");
Iterator<String> ef = eFactors.iterator();
ReferenceList collection = new ReferenceList();
collection.setName("experimentalFactors");
while (ef.hasNext()) {
String currentEF = ef.next();
collection.addRefId(eFactorIdRefMap.get(currentEF));
LOG.debug("EF REFS: ->" + currentEF + " ref: " + eFactorIdRefMap.get(currentEF));
}
if (!collection.equals(null)) {
LOG.debug("EF REFS: ->" + thisSubmissionId + "|"
+ submissionMap.get(thisSubmissionId).interMineObjectId);
getChadoDBConverter().store(collection,
submissionMap.get(thisSubmissionId).interMineObjectId);
}
}
LOG.info("TIME setting submission-exFactors references: "
+ (System.currentTimeMillis() - bT));
}
//sub -> publication
private void setSubmissionPublicationRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
Iterator<Integer> subs = publicationIdMap.keySet().iterator();
while (subs.hasNext()) {
Integer thisSubmissionId = subs.next();
// Integer im_oid = publicationIdMap.get(thisSubmissionId);
Reference reference = new Reference();
reference.setName("publication");
reference.setRefId(publicationIdRefMap.get(thisSubmissionId));
getChadoDBConverter().store(reference,
submissionMap.get(thisSubmissionId).interMineObjectId);
}
LOG.info("TIME setting submission-publication references: "
+ (System.currentTimeMillis() - bT));
}
/**
* to store references between applied protocols and their input data
* reverse reference: data -> next appliedProtocols
* and between applied protocols and their output data
* reverse reference: data -> previous appliedProtocols
* (many to many)
*/
private void setDAGRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
for (Integer thisAP : appliedProtocolMap.keySet()) {
AppliedProtocol ap = appliedProtocolMap.get(thisAP);
if (!ap.inputs.isEmpty()) {
ReferenceList collection = new ReferenceList("inputs");
for (Integer inputId : ap.inputs) {
collection.addRefId(appliedDataMap.get(inputId).itemIdentifier);
}
getChadoDBConverter().store(collection, appliedProtocolIdMap.get(thisAP));
}
if (!ap.outputs.isEmpty()) {
ReferenceList collection = new ReferenceList("outputs");
for (Integer outputId : ap.outputs) {
collection.addRefId(appliedDataMap.get(outputId).itemIdentifier);
}
getChadoDBConverter().store(collection, appliedProtocolIdMap.get(thisAP));
}
}
LOG.info("TIME setting DAG references: " + (System.currentTimeMillis() - bT));
}
/**
* maps from chado field names to ours.
*
* TODO: check if up to date
*
* if a field is not needed it is marked with NOT_TO_BE_LOADED
* a check is performed and fields unaccounted for are logged.
*/
private static final Map<String, String> FIELD_NAME_MAP =
new HashMap<String, String>();
private static final String NOT_TO_BE_LOADED = "this is ; illegal - anyway";
static {
// experiment
// swapping back to uniquename in experiment table
// FIELD_NAME_MAP.put("Investigation Title", "title");
FIELD_NAME_MAP.put("Investigation Title", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Project", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Project URL", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Lab", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Experiment Description", "description");
FIELD_NAME_MAP.put("Experimental Design", "design");
FIELD_NAME_MAP.put("Experimental Factor Type", "factorType");
FIELD_NAME_MAP.put("Experimental Factor Name", "factorName");
FIELD_NAME_MAP.put("Quality Control Type", "qualityControl");
FIELD_NAME_MAP.put("Replicate Type", "replicate");
FIELD_NAME_MAP.put("Date of Experiment", "experimentDate");
FIELD_NAME_MAP.put("Public Release Date", "publicReleaseDate");
FIELD_NAME_MAP.put("Embargo Date", "embargoDate");
FIELD_NAME_MAP.put("dcc_id", "DCCid");
FIELD_NAME_MAP.put("PubMed ID", "pubMedId");
FIELD_NAME_MAP.put("Person First Name", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Mid Initials", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Last Name", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Affiliation", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Address", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Phone", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Email", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Roles", NOT_TO_BE_LOADED);
// data: parameter values
FIELD_NAME_MAP.put("Array Data File", "arrayDataFile");
FIELD_NAME_MAP.put("Array Design REF", "arrayDesignRef");
FIELD_NAME_MAP.put("Derived Array Data File", "derivedArrayDataFile");
FIELD_NAME_MAP.put("Result File", "resultFile");
// protocol
FIELD_NAME_MAP.put("Protocol Type", "type");
FIELD_NAME_MAP.put("url protocol", "url");
FIELD_NAME_MAP.put("species", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("references", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("lab", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Comment", NOT_TO_BE_LOADED);
}
/**
* to store identifiers in project maps.
* @param i
* @param chadoId
* @param intermineObjectId
* @throws ObjectStoreException
*/
private void storeInProjectMaps(Item i, String surnamePI, Integer intermineObjectId)
throws ObjectStoreException {
if (i.getClassName().equals("Project")) {
projectIdMap .put(surnamePI, intermineObjectId);
projectIdRefMap .put(surnamePI, i.getIdentifier());
} else {
throw new IllegalArgumentException(
"Type mismatch: expecting Project, getting "
+ i.getClassName().substring(37) + " with intermineObjectId = "
+ intermineObjectId + ", project = " + surnamePI);
}
debugMap .put(i.getIdentifier(), i.getClassName());
}
/**
* to store identifiers in lab maps.
* @param i
* @param chadoId
* @param intermineObjectId
* @throws ObjectStoreException
*/
private void storeInLabMaps(Item i, String labName, Integer intermineObjectId)
throws ObjectStoreException {
if (i.getClassName().equals("Lab")) {
labIdMap .put(labName, intermineObjectId);
labIdRefMap .put(labName, i.getIdentifier());
} else {
throw new IllegalArgumentException(
"Type mismatch: expecting Lab, getting "
+ i.getClassName().substring(37) + " with intermineObjectId = "
+ intermineObjectId + ", lab = " + labName);
}
debugMap .put(i.getIdentifier(), i.getClassName());
}
private void mapSubmissionAndData(Integer submissionId, Integer dataId) {
addToMap(submissionDataMap, submissionId, dataId);
dataSubmissionMap.put(dataId, submissionId);
}
/**
* method to wrap the execution of a query, without log info
* @param connection
* @param query
* @return the result set
* @throws SQLException
*/
private ResultSet doQuery(Connection connection, String query)
throws SQLException {
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
/**
* method to wrap the execution of a query with log info)
* @param connection
* @param query
* @param comment for not logging
* @return the result set
* @throws SQLException
*/
private ResultSet doQuery(Connection connection, String query, String comment)
throws SQLException {
// we could avoid passing comment if we trace the calling method
// new Throwable().fillInStackTrace().getStackTrace()[1].getMethodName()
LOG.info("executing: " + query);
long bT = System.currentTimeMillis();
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
LOG.info("QUERY TIME " + comment + ": " + (System.currentTimeMillis() - bT));
return res;
}
/**
* adds an element to a list which is the value of a map
* @param m the map (<Integer, List<Integer>>)
* @param key the key for the map
* @param value the list
*/
private void addToMap(Map<Integer, List<Integer>> m, Integer key, Integer value) {
List<Integer> values = new ArrayList<Integer>();
if (m.containsKey(key)) {
values = m.get(key);
}
if (!values.contains(value)) {
values.add(value);
m.put(key, values);
}
}
/**
* adds an element to a list which is the value of a map
* @param m the map (<Integer, List<String>>)
* @param key the key for the map
* @param value the list
*/
private void addToMap(Map<Integer, List<String>> m, Integer key, String value) {
List<String> ids = new ArrayList<String>();
if (m.containsKey(key)) {
ids = m.get(key);
}
if (!ids.contains(value)) {
ids.add(value);
m.put(key, ids);
}
}
/**
* adds an element to a list which is the value of a map
* @param m the map (<String, List<Integer>>)
* @param key the key for the map
* @param value the list
*/
private void addToMap(Map<String, List<Integer>> m, String key, Integer value) {
List<Integer> ids = new ArrayList<Integer>();
if (m.containsKey(key)) {
ids = m.get(key);
}
if (!ids.contains(value)) {
ids.add(value);
m.put(key, ids);
}
}
}
|
package org.intermine.bio.dataconversion;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.bio.util.OrganismRepository;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.sql.writebatch.Batch;
import org.intermine.sql.writebatch.BatchWriterPostgresCopyImpl;
import org.intermine.util.Util;
import org.intermine.xml.full.Attribute;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.Reference;
import org.intermine.xml.full.ReferenceList;
/**
* Create items from the modENCODE metadata extensions to the chado schema.
* @author Kim Rutherford,sc,rns
*/
public class ModEncodeMetaDataProcessor extends ChadoProcessor
{
private static final Logger LOG = Logger.getLogger(ModEncodeMetaDataProcessor.class);
private static final String DATA_IDS_TABLE_NAME = "data_ids";
private static final String WIKI_URL = "http://wiki.modencode.org/project/index.php?title=";
private static final String FILE_URL = "http://submit.modencode.org/submit/public/get_file/";
private static final String DCC_PREFIX = "modENCODE_";
private static final String NA_PROP = "not applicable";
private static final Set<String> DB_RECORD_TYPES =
Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(
"GEO_record",
"ArrayExpress_record",
"TraceArchive_record",
"dbEST_record",
"ShortReadArchive_project_ID (SRA)",
"ShortReadArchive_project_ID_list (SRA)")));
// submission maps
private Map<Integer, String> submissionOrganismMap = new HashMap<Integer, String>();
// maps from chado identifier to lab/project details
private Map<Integer, SubmissionDetails> submissionMap =
new HashMap<Integer, SubmissionDetails>();
// chado submission id to list of top level attributes, e.g. dev stage, organism_part
private Map<Integer, ExperimentalFactor> submissionEFMap =
new HashMap<Integer, ExperimentalFactor>();
// subId to dcc id
private Map<Integer, String> dccIdMap = new HashMap<Integer, String>();
// superseded/deleted subId to dcc id: to be checked in case we need to skip
// loading a sub
private Map<Integer, String> deletedSubMap = new HashMap<Integer, String>();
// applied_protocol/data/attribute maps
// chado submission id to chado data_id
private Map<Integer, List<Integer>> submissionDataMap = new HashMap<Integer, List<Integer>>();
// chado data id to chado submission id
private Map<Integer, Integer> dataSubmissionMap = new HashMap<Integer, Integer>();
// to store protocol data until we create applied protocols
private Map<Integer, Protocol> protocolMap =
new HashMap<Integer, Protocol>();
// used when traversing dag of applied protocols
private Map<Integer, AppliedProtocol> appliedProtocolMap =
new HashMap<Integer, AppliedProtocol>();
// used when traversing dag of applied protocols
private Map<Integer, AppliedData> appliedDataMap =
new HashMap<Integer, AppliedData>();
// project/lab/experiment/submission maps
// for projects, the maps link the project name with the identifiers...
private Map<String, Integer> projectIdMap = new HashMap<String, Integer>();
private Map<String, String> projectIdRefMap = new HashMap<String, String>();
// for labs, the maps link the lab name with the identifiers...
private Map<String, Integer> labIdMap = new HashMap<String, Integer>();
private Map<String, String> labIdRefMap = new HashMap<String, String>();
// for experiment, the maps link the exp name (description!) with the identifiers...
private Map<String, Integer> experimentIdMap = new HashMap<String, Integer>();
private Map<String, String> experimentIdRefMap = new HashMap<String, String>();
private Map<String, List<Integer>> expSubMap = new HashMap<String, List<Integer>>();
// ...we need a further map to link to submission
private Map<Integer, String> submissionProjectMap = new HashMap<Integer, String>();
private Map<Integer, String> submissionLabMap = new HashMap<Integer, String>();
// to store the category in experiment
private Map<Integer, String> submissionExpCatMap = new HashMap<Integer, String>();
// to check if experiment type is set
private Set<Integer> submissionWithExpTypeSet = new HashSet<Integer>();
// submission/applied_protocol/protocol maps
private Map<String, String> protocolsMap = new HashMap<String, String>();
private Map<Integer, String> protocolItemIds = new HashMap<Integer, String>();
private Map<String, Integer> protocolItemToObjectId = new HashMap<String, Integer>();
// submission chado id to item identifier of Protocol used to generate GFF
private Map<Integer, String> scoreProtocols = new HashMap<Integer, String>();
private Map<Integer, String> protocolTypesMap = new HashMap<Integer, String>();
private Map<Integer, Integer> appliedProtocolIdMap = new HashMap<Integer, Integer>();
private Map<Integer, String> appliedProtocolIdRefMap = new HashMap<Integer, String>();
// list of firstAppliedProtocols, first level of the DAG linking
// the applied protocols through the data (and giving the flow of data)
private List<Integer> firstAppliedProtocols = new ArrayList<Integer>();
private Map<Integer, Integer> publicationIdMap = new HashMap<Integer, Integer>();
private Map<Integer, String> publicationIdRefMap = new HashMap<Integer, String>();
// experimental factor maps
private Map<String, Integer> eFactorIdMap = new HashMap<String, Integer>();
private Map<String, String> eFactorIdRefMap = new HashMap<String, String>();
private Map<Integer, List<String>> submissionEFactorMap = new HashMap<Integer, List<String>>();
// caches
// cache cv term names by id
private Map<String, String> cvtermCache = new HashMap<String, String>();
private Map<String, String> devStageTerms = new HashMap<String, String>();
private Map<String, String> devOntologies = new HashMap<String, String>();
// just for debugging, itemIdentifier, type
private Map<String, String> debugMap = new HashMap<String, String>();
private Map<String, Item> nonWikiSubmissionProperties = new HashMap<String, Item>();
private Map<String, Item> subItemsMap = new HashMap<String, Item>();
Map<Integer, List<SubmissionReference>> submissionRefs = null;
private IdResolverFactory flyResolverFactory = null;
private IdResolverFactory wormResolverFactory = null;
private Map<String, String> geneToItemIdentifier = new HashMap<String, String>();
// DbRecords Integer=objectId String=submission.itemId
// the second map is used directly to build the references
private Map<DatabaseRecordKey, Integer> dbRecords = new HashMap<DatabaseRecordKey, Integer>();
private Map<Integer, List<String>> dbRecordIdSubItems = new HashMap<Integer, List<String>>();
private static final class SubmissionDetails
{
// the identifier assigned to Item eg. "0_23"
private String itemIdentifier;
// the object id of the stored Item
private Integer interMineObjectId;
// the identifier assigned to lab Item for this object
private String labItemIdentifier;
private String title;
private SubmissionDetails() {
// don't instantiate
}
}
/**
* AppliedProtocol class to reconstruct the flow of submission data
*/
private static final class AppliedProtocol
{
private Integer submissionId; // chado
private Integer protocolId;
private Integer step; // the level in the dag for the AP
// the output data associated to this applied protocol
private List<Integer> outputs = new ArrayList<Integer>();
private List<Integer> inputs = new ArrayList<Integer>();
private AppliedProtocol() {
// don't instantiate
}
}
/**
* Protocol class to store protocol data
*/
private static final class Protocol
{
private Integer protocolId; // possibly we don't need this (map)
private String name;
private String description;
private String wikiLink;
private Integer version; // the level in the dag for the AP
private Protocol() {
// don't instantiate
}
}
/**
* AppliedData class
* to reconstruct the flow of submission data
*
*/
private static final class AppliedData
{
private String itemIdentifier;
private Integer intermineObjectId;
private Integer dataId;
private String value;
private String actualValue;
private String type;
private String name;
private String url; // in particular, it stores the dccid of the related sub needed for
// linking to a result file
// the list of applied protocols for which this data item is an input
private List<Integer> nextAppliedProtocols = new ArrayList<Integer>();
// the list of applied protocols for which this data item is an output
private List<Integer> previousAppliedProtocols = new ArrayList<Integer>();
private AppliedData() {
// don't instantiate
}
}
/**
* Experimental Factor class
* to store the couples (type, name/value) of EF
* note that in chado sometime the name is given, other times is the value
*/
private static final class ExperimentalFactor
{
private Map<String, String> efTypes = new HashMap<String, String>();
private List<String> efNames = new ArrayList<String>();
private ExperimentalFactor() {
// don't instantiate
}
}
/**
* Create a new ChadoProcessor object
* @param chadoDBConverter the converter that created this Processor
*/
public ModEncodeMetaDataProcessor(ChadoDBConverter chadoDBConverter) {
super(chadoDBConverter);
}
/**
* {@inheritDoc}
*/
@Override
public void process(Connection connection) throws Exception {
processDeleted(connection);
processProjectTable(connection);
processLabTable(connection);
processSubmissionOrganism(connection);
processSubmission(connection);
processSubmissionAttributes(connection);
processProtocolTable(connection);
processAppliedProtocolTable(connection);
processProtocolAttributes(connection);
processDag(connection);
processAppliedData(connection);
processAppliedDataAttributes(connection);
processExperiment(connection);
findScoreProtocols();
processFeatures(connection, submissionMap);
// set references
setSubmissionRefs(connection);
setSubmissionExperimentRefs(connection);
setDAGRefs(connection);
// create DatabaseRecords where necessary for each submission
createDatabaseRecords(connection);
// create result files per submission
createResultFiles(connection);
// for high level attributes and experimental factors (EF)
// TODO: clean up
processEFactor(connection);
flyResolverFactory = new FlyBaseIdResolverFactory("gene");
wormResolverFactory = new WormBaseChadoIdResolverFactory("gene");
processSubmissionProperties(connection);
createRelatedSubmissions(connection);
setSubmissionProtocolsRefs(connection);
setSubmissionEFactorsRefs(connection);
setSubmissionPublicationRefs(connection);
}
private void processDeleted(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getDeleted(connection);
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
String value = res.getString("value");
deletedSubMap.put(submissionId, value);
}
res.close();
LOG.info("found " + deletedSubMap.size() + " deleted submissions to skip in the build.");
LOG.info("PROCESS TIME deleted subs: " + (System.currentTimeMillis() - bT) + " ms");
}
/**
* Return deleted subs in the chado db.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getDeleted(Connection connection)
throws SQLException {
String query =
"SELECT distinct a.experiment_id, a.value "
+ " FROM experiment_prop a "
+ " where a.name = 'deleted' ";
return doQuery(connection, query, "getDeleted");
}
private void processFeatures(Connection connection,
Map<Integer, SubmissionDetails> submissionMap)
throws Exception {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
// keep map of feature to submissions it has been referenced by, some features appear in
// more than one submission
Map<Integer, List<String>> subCollections = new HashMap<Integer, List<String>>();
// hold features that should only be processed once across all submissions, initialise
// processor with this map each time
Map<Integer, FeatureData> commonFeaturesMap = new HashMap<Integer, FeatureData>();
for (Map.Entry<Integer, SubmissionDetails> entry: submissionMap.entrySet()) {
Integer chadoExperimentId = entry.getKey();
if (deletedSubMap.containsKey(chadoExperimentId)) {
continue;
}
Map<Integer, FeatureData> subFeatureMap = new HashMap<Integer, FeatureData>();
SubmissionDetails submissionDetails = entry.getValue();
String submissionItemIdentifier = submissionDetails.itemIdentifier;
String labItemIdentifier = submissionDetails.labItemIdentifier;
String submissionTitle = submissionDetails.title;
List<Integer> thisSubmissionDataIds = submissionDataMap.get(chadoExperimentId);
LOG.info("DATA IDS for " + dccIdMap.get(chadoExperimentId) + ": "
+ thisSubmissionDataIds.size());
// Create a temporary table with the feature ids related to this submission
// based on the data_feature table
String dataIdsTempTable = createDataIdsTempTable(connection, chadoExperimentId,
thisSubmissionDataIds);
ModEncodeFeatureProcessor processor =
new ModEncodeFeatureProcessor(getChadoDBConverter(), submissionItemIdentifier,
labItemIdentifier, dataIdsTempTable, submissionTitle,
scoreProtocols.get(chadoExperimentId));
processor.initialiseCommonFeatures(commonFeaturesMap);
processor.process(connection);
// all features related to this submission
subFeatureMap.putAll(processor.getFeatureMap());
// features common across many submissions
commonFeaturesMap.putAll(processor.getCommonFeaturesMap());
LOG.info("COMMON FEATURES: " + commonFeaturesMap.size());
if (subFeatureMap.keySet().size() == 0) {
LOG.error("FEATMAP: submission " + chadoExperimentId
+ " has no featureMap keys.");
continue;
}
LOG.info("FEATMAP: submission " + chadoExperimentId + "|"
+ "featureMap: " + subFeatureMap.keySet().size());
// Populate map of submissions to features, some features are in multiple submissions
processDataFeatureTable(connection, subCollections, subFeatureMap,
chadoExperimentId, dataIdsTempTable);
dropDataIdsTempTable(connection, dataIdsTempTable);
// 1- generate a map of gene-identifiers so we can re-use the same item identifiers
// when creating antibody/strain target genes late
// 2- fill the 'ChromatinState' state with the secondaryId
additionalProcessing(processor, subFeatureMap);
}
storeSubmissionsCollections(subCollections);
LOG.info("PROCESS TIME features: " + (System.currentTimeMillis() - bT) + " ms");
}
private void storeSubmissionsCollections(Map<Integer, List<String>> subCollections)
throws ObjectStoreException {
for (Map.Entry<Integer, List<String>> entry : subCollections.entrySet()) {
Integer featureObjectId = entry.getKey();
ReferenceList collection = new ReferenceList("submissions", entry.getValue());
getChadoDBConverter().store(collection, featureObjectId);
}
}
private void additionalProcessing(ModEncodeFeatureProcessor processor,
Map<Integer, FeatureData> subFeatureMap) throws ObjectStoreException{
for (FeatureData fData : subFeatureMap.values()) {
// 1- generate a map of gene-identifiers so we can re-use the same item identifiers
// when creating antibody/strain target genes late
if ("Gene".equals(fData.getInterMineType())) {
String geneIdentifier = processor.fixIdentifier(fData, fData.getUniqueName());
geneToItemIdentifier.put(geneIdentifier, fData.getItemIdentifier());
}
// 2- fill the 'ChromatinState' state with the secondaryId
if ("ChromatinState".equals(fData.getInterMineType())) {
String state = fData.getChadoFeatureName();
Integer imObjectId = fData.getIntermineObjectId();
setAttribute(imObjectId, "state", state);
}
}
}
private void processDataFeatureTable(Connection connection, Map<Integer, List<String>> subCols,
Map<Integer, FeatureData> featureMap, Integer chadoExperimentId, String dataIdTable)
throws SQLException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
String submissionItemId = submissionMap.get(chadoExperimentId).itemIdentifier;
bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getDataFeature(connection, dataIdTable);
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
Integer featureId = new Integer(res.getInt("feature_id"));
FeatureData featureData = featureMap.get(featureId);
if (featureData == null) {
LOG.debug("Check feature type: no data for feature_id: " + featureId
+ " in processDataFeatureTable(), data_id =" + dataId);
continue;
}
Integer featureObjectId = featureData.getIntermineObjectId();
List<String> subs = subCols.get(featureObjectId);
if (subs == null) {
subs = new ArrayList<String>();
subCols.put(featureObjectId, subs);
}
subs.add(submissionItemId);
}
LOG.info("DATA IDS PROCESS TIME data_feature table: " + (System.currentTimeMillis() - bT));
}
private String createDataIdsTempTable(Connection connection, Integer chadoExperimentId,
List<Integer> dataIds) throws SQLException {
// the batch writer system doesn't like to have duplicate named tables
String tableName = DATA_IDS_TABLE_NAME + "_" + chadoExperimentId + "_"
+ System.currentTimeMillis();
long bT = System.currentTimeMillis();
String query =
" CREATE TEMPORARY TABLE " + tableName + " (data_id int)";
Statement stmt = connection.createStatement();
LOG.info("executing: " + query);
stmt.execute(query);
try {
BatchWriterPostgresCopyImpl batchWriter = new BatchWriterPostgresCopyImpl();
Batch batch = new Batch(batchWriter);
HashSet<Integer> uniqueDataIds = new HashSet<Integer>(dataIds);
String[] colNames = new String[] {"data_id"};
for (Integer dataId : uniqueDataIds) {
batch.addRow(connection, tableName, dataId, colNames, new Object[] {dataId});
}
batch.flush(connection);
batch.close(connection);
LOG.info("CREATED DATA IDS TABLE: " + tableName + " with " + uniqueDataIds.size()
+ " data ids in " + (System.currentTimeMillis() - bT) + "ms");
String idIndexQuery = "CREATE INDEX " + tableName + "_data_id_index ON "
+ tableName + "(data_id)";
LOG.info("DATA IDS executing: " + idIndexQuery);
long bT1 = System.currentTimeMillis();
stmt.execute(idIndexQuery);
LOG.info("DATA IDS TIME creating INDEX: " + (System.currentTimeMillis() - bT1) + "ms");
String analyze = "ANALYZE " + tableName;
LOG.info("executing: " + analyze);
long bT2 = System.currentTimeMillis();
stmt.execute(analyze);
LOG.info("DATA IDS TIME analyzing: " + (System.currentTimeMillis() - bT2) + "ms");
} catch (SQLException e) {
// the batch writer system doesn't like to have duplicate named tables
query = "DROP TABLE " + tableName;
stmt.execute(query);
throw e;
}
return tableName;
}
private void dropDataIdsTempTable(Connection connection, String dataIdsTableName)
throws SQLException {
long bT = System.currentTimeMillis();
String query = " DROP TABLE " + dataIdsTableName;
LOG.info("executing: " + query);
Statement stmt = connection.createStatement();
stmt.execute(query);
LOG.info("DATA IDS TIME dropping table '" + dataIdsTableName + "': "
+ (System.currentTimeMillis() - bT));
}
private ResultSet getDataFeature(Connection connection, String dataIdTable)
throws SQLException {
String query =
"SELECT df.data_id, df.feature_id"
+ " FROM data_feature df, " + dataIdTable + " d"
+ " WHERE df.data_id = d.data_id";
return doQuery(connection, query, "getDataFeature");
}
private void processDag(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getDAG(connection);
AppliedProtocol node = new AppliedProtocol();
AppliedData branch = null;
Integer count = new Integer(0);
Integer actualSubmissionId = new Integer(0); // to store the experiment id (see below)
Integer previousAppliedProtocolId = new Integer(0);
boolean isADeletedSub = false;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
Integer protocolId = new Integer(res.getInt("protocol_id"));
Integer appliedProtocolId = new Integer(res.getInt("applied_protocol_id"));
Integer dataId = new Integer(res.getInt("data_id"));
String direction = res.getString("direction");
LOG.debug("DAG: " + submissionId + " p:" + protocolId + " ap:" + appliedProtocolId
+ " d:" + dataId + " | " + direction);
// the results are ordered, first ap have a subId
// if we find a deleted sub, we know that subsequent records with null
// subId belongs to the deleted sub
// note that while the subId is null in the database, it is = 0 here
if (submissionId == 0) {
if (isADeletedSub) {
LOG.debug("DEL: skipping" + isADeletedSub);
continue;
}
} else {
if (deletedSubMap.containsKey(submissionId)) {
isADeletedSub = true;
LOG.debug("DEL: " + submissionId + " ->" + isADeletedSub);
continue;
} else {
isADeletedSub = false;
LOG.debug("DEL: " + submissionId + " ->" + isADeletedSub);
}
}
// build a data node for each iteration
if (appliedDataMap.containsKey(dataId)) {
branch = appliedDataMap.get(dataId);
} else {
branch = new AppliedData();
}
// could use > (order by apid, apdataid, direction)
// NB: using isLast() is expensive
if (!appliedProtocolId.equals(previousAppliedProtocolId) || res.isLast()) {
// the submissionId != null for the first applied protocol
if (submissionId > 0) {
firstAppliedProtocols.add(appliedProtocolId);
LOG.debug("DAG fap subId:" + submissionId + " apID: " + appliedProtocolId);
// set actual submission id
// we can either be at a first applied protocol (submissionId > 0)..
actualSubmissionId = submissionId;
} else {
// ..or already down the dag, and we use the stored id.
submissionId = actualSubmissionId;
}
// last one: fill the list of outputs
// and add to the general list of data ids for the submission,
// used to fetch features
if (res.isLast()) {
if ("output".equalsIgnoreCase(direction)) {
node.outputs.add(dataId);
mapSubmissionAndData(submissionId, dataId);
}
}
// if it is not the first iteration, let's store it
if (previousAppliedProtocolId > 0) {
appliedProtocolMap.put(previousAppliedProtocolId, node);
}
// new node
AppliedProtocol newNode = new AppliedProtocol();
newNode.protocolId = protocolId;
newNode.submissionId = submissionId;
if (direction.startsWith("in")) {
// add this applied protocol to the list of nextAppliedProtocols
branch.nextAppliedProtocols.add(appliedProtocolId);
// ..and update the map
updateAppliedDataMap(branch, dataId);
// .. and add the dataId to the list of input Data for this applied protocol
newNode.inputs.add(dataId);
/**
* @param newAD
* @param dataId
*/
private void updateAppliedDataMap(AppliedData newAD, Integer dataId) {
if (appliedDataMap.containsKey(dataId)) {
appliedDataMap.remove(dataId);
}
appliedDataMap.put(dataId, newAD);
}
/**
* @param newAD the new appliedData
* @param dataId the data id
* @param intermineObjectId just a flag to do an update of attributes instead of a replecament
*/
private void updateADMap(AppliedData newAD, Integer dataId, Integer intermineObjectId) {
if (appliedDataMap.containsKey(dataId)) {
AppliedData datum = appliedDataMap.get(dataId);
datum.intermineObjectId = newAD.intermineObjectId;
datum.itemIdentifier = newAD.itemIdentifier;
datum.value = newAD.value;
datum.actualValue = newAD.actualValue;
datum.dataId = dataId;
datum.type = newAD.type;
datum.name = newAD.name;
datum.url = newAD.url;
} else {
appliedDataMap.put(dataId, newAD);
}
}
/**
* to set the step attribute for the applied protocols
*/
private void setAppliedProtocolSteps(Connection connection)
throws ObjectStoreException {
for (Integer appliedProtocolId : appliedProtocolMap.keySet()) {
Integer step = appliedProtocolMap.get(appliedProtocolId).step;
if (step != null) {
Attribute attr = new Attribute("step", step.toString());
getChadoDBConverter().store(attr, appliedProtocolIdMap.get(appliedProtocolId));
} else {
AppliedProtocol ap = appliedProtocolMap.get(appliedProtocolId);
LOG.warn("AppliedProtocol.step not set for chado id: " + appliedProtocolId
+ " sub " + dccIdMap.get(ap.submissionId) + " inputs " + ap.inputs
+ " outputs " + ap.outputs);
}
}
}
// Look for protocols that were used to generated GFF files, these are passed to the feature
// processor, if features have a score the protocol is set as the scoreProtocol reference.
// NOTE this could equally be done with data, data_feature and applied_protocol_data
private void findScoreProtocols() {
for (Map.Entry<Integer, AppliedData> entry : appliedDataMap.entrySet()) {
Integer dataId = entry.getKey();
AppliedData aData = entry.getValue();
if ("Result File".equals(aData.type)
&& (aData.value.endsWith(".gff") || aData.value.endsWith("gff3"))) {
for (Integer papId : aData.previousAppliedProtocols) {
AppliedProtocol aProtocol = appliedProtocolMap.get(papId);
String protocolItemId = protocolItemIds.get(aProtocol.protocolId);
scoreProtocols.put(dataSubmissionMap.get(dataId), protocolItemId);
}
}
}
}
/**
* Return the rows needed to construct the DAG of the data/protocols.
* The reference to the submission is available only for the first set
* of applied protocols, hence the outer join.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getDAG(Connection connection)
throws SQLException {
String query =
"SELECT eap.experiment_id, ap.protocol_id, apd.applied_protocol_id"
+ " , apd.data_id, apd.applied_protocol_data_id, apd.direction"
+ " FROM applied_protocol ap LEFT JOIN experiment_applied_protocol eap"
+ " ON (eap.first_applied_protocol_id = ap.applied_protocol_id )"
+ " , applied_protocol_data apd"
+ " WHERE apd.applied_protocol_id = ap.applied_protocol_id"
+ " ORDER By 3,5,6";
return doQuery(connection, query, "getDAG");
}
/**
* Applies iteratively buildADaglevel
*
* @throws SQLException
* @throws ObjectStoreException
*/
private void traverseDag()
throws ObjectStoreException {
List<Integer> currentIterationAP = firstAppliedProtocols;
List<Integer> nextIterationAP = new ArrayList<Integer>();
Integer step = 1; // DAG level
while (currentIterationAP.size() > 0) {
nextIterationAP = buildADagLevel (currentIterationAP, step);
currentIterationAP = nextIterationAP;
step++;
}
}
/**
* This method is given a set of applied protocols (already associated with a submission)
* and produces the next set of applied protocols. The latter are the protocols attached to the
* output data of the starting set (output data for a applied protocol is the input data for the
* next one).
* It also fills the map linking directly results ('leaf' output data) with submission
*
* @param previousAppliedProtocols
* @return the next batch of appliedProtocolId
* @throws SQLException
* @throws ObjectStoreException
*/
private List<Integer> buildADagLevel(List<Integer> previousAppliedProtocols, Integer step)
throws ObjectStoreException {
List<Integer> nextIterationProtocols = new ArrayList<Integer>();
Iterator<Integer> pap = previousAppliedProtocols.iterator();
while (pap.hasNext()) {
List<Integer> outputs = new ArrayList<Integer>();
List<Integer> inputs = new ArrayList<Integer>();
Integer currentId = pap.next();
// add the DAG level here only if these are the first AP
if (step == 1) {
appliedProtocolMap.get(currentId).step = step;
}
outputs.addAll(appliedProtocolMap.get(currentId).outputs);
Integer submissionId = appliedProtocolMap.get(currentId).submissionId;
Iterator<Integer> od = outputs.iterator();
while (od.hasNext()) {
Integer currentOD = od.next();
List<Integer> nextProtocols = new ArrayList<Integer>();
// build map submission-data
mapSubmissionAndData(submissionId, currentOD);
if (appliedDataMap.containsKey(currentOD)) {
// fill the list of next (children) protocols
nextProtocols.addAll(appliedDataMap.get(currentOD).nextAppliedProtocols);
if (appliedDataMap.get(currentOD).nextAppliedProtocols.isEmpty()) {
// this is a leaf!!
LOG.debug("DAG leaf: " + submissionId + " dataId: " + currentOD);
}
}
// to fill submission-dataId map
// this is needed, otherwise inputs to AP that are not outputs
// of a previous protocol are not considered
inputs.addAll(appliedProtocolMap.get(currentId).inputs);
Iterator<Integer> in = inputs.iterator();
while (in.hasNext()) {
Integer currentIn = in.next();
// build map submission-data
mapSubmissionAndData(submissionId, currentIn);
}
// build the list of children applied protocols chado identifiers
// as input for the next iteration
Iterator<Integer> nap = nextProtocols.iterator();
while (nap.hasNext()) {
// and fill the map with the chado experiment_id and the DAG level
Integer currentAPId = nap.next();
appliedProtocolMap.get(currentAPId).submissionId = submissionId;
appliedProtocolMap.get(currentAPId).step = step + 1;
nextIterationProtocols.add(currentAPId);
// and set the reference from applied protocol to the submission
Reference reference = new Reference();
reference.setName("submission");
reference.setRefId(submissionMap.get(submissionId).itemIdentifier);
getChadoDBConverter().store(reference, appliedProtocolIdMap.get(currentAPId));
}
}
}
return nextIterationProtocols;
}
private void processSubmissionOrganism(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getSubmissionOrganism(connection);
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
if (deletedSubMap.containsKey(submissionId)) {
continue;
}
String value = res.getString("value");
submissionOrganismMap.put(submissionId, value);
LOG.debug("TAXID " + submissionId + "|" + value);
}
res.close();
LOG.info("found an organism for " + submissionOrganismMap.size() + " submissions.");
LOG.info("PROCESS TIME organisms: " + (System.currentTimeMillis() - bT) + " ms");
}
/**
* Return the row needed for the organism.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getSubmissionOrganism(Connection connection)
throws SQLException {
String query =
"select distinct eap.experiment_id, a.value "
+ " from experiment_applied_protocol eap, applied_protocol ap, "
+ " protocol_attribute pa, attribute a "
+ " where eap.first_applied_protocol_id = ap.applied_protocol_id "
+ " and ap.protocol_id=pa.protocol_id "
+ " and pa.attribute_id=a.attribute_id "
+ " and a.heading='species' ";
return doQuery(connection, query, "getSubmissionOrganism");
}
private void processProjectTable(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getProjects(connection);
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
String value = res.getString("value");
if (deletedSubMap.containsKey(submissionId)) {
continue;
}
submissionProjectMap.put(submissionId, value);
}
res.close();
Set<Integer> exp = submissionProjectMap.keySet();
Iterator<Integer> i = exp.iterator();
while (i.hasNext()) {
Integer thisExp = i.next();
String project = submissionProjectMap.get(thisExp);
if (projectIdMap.containsKey(project)) {
continue;
}
LOG.debug("PROJECT: " + project);
Item pro = getChadoDBConverter().createItem("Project");
pro.setAttribute("surnamePI", project);
Integer intermineObjectId = getChadoDBConverter().store(pro);
storeInProjectMaps(pro, project, intermineObjectId);
}
LOG.info("created " + projectIdMap.size() + " project");
LOG.info("PROCESS TIME projects: " + (System.currentTimeMillis() - bT) + " ms");
}
/**
* Return the project name.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getProjects(Connection connection)
throws SQLException {
String query =
"SELECT distinct a.experiment_id, a.value "
+ " FROM experiment_prop a "
+ " where a.name = 'Project' "
+ " AND rank=0";
return doQuery(connection, query, "getProjects");
}
private void processLabTable(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getLabs(connection);
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
String value = res.getString("value");
if (deletedSubMap.containsKey(submissionId)) {
continue;
}
submissionLabMap.put(submissionId, value);
}
res.close();
Set<Integer> exp = submissionLabMap.keySet();
Iterator<Integer> i = exp.iterator();
while (i.hasNext()) {
Integer thisExp = i.next();
String prov = submissionLabMap.get(thisExp);
String project = submissionProjectMap.get(thisExp);
if (labIdMap.containsKey(prov)) {
continue;
}
LOG.debug("PROV: " + prov);
Item lab = getChadoDBConverter().createItem("Lab");
lab.setAttribute("surname", prov);
lab.setReference("project", projectIdRefMap.get(project));
Integer intermineObjectId = getChadoDBConverter().store(lab);
storeInLabMaps(lab, prov, intermineObjectId);
}
LOG.info("created " + labIdMap.size() + " labs");
LOG.info("PROCESS TIME labs: " + (System.currentTimeMillis() - bT) + " ms");
}
/**
* Return the lab name.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getLabs(Connection connection)
throws SQLException {
String query =
"SELECT distinct a.experiment_id, a.name, a.value "
+ " FROM experiment_prop a "
+ " where a.name = 'Lab' "
+ " AND a.rank=0";
return doQuery(connection, query, "getLabs");
}
private void processExperiment(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getExperimentTitles(connection);
Map<String, String> expProMap = new HashMap<String, String>();
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
if (deletedSubMap.containsKey(submissionId)) {
continue;
}
String name = cleanWikiLinks(res.getString("name"));
Util.addToListMap(expSubMap, name, submissionId);
expProMap.put(name, submissionProjectMap.get(submissionId));
}
res.close();
Set<String> experiment = expSubMap.keySet();
Iterator<String> i = experiment.iterator();
while (i.hasNext()) {
String name = i.next();
Item exp = getChadoDBConverter().createItem("Experiment");
exp.setAttribute("name", name);
// find experiment category from map (take first available)
// use the commented lines to get a report of assignments
String category = null;
for (Integer ii : expSubMap.get(name)) {
// String dccId = dccIdMap.get(ii);
category = submissionExpCatMap.get(ii);
if (category != null && !category.isEmpty()) {
// LOG.info("ECS " + name + "|" + dccId + ": " + category);
exp.setAttribute("category", category);
break;
} //else {
//LOG.warn("ECS " + name + "|" + dccId + ": no category");
}
String project = expProMap.get(name);
exp.setReference("project", projectIdRefMap.get(project));
// note: the reference to submission collection is in a separate method
Integer intermineObjectId = getChadoDBConverter().store(exp);
experimentIdMap .put(name, intermineObjectId);
experimentIdRefMap .put(name, exp.getIdentifier());
}
LOG.info("created " + expSubMap.size() + " experiments");
LOG.info("PROCESS TIME experiments: " + (System.currentTimeMillis() - bT) + " ms");
}
/**
* method to clean a wiki reference (url to a named page) in chado
* used also for experiment names
* @param w the wiki reference
*/
private String cleanWikiLinks(String w) {
String url = "http://wiki.modencode.org/project/index.php?title=";
// we are stripping from first ':', maybe we want to include project suffix
// now: Gene Model Prediction
// maybe? Gene Model Prediction:SC:1
String w1 = StringUtils.replace(w, url, "");
String s1 = null;
if (w1.contains(":")) {
s1 = StringUtils.substringBefore(w1, ":");
} else {
// for links missing the : char, e.g.
// MacAlpine Early Origin of Replication Identification&oldid=10464
s1 = StringUtils.substringBefore(w1, "&");
}
String s = s1.replace('"', ' ').trim();
if (s.contains("%E2%80%99")) {
// prime: for the Piano experiment
String s2 = s.replace("%E2%80%99", "'");
return s2;
}
if (s.contains("%28A%29%2B")) {
// this is (A)+, in
// Stranded Cell Line Transcriptional Profiling Using Illumina poly%28A%29%2B RNA-seq
String s2 = s.replace("%28A%29%2B", "(A)+");
return s2;
}
if (s.contains("%2B")) {
// +: for Celniker experiment "Tissue-specific Transcriptional Profiling..."
String s2 = s.replace("%2B", "+");
return s2;
}
return s;
}
/**
* Return the rows needed for experiment from the experiment_prop table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getExperimentTitles(Connection connection)
throws SQLException {
// TODO use standard SQl and deal with string in java
String query =
"select e.experiment_id, "
+ " translate(x.accession, '_', ' ') as name "
+ " from experiment_prop e, dbxref x "
+ " where e.dbxref_id = x.dbxref_id "
+ " and e.name='Experiment Description' ";
return doQuery(connection, query, "getExperimentTitles");
}
private void processSubmission(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getSubmissions(connection);
int count = 0;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
if (deletedSubMap.containsKey(submissionId)) {
continue;
}
String name = res.getString("uniquename");
Item submission = getChadoDBConverter().createItem("Submission");
submission.setAttribute("title", name);
String project = submissionProjectMap.get(submissionId);
String projectItemIdentifier = projectIdRefMap.get(project);
submission.setReference("project", projectItemIdentifier);
String labName = submissionLabMap.get(submissionId);
String labItemIdentifier = labIdRefMap.get(labName);
submission.setReference("lab", labItemIdentifier);
String organismName = submissionOrganismMap.get(submissionId);
int divPos = organismName.indexOf(' ');
String genus = organismName.substring(0, divPos);
String species = organismName.substring(divPos + 1);
OrganismRepository or = OrganismRepository.getOrganismRepository();
Integer taxId = Integer.valueOf(
or.getOrganismDataByGenusSpecies(genus, species).getTaxonId());
LOG.debug("SPECIES: " + organismName + "|" + taxId);
String organismItemIdentifier = getChadoDBConverter().getOrganismItem(
or.getOrganismDataByGenusSpecies(genus, species).getTaxonId()).getIdentifier();
submission.setReference("organism", organismItemIdentifier);
// ..store all
Integer intermineObjectId = getChadoDBConverter().store(submission);
// ..and fill the SubmissionDetails object
SubmissionDetails details = new SubmissionDetails();
details.interMineObjectId = intermineObjectId;
details.itemIdentifier = submission.getIdentifier();
details.labItemIdentifier = labItemIdentifier;
details.title = name;
submissionMap.put(submissionId, details);
debugMap .put(details.itemIdentifier, submission.getClassName());
count++;
}
LOG.info("created " + count + " submissions");
res.close();
LOG.info("PROCESS TIME submissions: " + (System.currentTimeMillis() - bT) + " ms");
}
/**
* Return the rows needed for the submission table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getSubmissions(Connection connection)
throws SQLException {
String query =
"SELECT experiment_id, uniquename "
+ "FROM experiment";
return doQuery(connection, query, "getSubmissions");
}
/**
* submission attributes (table experiment_prop)
*
* @param connection
* @throws SQLException
* @throws ObjectStoreException
*/
private void processSubmissionAttributes(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getExperimentProperties(connection);
int count = 0;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
if (deletedSubMap.containsKey(submissionId)) {
continue;
}
String heading = res.getString("name");
String value = res.getString("value");
// TODO this is a temporary hack to make sure we get properly matched Experiment.factors
// EF are dealt with separately
if (heading.startsWith("Experimental Factor")) {
continue;
}
String fieldName = FIELD_NAME_MAP.get(heading);
if (fieldName == null) {
LOG.error("NOT FOUND in FIELD_NAME_MAP: " + heading + " [experiment]");
continue;
} else if (fieldName == NOT_TO_BE_LOADED) {
continue;
}
if ("DCCid".equals(fieldName)) {
value = DCC_PREFIX + value;
LOG.debug("DCC: " + submissionId + ", " + value);
dccIdMap.put(submissionId, value);
}
if ("category".equals(fieldName)) {
// Data Type, stored in experiment
submissionExpCatMap.put(submissionId, value);
continue;
}
if (fieldName.endsWith("Read Count")) {
// all read counts are considered a collection for submission
Item readCount = getChadoDBConverter().createItem("ReadCount");
readCount.setAttribute("name", fieldName);
readCount.setAttribute("value", value);
// setting references to SubmissionData
readCount.setReference("submission",
submissionMap.get(submissionId).itemIdentifier);
Integer intermineObjectId = getChadoDBConverter().store(readCount);
continue;
}
if ("experimentType".equals(fieldName)) {
// Assay Type
submissionWithExpTypeSet.add(submissionId);
}
if ("pubMedId".equals(fieldName)) {
// sometime in the form PMID:16938558
if (value.contains(":")) {
value = value.substring(value.indexOf(':') + 1);
}
Item pub = getChadoDBConverter().createItem("Publication");
pub.setAttribute(fieldName, value);
Integer intermineObjectId = getChadoDBConverter().store(pub);
publicationIdMap.put(submissionId, intermineObjectId);
publicationIdRefMap.put(submissionId, pub.getIdentifier());
continue;
}
setAttribute(submissionMap.get(submissionId).interMineObjectId, fieldName, value);
count++;
}
LOG.info("created " + count + " submissions attributes");
res.close();
LOG.info("PROCESS TIME submissions attributes: "
+ (System.currentTimeMillis() - bT) + " ms");
}
/**
* Return the rows needed for submission from the experiment_prop table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getExperimentProperties(Connection connection)
throws SQLException {
String query =
"SELECT ep.experiment_id, ep.name, ep.value, ep.rank "
+ "from experiment_prop ep ";
return doQuery(connection, query, "getExperimentProperties");
}
private void processEFactor(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getEFactors(connection);
int count = 0;
int prevRank = -1;
int prevSub = -1;
ExperimentalFactor ef = null;
String name = null;
while (res.next()) {
Integer submissionId = new Integer(res.getInt("experiment_id"));
if (deletedSubMap.containsKey(submissionId)) {
continue;
}
Integer rank = new Integer(res.getInt("rank"));
String value = res.getString("value");
// the data is alternating between EF types and names, in order.
if (submissionId != prevSub) {
// except for the first record, this is a new EF object
if (!res.isFirst()) {
submissionEFMap.put(prevSub, ef);
LOG.debug("EF MAP: " + dccIdMap.get(submissionId) + "|" + ef.efNames);
}
ef = new ExperimentalFactor();
}
if (rank != prevRank || submissionId != prevSub) {
// this is a name
if (getPreferredSynonym(value) != null) {
value = getPreferredSynonym(value);
}
ef.efNames.add(value);
name = value;
count++;
} else {
// this is a type
ef.efTypes.put(name, value);
name = null;
if (res.isLast()) {
submissionEFMap.put(submissionId, ef);
LOG.debug("EF MAP last: " + submissionId + "|" + rank + "|" + ef.efNames);
}
}
prevRank = rank;
prevSub = submissionId;
}
res.close();
LOG.info("created " + count + " experimental factors");
LOG.info("PROCESS TIME experimental factors: " + (System.currentTimeMillis() - bT) + " ms");
LOG.info("EF Map 4141:" + submissionEFMap.get(363).efTypes + " experimental factors");
}
/**
* Return the rows needed for the experimental factors.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getEFactors(Connection connection)
throws SQLException {
String query =
"SELECT ep.experiment_id, ep.name, ep.value, ep.rank "
+ " FROM experiment_prop ep "
+ " where ep.name = 'Experimental Factor Name' "
+ " OR ep.name = 'Experimental Factor Type' "
+ " ORDER BY 1,4,2";
return doQuery(connection, query, "getEFactors");
}
private void processProtocolTable(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getProtocols(connection);
int count = 0;
while (res.next()) {
Integer protocolChadoId = new Integer(res.getInt("protocol_id"));
String name = res.getString("name");
String description = res.getString("description");
String wikiLink = res.getString("accession");
Integer version = res.getInt("version");
// needed: it breaks otherwise
if (description.length() == 0) {
description = "N/A";
}
Protocol thisProt = new Protocol();
thisProt.protocolId = protocolChadoId;
thisProt.name = name;
thisProt.description = description;
thisProt.wikiLink = wikiLink;
thisProt.version = version;
protocolMap.put(protocolChadoId, thisProt);
// we'll do it when creating AP
//createProtocol(protocolChadoId, name, description, wikiLink, version);
count++;
}
res.close();
LOG.info("found " + count + " protocols");
LOG.info("PROCESS TIME protocols: " + (System.currentTimeMillis() - bT) + " ms");
}
// now doing it with applied protocol (to avoid creating it for delete subs)
private String createProtocol(Integer chadoId, String name, String description, String wikiLink,
Integer version) throws ObjectStoreException {
String protocolItemId = protocolsMap.get(wikiLink); // rename?
if (protocolItemId == null) {
Item protocol = getChadoDBConverter().createItem("Protocol");
protocol.setAttribute("name", name);
protocol.setAttribute("description", description);
protocol.setAttribute("wikiLink", wikiLink);
protocol.setAttribute("version", "" + version);
Integer intermineObjectId = getChadoDBConverter().store(protocol);
protocolItemId = protocol.getIdentifier();
protocolItemToObjectId.put(protocolItemId, intermineObjectId);
protocolsMap.put(wikiLink, protocolItemId);
}
protocolItemIds.put(chadoId, protocolItemId);
return protocolItemId;
}
private Integer getProtocolInterMineId(Integer chadoId) {
return protocolItemToObjectId.get(protocolItemIds.get(chadoId));
}
/**
* Return the rows needed from the protocol table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getProtocols(Connection connection) throws SQLException {
String query =
"SELECT protocol_id, name, protocol.description, accession, protocol.version"
+ " FROM protocol, dbxref"
+ " WHERE protocol.dbxref_id = dbxref.dbxref_id";
return doQuery(connection, query, "getProtocols");
}
/**
* to store protocol attributes
*/
private void processProtocolAttributes(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getProtocolAttributes(connection);
int count = 0;
while (res.next()) {
Integer protocolId = new Integer(res.getInt("protocol_id"));
String heading = res.getString("heading");
String value = res.getString("value");
String fieldName = FIELD_NAME_MAP.get(heading);
if (fieldName == null) {
LOG.error("NOT FOUND in FIELD_NAME_MAP: " + heading + " [protocol]");
continue;
} else if (fieldName == NOT_TO_BE_LOADED) {
continue;
}
if (getProtocolInterMineId(protocolId) != null) { // in case of deleted sub
setAttribute(getProtocolInterMineId(protocolId), fieldName, value);
if ("type".equals(fieldName)) {
protocolTypesMap.put(protocolId, value);
}
count++;
}
}
LOG.info("created " + count + " protocol attributes");
res.close();
LOG.info("PROCESS TIME protocol attributes: " + (System.currentTimeMillis() - bT) + " ms");
}
/**
* Return the rows needed for protocols from the attribute table.
* This is a protected method so that it can be overridden for testing
* @param connection database connection
* @return rows needed for protocols from the attribute table
* @throws SQLException if something goes wrong.
*/
protected ResultSet getProtocolAttributes(Connection connection) throws SQLException {
String query =
"SELECT p.protocol_id, a.heading, a.value "
+ "from protocol p, attribute a, protocol_attribute pa "
+ "where pa.attribute_id = a.attribute_id "
+ "and pa.protocol_id = p.protocol_id ";
return doQuery(connection, query, "getProtocolAttributes");
}
private void processAppliedProtocolTable(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getAppliedProtocols(connection);
int count = 0;
boolean isADeletedSub = false;
while (res.next()) {
Integer appliedProtocolId = new Integer(res.getInt("applied_protocol_id"));
Integer protocolId = new Integer(res.getInt("protocol_id"));
Integer submissionId = new Integer(res.getInt("experiment_id"));
// the results are ordered, first ap have a subId
// if we find a deleted sub, we know that subsequent records with null
// subId belongs to the deleted sub
if (submissionId == 0) {
boolean t = true;
if (isADeletedSub == t) {
continue;
}
} else {
if (deletedSubMap.containsKey(submissionId)) {
isADeletedSub = true;
continue;
} else {
isADeletedSub = false;
}
}
Item appliedProtocol = getChadoDBConverter().createItem("AppliedProtocol");
// creating and setting references to protocols
// String protocolItemId = protocolItemIds.get(protocolId);
if (protocolId != null) {
Protocol qq = protocolMap.get(protocolId);
String protocolItemId = createProtocol(qq);
appliedProtocol.setReference("protocol", protocolItemId);
}
if (submissionId > 0) {
// setting reference to submission
// probably to rm (we do it later anyway). TODO: check
appliedProtocol.setReference("submission",
submissionMap.get(submissionId).itemIdentifier);
}
// store it and add to maps
Integer intermineObjectId = getChadoDBConverter().store(appliedProtocol);
appliedProtocolIdMap .put(appliedProtocolId, intermineObjectId);
appliedProtocolIdRefMap .put(appliedProtocolId, appliedProtocol.getIdentifier());
count++;
}
LOG.info("created " + count + " appliedProtocol");
res.close();
LOG.info("PROCESS TIME applied protocols: " + (System.currentTimeMillis() - bT) + " ms");
}
private String createProtocol(Protocol p)
throws ObjectStoreException {
String protocolItemId = protocolsMap.get(p.wikiLink); // rename map?
if (protocolItemId == null) {
Item protocol = getChadoDBConverter().createItem("Protocol");
protocol.setAttribute("name", p.name);
protocol.setAttribute("description", p.description);
protocol.setAttribute("wikiLink", p.wikiLink);
protocol.setAttribute("version", "" + p.version);
Integer intermineObjectId = getChadoDBConverter().store(protocol);
protocolItemId = protocol.getIdentifier();
protocolItemToObjectId.put(protocolItemId, intermineObjectId);
protocolsMap.put(p.wikiLink, protocolItemId);
}
protocolItemIds.put(p.protocolId, protocolItemId);
return protocolItemId;
}
/**
* Return the rows needed from the appliedProtocol table.
* This is a protected method so that it can be overridden for testing
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedProtocols(Connection connection)
throws SQLException {
String query =
"SELECT eap.experiment_id ,ap.applied_protocol_id, ap.protocol_id"
+ " FROM applied_protocol ap"
+ " LEFT JOIN experiment_applied_protocol eap"
+ " ON (eap.first_applied_protocol_id = ap.applied_protocol_id )";
return doQuery(connection, query, "getAppliedProtocols");
}
private void processAppliedData(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getAppliedData(connection);
int count = 0;
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
// check if not belonging to a deleted sub
Integer submissionId = dataSubmissionMap.get(dataId);
if (submissionId == null || deletedSubMap.containsKey(submissionId)) {
continue;
}
String name = res.getString("name");
String heading = res.getString("heading");
String value = res.getString("value");
String typeId = res.getString("type_id");
String url = res.getString("url");
// check if this datum has an official name:
ResultSet oName = getOfficialName(connection, dataId);
String officialName = null;
while (oName.next()) {
officialName = oName.getString(1);
}
// if there is one, use it instead of the value
String datumType = getCvterm(connection, typeId);
name = getCvterm(connection, typeId);
if (!StringUtils.isEmpty(officialName)
&& doReplaceWithOfficialName(heading, datumType)) {
value = officialName;
}
Item submissionData = getChadoDBConverter().createItem("SubmissionData");
if (name != null && !"".equals(name)) {
submissionData.setAttribute("name", name);
}
// if no name for attribute fetch the cvterm of the type
if ((name == null || "".equals(name)) && typeId != null) {
name = getCvterm(connection, typeId);
submissionData.setAttribute("name", name);
}
if (!StringUtils.isEmpty(value)) {
submissionData.setAttribute("value", value);
}
submissionData.setAttribute("type", heading);
// store it and add to object and maps
Integer intermineObjectId = getChadoDBConverter().store(submissionData);
AppliedData aData = new AppliedData();
aData.intermineObjectId = intermineObjectId;
aData.itemIdentifier = submissionData.getIdentifier();
aData.value = value;
aData.actualValue = res.getString("value");
aData.dataId = dataId;
aData.type = heading;
aData.name = name;
aData.url = url;
updateADMap(aData, dataId, intermineObjectId);
//appliedDataMap.put(dataId, aData);
count++;
}
LOG.info("created " + count + " SubmissionData");
res.close();
LOG.info("PROCESS TIME submission data: " + (System.currentTimeMillis() - bT) + " ms");
}
// For some data types we don't want to replace with official name - e.g. file names and
// database record ids. It looks like the official name shouldn't actually be present.
private boolean doReplaceWithOfficialName(String heading, String type) {
if ("Result File".equals(heading)) {
return false;
}
if ("Result Value".equals(heading) && DB_RECORD_TYPES.contains(type)) {
return false;
}
return true;
}
/**
* Return the rows needed for data from the applied_protocol_data table.
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedData(Connection connection)
throws SQLException {
String query =
"SELECT d.data_id,"
+ " d.heading, d.name, d.value, d.type_id, z.url"
+ " FROM data d"
+ " LEFT JOIN dbxref as y ON (d.dbxref_id = y.dbxref_id)"
+ " LEFT JOIN db as z ON (y.db_id = z.db_id)";
return doQuery(connection, query, "getAppliedData");
}
/**
* Return the rows needed for data from the applied_protocol_data table.
*
* @param connection the db connection
* @param dataId the dataId
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getOfficialName(Connection connection, Integer dataId)
throws SQLException {
String query =
"SELECT a.value "
+ " from attribute a, data_attribute da "
+ " where a.attribute_id=da.attribute_id "
+ " and da.data_id=" + dataId
+ " and a.heading='official name'";
return doQuery(connection, query);
}
/**
* Fetch a cvterm by id and cache results in cvtermCache. Returns null if the cv terms isn't
* found.
* @param connection to chado database
* @param cvtermId internal chado id for a cvterm
* @return the cvterm name or null if not found
* @throws SQLException if database access problem
*/
private String getCvterm(Connection connection, String cvtermId) throws SQLException {
String cvTerm = cvtermCache.get(cvtermId);
if (cvTerm == null) {
String query =
"SELECT c.name "
+ " from cvterm c"
+ " where c.cvterm_id=" + cvtermId;
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
while (res.next()) {
cvTerm = res.getString("name");
}
cvtermCache.put(cvtermId, cvTerm);
}
return cvTerm;
}
private void processAppliedDataAttributesNEW(Connection connection)
throws SQLException, ObjectStoreException {
// attempts to collate attributes
// TODO check!
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getAppliedDataAttributes(connection);
int count = 0;
Integer previousDataId = 0;
String previousName = null;
String value = null;
String type = null;
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
// check if not belonging to a deleted sub
// better way?
Integer submissionId = dataSubmissionMap.get(dataId);
if (submissionId == null || deletedSubMap.containsKey(submissionId)) {
continue;
}
String name = res.getString("heading");
// LOG.info("DA " + dataId + ": " + name);
if (previousDataId == 0) { //first pass
value = res.getString("value");
type = res.getString("name");
previousDataId = dataId;
previousName = name;
LOG.info("DA0 " + dataId + ": " + name + "|" + value);
continue;
}
if (dataId > previousDataId) {
Item dataAttribute = storeDataAttribute(value, type, previousDataId, previousName);
value = res.getString("value");
type = res.getString("name");
count++;
previousDataId = dataId;
previousName = name;
LOG.info("DA1 new: " + previousDataId + ": " + previousName + "|" + value);
continue;
}
if (!name.equalsIgnoreCase(previousName)) {
Item dataAttribute = storeDataAttribute(value, type, dataId, previousName);
// LOG.info("DA2 store: " + dataId + ": " + previousName + "|" + value);
count ++;
value = res.getString("value");
previousName = name;
LOG.info("DA2 new: " + dataId + ": " + previousName + "|" + value);
} else {
value = value + ", " + res.getString("value");
}
type = res.getString("name");
previousDataId = dataId;
if (res.isLast()) {
Item dataAttribute = storeDataAttribute(value, type, dataId, name);
count++;
}
}
LOG.info("created " + count + " data attributes");
res.close();
LOG.info("PROCESS TIME data attributes: " + (System.currentTimeMillis() - bT) + " ms");
}
/**
* @param value
* @param type
* @param dataId
* @param name
* @return
* @throws ObjectStoreException
*/
private Item storeDataAttribute(String value, String type, Integer dataId,
String name) throws ObjectStoreException {
Item dataAttribute = getChadoDBConverter().createItem("SubmissionDataAttribute");
if (name != null && !"".equals(name)) {
dataAttribute.setAttribute("name", name);
}
if (!StringUtils.isEmpty(value)) {
dataAttribute.setAttribute("value", value);
}
if (!StringUtils.isEmpty(type)) {
dataAttribute.setAttribute("type", type);
}
// setting references to SubmissionData
dataAttribute.setReference("submissionData", appliedDataMap.get(dataId).itemIdentifier);
getChadoDBConverter().store(dataAttribute);
return dataAttribute;
}
private void processAppliedDataAttributes(Connection connection)
throws SQLException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getAppliedDataAttributes(connection);
int count = 0;
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
// check if not belonging to a deleted sub
// better way?
Integer submissionId = dataSubmissionMap.get(dataId);
if (submissionId == null || deletedSubMap.containsKey(submissionId)) {
continue;
}
String name = res.getString("heading");
String value = res.getString("value");
String type = res.getString("name");
Item dataAttribute = storeDataAttribute(value, type, dataId, name);
count++;
}
LOG.info("created " + count + " data attributes");
res.close();
LOG.info("PROCESS TIME data attributes: " + (System.currentTimeMillis() - bT) + " ms");
}
// first value in the list of synonyms is the 'preferred' value
private static String[][] synonyms = new String[][]{
new String[] {"developmental stage", "stage", "developmental_stage", "dev stage",
"devstage"},
new String[] {"strain", "strain_or_line"},
new String[] {"cell line", "cell_line", "Cell line", "cell id"},
new String[] {"array", "adf"},
new String[] {"compound", "Compound"},
new String[] {"incubation time", "Incubation Time"},
new String[] {"RNAi reagent", "RNAi_reagent", "dsRNA"},
new String[] {"temperature", "temp"}
};
private static List<String> makeLookupList(String initialLookup) {
for (String[] synonymType : synonyms) {
for (String synonym : synonymType) {
if (synonym.equals(initialLookup)) {
return Arrays.asList(synonymType);
}
}
}
return new ArrayList<String>(Collections.singleton(initialLookup));
}
private static String getPreferredSynonym(String initialLookup) {
return makeLookupList(initialLookup).get(0);
}
private static Set<String> unifyFactorNames(Collection<String> original) {
Set<String> unified = new HashSet<String>();
for (String name : original) {
unified.add(getPreferredSynonym(name));
}
return unified;
}
private class SubmissionReference
{
public SubmissionReference(Integer referencedSubmissionId, String dataValue) {
this.referencedSubmissionId = referencedSubmissionId;
this.dataValue = dataValue;
}
private Integer referencedSubmissionId;
private String dataValue;
}
// process new query
// get DCC id
// add antibody to types
private void processSubmissionProperties(Connection connection) throws SQLException,
IOException, ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
ResultSet res = getAppliedDataAll(connection);
final String comma = ",";
String reportName = "build/"
+ getChadoDBConverter().getDatabase().getName() + "_subs_report.csv";
File f = new File(reportName);
FileWriter writer = new FileWriter(f);
writeHeader(comma, writer);
SubmissionProperty buildSubProperty = null;
Integer lastDataId = new Integer(-1);
Map<String, SubmissionProperty> props = new HashMap<String, SubmissionProperty>();
Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes =
new HashMap<Integer, Map<String, List<SubmissionProperty>>>();
submissionRefs = new HashMap<Integer, List<SubmissionReference>>();
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
String dataHeading = res.getString("data_heading");
String dataName = res.getString("data_name");
String wikiPageUrl = res.getString("data_value");
String cvTerm = res.getString("cv_term");
String attHeading = res.getString("att_heading");
String attName = res.getString("att_name");
String attValue = res.getString("att_value");
String attDbxref = res.getString("att_dbxref");
int attRank = res.getInt("att_rank");
Integer submissionId = dataSubmissionMap.get(dataId);
String dccId = dccIdMap.get(submissionId);
writer.write(dccId + comma + dataHeading + comma + dataName + comma
+ wikiPageUrl + comma + cvTerm + comma + attHeading + comma + attName
+ comma + attValue + comma + attDbxref + System.getProperty("line.separator"));
if (submissionId == null) {
LOG.warn("Failed to find a submission id for data id " + dataId + " - this probably"
+ " means there is a problem with the applied_protocol DAG strucuture.");
continue;
}
// Currently using attValue for referenced submission DCC id, should be dbUrl but seems
// to be filled in incorrectly
if (attHeading != null && attHeading.startsWith("modENCODE Reference")) {
attValue = checkRefSub(wikiPageUrl, attValue, submissionId, dccId);
}
// we are starting a new data row
if (dataId.intValue() != lastDataId.intValue()) {
// have we seen this modencodewiki entry before?
if (props.containsKey(wikiPageUrl)) {
buildSubProperty = null;
} else {
buildSubProperty =
new SubmissionProperty(getPreferredSynonym(dataName), wikiPageUrl);
props.put(wikiPageUrl, buildSubProperty);
}
// submissionId -> [type -> SubmissionProperty]
addToSubToTypes(subToTypes, submissionId, props.get(wikiPageUrl));
}
if (buildSubProperty != null) {
// we are building a new submission attribute, this is the first time we have
// seen a data.value that points to modencodewiki
buildSubProperty.addDetail(attHeading, attValue, attRank);
}
lastDataId = dataId;
}
writer.flush();
writer.close();
// Characteristics are modelled differently to protocol inputs/outputs, read in extra
// properties here
addSubmissionPropsFromCharacteristics(subToTypes, connection);
// some submissions use reagents created in reference submissions, find the properties
// of the reagents and add to referencing submission
addSubmissionPropsFromReferencedSubmissions(subToTypes, props, submissionRefs);
// create and store properties of submission
storeSubProperties(subToTypes);
LOG.info("PROCESS TIME submission properties: "
+ (System.currentTimeMillis() - bT) + " ms");
}
/**
* @param subToTypes
* @throws ObjectStoreException
*/
private void storeSubProperties(
Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes)
throws ObjectStoreException {
for (Integer submissionId : subToTypes.keySet()) {
Integer storedSubmissionId = submissionMap.get(submissionId).interMineObjectId;
if (deletedSubMap.containsKey(submissionId)) {
continue;
}
Map<String, List<SubmissionProperty>> typeToProp = subToTypes.get(submissionId);
String dccId = dccIdMap.get(submissionId);
ExperimentalFactor ef = submissionEFMap.get(submissionId);
if (ef == null) {
LOG.warn("No experimental factors found for submission: " + dccId);
continue;
}
Set<String> exFactorNames = unifyFactorNames(ef.efNames);
LOG.info("PROPERTIES " + dccId + " typeToProp keys: " + typeToProp.keySet());
List<Item> allPropertyItems = new ArrayList<Item>();
// DEVELOPMENTAL STAGE
List<Item> devStageItems = new ArrayList<Item>();
devStageItems.addAll(createFromWikiPage(dccId, "DevelopmentalStage", typeToProp,
makeLookupList("developmental stage")));
if (devStageItems.isEmpty()) {
devStageItems.addAll(lookForAttributesInOtherWikiPages(dccId, "DevelopmentalStage",
typeToProp, new String[] {
"developmental stage.developmental stage",
"tissue.developmental stage",
"tissue source.developmental stage",
"cell line.developmental stage",
"cell id.developmental stage"
//, "RNA extract.Cell Type"
}));
}
if (devStageItems.isEmpty()) {
addNotApplicable(devStageItems, "DevelopmentalStage", "developmental stage");
}
storeSubmissionCollection(storedSubmissionId, "developmentalStages", devStageItems);
if (!devStageItems.isEmpty() && exFactorNames.contains("developmental stage")) {
createExperimentalFactors(submissionId, "developmental stage", devStageItems);
exFactorNames.remove("developmental stage");
}
allPropertyItems.addAll(devStageItems);
// STRAIN
List<Item> strainItems = new ArrayList<Item>();
strainItems.addAll(createFromWikiPage(
dccId, "Strain", typeToProp, makeLookupList("strain")));
if (strainItems.isEmpty()) {
addNotApplicable(strainItems, "Strain", "strain");
}
storeSubmissionCollection(storedSubmissionId, "strains", strainItems);
// if (!strainItems.isEmpty() && exFactorNames.contains("strain")) {
if (exFactorNames.contains("strain")) {
createExperimentalFactors(submissionId, "strain", strainItems);
exFactorNames.remove("strain");
}
allPropertyItems.addAll(strainItems);
// ARRAY
List<Item> arrayItems = new ArrayList<Item>();
arrayItems.addAll(createFromWikiPage(
dccId, "Array", typeToProp, makeLookupList("array")));
LOG.debug("ARRAY: " + typeToProp.get("array"));
if (arrayItems.isEmpty()) {
arrayItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Array",
typeToProp, new String[] {"adf.official name"}));
if (!arrayItems.isEmpty()) {
LOG.debug("Attribute found in other wiki pages: " + dccId + " ARRAY ");
}
}
if (arrayItems.isEmpty()) {
addNotApplicable(arrayItems, "Array", "array");
}
storeSubmissionCollection(storedSubmissionId, "arrays", arrayItems);
// if (!arrayItems.isEmpty() && exFactorNames.contains("array")) {
if (exFactorNames.contains("array")) {
createExperimentalFactors(submissionId, "array", arrayItems);
exFactorNames.remove("array");
}
allPropertyItems.addAll(arrayItems);
// CELL LINE
List<Item> lineItems = new ArrayList<Item>();
lineItems.addAll(createFromWikiPage(dccId, "CellLine", typeToProp,
makeLookupList("cell line")));
if (lineItems.isEmpty()) {
addNotApplicable(lineItems, "CellLine", "cell line");
}
storeSubmissionCollection(storedSubmissionId, "cellLines", lineItems);
// if (!lineItems.isEmpty() && exFactorNames.contains("cell line")) {
if (exFactorNames.contains("cell line")) {
createExperimentalFactors(submissionId, "cell line", lineItems);
exFactorNames.remove("cell line");
}
allPropertyItems.addAll(lineItems);
// RNAi REAGENT
List<Item> reagentItems = new ArrayList<Item>();
reagentItems.addAll(createFromWikiPage(dccId, "SubmissionProperty", typeToProp,
makeLookupList("dsRNA")));
if (!reagentItems.isEmpty() && exFactorNames.contains("RNAi reagent")) {
createExperimentalFactors(submissionId, "RNAi reagent", reagentItems);
exFactorNames.remove("RNAi reagent");
}
allPropertyItems.addAll(reagentItems);
// ANTIBODY
List<Item> antibodyItems = new ArrayList<Item>();
antibodyItems.addAll(createFromWikiPage(dccId, "Antibody", typeToProp,
makeLookupList("antibody")));
if (antibodyItems.isEmpty()) {
LOG.debug("ANTIBODY: " + typeToProp.get("antibody"));
antibodyItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Antibody",
typeToProp, new String[] {"antibody.official name"}));
if (!antibodyItems.isEmpty()) {
LOG.debug("Attribute found in other wiki pages: " + dccId + " ANTIBODY ");
}
}
if (antibodyItems.isEmpty()) {
addNotApplicable(antibodyItems, "Antibody", "antibody");
}
storeSubmissionCollection(storedSubmissionId, "antibodies", antibodyItems);
// if (!antibodyItems.isEmpty() && exFactorNames.contains("antibody")) {
if (exFactorNames.contains("antibody")) {
createExperimentalFactors(submissionId, "antibody", antibodyItems);
exFactorNames.remove("antibody");
}
allPropertyItems.addAll(antibodyItems);
// TISSUE
List<Item> tissueItems = new ArrayList<Item>();
tissueItems.addAll(createFromWikiPage(
dccId, "Tissue", typeToProp, makeLookupList("tissue")));
if (tissueItems.isEmpty()) {
tissueItems.addAll(lookForAttributesInOtherWikiPages(dccId, "Tissue",
typeToProp, new String[] {"stage.tissue"
, "cell line.tissue"
, "cell id.tissue"}));
if (!tissueItems.isEmpty()) {
LOG.info("Attribute found in other wiki pages: " + dccId + " TISSUE");
}
}
if (tissueItems.isEmpty()) {
addNotApplicable(tissueItems, "Tissue", "tissue");
}
storeSubmissionCollection(storedSubmissionId, "tissues", tissueItems);
// if (!tissueItems.isEmpty() && exFactorNames.contains("tissue")) {
if (exFactorNames.contains("tissue")) {
createExperimentalFactors(submissionId, "tissue", tissueItems);
exFactorNames.remove("tissue");
}
allPropertyItems.addAll(tissueItems);
// There may be some other experimental factors that require SubmissionProperty objects
// but don't fall into the categories above. Create them here and set experimental
// factors.
ArrayList<String> extraPropNames = new ArrayList<String>(exFactorNames);
for (String exFactor : extraPropNames) {
List<Item> extraPropItems = new ArrayList<Item>();
LOG.info("PP??: " + exFactor);
extraPropItems.addAll(lookForAttributesInOtherWikiPages(dccId, "SubmissionProperty",
typeToProp, new String[] {exFactor}));
allPropertyItems.addAll(extraPropItems);
createExperimentalFactors(submissionId, exFactor, extraPropItems);
exFactorNames.remove(exFactor);
}
// deal with remaining factor names (e.g. the ones for which we did
// not find a corresponding attribute
for (String exFactor : exFactorNames) {
String type = ef.efTypes.get(exFactor);
createEFItem(submissionId, type, exFactor, null);
}
storeSubmissionCollection(storedSubmissionId, "properties", allPropertyItems);
}
}
/**
* @param wikiPageUrl
* @param attValue
* @param submissionId
* @param dccId
* @return
*/
private String checkRefSub(String wikiPageUrl, String attValue,
Integer submissionId, String dccId) {
if (attValue.indexOf(":") > 0) {
attValue = attValue.substring(0, attValue.indexOf(":"));
}
attValue = DCC_PREFIX + attValue;
Integer referencedSubId = getSubmissionIdFromDccId(attValue);
if (referencedSubId != null) {
SubmissionReference subRef =
new SubmissionReference(referencedSubId, wikiPageUrl);
Util.addToListMap(submissionRefs, submissionId, subRef);
LOG.info("Submission " + dccId + " (" + submissionId + ") has reference to "
+ attValue + " (" + referencedSubId + ")");
} else {
LOG.warn("Could not find submission " + attValue + " referenced by " + dccId);
}
return attValue;
}
/**
* @param comma
* @param writer
* @throws IOException
*/
private void writeHeader(final String comma, FileWriter writer)
throws IOException {
writer.write("submission" + comma);
writer.write("data_heading" + comma);
writer.write("data_name" + comma);
writer.write("data_value" + comma);
writer.write("cv_term" + comma);
writer.write("att_heading" + comma);
writer.write("att_name" + comma);
writer.write("att_value" + comma);
writer.write(System.getProperty("line.separator"));
}
// /**
// * @param submissionId
// * @param exFactorNames
// * @param devStageItems
// * @param clsName
// * @param propName
// * @throws ObjectStoreException
// */
// private void finishProp(Integer submissionId, Integer storedSubmissionId,
// Set<String> exFactorNames,
// List<Item> devStageItems, String clsName, String propName)
// throws ObjectStoreException {
// if (devStageItems.isEmpty()) {
// addNotApplicable(devStageItems, clsName, propName);
// storeSubmissionCollection(storedSubmissionId, "developmentalStages", devStageItems);
// } else {
// if (exFactorNames.contains(propName)) {
// createExperimentalFactors(submissionId, propName, devStageItems);
// exFactorNames.remove(propName);
/**
* @param devStageItems
* @param qq
* @throws ObjectStoreException
*/
// private void addNotApplicable(List<Item> items, String propName) {
// Item subProperty = getChadoDBConverter().createItem("SubmissionProperty");
// subProperty.setAttribute("type", propName);
// subProperty.setAttribute("name", NA_PROP);
// items.add(subProperty);
private void addNotApplicable(List<Item> items, String clsName, String propName)
throws ObjectStoreException {
Item subProperty = getChadoDBConverter().createItem(clsName);
subProperty.setAttribute("type", propName);
subProperty.setAttribute("name", NA_PROP);
items.add(subProperty);
getChadoDBConverter().store(subProperty);
}
// Traverse DAG following previous applied protocol links to build a list of all AppliedData
private void findAppliedProtocolsAndDataFromEarlierInDag(Integer startDataId,
List<AppliedData> foundAppliedData, List<AppliedProtocol> foundAppliedProtocols) {
AppliedData aData = appliedDataMap.get(startDataId);
if (foundAppliedData != null) {
foundAppliedData.add(aData);
}
for (Integer previousAppliedProtocolId : aData.previousAppliedProtocols) {
AppliedProtocol ap = appliedProtocolMap.get(previousAppliedProtocolId);
if (foundAppliedProtocols != null) {
foundAppliedProtocols.add(ap);
}
for (Integer previousDataId : ap.inputs) {
findAppliedProtocolsAndDataFromEarlierInDag(previousDataId, foundAppliedData,
foundAppliedProtocols);
}
}
}
private void createExperimentalFactors(Integer submissionId, String type,
Collection<Item> items) throws ObjectStoreException {
for (Item item : items) {
createEFItem(submissionId, type, item.getAttribute("name").getValue(),
item.getIdentifier());
}
}
private void createEFItem(Integer current, String type,
String efName, String propertyIdentifier) throws ObjectStoreException {
// don't create an EF if it is a primer
if (type.endsWith("primer")) {
LOG.debug("NOT EF PRIMER for sub " + current + ":" + efName + "|" + type);
return;
}
// create the EF, if not there already
if (!eFactorIdMap.containsKey(efName)) {
Item ef = getChadoDBConverter().createItem("ExperimentalFactor");
String preferredType = getPreferredSynonym(type);
ef.setAttribute ("type", preferredType);
ef.setAttribute ("name", efName);
if (propertyIdentifier != null) {
ef.setReference("property", propertyIdentifier);
}
LOG.info("ExFactor created for sub " + current + ":" + efName + "|" + type);
Integer intermineObjectId = getChadoDBConverter().store(ef);
eFactorIdMap.put(efName, intermineObjectId);
eFactorIdRefMap.put(efName, ef.getIdentifier());
}
// if pertinent to the current sub, add to the map for the references
LOG.info("PRIMER?? " + current + ":" + efName + "|" + type);
Util.addToListMap(submissionEFactorMap, current, efName);
}
private void addToSubToTypes(Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes,
Integer submissionId, SubmissionProperty prop) {
// submissionId -> [type -> SubmissionProperty]
if (submissionId == null) {
throw new RuntimeException("Called addToSubToTypes with a null sub id!");
}
Map<String, List<SubmissionProperty>> typeToSubProp = subToTypes.get(submissionId);
if (typeToSubProp == null) {
typeToSubProp = new HashMap<String, List<SubmissionProperty>>();
subToTypes.put(submissionId, typeToSubProp);
}
List<SubmissionProperty> subProps = typeToSubProp.get(prop.type);
if (subProps == null) {
subProps = new ArrayList<SubmissionProperty>();
typeToSubProp.put(prop.type, subProps);
}
subProps.add(prop);
}
private void addSubmissionPropsFromCharacteristics(
Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes,
Connection connection)
throws SQLException {
ResultSet res = getAppliedDataCharacteristics(connection);
Integer lastAttDbXref = new Integer(-1);
Integer lastDataId = new Integer(-1);
Map<Integer, SubmissionProperty> createdProps = new HashMap<Integer, SubmissionProperty>();
SubmissionProperty buildSubProperty = null;
boolean isValidCharacteristic = false;
Integer currentSubId = null; // we need those to attach the property to the correct sub
Integer previousSubId = null;
while (res.next()) {
Integer dataId = new Integer(res.getInt("data_id"));
String attHeading = res.getString("att_heading");
String attName = res.getString("att_name");
String attValue = res.getString("att_value");
Integer attDbxref = new Integer(res.getInt("att_dbxref"));
int attRank = res.getInt("att_rank");
currentSubId = dataSubmissionMap.get(dataId);
if (dataId.intValue() != lastDataId.intValue()
|| attDbxref.intValue() != lastAttDbXref.intValue()
|| currentSubId != previousSubId) {
// store the last build property if created, type is set only if we found an
// attHeading of Characteristics
// note: dbxref can remain the same in different subs -> or
if (buildSubProperty != null && buildSubProperty.type != null) {
createdProps.put(lastAttDbXref, buildSubProperty);
addToSubToTypes(subToTypes, previousSubId, buildSubProperty);
}
// set up for next attDbxref
if (createdProps.containsKey(attDbxref) && isValidCharacteristic) {
// seen this property before so just add for this submission, don't build again
buildSubProperty = null;
isValidCharacteristic = false;
addToSubToTypes(subToTypes, currentSubId, createdProps.get(attDbxref));
} else {
buildSubProperty = new SubmissionProperty();
isValidCharacteristic = false;
}
}
if (attHeading.startsWith("Characteristic")) {
isValidCharacteristic = true;
}
if (buildSubProperty != null) {
if (attHeading.startsWith("Characteristic")) {
buildSubProperty.type = getPreferredSynonym(attName);
buildSubProperty.wikiPageUrl = attValue;
// add detail here as some Characteristics don't reference a wiki page
// but have all information on single row
buildSubProperty.addDetail(attName, attValue, attRank);
} else {
buildSubProperty.addDetail(attHeading, attValue, attRank);
}
}
previousSubId = currentSubId;
lastAttDbXref = attDbxref;
lastDataId = dataId;
}
if (buildSubProperty != null && buildSubProperty.type != null) {
createdProps.put(lastAttDbXref, buildSubProperty);
addToSubToTypes(subToTypes, currentSubId, buildSubProperty);
}
}
// Some submission mention e.g. an RNA Sample but the details of how that sample was created,
// stage, strain, etc are in a previous submission. There are references to previous submission
// DCC ids where a sample with the corresponding name can be found. We then need to traverse
// backwards along the AppliedProtocol DAG to find the stage, strain, etc wiki pages. These
// should already have been processed so the properties can just be added to the referencing
// submission.
private void addSubmissionPropsFromReferencedSubmissions(
Map<Integer, Map<String, List<SubmissionProperty>>> subToTypes,
Map<String, SubmissionProperty> props,
Map<Integer, List<SubmissionReference>> submissionRefs) {
for (Map.Entry<Integer, List<SubmissionReference>> entry : submissionRefs.entrySet()) {
Integer submissionId = entry.getKey();
List<SubmissionReference> lref = entry.getValue();
Iterator<SubmissionReference> i = lref.iterator();
while (i.hasNext()) {
SubmissionReference ref = i.next();
List<AppliedData> refAppliedData = findAppliedDataFromReferencedSubmission(ref);
for (AppliedData aData : refAppliedData) {
String possibleWikiUrl = aData.actualValue;
if (possibleWikiUrl != null && props.containsKey(possibleWikiUrl)) {
//LOG.debug("EEFF possible wikiurl: " + possibleWikiUrl);
SubmissionProperty propFromReferencedSub = props.get(possibleWikiUrl);
if (propFromReferencedSub != null) {
addToSubToTypes(subToTypes, submissionId, propFromReferencedSub);
LOG.debug("EEFF from referenced sub: " + propFromReferencedSub.type
+ ": " + propFromReferencedSub.details);
}
}
}
}
}
}
private List<AppliedData> findAppliedDataFromReferencedSubmission(SubmissionReference subRef) {
List<AppliedData> foundAppliedData = new ArrayList<AppliedData>();
findAppliedProtocolsAndDataFromReferencedSubmission(subRef, foundAppliedData, null);
return foundAppliedData;
}
private List<AppliedProtocol> findAppliedProtocolsFromReferencedSubmission(
SubmissionReference subRef) {
List<AppliedProtocol> foundAppliedProtocols = new ArrayList<AppliedProtocol>();
findAppliedProtocolsAndDataFromReferencedSubmission(subRef, null, foundAppliedProtocols);
return foundAppliedProtocols;
}
private void findAppliedProtocolsAndDataFromReferencedSubmission(
SubmissionReference subRef,
List<AppliedData> foundAppliedData,
List<AppliedProtocol> foundAppliedProtocols) {
String refDataValue = subRef.dataValue;
Integer refSubId = subRef.referencedSubmissionId;
for (AppliedData aData : appliedDataMap.values()) {
String currentDataValue = aData.value;
Integer currentDataSubId = dataSubmissionMap.get(aData.dataId);
// added check that referenced and referring are not the same.
if (refDataValue.equals(currentDataValue)
&& refSubId.equals(currentDataSubId)) {
LOG.info("Found a matching data value: " + currentDataValue + " in referenced sub "
+ dccIdMap.get(currentDataSubId) + " for value "
+ aData.actualValue);
Integer foundDataId = aData.dataId;
findAppliedProtocolsAndDataFromEarlierInDag(foundDataId, foundAppliedData,
foundAppliedProtocols);
}
}
}
private List<Item> createFromWikiPage(String dccId, String clsName,
Map<String, List<SubmissionProperty>> typeToProp, List<String> types)
throws ObjectStoreException {
List<Item> items = new ArrayList<Item>();
List<SubmissionProperty> props = new ArrayList<SubmissionProperty>();
for (String type : types) {
if (typeToProp.containsKey(type)) {
props.addAll(typeToProp.get(type));
}
}
items.addAll(createItemsForSubmissionProperties(dccId, clsName, props));
return items;
}
private void storeSubmissionCollection(Integer storedSubmissionId, String name,
List<Item> items)
throws ObjectStoreException {
if (!items.isEmpty()) {
ReferenceList refList = new ReferenceList(name, getIdentifiersFromItems(items));
getChadoDBConverter().store(refList, storedSubmissionId);
}
}
private List<String> getIdentifiersFromItems(Collection<Item> items) {
List<String> ids = new ArrayList<String>();
for (Item item : items) {
ids.add(item.getIdentifier());
}
return ids;
}
private List<Item> createItemsForSubmissionProperties(String dccId, String clsName,
List<SubmissionProperty> subProps)
throws ObjectStoreException {
List<Item> items = new ArrayList<Item>();
for (SubmissionProperty subProp : subProps) {
Item item = getItemForSubmissionProperty(clsName, subProp, dccId);
if (item != null) {
items.add(item);
}
}
return items;
}
private Item getItemForSubmissionProperty(String clsName, SubmissionProperty prop, String dccId)
throws ObjectStoreException {
Item propItem = subItemsMap.get(prop.wikiPageUrl);
if (propItem == null) {
if (clsName != null) {
List<String> checkOfficialName = prop.details.get("official name");
if (checkOfficialName == null) {
LOG.warn("No 'official name', using 'name' instead for: " + prop.wikiPageUrl);
checkOfficialName = prop.details.get("name");
}
if (checkOfficialName == null) {
LOG.info("Official name - missing for property: "
+ prop.type + ", " + prop.wikiPageUrl);
return null;
} else if (checkOfficialName.size() != 1) {
LOG.info("Official name - multiple times for property: "
+ prop.type + ", " + prop.wikiPageUrl + ", "
+ checkOfficialName);
}
String officialName = getCorrectedOfficialName(prop);
propItem = createSubmissionProperty(clsName, officialName);
propItem.setAttribute("type", getPreferredSynonym(prop.type));
propItem.setAttribute("wikiLink", WIKI_URL + prop.wikiPageUrl);
if ("DevelopmentalStage".equals(clsName)) {
setAttributeOnProp(prop, propItem, "sex", "sex");
List<String> devStageValues = prop.details.get("developmental stage");
if (devStageValues != null) {
for (String devStageValue : devStageValues) {
propItem.addToCollection("ontologyTerms",
getDevStageTerm(devStageValue, dccId));
}
} else {
LOG.error("METADATA FAIL on " + dccId
+ ": no 'developmental stage' values for wiki page: "
+ prop.wikiPageUrl);
}
} else if ("Antibody".equals(clsName)) {
setAttributeOnProp(prop, propItem, "antigen", "antigen");
setAttributeOnProp(prop, propItem, "host", "hostOrganism");
setAttributeOnProp(prop, propItem, "target name", "targetName");
setGeneItem(dccId, prop, propItem, "Antibody");
} else if ("Array".equals(clsName)) {
setAttributeOnProp(prop, propItem, "platform", "platform");
setAttributeOnProp(prop, propItem, "resolution", "resolution");
setAttributeOnProp(prop, propItem, "genome", "genome");
} else if ("CellLine".equals(clsName)) {
setAttributeOnProp(prop, propItem, "sex", "sex");
setAttributeOnProp(prop, propItem, "short description", "description");
setAttributeOnProp(prop, propItem, "species", "species");
setAttributeOnProp(prop, propItem, "tissue", "tissue");
setAttributeOnProp(prop, propItem, "cell type", "cellType");
setAttributeOnProp(prop, propItem, "target name", "targetName");
setGeneItem(dccId, prop, propItem, "CellLine");
} else if ("Strain".equals(clsName)) {
setAttributeOnProp(prop, propItem, "species", "species");
setAttributeOnProp(prop, propItem, "source", "source");
// the following 2 should be mutually exclusive
setAttributeOnProp(prop, propItem, "Description", "description");
setAttributeOnProp(prop, propItem, "details", "description");
setAttributeOnProp(prop, propItem, "aliases", "name");
setAttributeOnProp(prop, propItem, "reference", "reference");
setAttributeOnProp(prop, propItem, "target name", "targetName");
setGeneItem(dccId, prop, propItem, "Strain");
} else if ("Tissue".equals(clsName)) {
setAttributeOnProp(prop, propItem, "species", "species");
setAttributeOnProp(prop, propItem, "sex", "sex");
setAttributeOnProp(prop, propItem, "organismPart", "organismPart");
}
getChadoDBConverter().store(propItem);
}
subItemsMap.put(prop.wikiPageUrl, propItem);
}
return propItem;
}
private void setGeneItem(String dccId, SubmissionProperty prop, Item propItem, String source)
throws ObjectStoreException {
String targetText = null;
String[] possibleTypes = new String[] {"target id"};
boolean tooMany = false;
for (String targetType : possibleTypes) {
if (prop.details.containsKey(targetType)) {
if (prop.details.get(targetType).size() != 1) {
// we used to complain if multiple values, now only
// if they don't have the same value
if (sameTargetValue(prop, source, targetType)) {
tooMany = true;
break;
}
}
if (!tooMany) {
targetText = prop.details.get(targetType).get(0);
}
break;
}
}
if (targetText != null) {
// if no target name was found use the target id
if (!propItem.hasAttribute("targetName")) {
propItem.setAttribute("targetName", targetText);
}
String geneItemId = getTargetGeneItemIdentfier(targetText, dccId);
if (geneItemId != null) {
propItem.setReference("target", geneItemId);
}
}
}
private boolean sameTargetValue(SubmissionProperty prop, String source,
String targetType) {
String value = prop.details.get(targetType).get(0);
for (int i = 1; i < prop.details.get(targetType).size(); i++) {
String newValue = prop.details.get(targetType).get(i);
if (!newValue.equals(value)) {
LOG.error(source + " (" + prop.wikiPageUrl + ") has more than 1 value for '"
+ targetType + "' field: " + prop.details.get(targetType));
//throw new RuntimeException(source + " should only have one value for '"
// + targetType + "' field: " + prop.details.get(targetType));
return true;
}
}
return false;
}
private void setAttributeOnProp(SubmissionProperty subProp, Item item, String metadataName,
String attributeName) {
if (subProp.details.containsKey(metadataName)) {
if ("aliases".equalsIgnoreCase(metadataName)) {
for (String s :subProp.details.get(metadataName)) {
if ("yellow cinnabar brown speck".equalsIgnoreCase(s)) {
// swapping name with fullName
String full = item.getAttribute("name").getValue();
item.setAttribute("fullName", full);
item.setAttribute(attributeName, s);
break;
}
}
} else if ("description".equalsIgnoreCase(metadataName)
|| "details".equalsIgnoreCase(metadataName)) {
// description is often split in more than 1 line, details should be correct order
StringBuffer sb = new StringBuffer();
for (String desc : subProp.details.get(metadataName)) {
sb.append(desc);
}
if (sb.length() > 0) {
item.setAttribute(attributeName, sb.toString());
}
} else {
String value = subProp.details.get(metadataName).get(0);
item.setAttribute(attributeName, value);
}
}
}
private String getTargetGeneItemIdentfier(String geneTargetIdText, String dccId)
throws ObjectStoreException {
// TODO check: why not using only the else?
String taxonId = "";
String originalId = null;
String flyPrefix = "fly_genes:";
String wormPrefix = "worm_genes:";
if (geneTargetIdText.startsWith(flyPrefix)) {
originalId = geneTargetIdText.substring(flyPrefix.length());
taxonId = "7227";
} else if (geneTargetIdText.startsWith(wormPrefix)) {
originalId = geneTargetIdText.substring(wormPrefix.length());
taxonId = "6239";
} else {
// attempt to work out the organism from the submission
taxonId = getTaxonIdForSubmission(dccId);
originalId = geneTargetIdText;
LOG.debug("RESOLVER: found taxon " + taxonId + " for submission " + dccId);
}
IdResolver resolver = null;
if ("7227".equals(taxonId)) {
resolver = flyResolverFactory.getIdResolver();
} else if ("6239".equals(taxonId)) {
resolver = wormResolverFactory.getIdResolver();
} else {
LOG.info("RESOLVER: unable to work out organism for target id text: "
+ geneTargetIdText + " in submission " + dccId);
}
String geneItemId = null;
String primaryIdentifier = resolveGene(originalId, taxonId, resolver);
if (primaryIdentifier != null) {
geneItemId = geneToItemIdentifier.get(primaryIdentifier);
if (geneItemId == null) {
Item gene = getChadoDBConverter().createItem("Gene");
geneItemId = gene.getIdentifier();
gene.setAttribute("primaryIdentifier", primaryIdentifier);
getChadoDBConverter().store(gene);
geneToItemIdentifier.put(primaryIdentifier, geneItemId);
} else {
LOG.info("RESOLVER fetched gene from cache: " + primaryIdentifier);
}
}
return geneItemId;
}
private String resolveGene(String originalId, String taxonId, IdResolver resolver) {
String primaryIdentifier = null;
int resCount = resolver.countResolutions(taxonId, originalId);
if (resCount != 1) {
LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring "
+ "gene: " + originalId + " for organism " + taxonId + " count: " + resCount
+ " found ids: " + resolver.resolveId(taxonId, originalId) + ".");
} else {
primaryIdentifier =
resolver.resolveId(taxonId, originalId).iterator().next();
LOG.info("RESOLVER found gene " + primaryIdentifier
+ " for original id: " + originalId);
}
return primaryIdentifier;
}
private List<Item> lookForAttributesInOtherWikiPages(String dccId, String clsName,
Map<String, List<SubmissionProperty>> typeToProp, String[] lookFor)
throws ObjectStoreException {
List<Item> items = new ArrayList<Item>();
for (String typeProp : lookFor) {
if (typeProp.indexOf(".") > 0) {
String[] bits = StringUtils.split(typeProp, '.');
String type = bits[0];
String propName = bits[1];
if (typeToProp.containsKey(type)) {
for (SubmissionProperty subProp : typeToProp.get(type)) {
if (subProp.details.containsKey(propName)) {
for (String value : subProp.details.get(propName)) {
items.add(createNonWikiSubmissionPropertyItem(dccId, clsName,
getPreferredSynonym(propName),
correctAttrValue(value)));
}
}
}
if (!items.isEmpty()) {
break;
}
}
} else {
// no attribute type given so use the data.value (SubmissionProperty.wikiPageUrl)
// which probably won't be a wiki page
if (typeToProp.containsKey(typeProp)) {
for (SubmissionProperty subProp : typeToProp.get(typeProp)) {
String value = subProp.wikiPageUrl;
// This is an ugly special case to deal with 'exposure time/24 hours'
if (subProp.details.containsKey("Unit")) {
String unit = subProp.details.get("Unit").get(0);
value = value + " " + unit + (unit.endsWith("s") ? "" : "s");
}
LOG.info("PP2 " + dccId + ": " + subProp.type
+ " - " + correctAttrValue(value));
items.add(createNonWikiSubmissionPropertyItem(dccId, clsName, subProp.type,
correctAttrValue(value)));
}
}
}
}
return items;
}
private String correctAttrValue(String value) {
if (value == null) {
return null;
}
value = value.replace("–", "-");
return value;
}
private Item createNonWikiSubmissionPropertyItem(String dccId, String clsName, String type,
String name)
throws ObjectStoreException {
if ("DevelopmentalStage".equals(clsName)) {
name = correctDevStageTerm(name);
}
Item item = nonWikiSubmissionProperties.get(name);
if (item == null) {
item = createSubmissionProperty(clsName, name);
item.setAttribute("type", getPreferredSynonym(type));
if ("DevelopmentalStage".equals(clsName)) {
String ontologyTermId = getDevStageTerm(name, dccId);
item.addToCollection("ontologyTerms", ontologyTermId);
}
getChadoDBConverter().store(item);
nonWikiSubmissionProperties.put(name, item);
}
return item;
}
private Item createSubmissionProperty(String clsName, String name) {
Item subProp = getChadoDBConverter().createItem(clsName);
if (name != null) {
subProp.setAttribute("name", name);
}
return subProp;
}
private String getCorrectedOfficialName(SubmissionProperty prop) {
String preferredType = getPreferredSynonym(prop.type);
String name = null;
if (prop.details.containsKey("official name")) {
name = prop.details.get("official name").get(0);
} else if (prop.details.containsKey("name")) {
name = prop.details.get("name").get(0);
} else {
// no official name so maybe there is a key that matches the type - sometimes the
// setup for Characteristics
for (String lookup : makeLookupList(prop.type)) {
if (prop.details.containsKey(lookup)) {
name = prop.details.get(lookup).get(0);
}
}
}
return correctOfficialName(name, preferredType);
}
/**
* Unify variations on similar official names.
* @param name the original 'official name' value
* @param type the treatment depends on the type
* @return a unified official name
*/
protected String correctOfficialName(String name, String type) {
if (name == null) {
return null;
}
if ("developmental stage".equals(type)) {
name = name.replace("_", " ");
name = name.replaceFirst("embryo", "Embryo");
name = name.replaceFirst("Embyro", "Embryo");
if (name.matches("E\\d.*")) {
name = name.replaceFirst("^E", "Embryo ");
}
if (name.matches("Embryo.*\\d")) {
name = name + " h";
}
if (name.matches(".*hr")) {
name = name.replace("hr", "h");
}
if (name.matches("Embryo.*\\dh")) {
name = name.replaceFirst("h", " h");
}
if (name.startsWith("DevStage:")) {
name = name.replaceFirst("DevStage:", "").trim();
}
if (name.matches("L\\d")) {
name = name + " stage larvae";
}
if (name.matches(".*L\\d")) {
name = name + " stage larvae";
}
if (name.matches("WPP.*")) {
name = name.replaceFirst("WPP", "White prepupae (WPP)");
}
}
return name;
}
private String getDevStageTerm(String value, String dccId) throws ObjectStoreException {
value = correctDevStageTerm(value);
// there may be duplicate terms for fly and worm, include taxon in key
String taxonId = getTaxonIdForSubmission(dccId);
OrganismRepository or = OrganismRepository.getOrganismRepository();
String genus = or.getOrganismDataByTaxon(Integer.parseInt(taxonId)).getGenus();
String key = value + "_" + genus;
String identifier = devStageTerms.get(key);
if (identifier == null) {
Item term = getChadoDBConverter().createItem("OntologyTerm");
term.setAttribute("name", value);
String ontologyRef = getDevelopmentOntologyByTaxon(taxonId);
if (ontologyRef != null) {
term.setReference("ontology", ontologyRef);
}
getChadoDBConverter().store(term);
devStageTerms.put(key, term.getIdentifier());
identifier = term.getIdentifier();
}
return identifier;
}
private String correctDevStageTerm(String value) {
// some terms are prefixed with ontology namespace
String prefix = "FlyBase development CV:";
if (value.startsWith(prefix)) {
value = value.substring(prefix.length());
}
return value;
}
private String getTaxonIdForSubmission(String dccId) {
Integer subChadoId = getSubmissionIdFromDccId(dccId);
String organism = submissionOrganismMap.get(subChadoId);
OrganismRepository or = OrganismRepository.getOrganismRepository();
return "" + or.getOrganismDataByFullName(organism).getTaxonId();
}
private String getDevelopmentOntologyByTaxon(String taxonId) throws ObjectStoreException {
if (taxonId == null) {
return null;
}
String ontologyName = null;
OrganismRepository or = OrganismRepository.getOrganismRepository();
String genus = or.getOrganismDataByTaxon(Integer.parseInt(taxonId)).getGenus();
if ("Drosophila".equals(genus)) {
ontologyName = "Fly Development";
} else {
ontologyName = "Worm Development";
}
String ontologyId = devOntologies.get(ontologyName);
if (ontologyId == null) {
Item ontology = getChadoDBConverter().createItem("Ontology");
ontology.setAttribute("name", ontologyName);
getChadoDBConverter().store(ontology);
ontologyId = ontology.getIdentifier();
devOntologies.put(ontologyName, ontologyId);
}
return ontologyId;
}
private Integer getSubmissionIdFromDccId(String dccId) {
for (Map.Entry<Integer, String> entry : dccIdMap.entrySet()) {
if (entry.getValue().equals(dccId)) {
return entry.getKey();
}
}
return null;
}
/**
* Return the rows needed for data from the applied_protocol_data table.
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedDataAll(Connection connection)
throws SQLException {
String sraAcc = "SRA acc";
String query = "SELECT d.data_id, d.heading as data_heading,"
+ " d.name as data_name, d.value as data_value,"
+ " c.name as cv_term,"
+ " a.attribute_id, a.heading as att_heading, a.name as att_name,"
+ " a.value as att_value,"
+ " a.dbxref_id as att_dbxref, a.rank as att_rank"
+ " FROM data d"
+ " LEFT JOIN data_attribute da ON (d.data_id = da.data_id)"
+ " LEFT JOIN attribute a ON (da.attribute_id = a.attribute_id)"
+ " LEFT JOIN cvterm c ON (d.type_id = c.cvterm_id)"
+ " LEFT JOIN dbxref as x ON (a.dbxref_id = x.dbxref_id)"
+ " WHERE d.name != '" + sraAcc + "'"
+ " AND d.value != '' "
+ " ORDER BY d.data_id";
return doQuery(connection, query, "getAppliedDataAll");
}
/**
* Return the rows needed for data from the applied_protocol_data table.
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedDataCharacteristics(Connection connection)
throws SQLException {
String query = "select d.data_id, d.heading as data_heading,"
+ " d.name as data_name, d.value as data_value,"
+ " a.attribute_id, a.heading as att_heading, a.name as att_name,"
+ " a.value as att_value,"
+ " a.dbxref_id as att_dbxref, a.rank as att_rank"
+ " FROM data d, data_attribute da, attribute a, dbxref ax, db"
+ " WHERE d.data_id = da.data_id"
+ " AND da.attribute_id = a.attribute_id"
+ " AND a.dbxref_id = ax.dbxref_id"
+ " AND ax.db_id = db.db_id"
+ " ORDER BY d.data_id, a.dbxref_id ";
return doQuery(connection, query, "getAppliedDataCharacteristics");
}
private class SubmissionProperty
{
protected String type;
protected String wikiPageUrl;
protected Map<String, List<String>> details;
protected SubmissionProperty() {
details = new HashMap<String, List<String>>();
}
public SubmissionProperty(String type, String wikiPageUrl) {
this.type = type;
this.wikiPageUrl = wikiPageUrl;
details = new HashMap<String, List<String>>();
}
public void addDetail(String type, String value, int rank) {
List<String> values = details.get(type);
if (values == null) {
values = new ArrayList<String>();
details.put(type, values);
}
while (values.size() <= rank) {
values.add(null);
}
values.set(rank, value);
}
public String toString() {
return this.type + ": " + this.wikiPageUrl + this.details.entrySet();
}
}
private final class DatabaseRecordConfig
{
private String dbName;
private String dbDescrition;
private String dbURL;
private Set<String> types = new HashSet<String>();
private DatabaseRecordConfig() {
// don't
}
}
private Set<DatabaseRecordConfig> initDatabaseRecordConfigs() {
Set<DatabaseRecordConfig> configs = new HashSet<DatabaseRecordConfig>();
DatabaseRecordConfig geo = new DatabaseRecordConfig();
geo.dbName = "GEO";
geo.dbDescrition = "Gene Expression Omnibus (NCBI)";
geo.dbURL = "http:
geo.types.add("GEO_record");
configs.add(geo);
DatabaseRecordConfig ae = new DatabaseRecordConfig();
ae.dbName = "ArrayExpress";
ae.dbDescrition = "ArrayExpress (EMBL-EBI)";
ae.dbURL = "http:
ae.types.add("ArrayExpress_record");
configs.add(ae);
DatabaseRecordConfig sra = new DatabaseRecordConfig();
sra.dbName = "SRA";
sra.dbDescrition = "Sequence Read Archive (NCBI)";
sra.dbURL =
"http:
sra.types.add("ShortReadArchive_project_ID_list (SRA)");
sra.types.add("ShortReadArchive_project_ID (SRA)");
configs.add(sra);
DatabaseRecordConfig ta = new DatabaseRecordConfig();
ta.dbName = "Trace Archive";
ta.dbDescrition = "Trace Archive (NCBI)";
ta.dbURL = "http:
ta.types.add("TraceArchive_record");
configs.add(ta);
DatabaseRecordConfig de = new DatabaseRecordConfig();
de.dbName = "dbEST";
de.dbDescrition = "Expressed Sequence Tags database (NCBI)";
de.dbURL = "http:
de.types.add("dbEST_record");
configs.add(de);
return configs;
}
/**
* Query to get data attributes.
*
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getAppliedDataAttributes(Connection connection)
throws SQLException {
String query =
"select da.data_id, a.heading, a.value, a.name "
+ " from data_attribute da, attribute a"
+ " where da.attribute_id = a.attribute_id";
return doQuery(connection, query, "getAppliedDataAttributes");
}
private void setSubmissionRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
// note: the map should contain only live submissions
for (Integer submissionId : submissionDataMap.keySet()) {
for (Integer dataId : submissionDataMap.get(submissionId)) {
LOG.debug("DAG subRef subid: " + submissionId + " dataId: " + dataId);
if (appliedDataMap.get(dataId).intermineObjectId == null) {
continue;
}
Reference reference = new Reference();
reference.setName("submission");
reference.setRefId(submissionMap.get(submissionId).itemIdentifier);
getChadoDBConverter().store(reference,
appliedDataMap.get(dataId).intermineObjectId);
}
}
LOG.info("TIME setting submission-data references: "
+ (System.currentTimeMillis() - bT) + " ms");
}
private void createDatabaseRecords(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
Set<DatabaseRecordConfig> configs = initDatabaseRecordConfigs();
for (Integer submissionId : submissionDataMap.keySet()) {
LOG.info("DB RECORD for sub " + dccIdMap.get(submissionId) + "...");
List<Integer> submissionDbRecords = new ArrayList<Integer>();
for (Integer dataId : submissionDataMap.get(submissionId)) {
AppliedData ad = appliedDataMap.get(dataId);
if (ad.type.equalsIgnoreCase("Result Value")) {
for (DatabaseRecordConfig conf : configs) {
for (String type : conf.types) {
if (ad.name.equals(type)) {
submissionDbRecords.addAll(createDatabaseRecords(ad.value, conf));
}
}
}
}
// prepare map for setting references
if (!submissionDbRecords.isEmpty()) {
for (Integer dbRecord : submissionDbRecords) {
addToMap(dbRecordIdSubItems, dbRecord,
submissionMap.get(submissionId).itemIdentifier);
}
}
}
}
LOG.info("TIME creating DatabaseRecord objects: "
+ (System.currentTimeMillis() - bT) + " ms");
bT = System.currentTimeMillis();
// set references
// NB: we are setting them from dbRecord to submissions because more efficient
// (a few subs have a big collection of dbRecords)
for (Integer dbRecordId : dbRecordIdSubItems.keySet()) {
ReferenceList col = new ReferenceList("submissions",
dbRecordIdSubItems.get(dbRecordId));
getChadoDBConverter().store(col, dbRecordId);
}
LOG.info("TIME creating refs DatabaseRecord objects: "
+ (System.currentTimeMillis() - bT) + " ms");
}
private List<Integer> createDatabaseRecords(String accession, DatabaseRecordConfig config)
throws ObjectStoreException {
List<Integer> dbRecordIds = new ArrayList<Integer>();
String defaultURL = config.dbURL;
Set<String> cleanAccessions = new HashSet<String>();
// NOTE - this is a special case to deal with a very strange SRA accession format in some
// Celniker submissions. The 'accession' is provided as e.g.
// SRR013492.225322.1;SRR013492.462158.1;...
// We just want the unique SRR ids
if ("SRA".equals(config.dbName) && (accession.indexOf(';') != -1
|| accession.indexOf('.') != -1)) {
for (String part : accession.split(";")) {
if (part.indexOf('.') != -1) {
cleanAccessions.add(part.substring(0, part.indexOf('.')));
} else {
cleanAccessions.add(part);
}
}
} else if ("SRA".equals(config.dbName) && (accession.startsWith("SRX"))) {
config.dbURL = "http:
dbRecordIds.add(createDatabaseRecord(accession, config));
config.dbURL = defaultURL;
} else {
cleanAccessions.add(accession);
}
for (String cleanAccession : cleanAccessions) {
dbRecordIds.add(createDatabaseRecord(cleanAccession, config));
}
return dbRecordIds;
}
private Integer createDatabaseRecord(String accession, DatabaseRecordConfig config)
throws ObjectStoreException {
DatabaseRecordKey key = new DatabaseRecordKey(config.dbName, accession);
Integer dbRecordId = dbRecords.get(key);
if (dbRecordId == null) {
Item dbRecord = getChadoDBConverter().createItem("DatabaseRecord");
dbRecord.setAttribute("database", config.dbName);
dbRecord.setAttribute("description", config.dbDescrition);
if (StringUtils.isEmpty(accession)) {
dbRecord.setAttribute("accession", "To be confirmed");
} else {
dbRecord.setAttribute("url", config.dbURL + accession);
dbRecord.setAttribute("accession", accession);
}
dbRecordId = getChadoDBConverter().store(dbRecord);
dbRecords.put(key, dbRecordId);
}
return dbRecordId;
}
private class DatabaseRecordKey
{
private String db;
private String accession;
/**
* Construct with the database and accession
* @param db database name
* @param accession id in database
*/
public DatabaseRecordKey(String db, String accession) {
this.db = db;
this.accession = accession;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object o) {
if (o instanceof DatabaseRecordKey) {
DatabaseRecordKey otherKey = (DatabaseRecordKey) o;
if (StringUtils.isNotEmpty(accession)
&& StringUtils.isNotEmpty(otherKey.accession)) {
return this.db.equals(otherKey.db)
&& this.accession.equals(otherKey.accession);
}
}
return false;
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return db.hashCode() + 3 * accession.hashCode();
}
}
private void createResultFiles(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
for (Integer submissionId : submissionDataMap.keySet()) {
// the applied data is repeated for each protocol
// so we want to uniquefy the created object
Set<String> subFiles = new HashSet<String>();
for (Integer dataId : submissionDataMap.get(submissionId)) {
AppliedData ad = appliedDataMap.get(dataId);
// now checking only for 'file', not 'result file'
if (StringUtils.containsIgnoreCase(ad.type, "file")) {
if (!StringUtils.isBlank(ad.value)
&& !subFiles.contains(ad.value)) {
String direction = null;
if (StringUtils.containsIgnoreCase(ad.type, "result")) {
direction = "result";
} else {
direction = "input";
}
createResultFile(ad.value, ad.name, ad.url, direction, submissionId);
subFiles.add(ad.value);
}
}
}
}
LOG.info("TIME creating ResultFile objects: " + (System.currentTimeMillis() - bT) + " ms");
}
private void createResultFile(String fileName, String type, String relDccId, String direction,
Integer submissionId)
throws ObjectStoreException {
Item resultFile = getChadoDBConverter().createItem("ResultFile");
resultFile.setAttribute("name", unversionName(fileName));
String url = null;
if (fileName.startsWith("http") || fileName.startsWith("ftp")) {
url = fileName;
} else {
if (relDccId != null) { // the file actually belongs to a related sub
url = FILE_URL + relDccId + "/extracted/" + unversionName(fileName);
} else {
// note: on ftp site submission directories are named with the digits only
String dccId = dccIdMap.get(submissionId).substring(DCC_PREFIX.length());
url = FILE_URL + dccId + "/extracted/" + unversionName(fileName);
}
}
resultFile.setAttribute("url", url);
resultFile.setAttribute("type", type);
resultFile.setAttribute("direction", direction);
resultFile.setReference("submission", submissionMap.get(submissionId).itemIdentifier);
getChadoDBConverter().store(resultFile);
}
/**
* @param fileName
*/
private String unversionName(String fileName) {
// String versionRegex = "\\.*_*[WS|ws]+\\d\\d\\d+";
String versionRegex = "\\.*_*[Ww][Ss]+\\d\\d\\d+";
LOG.debug("FFFF: " + fileName + "
+ "====>" + fileName.replaceAll(versionRegex, ""));
return fileName.replaceAll(versionRegex, "");
}
private void createRelatedSubmissions(Connection connection) throws ObjectStoreException {
Map<Integer, Set<String>> relatedSubs = new HashMap<Integer, Set<String>>();
for (Map.Entry<Integer, List<SubmissionReference>> entry : submissionRefs.entrySet()) {
Integer submissionId = entry.getKey();
List<SubmissionReference> lref = entry.getValue();
Iterator<SubmissionReference> i = lref.iterator();
while (i.hasNext()) {
SubmissionReference ref = i.next();
addRelatedSubmissions(relatedSubs, submissionId, ref.referencedSubmissionId);
addRelatedSubmissions(relatedSubs, ref.referencedSubmissionId, submissionId);
}
LOG.debug("RRSS11 " + relatedSubs.size() + "|" + relatedSubs.keySet() + "|"
+ relatedSubs.values());
}
for (Map.Entry<Integer, Set<String>> entry : relatedSubs.entrySet()) {
ReferenceList related = new ReferenceList("relatedSubmissions",
new ArrayList<String>(entry.getValue()));
getChadoDBConverter().store(related, entry.getKey());
}
}
private void addRelatedSubmissions(Map<Integer, Set<String>> relatedSubs, Integer subId,
Integer relatedId) {
Integer subIdObjectId = submissionMap.get(subId).interMineObjectId;
Set<String> itemIds = relatedSubs.get(subIdObjectId);
if (itemIds == null) {
itemIds = new HashSet<String>();
relatedSubs.put(submissionMap.get(subId).interMineObjectId, itemIds);
}
itemIds.add(submissionMap.get(relatedId).itemIdentifier);
}
//sub -> prot
private void setSubmissionProtocolsRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
Map<Integer, List<Integer>> submissionProtocolMap = new HashMap<Integer, List<Integer>>();
Iterator<Integer> apId = appliedProtocolMap.keySet().iterator();
while (apId.hasNext()) {
Integer thisAP = apId.next();
AppliedProtocol ap = appliedProtocolMap.get(thisAP);
Util.addToListMap(submissionProtocolMap, ap.submissionId, ap.protocolId);
}
Iterator<Integer> subs = submissionProtocolMap.keySet().iterator();
while (subs.hasNext()) {
Integer thisSubmissionId = subs.next();
List<Integer> protocolChadoIds = submissionProtocolMap.get(thisSubmissionId);
ReferenceList collection = new ReferenceList();
collection.setName("protocols");
for (Integer protocolChadoId : protocolChadoIds) {
collection.addRefId(protocolItemIds.get(protocolChadoId));
}
Integer storedSubmissionId = submissionMap.get(thisSubmissionId).interMineObjectId;
getChadoDBConverter().store(collection, storedSubmissionId);
// TODO use Item?
// if the experiment type is not set in the db, check protocols
if (!submissionWithExpTypeSet.contains(thisSubmissionId)) {
LOG.warn("EXPERIMENT TYPE NOT SET in chado for submission: "
+ dccIdMap.get(thisSubmissionId));
// may need protocols from referenced submissions to work out experiment type
List<Integer> relatedSubsProtocolIds = new ArrayList<Integer>(
findProtocolIdsFromReferencedSubmissions(thisSubmissionId));
if (relatedSubsProtocolIds != null) {
protocolChadoIds.addAll(relatedSubsProtocolIds);
}
String piName = submissionProjectMap.get(thisSubmissionId);
setSubmissionExperimentType(storedSubmissionId, protocolChadoIds, piName);
}
}
LOG.info("TIME setting submission-protocol references: "
+ (System.currentTimeMillis() - bT) + " ms");
}
// store Submission.experimentType if it can be inferred from protocols
private void setSubmissionExperimentType(Integer storedSubId, List<Integer> protocolIds,
String piName) throws ObjectStoreException {
Set<String> protocolTypes = new HashSet<String>();
for (Integer protocolId : protocolIds) {
protocolTypes.add(protocolTypesMap.get(protocolId).trim());
}
String experimentType = inferExperimentType(protocolTypes, piName);
if (experimentType != null) {
Attribute expTypeAtt = new Attribute("experimentType", experimentType);
getChadoDBConverter().store(expTypeAtt, storedSubId);
}
}
// Fetch protocols used to create reagents that are inputs to this submission, these are
// found in referenced submissions
private List<Integer> findProtocolIdsFromReferencedSubmissions(Integer submissionId) {
List<Integer> protocolIds = new ArrayList<Integer>();
if (submissionRefs == null) {
throw new RuntimeException("Attempting to access submissionRefs before it has been"
+ " populated, this method needs to be called after"
+ " processSubmissionProperties");
}
List<SubmissionReference> refs = submissionRefs.get(submissionId);
if (refs == null) {
return protocolIds;
}
for (SubmissionReference subRef : refs) {
LOG.info("RRSSprot: " + subRef.referencedSubmissionId
+ "|" + subRef.dataValue);
for (AppliedProtocol aProtocol : findAppliedProtocolsFromReferencedSubmission(subRef)) {
LOG.info("RRSSprotId: " + aProtocol.protocolId);
protocolIds.add(aProtocol.protocolId);
}
}
return protocolIds;
}
/**
* Work out an experiment type give the combination of protocols used for the
* submission. e.g. *immunoprecipitation + hybridization = chIP-chip
* @param protocolTypes the protocol types
* @param piName name of PI
* @return a short experiment type
*/
protected String inferExperimentType(Set<String> protocolTypes, String piName) {
// extraction + sequencing + reverse transcription - ChIP = RTPCR
// extraction + sequencing - reverse transcription - ChIP = RNA-seq
if (containsMatch(protocolTypes, "nucleic_acid_extraction|RNA extraction")
&& containsMatch(protocolTypes, "sequencing(_protocol)?")
&& !containsMatch(protocolTypes, "chromatin_immunoprecipitation")) {
if (containsMatch(protocolTypes, "reverse_transcription")) {
return "RTPCR";
} else {
return "RNA-seq";
}
}
// reverse transcription + PCR + RACE = RACE
// reverse transcription + PCR - RACE = RTPCR
if (containsMatch(protocolTypes, "reverse_transcription")
&& containsMatch(protocolTypes, "PCR(_amplification)?")) {
if (containsMatch(protocolTypes, "RACE")) {
return "RACE";
} else {
return "RTPCR";
}
}
// ChIP + hybridization = ChIP-chip
// ChIP - hybridization = ChIP-seq
if (containsMatch(protocolTypes, "(.*)?immunoprecipitation")) {
if (containsMatch(protocolTypes, "hybridization")) {
return "ChIP-chip";
} else {
return "ChIP-seq";
}
}
// hybridization - ChIP =
// Celniker: RNA tiling array
// Henikoff: Chromatin-chip
// otherwise: Tiling array
if (containsMatch(protocolTypes, "hybridization")
&& !containsMatch(protocolTypes, "immunoprecipitation")) {
if ("Celniker".equals(piName)) {
return "RNA tiling array";
} else if ("Henikoff".equals(piName)) {
return "Chromatin-chip";
} else {
return "Tiling array";
}
}
// annotation = Computational annotation
if (containsMatch(protocolTypes, "annotation")) {
return "Computational annotation";
}
// If we haven't found a type yet, and there is a growth protocol, then
// this is probably an RNA sample creation experiment from Celniker
if (containsMatch(protocolTypes, "grow")) {
return "RNA sample creation";
}
return null;
}
// utility method for looking up in a set by regular expression
private boolean containsMatch(Set<String> testSet, String regex) {
boolean matches = false;
Pattern p = Pattern.compile(regex);
for (String test : testSet) {
Matcher m = p.matcher(test);
if (m.matches()) {
matches = true;
}
}
return matches;
}
//sub -> exp
private void setSubmissionExperimentRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
// the map should contain only live submissions
Iterator<String> exp = expSubMap.keySet().iterator();
while (exp.hasNext()) {
String thisExp = exp.next();
List<Integer> subs = expSubMap.get(thisExp);
Iterator<Integer> s = subs.iterator();
while (s.hasNext()) {
Integer thisSubId = s.next();
Reference reference = new Reference();
reference.setName("experiment");
reference.setRefId(experimentIdRefMap.get(thisExp));
getChadoDBConverter().store(reference,
submissionMap.get(thisSubId).interMineObjectId);
}
}
LOG.info("TIME setting submission-experiment references: "
+ (System.currentTimeMillis() - bT) + " ms");
}
//sub -> ef
private void setSubmissionEFactorsRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
Iterator<Integer> subs = submissionEFactorMap.keySet().iterator();
while (subs.hasNext()) {
Integer thisSubmissionId = subs.next();
List<String> eFactors = submissionEFactorMap.get(thisSubmissionId);
LOG.info("EF REFS: " + thisSubmissionId + " (" + eFactors + ")");
Iterator<String> ef = eFactors.iterator();
ReferenceList collection = new ReferenceList();
collection.setName("experimentalFactors");
while (ef.hasNext()) {
String currentEF = ef.next();
collection.addRefId(eFactorIdRefMap.get(currentEF));
LOG.debug("EF REFS: ->" + currentEF + " ref: " + eFactorIdRefMap.get(currentEF));
}
if (!collection.equals(null)) {
LOG.info("EF REFS: ->" + thisSubmissionId + "|"
+ submissionMap.get(thisSubmissionId).interMineObjectId);
getChadoDBConverter().store(collection,
submissionMap.get(thisSubmissionId).interMineObjectId);
}
}
LOG.info("TIME setting submission-exFactors references: "
+ (System.currentTimeMillis() - bT) + " ms");
}
//sub -> publication
private void setSubmissionPublicationRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
Iterator<Integer> subs = publicationIdMap.keySet().iterator();
while (subs.hasNext()) {
Integer thisSubmissionId = subs.next();
Reference reference = new Reference();
reference.setName("publication");
reference.setRefId(publicationIdRefMap.get(thisSubmissionId));
getChadoDBConverter().store(reference,
submissionMap.get(thisSubmissionId).interMineObjectId);
}
LOG.info("TIME setting submission-publication references: "
+ (System.currentTimeMillis() - bT) + " ms");
}
/**
* to store references between applied protocols and their input data
* reverse reference: data -> next appliedProtocols
* and between applied protocols and their output data
* reverse reference: data -> previous appliedProtocols
* (many to many)
*/
private void setDAGRefs(Connection connection)
throws ObjectStoreException {
long bT = System.currentTimeMillis(); // to monitor time spent in the process
for (Integer thisAP : appliedProtocolMap.keySet()) {
AppliedProtocol ap = appliedProtocolMap.get(thisAP);
if (!ap.inputs.isEmpty()) {
ReferenceList collection = new ReferenceList("inputs");
for (Integer inputId : ap.inputs) {
collection.addRefId(appliedDataMap.get(inputId).itemIdentifier);
//if (collection.getRefIds().contains(null)) {
// LOG.info("Applied Protocol " + thisAP + " of protocol " + ap.protocolId
// + " and inputs " + ap.inputs );
}
if (collection.getRefIds().contains(null)) {
LOG.warn("Applied Protocol " + thisAP + " has only inputs not corresponding"
+ " to any output in previous protocol"
+ " and cannot be linked in the DAG.");
continue;
}
getChadoDBConverter().store(collection, appliedProtocolIdMap.get(thisAP));
}
if (!ap.outputs.isEmpty()) {
ReferenceList collection = new ReferenceList("outputs");
for (Integer outputId : ap.outputs) {
collection.addRefId(appliedDataMap.get(outputId).itemIdentifier);
}
if (collection.getRefIds().contains(null)) {
LOG.warn("Applied Protocol " + thisAP + " has null AD.itemidentifiers");
continue;
}
getChadoDBConverter().store(collection, appliedProtocolIdMap.get(thisAP));
}
}
LOG.info("TIME setting DAG references: " + (System.currentTimeMillis() - bT) + " ms");
}
/**
* maps from chado field names to ours.
*
* TODO: check if up to date
*
* if a field is not needed it is marked with NOT_TO_BE_LOADED
* a check is performed and fields unaccounted for are logged.
*/
private static final Map<String, String> FIELD_NAME_MAP =
new HashMap<String, String>();
private static final String NOT_TO_BE_LOADED = "this is ; illegal - anyway";
static {
// experiment
// swapping back to uniquename in experiment table
// FIELD_NAME_MAP.put("Investigation Title", "title");
FIELD_NAME_MAP.put("Investigation Title", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Project", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Project URL", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Lab", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Experiment Description", "description");
FIELD_NAME_MAP.put("Experimental Design", "design");
FIELD_NAME_MAP.put("Experimental Factor Type", "factorType");
FIELD_NAME_MAP.put("Experimental Factor Name", "factorName");
FIELD_NAME_MAP.put("Quality Control Type", "qualityControl");
FIELD_NAME_MAP.put("Replicate Type", "replicate");
FIELD_NAME_MAP.put("Date of Experiment", "experimentDate");
FIELD_NAME_MAP.put("Public Release Date", "publicReleaseDate");
FIELD_NAME_MAP.put("Embargo Date", "embargoDate");
FIELD_NAME_MAP.put("dcc_id", "DCCid");
FIELD_NAME_MAP.put("replaces", "replacesSubmission");
FIELD_NAME_MAP.put("PubMed ID", "pubMedId");
FIELD_NAME_MAP.put("Person First Name", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Mid Initials", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Last Name", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Affiliation", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Address", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Phone", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Email", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Person Roles", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Data Type", "category");
FIELD_NAME_MAP.put("Assay Type", "experimentType");
FIELD_NAME_MAP.put("Release Reservations", "notice");
FIELD_NAME_MAP.put("RNAsize", "RNAsize");
// these are names in name/value couples for ReadCount
FIELD_NAME_MAP.put("Total Read Count", "totalReadCount");
FIELD_NAME_MAP.put("Total Mapped Read Count", "totalMappedReadCount");
FIELD_NAME_MAP.put("Multiply Mapped Read Count", "multiplyMappedReadCount");
FIELD_NAME_MAP.put("Uniquely Mapped Read Count", "uniquelyMappedReadCount");
// data: parameter values
FIELD_NAME_MAP.put("Array Data File", "arrayDataFile");
FIELD_NAME_MAP.put("Array Design REF", "arrayDesignRef");
FIELD_NAME_MAP.put("Derived Array Data File", "derivedArrayDataFile");
FIELD_NAME_MAP.put("Result File", "resultFile");
// protocol
FIELD_NAME_MAP.put("Protocol Type", "type");
FIELD_NAME_MAP.put("url protocol", "url");
FIELD_NAME_MAP.put("Characteristics", "characteristics");
FIELD_NAME_MAP.put("species", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("references", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("lab", NOT_TO_BE_LOADED);
FIELD_NAME_MAP.put("Comment", NOT_TO_BE_LOADED);
}
/**
* to store identifiers in project maps.
* @param i
* @param chadoId
* @param intermineObjectId
* @throws ObjectStoreException
*/
private void storeInProjectMaps(Item i, String surnamePI, Integer intermineObjectId)
throws ObjectStoreException {
if ("Project".equals(i.getClassName())) {
projectIdMap .put(surnamePI, intermineObjectId);
projectIdRefMap .put(surnamePI, i.getIdentifier());
} else {
throw new IllegalArgumentException(
"Type mismatch: expecting Project, getting "
+ i.getClassName().substring(37) + " with intermineObjectId = "
+ intermineObjectId + ", project = " + surnamePI);
}
debugMap .put(i.getIdentifier(), i.getClassName());
}
/**
* to store identifiers in lab maps.
* @param i
* @param chadoId
* @param intermineObjectId
* @throws ObjectStoreException
*/
private void storeInLabMaps(Item i, String labName, Integer intermineObjectId)
throws ObjectStoreException {
if ("Lab".equals(i.getClassName())) {
labIdMap .put(labName, intermineObjectId);
labIdRefMap .put(labName, i.getIdentifier());
} else {
throw new IllegalArgumentException(
"Type mismatch: expecting Lab, getting "
+ i.getClassName().substring(37) + " with intermineObjectId = "
+ intermineObjectId + ", lab = " + labName);
}
debugMap .put(i.getIdentifier(), i.getClassName());
}
private void mapSubmissionAndData(Integer submissionId, Integer dataId) {
Util.addToListMap(submissionDataMap, submissionId, dataId);
dataSubmissionMap.put(dataId, submissionId);
}
/**
* method to wrap the execution of a query, without log info
* @param connection
* @param query
* @return the result set
* @throws SQLException
*/
private ResultSet doQuery(Connection connection, String query)
throws SQLException {
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
/**
* method to wrap the execution of a query with log info)
* @param connection
* @param query
* @param comment for not logging
* @return the result set
* @throws SQLException
*/
private ResultSet doQuery(Connection connection, String query, String comment)
throws SQLException {
// we could avoid passing comment if we trace the calling method
// new Throwable().fillInStackTrace().getStackTrace()[1].getMethodName()
LOG.info("executing: " + query);
long bT = System.currentTimeMillis();
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
LOG.info("QUERY TIME " + comment + ": " + (System.currentTimeMillis() - bT) + " ms");
return res;
}
/**
* adds an element to a list which is the value of a map
* @param m the map (<Integer, List<String>>)
* @param key the key for the map
* @param value the list
*/
private static void addToMap(Map<Integer, List<String>> m, Integer key, String value) {
List<String> ids = new ArrayList<String>();
if (m.containsKey(key)) {
ids = m.get(key);
}
if (!ids.contains(value)) {
ids.add(value);
m.put(key, ids);
}
}
}
|
package gov.nih.nci.cagrid.data.service;
import gov.nih.nci.cagrid.common.FaultHelper;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults;
import gov.nih.nci.cagrid.data.DataServiceConstants;
import gov.nih.nci.cagrid.data.MalformedQueryException;
import gov.nih.nci.cagrid.data.QueryProcessingException;
import gov.nih.nci.cagrid.data.QueryProcessorConstants;
import gov.nih.nci.cagrid.data.cql.CQLQueryProcessor;
import gov.nih.nci.cagrid.data.cql.LazyCQLQueryProcessor;
import gov.nih.nci.cagrid.data.cql2.CQL1toCQL2Converter;
import gov.nih.nci.cagrid.data.cql2.CQL2QueryProcessor;
import gov.nih.nci.cagrid.data.mapping.Mappings;
import gov.nih.nci.cagrid.data.utilities.CQLQueryResultsIterator;
import gov.nih.nci.cagrid.metadata.dataservice.DomainModel;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.wsrf.Resource;
import org.globus.wsrf.ResourceContext;
import org.oasis.wsrf.faults.BaseFaultType;
/**
* BaseDataServiceImpl
* Base class of data service implementations. Handles common functionality
* such as query processor instantiation, CQL query conversion, and basic
* auditing support.
*
* @author David
*/
public abstract class BaseDataServiceImpl {
private static Log LOG = LogFactory.getLog(BaseDataServiceImpl.class);
private byte[] serverConfigBytes = null;
private Properties dataServiceConfig = null;
private DomainModel domainModel = null;
private CQLQueryProcessor cql1QueryProcessor = null;
private CQL2QueryProcessor cql2QueryProcessor = null;
private Properties cql1ProcessorConfig = null;
private Properties cql2ProcessorConfig = null;
private CqlValidationUtil queryValidator = null;
private CQL1toCQL2Converter cql1to2converter = null;
public BaseDataServiceImpl() throws DataServiceInitializationException {
initialize();
}
private void initialize() throws DataServiceInitializationException {
// load the core data service infrastructure configuration
LOG.debug("Loading data service configuration properties");
try {
dataServiceConfig = ServiceConfigUtil.getDataServiceParams();
} catch (Exception ex) {
throw new DataServiceInitializationException(
"Error getting data service configuration parameters: " + ex.getMessage(), ex);
}
// load the domain model
LOG.debug("Attempting to locate Domain Model in base resource");
Resource serviceBaseResource;
try {
serviceBaseResource = ResourceContext.getResourceContext().getResource();
} catch (Exception ex) {
throw new DataServiceInitializationException("Error obtaining base resource: " + ex.getMessage(), ex);
}
Method[] resourceMethods = serviceBaseResource.getClass().getMethods();
for (Method method : resourceMethods) {
if (method.getReturnType() != null
&& method.getReturnType().equals(DomainModel.class)) {
try {
domainModel = (DomainModel) method.invoke(serviceBaseResource, new Object[] {});
} catch (Exception ex) {
throw new DataServiceInitializationException("Error invoking method "
+ method.getName() + " of base resource to obtain the Domain Model: "
+ ex.getMessage(), ex);
}
break;
}
}
if (domainModel != null) {
LOG.debug("Domain Model found in base resource");
} else {
LOG.warn("Domain Model NOT FOUND in base resource");
}
// initialize the query validator
LOG.debug("Initializing query validator");
queryValidator = new CqlValidationUtil(dataServiceConfig, domainModel);
// set up the query conversion tools
LOG.debug("Setting up query conversion tools");
cql1to2converter = new CQL1toCQL2Converter(domainModel);
// load the server-config.wsdd into memory
try {
String serverConfigLocation = ServiceConfigUtil.getConfigProperty(
DataServiceConstants.SERVER_CONFIG_LOCATION);
LOG.debug("Loading server side wsdd from " + serverConfigLocation);
InputStream configStream = new FileInputStream(serverConfigLocation);
serverConfigBytes = Utils.inputStreamToStringBuffer(configStream).toString().getBytes();
} catch (Exception ex) {
throw new DataServiceInitializationException("Error loading server config wsdd: " + ex.getMessage(), ex);
}
}
protected Properties getDataServiceConfig() {
return dataServiceConfig;
}
protected DomainModel getDomainModel() {
return domainModel;
}
protected InputStream getServerConfigWsddStream() {
return new ByteArrayInputStream(serverConfigBytes);
}
/**
* Helper method to easily and consistently create a typed exception
*
* @param cause
* @param fault
* @return
*/
protected Exception getTypedException(Exception cause, BaseFaultType fault) {
FaultHelper helper = new FaultHelper(fault);
helper.addFaultCause(cause);
helper.setDescription(cause.getClass().getSimpleName() + " -- " + cause.getMessage());
return helper.getFault();
}
/**
* Gets the cql query processor configuration properties specified in
* the service's deploy.properties and therefore JNDI at runtime.
*
* This will NOT return the default properties for the query processor
*
* @return
* The configured cql query processor properties available
* at runtime in the JNDI
* @throws QueryProcessingException
*/
protected Properties getCql1QueryProcessorConfig() throws QueryProcessingException {
if (cql1ProcessorConfig == null) {
LOG.debug("Loading CQL query processor configuration properties");
try {
cql1ProcessorConfig = ServiceConfigUtil.getQueryProcessorConfigurationParameters();
} catch (Exception ex) {
throw new QueryProcessingException(
"Error getting query processor configuration parameters: " + ex.getMessage(), ex);
}
}
// clone the query processor config instance
Properties clone = new Properties();
Enumeration<?> keyEnumeration = cql1ProcessorConfig.keys();
while (keyEnumeration.hasMoreElements()) {
String key = (String) keyEnumeration.nextElement();
String value = cql1ProcessorConfig.getProperty(key);
clone.setProperty(key, value);
}
return clone;
}
/**
* Gets the cql 2 query processor configuration properties specified in
* the service's deploy.properties and therefore JNDI at runtime.
*
* This will NOT return the default properties for the query processor
*
* @return
* The configured cql query processor properties available
* at runtime in the JNDI
* @throws QueryProcessingException
*/
protected Properties getCql2QueryProcessorConfig() throws QueryProcessingException {
if (cql2ProcessorConfig == null) {
LOG.debug("Loading CQL query processor configuration properties");
try {
cql2ProcessorConfig = ServiceConfigUtil.getCql2QueryProcessorConfigurationParameters();
} catch (Exception ex) {
throw new QueryProcessingException(
"Error getting query processor configuration parameters: " + ex.getMessage(), ex);
}
}
// clone the query processor config instance
Properties clone = new Properties();
Enumeration<?> keyEnumeration = cql2ProcessorConfig.keys();
while (keyEnumeration.hasMoreElements()) {
String key = (String) keyEnumeration.nextElement();
String value = cql2ProcessorConfig.getProperty(key);
clone.setProperty(key, value);
}
return clone;
}
/**
* Processes a CQL query using the CQL query processor, performing any
* necessary conversions to / from CQL 2
*
* @param query
* @return
* @throws QueryProcessingException
* @throws MalformedQueryException
*/
public CQLQueryResults processCql1Query(CQLQuery query) throws QueryProcessingException, MalformedQueryException {
// TODO:
// 1. Validate query
// 2. If can process native, process and return
// 3. Else, convert, process w/ CQL 2, convert results, return
queryValidator.validateCql1Query(query);
CQLQueryResults results = null;
boolean processNative = true;
try {
processNative = hasNativeCql1Processor();
} catch (Exception ex) {
throw new QueryProcessingException(
"Error determining if a native CQL 1 query processor has been configured: " + ex.getMessage(), ex);
}
if (processNative) {
LOG.debug("Processing CQL 1 query with native query processor");
results = getCql1QueryProcessor().processQuery(query);
} else {
LOG.debug("Converting CQL 1 to CQL 2 for non-native processing");
org.cagrid.cql2.CQLQuery cql2Query = cql1to2converter.convertToCql2Query(query);
org.cagrid.cql2.results.CQLQueryResults cql2Results = processCql2Query(cql2Query);
// TODO: converter to turn CQL 2 results into CQL 1
}
return results;
}
public Iterator<?> processCql1QueryAndIterate(CQLQuery query) throws QueryProcessingException, MalformedQueryException {
Iterator<?> resultsIterator = null;
boolean processNative = true;
try {
processNative = hasNativeCql1Processor();
} catch (Exception ex) {
throw new QueryProcessingException(
"Error determining if a native CQL 1 query processor has been configured: " + ex.getMessage(), ex);
}
if (processNative && getCql1QueryProcessor() instanceof LazyCQLQueryProcessor) {
// if we can natively handle the query with a lazy implementation, do so
queryValidator.validateCql1Query(query);
resultsIterator = ((LazyCQLQueryProcessor) getCql1QueryProcessor()).processQueryLazy(query);
} else {
// process normally and wrap the results with an iterator
CQLQueryResults results = processCql1Query(query);
resultsIterator = new CQLQueryResultsIterator(results, getServerConfigWsddStream());
}
return resultsIterator;
}
public org.cagrid.cql2.results.CQLQueryResults processCql2Query(org.cagrid.cql2.CQLQuery query) throws QueryProcessingException, MalformedQueryException {
// TODO:
// 1. Validate query
// 2. If can process native, process and return
// 3. Else, convert, process w/ CQL 1, convert results, return
queryValidator.validateCql2Query(query);
org.cagrid.cql2.results.CQLQueryResults results = null;
boolean processNative = true;
try {
processNative = hasNativeCql2Processor();
} catch (Exception ex) {
throw new QueryProcessingException(
"Error determining if a native CQL 2 query processor has been configured: " + ex.getMessage(), ex);
}
if (processNative) {
LOG.debug("Processing CQL 2 query with native query processor");
results = getCql2QueryProcessor().processQuery(query);
} else {
LOG.debug("Converting CQL 2 to CQL 1 for non-native processing");
// TODO: convert query and results
}
return results;
}
public Iterator<org.cagrid.cql2.results.CQLResult> processCql2QueryAndIterate(org.cagrid.cql2.CQLQuery query) throws QueryProcessingException, MalformedQueryException {
queryValidator.validateCql2Query(query);
Iterator<org.cagrid.cql2.results.CQLResult> resultsIterator = null;
boolean processNative = true;
try {
processNative = hasNativeCql2Processor();
} catch (Exception ex) {
throw new QueryProcessingException(
"Error determining if a native CQL 2 query processor has been configured: " + ex.getMessage(), ex);
}
if (processNative) {
LOG.debug("Processing CQL 2 query with native query processor");
resultsIterator = getCql2QueryProcessor().processQueryAndIterate(query);
} else {
LOG.debug("Converting CQL 2 to CQL 1 for non-native processing");
// TODO: convert query and results
}
return resultsIterator;
}
private CQLQueryProcessor getCql1QueryProcessor() throws QueryProcessingException {
if (cql1QueryProcessor != null) {
LOG.debug("Instantiating CQL query processor");
// get the query processor's class
String qpClassName = null;
try {
qpClassName = ServiceConfigUtil.getCqlQueryProcessorClassName();
LOG.debug("CQL Query Processor class name is " + qpClassName);
} catch (Exception ex) {
throw new QueryProcessingException(
"Error determining query processor class name: " + ex.getMessage(), ex);
}
Class<?> cqlQueryProcessorClass = null;
try {
cqlQueryProcessorClass = Class.forName(qpClassName);
} catch (ClassNotFoundException ex) {
throw new QueryProcessingException(
"Error loading query processor class: " + ex.getMessage(), ex);
}
// create a new instance of the query processor
try {
cql1QueryProcessor = (CQLQueryProcessor) cqlQueryProcessorClass.newInstance();
} catch (Exception ex) {
throw new QueryProcessingException(
"Error creating query processor instance: " + ex.getMessage(), ex);
}
// configure the instance
LOG.debug("Configuring CQL query processor");
try {
String serverConfigLocation = ServiceConfigUtil.getConfigProperty(
DataServiceConstants.SERVER_CONFIG_LOCATION);
InputStream configStream = new FileInputStream(serverConfigLocation);
Properties configuredProperties = getCql1QueryProcessorConfig();
Properties defaultProperties = cql1QueryProcessor.getRequiredParameters();
Properties unionProperties = new Properties();
Enumeration<?> defaultKeys = defaultProperties.keys();
while (defaultKeys.hasMoreElements()) {
String key = (String) defaultKeys.nextElement();
String value = null;
if (configuredProperties.keySet().contains(key)) {
value = configuredProperties.getProperty(key);
} else {
value = defaultProperties.getProperty(key);
}
unionProperties.setProperty(key, value);
}
cql1QueryProcessor.initialize(unionProperties, configStream);
} catch (Exception ex) {
throw new QueryProcessingException("Error initializing query processor: " + ex.getMessage(), ex);
}
}
return cql1QueryProcessor;
}
private CQL2QueryProcessor getCql2QueryProcessor() throws QueryProcessingException {
if (cql2QueryProcessor != null) {
LOG.debug("Instantiating CQL 2 query processor");
// get the query processor's class
String qpClassName = null;
try {
qpClassName = ServiceConfigUtil.getCql2QueryProcessorClassName();
LOG.debug("CQL 2 Query Processor class name is " + qpClassName);
} catch (Exception ex) {
throw new QueryProcessingException(
"Error determining query processor class name: " + ex.getMessage(), ex);
}
Class<?> cqlQueryProcessorClass = null;
try {
cqlQueryProcessorClass = Class.forName(qpClassName);
} catch (ClassNotFoundException ex) {
throw new QueryProcessingException(
"Error loading query processor class: " + ex.getMessage(), ex);
}
// create a new instance of the query processor
try {
cql2QueryProcessor = (CQL2QueryProcessor) cqlQueryProcessorClass.newInstance();
} catch (Exception ex) {
throw new QueryProcessingException(
"Error creating query processor instance: " + ex.getMessage(), ex);
}
// configure the instance
LOG.debug("Configuring CQL 2 query processor");
try {
String serverConfigLocation = ServiceConfigUtil.getConfigProperty(
DataServiceConstants.SERVER_CONFIG_LOCATION);
InputStream configStream = new FileInputStream(serverConfigLocation);
Properties configuredProperties = getCql2QueryProcessorConfig();
Properties defaultProperties = cql2QueryProcessor.getRequiredParameters();
Properties unionProperties = new Properties();
Enumeration<?> defaultKeys = defaultProperties.keys();
while (defaultKeys.hasMoreElements()) {
String key = (String) defaultKeys.nextElement();
String value = null;
if (configuredProperties.keySet().contains(key)) {
value = configuredProperties.getProperty(key);
} else {
value = defaultProperties.getProperty(key);
}
unionProperties.setProperty(key, value);
}
// get the mapping file name
String filename = ServiceConfigUtil.getClassToQnameMappingsFile();
// deserialize the mapping file
Mappings mappings = Utils.deserializeDocument(filename, Mappings.class);
cql2QueryProcessor.configure(unionProperties, configStream, mappings);
} catch (Exception ex) {
throw new QueryProcessingException("Error initializing query processor: " + ex.getMessage(), ex);
}
}
return cql2QueryProcessor;
}
private boolean hasNativeCql1Processor() throws Exception {
boolean hasProcessor = false;
if (ServiceConfigUtil.hasConfigProperty(QueryProcessorConstants.QUERY_PROCESSOR_CLASS_PROPERTY)) {
String processorClassname = ServiceConfigUtil.getCqlQueryProcessorClassName();
hasProcessor = processorClassname != null && processorClassname.length() != 0;
}
return hasProcessor;
}
private boolean hasNativeCql2Processor() throws Exception {
boolean hasProcessor = false;
if (ServiceConfigUtil.hasConfigProperty(QueryProcessorConstants.CQL2_QUERY_PROCESSOR_CLASS_PROPERTY)) {
String processorClassname = getDataServiceConfig().getProperty(QueryProcessorConstants.CQL2_QUERY_PROCESSOR_CLASS_PROPERTY);
hasProcessor = processorClassname != null && processorClassname.length() != 0;
}
return hasProcessor;
}
}
|
package com.orm;
import android.content.Context;
import com.orm.util.ContextUtil;
import com.orm.util.ManifestHelper;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
public class SugarContext {
private static SugarContext instance = null;
private SugarDb sugarDb;
private Map<Object, Long> entitiesMap;
private SugarContext() {
ManifestHelper.loadDebugEnabled();
this.sugarDb = SugarDb.getInstance();
this.entitiesMap = Collections.synchronizedMap(new WeakHashMap<Object, Long>());
}
public static SugarContext getSugarContext() {
if (instance == null) {
throw new NullPointerException("SugarContext has not been initialized properly. Call SugarContext.init(Context) in your Application.onCreate() method and SugarContext.terminate() in your Application.onTerminate() method.");
}
return instance;
}
public static void init(Context context) {
ContextUtil.init(context);
instance = new SugarContext();
}
public static void terminate() {
if (instance == null) {
return;
}
instance.doTerminate();
ContextUtil.terminate();
}
/*
* Per issue #106 on Github, this method won't be called in
* any real Android device. This method is used purely in
* emulated process environments such as an emulator or
* Robolectric Android mock.
*/
private void doTerminate() {
if (this.sugarDb != null) {
this.sugarDb.getDB().close();
}
}
public SugarDb getSugarDb() {
return sugarDb;
}
Map<Object, Long> getEntitiesMap() {
return entitiesMap;
}
}
|
package org.semanticweb.clipper.hornshiq.cli;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import lombok.Getter;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.util.ShortFormProvider;
import org.semanticweb.owlapi.util.SimpleShortFormProvider;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameters;
@Parameters(commandNames = { "load" }, separators = "=", commandDescription = "Load ABox facts to Database")
public class CommandLoad extends DBCommandBase {
private Connection conn;
public CommandLoad(JCommander jc) {
super(jc);
}
@Override
boolean validate() {
// TODO Auto-generated method stub
return true;
}
Map<String, Integer> concept2IdMap = new HashMap<String, Integer>();
Map<String, Integer> objectRole2IdMap = new HashMap<String, Integer>();
Map<String, Integer> individual2IdMap = new HashMap<String, Integer>();;
@Override
void exec() {
long t1 = System.currentTimeMillis();
conn = createConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
ShortFormProvider sfp = new SimpleShortFormProvider();
OWLOntology ontology = null;
try {
for (String ontologyFile : this.getOntologyFiles()) {
ontology = manager.loadOntologyFromOntologyDocument(new File(
ontologyFile));
// insertConcepts(stmt, sfp, ontology);
// insertObjectRoles(stmt, sfp, ontology);
insertIndividuals(stmt, ontology);
// insertConceptAssertions(stmt, sfp, ontology);
// insertObjectRoleAssertions(stmt, sfp, ontology);
// manager.removeOntology(ontology);
// stmt.executeBatch();
System.err.println(ontologyFile + " loaded!");
}
stmt.close();
} catch (OWLOntologyCreationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long t2 = System.currentTimeMillis();
System.out.println("TIME: " + (t2 - t1));
}
//@SuppressWarnings("unused")
private void insertIndividuals(Statement stmt, OWLOntology ontology) {
Set<OWLNamedIndividual> individuals = ontology
.getIndividualsInSignature();
if (true) {
StringBuilder exisitingValuesBuilder = new StringBuilder();
Set<String> newInds = new HashSet<String>();
boolean first = true;
for (OWLNamedIndividual ind : individuals) {
newInds.add(ind.toString());
if (!first)
exisitingValuesBuilder.append(",");
first = false;
exisitingValuesBuilder.append("('").append(ind).append("')");
}
StringBuilder sqlExistingNamesBuilder = new StringBuilder();
sqlExistingNamesBuilder.append("SELECT individual_name.name FROM (VALUES ");
sqlExistingNamesBuilder.append(exisitingValuesBuilder.toString());
sqlExistingNamesBuilder
.append(") AS foo (name), individual_name WHERE foo.name = individual_name.name");
StringBuilder sqlCountNewValuesBuilder = new StringBuilder();
sqlCountNewValuesBuilder.append("SELECT COUNT(*) FROM (VALUES ");
sqlCountNewValuesBuilder.append(exisitingValuesBuilder.toString());
sqlCountNewValuesBuilder.append(") AS foo (name)");
StringBuilder sqlBuilder3 = new StringBuilder();
sqlBuilder3
.append("SELECT individual_name.id, individual_name.name FROM (VALUES ");
sqlBuilder3.append(exisitingValuesBuilder.toString());
sqlBuilder3
.append(") AS foo (name), individual_name WHERE foo.name = individual_name.name");
try {
Set<String> existingInds = new HashSet<String>();
Statement statement = conn.createStatement();
//System.out.println(sqlBuilder1);
ResultSet rs = statement.executeQuery(sqlExistingNamesBuilder.toString());
while (rs.next()) {
String ind = rs.getString(1);
existingInds.add(ind);
}
newInds.removeAll(existingInds);
if (newInds.size() > 0) {
StringBuilder newValuesBuilder = new StringBuilder();
first = true;
for (String ind : newInds) {
if (!first)
newValuesBuilder.append(",");
first = false;
newValuesBuilder.append("('").append(ind).append("')");
}
StringBuilder sqlBuilder4 = new StringBuilder();
sqlBuilder4
.append("INSERT INTO individual_name(name) VALUES ");
sqlBuilder4.append(newValuesBuilder.toString());
System.err.println(sqlBuilder4);
int i = statement.executeUpdate(sqlBuilder4.toString());
System.err.println("i=" + i);
}
// System.out.println(sqlBuilder2);
// ResultSet rs2 =
// statement.executeQuery(sqlBuilder2.toString());
// while (rs2.next()) {
// System.out.println(rs2.getInt(1));
//System.out.println(sqlBuilder3);
ResultSet rs3 = statement.executeQuery(sqlBuilder3.toString());
while (rs3.next()) {
//System.out.println(rs3.getInt(1) + " " + rs3.getString(2));
individual2IdMap.put(rs3.getString(2), rs3.getInt(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
if (false) {
String sql = "insert INTO individual_name (name)"
+ "SELECT (?)"
+ "WHERE NOT EXISTS (SELECT * FROM individual_name WHERE name=?) ";
try {
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn
.prepareStatement(sql);
for (OWLNamedIndividual ind : individuals) {
preparedStatement.setString(1, ind.toString());
preparedStatement.setString(2, ind.toString());
preparedStatement.executeUpdate();
conn.commit();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private void insertConcepts(Statement stmt, ShortFormProvider sfp,
OWLOntology ontology) throws SQLException {
Set<OWLClass> classes = ontology.getClassesInSignature(true);
for (OWLClass cls : classes) {
String clsName = sfp.getShortForm(cls).toLowerCase();
String sql = String
.format("INSERT INTO predicate_name (name)"
+ "SELECT ('%s')"
+ "WHERE NOT EXISTS (SELECT * FROM predicate_name WHERE name='%s') ",
clsName, clsName);
stmt.addBatch(sql);
// stmt.execute(sql);
sql = String.format("DROP TABLE IF EXISTS %s CASCADE", clsName);
stmt.addBatch(sql);
// stmt.execute(sql);
sql = String.format("CREATE TABLE %s ("
+ "individual integer NOT NULL )", clsName);
stmt.addBatch(sql);
// stmt.execute(sql);
}
}
private void insertObjectRoles(Statement stmt, ShortFormProvider sfp,
OWLOntology ontology) throws SQLException {
Set<OWLObjectProperty> objectProperties = ontology
.getObjectPropertiesInSignature(true);
for (OWLObjectProperty property : objectProperties) {
String propertyName = sfp.getShortForm(property).toLowerCase();
String sql = String
.format("INSERT INTO predicate_name (name)"
+ "SELECT ('%s')"
+ "WHERE NOT EXISTS (SELECT * FROM predicate_name WHERE name='%s') ",
propertyName, propertyName);
stmt.addBatch(sql);
// stmt.execute(sql);
sql = String
.format("DROP TABLE IF EXISTS %s CASCADE", propertyName);
stmt.addBatch(sql);
// stmt.execute(sql);
sql = String.format("CREATE TABLE %s ("
+ "a integer NOT NULL, "
+ "b integer NOT NULL" + " )", propertyName);
stmt.addBatch(sql);
// stmt.execute(sql);
}
}
private void insertConceptAssertions(Statement stmt, ShortFormProvider sfp,
OWLOntology ontology) throws SQLException {
Set<OWLClassAssertionAxiom> classAssertionAxioms = ontology.getAxioms(
AxiomType.CLASS_ASSERTION, false);
String sql = "INSERT INTO concept_assertion (concept , individual) "
+ "SELECT predicate_name.id, individual_name.id "
+ "FROM predicate_name, individual_name "
+ "WHERE predicate_name.name = ? and individual_name.name = ?"
+ "AND NOT EXISTS (SELECT * FROM concept_assertion "
+ "WHERE predicate_name.id = concept_assertion.concept "
+ " AND individual_name.id = concept_assertion.individual)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
for (OWLClassAssertionAxiom axiom : classAssertionAxioms) {
OWLClassExpression classExpression = axiom.getClassExpression();
String tableName = sfp.getShortForm(classExpression.asOWLClass())
.toLowerCase();
preparedStatement.setString(1, tableName);
preparedStatement.setString(2, axiom.getIndividual().toString());
preparedStatement.executeUpdate();
conn.commit();
// String sql = String
// .format("INSERT INTO concept_assertion (concept , individual) "
// "SELECT predicate_name.id, individual_name.id "
// "FROM predicate_name, individual_name "
// "WHERE predicate_name.name = '%s' and individual_name.name = '%s'"
// + "AND NOT EXISTS (SELECT * FROM concept_assertion "
// + "WHERE predicate_name.id = concept_assertion.concept "
// + " AND individual_name.id = concept_assertion.individual)",
// tableName, axiom.getIndividual());
// stmt.addBatch(sql);
// stmt.execute(sql);
}
}
private void insertObjectRoleAssertions(Statement stmt,
ShortFormProvider sfp, OWLOntology ontology) throws SQLException {
Set<OWLObjectPropertyAssertionAxiom> objectRoleAssertionAxioms = ontology
.getAxioms(AxiomType.OBJECT_PROPERTY_ASSERTION, false);
for (OWLObjectPropertyAssertionAxiom axiom : objectRoleAssertionAxioms) {
OWLObjectProperty property = axiom.getProperty()
.asOWLObjectProperty();
String tableName = sfp.getShortForm(property).toLowerCase();
String sql = String
.format("INSERT INTO object_role_assertion (object_role, a, b) "
+ "SELECT predicate_name.id, ind1.id, ind2.id "
+ "FROM predicate_name, individual_name as ind1, individual_name as ind2 "
+ "WHERE predicate_name.name = '%s' and ind1.name = '%s' and ind2.name = '%s'"
+ "AND NOT EXISTS (SELECT * FROM object_role_assertion "
+ "WHERE predicate_name.id = object_role_assertion.object_role "
+ " AND ind1.id = object_role_assertion.a"
+ " AND ind2.id = object_role_assertion.b)",
tableName, axiom.getSubject(), axiom.getObject());
stmt.addBatch(sql);
// stmt.execute(sql);
}
}
}
|
package com.tazine.thread.sync.unstable;
/**
* VolatileTest
*
* @author frank
* @date 2017/8/31
*/
public class VolatileTest {
private static volatile boolean runFlag = true;
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
for (; ; ) {
if (runFlag == !runFlag) {
System.out.println("");
System.exit(0);
}
}
}
}.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread() {
@Override
public void run() {
for (; ; ) {
runFlag = !runFlag;
}
}
}.start();
}
}
|
public class Orc implements Monster {
private int currentHitpoints;
public Orc(){
this.currentHitpoints = 20;
}
public Orc(int hitpoints) {
this.currentHitpoints = hitpoints;
}
public void takeDamage(int amount){
this.currentHitpoints -= amount;
}
public String name(){
return "Orc";
}
public int currentHitpoints(){
return currentHitpoints;
}
}
|
package com.griddynamics.jagger.user.test.configurations.limits;
import com.griddynamics.jagger.user.test.configurations.limits.auxiliary.LowErrThresh;
import com.griddynamics.jagger.user.test.configurations.limits.auxiliary.LowWarnThresh;
import com.griddynamics.jagger.user.test.configurations.limits.auxiliary.UpWarnThresh;
import com.griddynamics.jagger.user.test.configurations.limits.auxiliary.UpErrThresh;
import java.util.Objects;
/**
* Allow to compare your results with predefined reference values or baseline session values
* and decide whether performance of your system meet acceptance criteria or not. As a result of comparison you
* can make decision and mark this test session with status flag (OK, WARNING, FATAL, ERROR).
* In WebUI and PDF report summary values will be highlighted according to results of comparison.
*/
public abstract class JLimit {
private final String metricName;
private final Double lowWarnThresh;
private final Double upperWarningThreshold;
private final Double lowerErrorThreshold;
private final Double upperErrorThreshold;
JLimit(Builder builder) {
this.metricName = builder.metricName;
this.lowWarnThresh = builder.lowWarnThresh.value();
this.upperWarningThreshold = builder.upWarnThresh.value();
this.lowerErrorThreshold = builder.lowErrThresh.value();
this.upperErrorThreshold = builder.upErrThresh.value();
}
public abstract static class Builder {
String metricName;
LowWarnThresh lowWarnThresh = LowWarnThresh.of(1.0);
UpWarnThresh upWarnThresh = UpWarnThresh.of(1.0);
LowErrThresh lowErrThresh = LowErrThresh.of(1.0);
UpErrThresh upErrThresh = UpErrThresh.of(1.0);
// I'm really sorry for that, but I have no idea how to do it better.
private boolean initialized;
/**
* Set limits for warnings criteria only.
* Cannot be initialized more than once.
*
* @param lowWarnThresh lower warning threshold.
* @param upWarnThresh upper warning threshold.
*/
public Builder withOnlyWarnings(LowWarnThresh lowWarnThresh, UpWarnThresh upWarnThresh) {
if (initialized) {
throw new IllegalArgumentException("It is already initialized with values: " +
this.lowWarnThresh + ", " + this.lowErrThresh + ", " + this.upWarnThresh + ", " + this.upErrThresh);
}
Objects.requireNonNull(lowWarnThresh);
Objects.requireNonNull(upWarnThresh);
this.lowErrThresh = LowErrThresh.of(Double.NEGATIVE_INFINITY);
this.upErrThresh = UpErrThresh.of(Double.POSITIVE_INFINITY);
this.lowWarnThresh = lowWarnThresh;
this.upWarnThresh = upWarnThresh;
initialized = true;
return this;
}
/**
* Set limits for errors criteria only.
* Cannot be initialized more than once.
*
* @param lowErrThresh lower error threshold.
* @param upErrThresh upper error threshold.
*/
public Builder withOnlyErrors(LowErrThresh lowErrThresh, UpErrThresh upErrThresh) {
if (initialized) {
throw new IllegalArgumentException("It is already initialized with values: " +
this.lowWarnThresh + ", " + this.lowErrThresh + ", " + this.upWarnThresh + ", " + this.upErrThresh);
}
Objects.requireNonNull(lowErrThresh);
Objects.requireNonNull(upErrThresh);
this.lowErrThresh = lowErrThresh;
this.upErrThresh = upErrThresh;
this.lowWarnThresh = LowWarnThresh.of(this.lowErrThresh.value());
this.upWarnThresh = UpWarnThresh.of(this.upErrThresh.value());
initialized = true;
return this;
}
/**
* Set limits for upper limits only.
* Cannot be initialized more than once.
*
* @param upWarnThresh upper warning threshold.
* @param upErrThresh upper error threshold.
*/
public Builder withOnlyUpperThresholds(UpWarnThresh upWarnThresh, UpErrThresh upErrThresh) {
if (initialized) {
throw new IllegalArgumentException("It is already initialized with values: " +
this.lowWarnThresh + ", " + this.lowErrThresh + ", " + this.upWarnThresh + ", " + this.upErrThresh);
}
Objects.requireNonNull(upWarnThresh);
Objects.requireNonNull(upErrThresh);
this.lowErrThresh = LowErrThresh.of(Double.NEGATIVE_INFINITY);
this.upErrThresh = upErrThresh;
this.lowWarnThresh = LowWarnThresh.of(Double.NEGATIVE_INFINITY);
this.upWarnThresh = upWarnThresh;
initialized = true;
return this;
}
/**
* Set limits for warnings criteria only.
* Cannot be initialized more than once.
*
* @param lowWarnThresh lower warning threshold.
* @param lowErrThresh lower error threshold.
*/
public Builder withOnlyLowerThresholds(LowWarnThresh lowWarnThresh, LowErrThresh lowErrThresh) {
if (initialized) {
throw new IllegalArgumentException("It is already initialized with values: " +
this.lowWarnThresh + ", " + this.lowErrThresh + ", " + this.upWarnThresh + ", " + this.upErrThresh);
}
Objects.requireNonNull(lowWarnThresh);
Objects.requireNonNull(lowErrThresh);
this.lowErrThresh = lowErrThresh;
this.upErrThresh = UpErrThresh.of(Double.POSITIVE_INFINITY);
this.lowWarnThresh = lowWarnThresh;
this.upWarnThresh = UpWarnThresh.of(Double.POSITIVE_INFINITY);
initialized = true;
return this;
}
/**
* Set all limits.
* Cannot be initialized more than once.
*
* @param lowWarnThresh lower warning threshold.
* @param lowErrThresh lower error threshold.
* @param upWarnThresh upper warning threshold.
* @param upErrThresh upper error threshold.
*/
public Builder withExactLimits(LowWarnThresh lowWarnThresh, LowErrThresh lowErrThresh, UpWarnThresh upWarnThresh, UpErrThresh upErrThresh) {
if (initialized) {
throw new IllegalArgumentException("It is already initialized with values: " +
this.lowWarnThresh + ", " + this.lowErrThresh + ", " + this.upWarnThresh + ", " + this.upErrThresh);
}
Objects.requireNonNull(lowWarnThresh);
Objects.requireNonNull(lowErrThresh);
Objects.requireNonNull(upWarnThresh);
Objects.requireNonNull(upErrThresh);
this.lowErrThresh = lowErrThresh;
this.upErrThresh = upErrThresh;
this.lowWarnThresh = lowWarnThresh;
this.upWarnThresh = upWarnThresh;
initialized = true;
return this;
}
/**
* Create {@link JLimit} instance.
* If non of methods that sets limits were called the default value 1.0 for all limits will be set.
*
* @return instance of {@link JLimit}.
*/
public abstract JLimit build();
}
public String getMetricName() {
return metricName;
}
public Double getLowWarnThresh() {
return lowWarnThresh;
}
public Double getUpperWarningThreshold() {
return upperWarningThreshold;
}
public Double getLowerErrorThreshold() {
return lowerErrorThreshold;
}
public Double getUpperErrorThreshold() {
return upperErrorThreshold;
}
}
|
import com.twilio.twiml.voice.Gather;
import com.twilio.twiml.VoiceResponse;
import com.twilio.twiml.voice.Say;
import com.twilio.twiml.TwiMLException;
public class Example {
public static void main(String[] args) {
Say say = new Say.Builder("Please press 1 or say sales for sales.")
.build();
Gather gather = new Gather.Builder().inputs(Gather.Input.DTMF_SPEECH)
.timeout(3).numDigits(1).say(say).build();
VoiceResponse response = new VoiceResponse.Builder().gather(gather)
.build();
try {
System.out.println(response.toXml());
} catch (TwiMLException e) {
e.printStackTrace();
}
}
}
|
package com.kirinpatel.gui;
import com.kirinpatel.Main;
import com.kirinpatel.net.Client;
import com.kirinpatel.net.Server;
import com.kirinpatel.util.Debug;
import com.kirinpatel.util.UIMessage;
import com.kirinpatel.util.User;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
/**
* @author Kirin Patel
* @version 0.0.3
* @date 6/21/17
*/
public class ControlPanel extends JPanel {
private JList connectedClients;
private JScrollPane connectedClientsScroll;
private JPanel mediaControlPanel;
private JTextField urlField;
private JButton setUrl;
private JPanel chatPanel;
private JPanel messagePanel;
private JTextArea chatWindow;
private JScrollPane chatWindowScroll;
private JTextField chatField;
private JButton send;
public ControlPanel(int type) {
super(new GridLayout(3, 1));
Debug.Log("Creating ControlPanel...", 3);
connectedClients = new JList();
connectedClients.setToolTipText("Connected Clients");
connectedClients.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
connectedClientsScroll = new JScrollPane(connectedClients);
connectedClientsScroll.setBorder(null);
add(connectedClientsScroll);
if (type == 0) {
mediaControlPanel = new JPanel(new GridLayout(2, 1));
urlField = new JTextField();
urlField.setToolTipText("Media URL");
mediaControlPanel.add(urlField);
setUrl = new JButton("Set Media URL");
setUrl.addActionListener(e -> {
if (!urlField.getText().isEmpty() && urlField.getText().endsWith(".mp4")) {
ServerGUI.mediaPanel.setMediaURL(urlField.getText());
} else if (urlField.getText().isEmpty()) {
if (!ServerGUI.mediaPanel.getMediaURL().isEmpty()) {
ServerGUI.mediaPanel.setMediaURL("");
} else {
Debug.Log("Media URL not specified!", 2);
new UIMessage("Error setting Media URL!", "The Media URL must be specified!", 1);
}
} else if (!urlField.getText().endsWith(".mp4")) {
Debug.Log("Media URL is not .mp4 format!", 2);
new UIMessage("Error setting Media URL!", "The Media URL must be of .mp4 format!", 1);
}
});
mediaControlPanel.add(setUrl);
add(mediaControlPanel);
} else {
add(new JPanel());
}
chatPanel = new JPanel(new BorderLayout());
chatWindow = new JTextArea();
chatWindow.setEditable(false);
chatWindow.setToolTipText("Chat Box");
chatWindowScroll = new JScrollPane(chatWindow);
chatWindowScroll.setBorder(null);
chatPanel.add(chatWindowScroll, BorderLayout.CENTER);
messagePanel = new JPanel(new BorderLayout());
chatField = new JTextField();
chatField.setToolTipText("Message Box");
chatField.addActionListener(new ControlPanel.SendMessageListener(type));
messagePanel.add(chatField, BorderLayout.CENTER);
send = new JButton("Send");
send.addActionListener(new ControlPanel.SendMessageListener(type));
messagePanel.add(send, BorderLayout.EAST);
chatPanel.add(messagePanel, BorderLayout.SOUTH);
add(chatPanel);
if (Main.isDarkModeEnabled) {
setBackground(Color.black);
connectedClients.setBackground(Color.black);
Color foreground = getBackground();
connectedClients.setForeground(foreground);
mediaControlPanel.setBackground(Color.black);
urlField.setBackground(Color.black);
urlField.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(7, 2, 7, 2), BorderFactory.createLineBorder(foreground, 3, true)));
urlField.setForeground(foreground);
setUrl.setBackground(Color.black);
setUrl.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2), BorderFactory.createLineBorder(foreground, 3, true)));
setUrl.setForeground(foreground);
chatPanel.setBackground(Color.black);
messagePanel.setBackground(Color.black);
chatWindow.setBackground(Color.black);
chatWindow.setForeground(foreground);
chatField.setBackground(Color.black);
chatField.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(7, 2, 7, 2), BorderFactory.createLineBorder(foreground, 3, true)));
chatField.setForeground(foreground);
send.setBackground(Color.black);
send.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2), BorderFactory.createLineBorder(foreground, 3, true)));
send.setForeground(foreground);
}
Debug.Log("ControlPanel created.", 3);
}
public void resizePanel(int width, int height) {
width = ((width - (height * 16 / 9)) < 200) ? 200 : width - (height * 16 / 9);
if (urlField != null) urlField.setPreferredSize(new Dimension(width, height / 3));
connectedClientsScroll.setPreferredSize(new Dimension(width, height / 3));
}
public void updateConnectedClients(ArrayList<User> users) {
Debug.Log("Updating connected clients in gui...", 3);
DefaultListModel listModel = new DefaultListModel();
for (User user : users) {
listModel.addElement(user);
}
connectedClients.setModel(listModel);
Debug.Log("Connected clients updated in gui.", 3);
}
public void setMessages(ArrayList<String> messages) {
chatWindow.setText("");
for (String message : messages) {
if (messages.indexOf(message) != messages.size() - 1) {
chatWindow.append(message + "\n");
} else {
chatWindow.append(message);
}
}
chatWindowScroll.getVerticalScrollBar().setValue(chatWindowScroll.getVerticalScrollBar().getMaximum());
}
public void addMessages(ArrayList<String> messages) {
if (!chatWindow.getText().isEmpty()) {
chatWindow.append("\n");
}
for (String message : messages) {
chatWindow.append(message + "\n");
}
chatWindow.replaceRange("", chatWindow.getText().length() - 1, chatWindow.getText().length());
chatWindowScroll.getVerticalScrollBar().setValue(chatWindowScroll.getVerticalScrollBar().getMaximum());
}
class SendMessageListener implements ActionListener {
private int type;
public SendMessageListener(int type) {
this.type = type;
}
@Override
public void actionPerformed(ActionEvent e) {
if (!chatField.getText().isEmpty()) {
if (type == 0) {
Server.sendMessage(Server.connectedClients.get(0) + ": " + chatField.getText());
chatField.setText("");
} else {
Client.sendMessage(Client.user.getUsername() + ": " + chatField.getText());
chatField.setText("");
}
}
}
}
}
|
package es.deusto.weblab.client.lab.experiments.plugins.es.deusto.weblab.vm.ui;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import es.deusto.weblab.client.comm.exceptions.WlCommException;
import es.deusto.weblab.client.configuration.IConfigurationRetriever;
import es.deusto.weblab.client.dto.experiments.Command;
import es.deusto.weblab.client.dto.experiments.ResponseCommand;
import es.deusto.weblab.client.lab.comm.callbacks.IResponseCommandCallback;
import es.deusto.weblab.client.lab.experiments.plugins.es.deusto.weblab.xilinx.ui.WlDeustoXilinxBasedBoard;
import es.deusto.weblab.client.lab.ui.BoardBase;
import es.deusto.weblab.client.ui.widgets.WlPredictiveProgressBar;
import es.deusto.weblab.client.ui.widgets.WlTimer;
import es.deusto.weblab.client.ui.widgets.WlWaitingLabel;
import es.deusto.weblab.client.ui.widgets.WlPredictiveProgressBar.IProgressBarListener;
import es.deusto.weblab.client.ui.widgets.WlPredictiveProgressBar.IProgressBarTextUpdater;
import es.deusto.weblab.client.ui.widgets.WlPredictiveProgressBar.TextProgressBarTextUpdater;
import es.deusto.weblab.client.ui.widgets.WlTimer.IWlTimerFinishedCallback;
public class VMBoard extends BoardBase {
private static final String DEFAULT_VNC_HEIGHT = "900";
private static final String DEFAULT_VNC_WIDTH = "1152";
private static final String VNC_WIDTH = "vnc.width";
private static final String VNC_HEIGHT = "vnc.height";
interface VMBoardUiBinder extends UiBinder<Widget, VMBoard> {
}
private static final VMBoardUiBinder uiBinder = GWT.create(VMBoardUiBinder.class);
private static final int IS_READY_QUERY_TIMER = 1000;
public static class Style {
public static final String TIME_REMAINING = "wl-time_remaining";
public static final String CLOCK_ACTIVATION_PANEL = "wl-clock_activation_panel";
}
private final IConfigurationRetriever configurationRetriever;
// Root panel.
@UiField VerticalPanel widget;
@UiField WlWaitingLabel messages;
@UiField Label url;
@UiField VerticalPanel applets;
@UiField WlPredictiveProgressBar progressBar;
@UiField(provided = true) WlTimer timer;
private Timer readyTimer;
private String fullURLPassword = "";
private String protocol = "";
private boolean progressBarRun = false;
private boolean vmReady = false;
public VMBoard(IConfigurationRetriever configurationRetriever, IBoardBaseController commandSender) {
super(commandSender);
this.configurationRetriever = configurationRetriever;
this.createProvidedWidgets();
VMBoard.uiBinder.createAndBindUi(this);
}
/**
* Setup certain widgets that require it after the experiment has been
* started.
*/
private void setupWidgets() {
this.timer.setTimerFinishedCallback(new IWlTimerFinishedCallback(){
@Override
public void onFinished() {
VMBoard.this.boardController.onClean();
}
});
this.timer.start();
this.progressBar.setVisible(true);
this.readyTimer = new Timer() {
@Override
public void run() {
final Command command = new Command() {
@Override
public String getCommandString() {
return "is_ready";
}
};
VMBoard.this.boardController.sendCommand(command, new IResponseCommandCallback() {
@Override
public void onFailure(WlCommException e) {
VMBoard.this.setMessage("There was an error while trying to find out whether the Virtual Machine is ready");
VMBoard.this.progressBar.setTextUpdater(new IProgressBarTextUpdater() {
@Override
public String generateText(double progress) {
return "Error: Server not available";
}} );
if(VMBoard.this.progressBar.isWaiting()){
VMBoard.this.progressBar.stop();
VMBoard.this.progressBar.setVisible(false);
}else{
// Will automatically remove itself once it reaches 100%, when the
// finished callback gets called.
VMBoard.this.progressBar.finish(300);
}
}
@Override
public void onSuccess(ResponseCommand responseCommand) {
// Read the full message returned by the exp server and ensure it's not empty
final String resp = responseCommand.getCommandString();
if(resp.length() == 0)
VMBoard.this.setMessage("The is_ready query returned an empty result");
// It may come with an argument, in the format <code>;<arg>,
// so we split it to retrieve the <code> and the <arg>.
final String [] codeSplit = resp.split(";", 2);
final String codeStr;
if(codeSplit.length == 0)
codeStr = resp;
else
codeStr = codeSplit[0];
final String argStr;
if(codeSplit.length >= 2)
argStr = codeSplit[1];
else
argStr = "";
if(codeStr.equals("0")) {
// Not ready
VMBoard.this.setMessage("Your Virtual Machine is not yet ready. Please, wait. It often takes around " + argStr + " seconds.");
VMBoard.this.readyTimer.schedule(IS_READY_QUERY_TIMER);
if(!VMBoard.this.progressBar.isRunning() && !VMBoard.this.progressBarRun) {
VMBoard.this.progressBarRun = true;
final double estimatedSeconds = Double.parseDouble(argStr);
VMBoard.this.progressBar.setEstimatedTime((int) (estimatedSeconds * 1000));
VMBoard.this.progressBar.setResolution(40);
VMBoard.this.progressBar.setWaitPoint(0.9);
// The progress bar will automatically disappear as soon as it
// is full.
VMBoard.this.progressBar.setListener(new IProgressBarListener(){
@Override
public void onFinished() {
if(VMBoard.this.vmReady){
VMBoard.this.progressBar.setVisible(false);
}else{
VMBoard.this.progressBar.keepWaiting();
VMBoard.this.progressBar.setTextUpdater(new TextProgressBarTextUpdater("Finishing..."));
}
}});
VMBoard.this.progressBar.setTextUpdater(new IProgressBarTextUpdater() {
@Override
public String generateText(double progress) {
final long elapsed = VMBoard.this.progressBar.getElapsedTime();
if(elapsed > 1000 * (estimatedSeconds + 1)) {
VMBoard.this.setMessage("Setting up the VM is taking longer than expected. There might be some problem.");
return "Taking longer than expected.";
}
if(progress == 1) {
return "Done. VM is ready";
}
return "Loading, please wait (" + (int)(progress*100) + "%)";
}} );
VMBoard.this.progressBar.start();
}
} else if(codeStr.equals("1")) {
VMBoard.this.vmReady = true;
// Ready
VMBoard.this.setMessage("Your Virtual Machine is now ready!");
if(VMBoard.this.protocol.equals("vnc"))
loadVNCApplet();
if(VMBoard.this.progressBar.isWaiting()){
VMBoard.this.progressBar.stop();
VMBoard.this.progressBar.setVisible(false);
}else{
// Will automatically remove itself once it reaches 100%, when the
// finished callback gets called.
VMBoard.this.progressBar.finish(300);
}
} else {
VMBoard.this.vmReady = true;
// Unexpected answer
VMBoard.this.setMessage("Received unexpected response to the is_ready query");
VMBoard.this.progressBar.setTextUpdater(new IProgressBarTextUpdater() {
@Override
public String generateText(double progress) {
return "Error: Unexpected reply";
}} );
if(VMBoard.this.progressBar.isWaiting()){
VMBoard.this.progressBar.stop();
VMBoard.this.progressBar.setVisible(false);
}else{
// Will automatically remove itself once it reaches 100%, when the
// finished callback gets called.
VMBoard.this.progressBar.finish(300);
}
}
}
});
}
};
// We do not do a Repeating schedule because we want to wait for a response before asking again
this.readyTimer.schedule(IS_READY_QUERY_TIMER);
}
private void loadVNCApplet(){
this.applets.clear();
final Anchor anchor = new Anchor("Load Java applet VNC Client");
this.applets.add(anchor);
final String archive = GWT.getModuleBaseURL() + "vnc/tightvncviewer.jar";
final String code = "VncViewer.class";
final String width = this.configurationRetriever.getProperty(VNC_WIDTH, DEFAULT_VNC_WIDTH);
final String height = this.configurationRetriever.getProperty(VNC_HEIGHT, DEFAULT_VNC_HEIGHT);
final String [] tokens = this.fullURLPassword.split(" ");
// "vnc://host:port/ with password: asdf"
final String hostPort = tokens[0].split("//")[1].split("/")[0];
final String host;
final String port;
if(hostPort.indexOf(":") >= 0){
host = hostPort.split(":")[0];
port = hostPort.split(":")[1];
}else{
host = hostPort;
port = "5900"; // standard default VNC port
}
final String password = tokens[tokens.length - 1];
anchor.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
VMBoard.this.applets.clear();
final HTML appletHTML = new HTML();
appletHTML.setHTML("<applet archive='" + archive + "' " +
"code='" + code + "' " +
"width='" + width + "' " +
"height='" + height + "' " +
"> " +
"<PARAM NAME=\"PORT\" VALUE=\"" + port + "\"> " +
"<PARAM NAME=\"HOST\" VALUE=\"" + host + "\"> " +
"<PARAM NAME=\"PASSWORD\" VALUE=\"" + password + "\"> " +
"</applet>");
VMBoard.this.applets.add(appletHTML);
}
});
}
/* Creates those widgets that are placed through UiBinder but
* whose ctors need to take certain parameters and hence be
* instanced in code.
*/
private void createProvidedWidgets() {
this.timer = new WlTimer(false);
}
/**
* The initialize function gets called on the "reserve" stage,
* before the experiment starts.
*/
@Override
public void initialize(){
}
/**
* This function gets called just when the actual experiment starts, after
* the reserve is done and the queue is over.
*/
@Override
public void start() {
this.widget.setVisible(true);
this.setupWidgets();
this.setMessage("Obtaining VM config...");
this.sendGetConfigurationCommand();
this.progressBarRun = false;
}
@Override
public void setTime(int time) {
this.timer.updateTime(time);
}
@Override
public Widget getWidget() {
return this.widget;
}
@Override
public void end() {
if(this.timer != null){
this.timer.dispose();
this.timer = null;
}
if(this.progressBar != null)
this.progressBar.stop();
}
public void setMessage(String msg) {
this.messages.setText(msg);
}
private void sendGetConfigurationCommand(){
final Command command = new Command() {
@Override
public String getCommandString() {
return "get_configuration";
}
};
this.boardController.sendCommand(command, new IResponseCommandCallback() {
@Override
public void onFailure(WlCommException e) {
VMBoard.this.setMessage("It was not possible to obtain the VM configuration");
}
@Override
public void onSuccess(ResponseCommand responseCommand) {
final String msg = "VM address:";
VMBoard.this.setMessage(msg);
VMBoard.this.url.setText(responseCommand.getCommandString());
VMBoard.this.protocol = responseCommand.getCommandString().split(":")[0].toLowerCase();
VMBoard.this.fullURLPassword = responseCommand.getCommandString();
}
});
}
}
|
package com.common.android.utils.extensions;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import static com.common.android.utils.ContextHelper.getContext;
public class DrawableExtensions {
@Nullable
public static Drawable scaleImage(@Nullable Drawable image, float scaleFactor) {
if ((image == null) || !(image instanceof BitmapDrawable)) {
return image;
}
Bitmap b = ((BitmapDrawable) image).getBitmap();
int sizeX = Math.round(image.getIntrinsicWidth() * scaleFactor);
int sizeY = Math.round(image.getIntrinsicHeight() * scaleFactor);
Bitmap bitmapResized = Bitmap.createScaledBitmap(b, sizeX, sizeY, false);
image = new BitmapDrawable(getContext().getResources(), bitmapResized);
return image;
}
}
|
package com.yahoo.vespa.config.server.application;
import com.google.common.collect.ImmutableSet;
import com.yahoo.concurrent.ThreadFactoryFactory;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.TenantName;
import com.yahoo.log.LogLevel;
import com.yahoo.path.Path;
import com.yahoo.text.Utf8;
import com.yahoo.transaction.Transaction;
import com.yahoo.vespa.config.server.ReloadHandler;
import com.yahoo.vespa.config.server.tenant.TenantRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.curator.transaction.CuratorOperations;
import com.yahoo.vespa.curator.transaction.CuratorTransaction;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
/**
* The applications of a tenant, backed by ZooKeeper.
* Each application is stored as a single node under /config/v2/tenants/<tenant>/applications/<applications>,
* named the same as the application id and containing the id of the session storing the content of the application.
*
* @author Ulf Lilleengen
*/
// TODO: Merge into interface and separate out curator layer instead
public class ZKTenantApplications implements TenantApplications, PathChildrenCacheListener {
private static final Logger log = Logger.getLogger(ZKTenantApplications.class.getName());
private final Curator curator;
private final Path applicationsPath;
// One thread pool for all instances of this class
private static final ExecutorService pathChildrenExecutor =
Executors.newCachedThreadPool(ThreadFactoryFactory.getThreadFactory(ZKTenantApplications.class.getName()));
private final Curator.DirectoryCache directoryCache;
private final ReloadHandler reloadHandler;
private final TenantName tenant;
private ZKTenantApplications(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) {
this.curator = curator;
this.applicationsPath = applicationsPath;
curator.create(applicationsPath);
this.reloadHandler = reloadHandler;
this.tenant = tenant;
this.directoryCache = curator.createDirectoryCache(applicationsPath.getAbsolute(), false, false, pathChildrenExecutor);
this.directoryCache.start();
this.directoryCache.addListener(this);
}
public static TenantApplications create(Curator curator, ReloadHandler reloadHandler, TenantName tenant) {
try {
return new ZKTenantApplications(curator, TenantRepository.getApplicationsPath(tenant), reloadHandler, tenant);
} catch (Exception e) {
throw new RuntimeException(TenantRepository.logPre(tenant) + "Error creating application repo", e);
}
}
private long readSessionId(ApplicationId appId, String appNode) {
String path = applicationsPath.append(appNode).getAbsolute();
try {
return Long.parseLong(Utf8.toString(curator.framework().getData().forPath(path)));
} catch (Exception e) {
throw new IllegalArgumentException(TenantRepository.logPre(appId) + "Unable to read the session id from '" + path + "'", e);
}
}
@Override
public List<ApplicationId> listApplications() {
try {
List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute());
List<ApplicationId> applicationIds = new ArrayList<>();
for (String appNode : appNodes) {
parseApplication(appNode).ifPresent(applicationIds::add);
}
return applicationIds;
} catch (Exception e) {
throw new RuntimeException(TenantRepository.logPre(tenant)+"Unable to list applications", e);
}
}
private Optional<ApplicationId> parseApplication(String appNode) {
try {
return Optional.of(ApplicationId.fromSerializedForm(appNode));
} catch (IllegalArgumentException e) {
log.log(LogLevel.INFO, TenantRepository.logPre(tenant)+"Unable to parse application with id '" + appNode + "', ignoring.");
return Optional.empty();
}
}
@Override
public Transaction createPutApplicationTransaction(ApplicationId applicationId, long sessionId) {
if (listApplications().contains(applicationId)) {
return new CuratorTransaction(curator).add(CuratorOperations.setData(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId)));
} else {
return new CuratorTransaction(curator).add(CuratorOperations.create(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId)));
}
}
@Override
public long getSessionIdForApplication(ApplicationId applicationId) {
return readSessionId(applicationId, applicationId.serializedForm());
}
@Override
public CuratorTransaction deleteApplication(ApplicationId applicationId) {
Path path = applicationsPath.append(applicationId.serializedForm());
return CuratorTransaction.from(CuratorOperations.delete(path.getAbsolute()), curator);
}
@Override
public void close() {
directoryCache.close();
pathChildrenExecutor.shutdown();
}
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
switch (event.getType()) {
case CHILD_ADDED:
applicationAdded(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName()));
break;
// Event CHILD_REMOVED will be triggered on all config servers if deleteApplication() above is called on one of them
case CHILD_REMOVED:
applicationRemoved(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName()));
break;
case CHILD_UPDATED:
// do nothing, application just got redeployed
break;
default:
break;
}
// We might have lost events and might need to remove applications (new applications are
// not added by listening for events here, they are added when session is added, see RemoteSessionRepo)
removeUnusedApplications();
}
private void applicationRemoved(ApplicationId applicationId) {
reloadHandler.removeApplication(applicationId);
log.log(LogLevel.INFO, TenantRepository.logPre(applicationId) + "Application removed: " + applicationId);
}
private void applicationAdded(ApplicationId applicationId) {
log.log(LogLevel.DEBUG, TenantRepository.logPre(applicationId) + "Application added: " + applicationId);
}
public void removeUnusedApplications() {
ImmutableSet<ApplicationId> activeApplications = ImmutableSet.copyOf(listApplications());
log.log(LogLevel.DEBUG, "Removing stale applications for tenant '" + tenant +
"', not removing these active applications: " + activeApplications);
reloadHandler.removeApplicationsExcept(activeApplications);
}
}
|
package com.yahoo.vespa.config.server.http.v2;
import com.yahoo.config.application.api.ApplicationMetaData;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.model.NullConfigModelRegistry;
import com.yahoo.config.model.application.provider.BaseDeployLogger;
import com.yahoo.config.model.application.provider.DeployData;
import com.yahoo.config.model.application.provider.FilesApplicationPackage;
import com.yahoo.config.model.application.provider.MockFileRegistry;
import com.yahoo.config.provision.AllocatedHosts;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.Zone;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.slime.JsonFormat;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.config.server.MockReloadHandler;
import com.yahoo.vespa.config.server.TestComponentRegistry;
import com.yahoo.vespa.config.server.application.OrchestratorMock;
import com.yahoo.vespa.config.server.application.TenantApplications;
import com.yahoo.vespa.config.server.deploy.TenantFileSystemDirs;
import com.yahoo.vespa.config.server.deploy.ZooKeeperClient;
import com.yahoo.vespa.config.server.host.HostRegistry;
import com.yahoo.vespa.config.server.http.HandlerTest;
import com.yahoo.vespa.config.server.http.HttpErrorResponse;
import com.yahoo.vespa.config.server.http.SessionHandler;
import com.yahoo.vespa.config.server.http.SessionHandlerTest;
import com.yahoo.vespa.config.server.modelfactory.ModelFactoryRegistry;
import com.yahoo.vespa.config.server.session.LocalSession;
import com.yahoo.vespa.config.server.session.LocalSessionRepo;
import com.yahoo.vespa.config.server.session.MockSessionZKClient;
import com.yahoo.vespa.config.server.session.RemoteSession;
import com.yahoo.vespa.config.server.session.Session;
import com.yahoo.vespa.config.server.session.SessionTest;
import com.yahoo.vespa.config.server.session.SessionZooKeeperClient;
import com.yahoo.vespa.config.server.tenant.TenantBuilder;
import com.yahoo.vespa.config.server.tenant.TenantRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.curator.mock.MockCurator;
import com.yahoo.vespa.model.VespaModelFactory;
import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import static com.yahoo.jdisc.Response.Status.BAD_REQUEST;
import static com.yahoo.jdisc.Response.Status.CONFLICT;
import static com.yahoo.jdisc.Response.Status.METHOD_NOT_ALLOWED;
import static com.yahoo.jdisc.Response.Status.NOT_FOUND;
import static com.yahoo.jdisc.Response.Status.OK;
import static com.yahoo.vespa.config.server.http.SessionHandlerTest.createTestRequest;
import static com.yahoo.vespa.config.server.http.SessionHandlerTest.Cmd;
import static com.yahoo.vespa.config.server.http.SessionHandlerTest.FailingMockProvisioner;
import static com.yahoo.vespa.config.server.http.SessionHandlerTest.getRenderedString;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class SessionActiveHandlerTest {
private static final File testApp = new File("src/test/apps/app");
private static final String appName = "default";
private static final TenantName tenantName = TenantName.from("activatetest");
private static final String activatedMessage = " for tenant '" + tenantName + "' activated.";
private static final String pathPrefix = "/application/v2/tenant/" + tenantName + "/session/";
private Curator curator;
private LocalSessionRepo localRepo;
private TenantApplications applicationRepo;
private SessionHandlerTest.MockProvisioner hostProvisioner;
private VespaModelFactory modelFactory;
private TestComponentRegistry componentRegistry;
private TenantRepository tenantRepository;
private SessionActiveHandler handler;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
public void setup() {
curator = new MockCurator();
modelFactory = new VespaModelFactory(new NullConfigModelRegistry());
componentRegistry = new TestComponentRegistry.Builder()
.curator(curator)
.modelFactoryRegistry(new ModelFactoryRegistry(Collections.singletonList(modelFactory)))
.build();
tenantRepository = new TenantRepository(componentRegistry, false);
applicationRepo = TenantApplications.create(componentRegistry, new MockReloadHandler(), tenantName);
localRepo = new LocalSessionRepo(tenantName, componentRegistry);
hostProvisioner = new SessionHandlerTest.MockProvisioner();
TenantBuilder tenantBuilder = TenantBuilder.create(componentRegistry, tenantName)
.withLocalSessionRepo(localRepo)
.withApplicationRepo(applicationRepo);
tenantRepository.addTenant(tenantBuilder);
handler = createHandler();
}
@Test
public void testThatPreviousSessionIsDeactivated() throws Exception {
RemoteSession firstSession = activateAndAssertOK(90, 0);
activateAndAssertOK(91, 90);
assertThat(firstSession.getStatus(), Is.is(Session.Status.DEACTIVATE));
}
@Test
public void testForceActivationWithActivationInBetween() throws Exception {
activateAndAssertOK(90, 0);
activateAndAssertOK(92, 89, "?force=true");
}
@Test
public void testUnknownSession() {
HttpResponse response = handler.handle(createTestRequest(pathPrefix, HttpRequest.Method.PUT, Cmd.ACTIVE, 9999L, "?timeout=1.0"));
assertEquals(response.getStatus(), NOT_FOUND);
}
@Test
public void require_that_session_created_from_active_that_is_no_longer_active_cannot_be_activated() throws Exception {
long sessionId = 1;
activateAndAssertOK(1, 0);
sessionId++;
activateAndAssertOK(sessionId, 1);
sessionId++;
ActivateRequest activateRequest = new ActivateRequest(sessionId, 1, "").invoke();
HttpResponse actResponse = activateRequest.getActResponse();
String message = getRenderedString(actResponse);
assertThat(message, actResponse.getStatus(), Is.is(CONFLICT));
assertThat(message,
containsString("Cannot activate session 3 because the currently active session (2) has changed since session 3 was created (was 1 at creation time)"));
}
@Test
public void testAlreadyActivatedSession() throws Exception {
activateAndAssertOK(1, 0);
HttpResponse response = handler.handle(createTestRequest(pathPrefix, HttpRequest.Method.PUT, Cmd.ACTIVE, 1L));
String message = getRenderedString(response);
assertThat(message, response.getStatus(), Is.is(BAD_REQUEST));
assertThat(message, containsString("Session 1 is already active"));
}
@Test
public void testActivation() throws Exception {
activateAndAssertOK(1, 0);
}
@Test
public void testActivationWithActivationInBetween() throws Exception {
activateAndAssertOK(90, 0);
activateAndAssertError(92, 89,
Response.Status.CONFLICT, HttpErrorResponse.errorCodes.ACTIVATION_CONFLICT,
"tenant:" + tenantName + " app:default:default Cannot activate session 92 because the currently active session (90) has changed since session 92 was created (was 89 at creation time)");
}
@Test
public void require_that_handler_gives_error_for_unsupported_methods() throws Exception {
testUnsupportedMethod(createTestRequest(pathPrefix, HttpRequest.Method.POST, Cmd.PREPARED, 1L));
testUnsupportedMethod(createTestRequest(pathPrefix, HttpRequest.Method.DELETE, Cmd.PREPARED, 1L));
testUnsupportedMethod(createTestRequest(pathPrefix, HttpRequest.Method.GET, Cmd.PREPARED, 1L));
}
@Test
@Ignore
public void require_that_handler_gives_error_when_provisioner_activated_fails() throws Exception {
hostProvisioner = new FailingMockProvisioner();
hostProvisioner.activated = false;
activateAndAssertError(1, 0, BAD_REQUEST, HttpErrorResponse.errorCodes.BAD_REQUEST, "Cannot activate application");
assertFalse(hostProvisioner.activated);
}
private RemoteSession createRemoteSession(long sessionId, Session.Status status, SessionZooKeeperClient zkClient) throws IOException {
zkClient.writeStatus(status);
ZooKeeperClient zkC = new ZooKeeperClient(componentRegistry.getConfigCurator(), new BaseDeployLogger(), false,
TenantRepository.getSessionsPath(tenantName).append(String.valueOf(sessionId)));
zkC.write(Collections.singletonMap(modelFactory.version(), new MockFileRegistry()));
zkC.write(AllocatedHosts.withHosts(Collections.emptySet()));
return new RemoteSession(tenantName, sessionId, componentRegistry, zkClient);
}
private void addLocalSession(long sessionId, DeployData deployData, SessionZooKeeperClient zkc) throws IOException {
writeApplicationId(zkc, deployData.getApplicationId());
TenantFileSystemDirs tenantFileSystemDirs = new TenantFileSystemDirs(temporaryFolder.newFolder(), tenantName);
ApplicationPackage app = FilesApplicationPackage.fromFileWithDeployData(testApp, deployData);
localRepo.addSession(new LocalSession(tenantName, sessionId, new SessionTest.MockSessionPreparer(),
app, zkc, new File(tenantFileSystemDirs.sessionsPath(), String.valueOf(sessionId)),
applicationRepo, new HostRegistry<>()));
}
private ActivateRequest activateAndAssertOKPut(long sessionId, long previousSessionId, String subPath) throws Exception {
ActivateRequest activateRequest = new ActivateRequest(sessionId, previousSessionId, subPath);
activateRequest.invoke();
HttpResponse actResponse = activateRequest.getActResponse();
String message = getRenderedString(actResponse);
assertThat(message, actResponse.getStatus(), Is.is(OK));
assertActivationMessageOK(activateRequest, message);
RemoteSession session = activateRequest.getSession();
assertThat(session.getStatus(), Is.is(Session.Status.ACTIVATE));
return activateRequest;
}
private void activateAndAssertErrorPut(long sessionId, long previousSessionId,
int statusCode, HttpErrorResponse.errorCodes errorCode, String expectedError) throws Exception {
ActivateRequest activateRequest = new ActivateRequest(sessionId, previousSessionId, "");
activateRequest.invoke();
HttpResponse actResponse = activateRequest.getActResponse();
RemoteSession session = activateRequest.getSession();
assertThat(actResponse.getStatus(), Is.is(statusCode));
String message = getRenderedString(actResponse);
assertThat(message, Is.is("{\"error-code\":\"" + errorCode.name() + "\",\"message\":\"" + expectedError + "\"}"));
assertThat(session.getStatus(), Is.is(Session.Status.PREPARE));
}
private void testUnsupportedMethod(com.yahoo.container.jdisc.HttpRequest request) throws Exception {
HttpResponse response = handler.handle(request);
HandlerTest.assertHttpStatusCodeErrorCodeAndMessage(response,
METHOD_NOT_ALLOWED,
HttpErrorResponse.errorCodes.METHOD_NOT_ALLOWED,
"Method '" + request.getMethod().name() + "' is not supported");
}
protected class ActivateRequest {
private long sessionId;
private RemoteSession session;
private HttpResponse actResponse;
private Session.Status initialStatus;
private DeployData deployData;
private ApplicationMetaData metaData;
private String subPath;
ActivateRequest(long sessionId, long previousSessionId, String subPath) {
this(sessionId, previousSessionId, Session.Status.PREPARE, subPath);
}
ActivateRequest(long sessionId, long previousSessionId, Session.Status initialStatus, String subPath) {
this.sessionId = sessionId;
this.initialStatus = initialStatus;
this.deployData = new DeployData("foo",
"bar",
ApplicationId.from(tenantName.value(), appName, "default"),
0L,
false,
sessionId,
previousSessionId);
this.subPath = subPath;
}
public RemoteSession getSession() {
return session;
}
public SessionHandler getHandler() {
return handler;
}
HttpResponse getActResponse() {
return actResponse;
}
public long getSessionId() {
return sessionId;
}
ApplicationMetaData getMetaData() {
return metaData;
}
ActivateRequest invoke() throws Exception {
SessionZooKeeperClient zkClient =
new MockSessionZKClient(curator, tenantName, sessionId,
Optional.of(AllocatedHosts.withHosts(Set.of(new HostSpec("bar", Collections.emptyList(), Optional.empty())))));
session = createRemoteSession(sessionId, initialStatus, zkClient);
addLocalSession(sessionId, deployData, zkClient);
tenantRepository.getTenant(tenantName).getApplicationRepo().createApplication(deployData.getApplicationId());
metaData = localRepo.getSession(sessionId).getMetaData();
actResponse = handler.handle(createTestRequest(pathPrefix, HttpRequest.Method.PUT, Cmd.ACTIVE, sessionId, subPath));
return this;
}
}
private RemoteSession activateAndAssertOK(long sessionId, long previousSessionId) throws Exception {
ActivateRequest activateRequest = activateAndAssertOKPut(sessionId, previousSessionId, "");
return activateRequest.getSession();
}
private void activateAndAssertOK(long sessionId, long previousSessionId, String subPath) throws Exception {
activateAndAssertOKPut(sessionId, previousSessionId, subPath);
}
private void assertActivationMessageOK(ActivateRequest activateRequest, String message) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
new JsonFormat(true).encode(byteArrayOutputStream, activateRequest.getMetaData().getSlime());
assertThat(message, containsString("\"tenant\":\"" + tenantName + "\",\"message\":\"Session " + activateRequest.getSessionId() + activatedMessage));
assertThat(message, containsString("/application/v2/tenant/" + tenantName +
"/application/" + appName +
"/environment/" + "prod" +
"/region/" + "default" +
"/instance/" + "default"));
assertTrue(hostProvisioner.activated);
assertThat(hostProvisioner.lastHosts.size(), is(1));
}
private void activateAndAssertError(long sessionId, long previousSessionId, int statusCode, HttpErrorResponse.errorCodes errorCode, String expectedError) throws Exception {
hostProvisioner.activated = false;
activateAndAssertErrorPut(sessionId, previousSessionId, statusCode, errorCode, expectedError);
assertFalse(hostProvisioner.activated);
}
private void writeApplicationId(SessionZooKeeperClient zkc, ApplicationId id) {
zkc.writeApplicationId(id);
}
private SessionActiveHandler createHandler() {
return new SessionActiveHandler(SessionActiveHandler.testOnlyContext(),
new ApplicationRepository(tenantRepository,
hostProvisioner,
new OrchestratorMock(),
componentRegistry.getClock()),
Zone.defaultZone());
}
}
|
package io.lumify.model.rabbitmq;
import com.google.inject.Inject;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
import io.lumify.core.config.Configuration;
import io.lumify.core.exception.LumifyException;
import io.lumify.core.ingest.WorkerSpout;
import io.lumify.core.ingest.WorkerTuple;
import io.lumify.core.ingest.graphProperty.GraphPropertyWorkerTuple;
import io.lumify.core.util.LumifyLogger;
import io.lumify.core.util.LumifyLoggerFactory;
import org.json.JSONObject;
import java.io.IOException;
public class RabbitMQWorkQueueSpout extends WorkerSpout {
private static final LumifyLogger LOGGER = LumifyLoggerFactory.getLogger(RabbitMQWorkQueueSpout.class);
private final String queueName;
private Channel channel;
private QueueingConsumer consumer;
private Connection connection;
private Configuration configuration;
public RabbitMQWorkQueueSpout(String queueName) {
this.queueName = queueName;
}
@Override
public void open() {
try {
this.connection = RabbitMQUtils.openConnection(configuration);
this.channel = RabbitMQUtils.openChannel(this.connection);
this.channel.queueDeclare(queueName, true, false, false, null);
this.consumer = new QueueingConsumer(channel);
this.channel.basicConsume(this.queueName, false, consumer);
} catch (IOException ex) {
throw new LumifyException("Could not startup RabbitMQ", ex);
}
}
@Override
public void close() {
super.close();
try {
LOGGER.debug("Closing RabbitMQ channel");
this.channel.close();
LOGGER.debug("Closing RabbitMQ connection");
this.connection.close();
} catch (IOException ex) {
LOGGER.error("Could not close RabbitMQ connection and channel", ex);
}
}
@Override
public WorkerTuple nextTuple() throws InterruptedException {
QueueingConsumer.Delivery delivery = this.consumer.nextDelivery(100);
if (delivery == null) {
return null;
}
JSONObject json = new JSONObject(new String(delivery.getBody()));
LOGGER.debug("emit (%s): %s", this.queueName, json.toString());
return new GraphPropertyWorkerTuple(delivery.getEnvelope().getDeliveryTag(), json);
}
@Override
public void ack(Object msgId) {
super.ack(msgId);
long deliveryTag = (Long) msgId;
try {
this.channel.basicAck(deliveryTag, false);
} catch (IOException ex) {
LOGGER.error("Could not ack: %d", deliveryTag, ex);
}
}
@Override
public void fail(Object msgId) {
super.fail(msgId);
long deliveryTag = (Long) msgId;
try {
this.channel.basicNack(deliveryTag, false, false);
} catch (IOException ex) {
LOGGER.error("Could not ack: %d", deliveryTag, ex);
}
}
protected QueueingConsumer getConsumer () { return this.consumer; }
@Inject
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
}
|
package org.hisp.dhis.android.core.relationship;
import android.content.ContentValues;
import android.database.MatrixCursor;
import android.support.test.runner.AndroidJUnit4;
import org.hisp.dhis.android.core.common.BaseIdentifiableObject;
import org.hisp.dhis.android.core.common.BaseIdentifiableObjectModel;
import org.hisp.dhis.android.core.common.BaseModel;
import org.hisp.dhis.android.core.relationship.RelationshipModel.Columns;
import org.hisp.dhis.android.core.utils.Utils;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Date;
import static com.google.common.truth.Truth.assertThat;
@RunWith(AndroidJUnit4.class)
public class RelationshipModelShould {
//BaseIdentifiableModel attributes:
private static final long ID = 11L;
private static final String UID = "test_uid";
private static final String NAME = "test_display_name";
private static final String RELATIONSHIP_TYPE = "RelationshipType uid";
private final Date date;
private final String dateString;
public RelationshipModelShould() {
this.date = new Date();
this.dateString = BaseIdentifiableObject.DATE_FORMAT.format(date);
}
@Test
public void create_model_when_created_from_database_cursor() {
String[] columnsWithId = Utils.appendInNewArray(new RelationshipModel.Columns().all(),
BaseModel.Columns.ID);
MatrixCursor cursor = new MatrixCursor(columnsWithId);
cursor.addRow(new Object[]{
UID,
NAME,
dateString,
dateString,
RELATIONSHIP_TYPE,
ID
});
cursor.moveToFirst();
Relationship relationship = Relationship.create(cursor);
cursor.close();
assertThat(relationship.id()).isEqualTo(ID);
assertThat(relationship.uid()).isEqualTo(UID);
assertThat(relationship.name()).isEqualTo(NAME);
assertThat(relationship.created()).isEqualTo(date);
assertThat(relationship.lastUpdated()).isEqualTo(date);
assertThat(relationship.relationshipType()).isEqualTo(RELATIONSHIP_TYPE);
}
@Test
public void create_content_values_when_created_from_builder() {
Relationship relationship = Relationship.builder()
.id(ID)
.uid(UID)
.name(NAME)
.created(date)
.lastUpdated(date)
.relationshipType(RELATIONSHIP_TYPE)
.build();
ContentValues contentValues = relationship.toContentValues();
assertThat(contentValues.getAsLong(Columns.ID)).isEqualTo(ID);
assertThat(contentValues.getAsString(BaseIdentifiableObjectModel.Columns.UID)).isEqualTo(UID);
assertThat(contentValues.getAsString(BaseIdentifiableObjectModel.Columns.NAME)).isEqualTo(NAME);
assertThat(contentValues.getAsString(BaseIdentifiableObjectModel.Columns.CREATED)).isEqualTo(dateString);
assertThat(contentValues.getAsString(BaseIdentifiableObjectModel.Columns.LAST_UPDATED)).isEqualTo(dateString);
assertThat(contentValues.getAsString(Columns.RELATIONSHIP_TYPE)).isEqualTo(RELATIONSHIP_TYPE);
}
}
|
package org.eclipse.birt.data.engine.impl.document;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.birt.core.util.IOUtil;
import org.eclipse.birt.data.engine.api.IBaseQueryDefinition;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IGroupInstanceInfo;
import org.eclipse.birt.data.engine.api.IQueryDefinition;
import org.eclipse.birt.data.engine.api.IQueryExecutionHints;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.api.ISortDefinition;
import org.eclipse.birt.data.engine.api.ISubqueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.BaseQueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.GroupInstanceInfo;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.QueryExecutionHints;
import org.eclipse.birt.data.engine.api.querydefn.SortDefinition;
import org.eclipse.birt.data.engine.api.querydefn.SubqueryDefinition;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.document.stream.VersionManager;
import com.ibm.icu.util.ULocale;
/**
* Save query definition structure into report document and loading from report
* document.
*/
public class QueryDefnIOUtil
{
/**
* @param outputStream
* @param queryDefn
* @throws DataException
* @throws IOException
*/
static void saveBaseQueryDefn( OutputStream outputStream,
IBaseQueryDefinition queryDefn, int version ) throws DataException
{
try
{
// binding column definition
saveBinding( outputStream, queryDefn.getBindings( ), version );
// filter definition
FilterDefnUtil.saveFilterDefn( outputStream, queryDefn.getFilters( ) );
// group definition
GroupDefnUtil.saveGroupDefn( outputStream, queryDefn.getGroups( ), version );
// sort definition
saveSorts( outputStream, queryDefn.getSorts( ), version );
// misc property: max row, use details
IOUtil.writeInt( outputStream, queryDefn.getMaxRows( ) );
IOUtil.writeBool( outputStream, queryDefn.usesDetails( ) );
if ( version >= VersionManager.VERSION_2_5_1_1 )
IOUtil.writeBool( outputStream, queryDefn.cacheQueryResults( ) );
// sub query name
saveSubQuery( outputStream, queryDefn.getSubqueries( ), version );
// query execution hint
saveQueryExecutionHints( outputStream, queryDefn.getQueryExecutionHints( ), version );
saveSummaryTableInfo( outputStream, queryDefn, version );
}
catch ( IOException e )
{
throw new DataException( ResourceConstants.RD_SAVE_ERROR, e );
}
}
private static void saveSummaryTableInfo( OutputStream outputStream,
IBaseQueryDefinition queryDefn, int version ) throws IOException
{
if( version >= VersionManager.VERSION_2_5_1_1 && queryDefn instanceof IQueryDefinition)
{
IOUtil.writeBool( outputStream, ((IQueryDefinition)queryDefn).isSummaryQuery( ));
}
}
/**
*
* @param outputStream
* @param hint
* @param version
* @throws DataException
*/
private static void saveQueryExecutionHints( OutputStream outputStream, IQueryExecutionHints hint, int version ) throws DataException
{
if( version < VersionManager.VERSION_2_3_2_1 )
return;
try
{
IOUtil.writeBool( outputStream, hint == null? true:hint.doSortBeforeGrouping( ) );
List<IGroupInstanceInfo> list = hint == null? new ArrayList<IGroupInstanceInfo>():hint.getTargetGroupInstances( );
IOUtil.writeInt( outputStream, list.size( ) );
for( IGroupInstanceInfo info: list )
{
IOUtil.writeInt( outputStream, info.getGroupLevel( ) );
IOUtil.writeInt( outputStream, info.getRowId( ) );
}
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ),e );
}
}
/**
* @param outputStream
* @param exprMap
* @throws IOException
* @throws DataException
*/
private static void saveBinding( OutputStream outputStream, Map exprMap, int version )
throws IOException, DataException
{
DataOutputStream dos = new DataOutputStream( outputStream );
if ( exprMap == null )
{
IOUtil.writeInt( dos, 0 );
}
else
{
IOUtil.writeInt( dos, exprMap.size( ) );
Iterator it = exprMap.entrySet( ).iterator( );
while ( it.hasNext( ) )
{
Map.Entry entry = (Entry) it.next( );
IOUtil.writeString( dos, (String) entry.getKey( ) );
if ( version < VersionManager.VERSION_2_2_1 )
ExprUtil.saveBaseExpr( dos,
( (IBinding) entry.getValue( ) ).getExpression( ) );
else
BindingIOUtil.saveBinding( dos, (IBinding) entry.getValue( ) );
}
}
dos.flush( );
}
/**
* @param outputStream
* @param sorts
* @throws IOException
*/
public static void saveSorts( OutputStream outputStream, List sorts, int version )
throws IOException
{
DataOutputStream dos = new DataOutputStream( outputStream );
if ( sorts == null )
{
IOUtil.writeInt( dos, 0 );
}
else
{
IOUtil.writeInt( dos, sorts.size( ) );
Iterator it = sorts.iterator( );
while ( it.hasNext( ) )
{
ISortDefinition sortDefn = (ISortDefinition) it.next( );
IOUtil.writeString( dos, sortDefn.getColumn( ) );
ExprUtil.saveBaseExpr( dos, sortDefn.getExpression( ) );
IOUtil.writeInt( dos, sortDefn.getSortDirection( ) );
if ( version >= VersionManager.VERSION_2_3_1 )
IOUtil.writeInt( dos, sortDefn.getSortStrength( ) );
if ( version >= VersionManager.VERSION_2_5_0_1 )
IOUtil.writeString( dos, sortDefn.getSortLocale( ) == null? null:sortDefn.getSortLocale( ).getBaseName( ) );
}
}
dos.flush( );
}
/**
* @throws IOException
* @throws DataException
*
*/
static void saveSubQuery( OutputStream outputStream,
Collection subQuery, int version ) throws DataException, IOException
{
DataOutputStream dos = new DataOutputStream( outputStream );
if ( subQuery == null )
{
IOUtil.writeInt( dos, 0 );
}
else
{
IOUtil.writeInt( dos, subQuery.size( ) );
Iterator it = subQuery.iterator( );
while ( it.hasNext( ) )
{
ISubqueryDefinition subQueryDefn = (ISubqueryDefinition) it.next( );
IOUtil.writeString( dos, subQueryDefn.getName( ) );
IOUtil.writeBool( outputStream, subQueryDefn.applyOnGroup( ) );
saveBaseQueryDefn( outputStream, subQueryDefn, version );
}
}
dos.flush( );
}
/**
* @param outputStream
* @throws DataException
* @throws IOException
*/
static IQueryDefinition loadQueryDefn( InputStream inputStream, int version )
throws DataException
{
QueryDefinition queryDefn = new QueryDefinition( );
loadBaseQueryDefn( inputStream, queryDefn, version );
return queryDefn;
}
/**
* @param inputStream
* @param queryDefn
* @throws DataException
*/
private static void loadBaseQueryDefn( InputStream inputStream,
BaseQueryDefinition queryDefn, int version ) throws DataException
{
try
{
queryDefn.getBindings( )
.putAll( loadBinding( inputStream, version ) );
// filter definition
queryDefn.getFilters( )
.addAll( FilterDefnUtil.loadFilterDefn( inputStream ) );
// group definition
queryDefn.getGroups( )
.addAll( GroupDefnUtil.loadGroupDefn( inputStream, queryDefn, version ) );
// sort definition
queryDefn.getSorts( ).addAll( loadSorts( inputStream, version ) );
// misc property: max row, use details
queryDefn.setMaxRows( IOUtil.readInt( inputStream ) );
queryDefn.setUsesDetails( IOUtil.readBool( inputStream ) );
if ( version >= VersionManager.VERSION_2_5_1_1 )
queryDefn.setCacheQueryResults( IOUtil.readBool( inputStream ) );
// sub query name
queryDefn.getSubqueries( ).addAll( loadSubQuery( inputStream, queryDefn, version) );
// QueryExecutionHints
queryDefn.setQueryExecutionHints( loadQueryExecutionHints( inputStream, version ) );
if( queryDefn instanceof IQueryDefinition && version >= VersionManager.VERSION_2_5_1_1 )
{
((QueryDefinition)queryDefn).setIsSummaryQuery( IOUtil.readBool( inputStream ) );
}
}
catch ( IOException e )
{
throw new DataException( ResourceConstants.RD_LOAD_ERROR, e );
}
}
/**
* This method loads the query execution hints
* @param inputStream
* @param version
* @return
* @throws DataException
*/
private static IQueryExecutionHints loadQueryExecutionHints(
InputStream inputStream, int version ) throws DataException
{
if( version < VersionManager.VERSION_2_3_2_1 )
return null;
try
{
QueryExecutionHints hints = new QueryExecutionHints();
hints.setSortBeforeGrouping( IOUtil.readBool( inputStream ) );
int groupInstanceInfoSize = IOUtil.readInt( inputStream );
for( int i = 0; i < groupInstanceInfoSize; i++ )
{
hints.addTargetGroupInstance( new GroupInstanceInfo( IOUtil.readInt( inputStream ), IOUtil.readInt( inputStream )) );
}
return hints;
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ),e );
}
}
/**
* @param outputStream
* @param exprMap
* @throws IOException
* @throws DataException
*/
private static Map loadBinding( InputStream inputStream, int version )
throws IOException, DataException
{
DataInputStream dis = new DataInputStream( inputStream );
Map exprMap = new HashMap( );
int size = IOUtil.readInt( dis );
for ( int i = 0; i < size; i++ )
{
String exprName = IOUtil.readString( dis );
if ( version < VersionManager.VERSION_2_2_1 )
exprMap.put( exprName, new Binding( exprName,
ExprUtil.loadBaseExpr( dis ) ) );
else
exprMap.put( exprName, BindingIOUtil.loadBinding( dis ));
}
return exprMap;
}
/**
* @param outputStream
* @param sorts
* @throws IOException
*/
public static List loadSorts( InputStream inputStream, int version ) throws IOException
{
DataInputStream dis = new DataInputStream( inputStream );
List sortList = new ArrayList( );
int size = IOUtil.readInt( dis );
for ( int i = 0; i < size; i++ )
{
String sortKeyColumn = IOUtil.readString( dis );
IScriptExpression sortKeyExpr = (IScriptExpression) ExprUtil.loadBaseExpr( dis );
int direction = IOUtil.readInt( dis );
SortDefinition sortDefn = new SortDefinition( );
if ( sortKeyColumn != null )
sortDefn.setColumn( sortKeyColumn );
else
sortDefn.setExpression( sortKeyExpr );
sortDefn.setSortDirection( direction );
if ( version >= VersionManager.VERSION_2_3_1 )
sortDefn.setSortStrength( IOUtil.readInt( dis ));
if ( version >= VersionManager.VERSION_2_5_0_1 )
{
String locale = IOUtil.readString( dis );
if( locale != null )
sortDefn.setSortLocale( new ULocale( locale ) );
}
sortList.add( sortDefn );
}
return sortList;
}
/**
* @param inputStream
* @return
* @throws DataException
* @throws IOException
*/
static Collection loadSubQuery( InputStream inputStream, IBaseQueryDefinition parent, int version )
throws DataException, IOException
{
DataInputStream dis = new DataInputStream( inputStream );
Collection subQuerys = new ArrayList( );
int size = IOUtil.readInt( dis );
for ( int i = 0; i < size; i++ )
{
SubqueryDefinition subQueryDefn = new SubqueryDefinition( IOUtil.readString( dis ), parent );
subQueryDefn.setApplyOnGroupFlag( IOUtil.readBool( dis ) );
loadBaseQueryDefn( dis, subQueryDefn, version );
subQuerys.add( subQueryDefn );
}
return subQuerys;
}
}
|
package org.eclipse.birt.data.engine.impl.index;
import java.io.DataInputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.birt.core.archive.RAInputStream;
import org.eclipse.birt.core.util.IOUtil;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.script.ScriptEvalUtil;
public class DataSetNumberIndex implements IDataSetIndex
{
private int segNumber;
private List boundaryStartingValues = new ArrayList();
private Seg[] segs;
public DataSetNumberIndex( RAInputStream raIn ) throws DataException
{
try
{
this.segNumber = IOUtil.readInt( raIn );
this.segs = new Seg[this.segNumber];
this.boundaryStartingValues = new ArrayList();
long[] offsets = new long[this.segNumber];
DataInputStream din = new DataInputStream( raIn );
for ( int i = 0; i < offsets.length; i++ )
{
offsets[i] = IOUtil.readLong( din );
}
for ( int i = 0; i < segNumber; i++ )
{
this.boundaryStartingValues.add( IOUtil.readObject( din ) );
this.segs[i] = new Seg( raIn, offsets[i] );
}
}
catch ( IOException e )
{
throw new DataException( e.getLocalizedMessage( ), e );
}
}
public List<Integer> seekG( Object target, boolean incEqual) throws DataException
{
List<Integer> result = new ArrayList<Integer>();
int primaryIndex = binarySearch( target, this.boundaryStartingValues, IConditionalExpression.OP_LE );
if( primaryIndex < 0 || primaryIndex >= this.boundaryStartingValues.size( ))
return result;
result = segs[primaryIndex].seekG( target, incEqual );
for( int i = primaryIndex+1; i < segs.length; i++ )
{
result.addAll( segs[i].seekAll( ) );
}
return result;
}
public List<Integer> seekL( Object target, boolean incEqual ) throws DataException
{
List<Integer> result = new ArrayList<Integer>();
int primaryIndex = binarySearch( target, this.boundaryStartingValues, IConditionalExpression.OP_LE );
if( primaryIndex < 0 || primaryIndex >= this.boundaryStartingValues.size( ))
return result;
result = segs[primaryIndex].seekL( target, incEqual );
for( int i = 0; i < primaryIndex; i++ )
{
result.addAll( segs[i].seekAll( ) );
}
return result;
}
public List<Integer> seekEQ( Object target ) throws DataException
{
List<Integer> result = new ArrayList<Integer>();
int primaryIndex = binarySearch( target, this.boundaryStartingValues, IConditionalExpression.OP_LE );
if( primaryIndex < 0 || primaryIndex >= this.boundaryStartingValues.size( ))
return result;
return segs[primaryIndex].seek( target );
}
public List<Integer> seekBetween( Object target1, Object target2 ) throws DataException
{
List<Integer> result = new ArrayList<Integer>( );
int primaryIndex1 = binarySearch( target1,
this.boundaryStartingValues,
IConditionalExpression.OP_LE );
int primaryIndex2 = binarySearch( target2,
this.boundaryStartingValues,
IConditionalExpression.OP_LE );
if ( ( primaryIndex1 == primaryIndex2 )
&& primaryIndex1 >= 0
&& primaryIndex1 < this.boundaryStartingValues.size( ) )
{
return segs[primaryIndex1].seekBetween( target1, target2 );
}
if( primaryIndex1 > primaryIndex2 )
return result;
result.addAll( segs[primaryIndex1].seekG( target1, true ) );
result.addAll( segs[primaryIndex2].seekL( target2, true ) );
for( int i = primaryIndex1 + 1; i < primaryIndex2 ; i++ )
result.addAll( segs[i].seekAll( ) );
return result;
}
private static Integer binarySearch( Object target, List sortedList,
int searchOption ) throws DataException
{
int low = 0;
int high = sortedList.size( ) - 1;
int mid = ( low + high ) >> 1;
while ( low <= high )
{
mid = ( low + high ) >> 1;
Object midVal = sortedList.get( mid );
int cmp = ScriptEvalUtil.compare( midVal, target );
if ( cmp < 0 )
low = mid + 1;
else if ( cmp > 0 )
high = mid - 1;
else
{
if ( searchOption == IConditionalExpression.OP_EQ
|| searchOption == IConditionalExpression.OP_GE
|| searchOption == IConditionalExpression.OP_LE )
return mid;
break;
}
}
if( low > high )
{
int temp = low;
low = high;
high = temp;
if( high >= sortedList.size( ))
high = sortedList.size( ) - 1;
}
if ( searchOption == IConditionalExpression.OP_EQ )
{
int threshHold = -1;
for ( int i = low; i <= high; i++ )
{
if ( ScriptEvalUtil.compare( sortedList.get( i ), target ) == 0 )
{
return i;
}
}
}
else if ( searchOption == IConditionalExpression.OP_GE )
{
for ( int i = low; i <= high; i++ )
{
if ( ScriptEvalUtil.compare( sortedList.get( i ), target ) >= 0 )
{
return i;
}
}
}
else if ( searchOption == IConditionalExpression.OP_LE )
{
for ( int i = high; i >= low; i
{
if ( ScriptEvalUtil.compare( sortedList.get( i ), target ) <= 0 )
{
return i;
}
}
}
else if ( searchOption == IConditionalExpression.OP_GT )
{
//If value is found
if ( high == low )
return high + 1;
for ( int i = low; i <= high; i++ )
{
if ( ScriptEvalUtil.compare( sortedList.get( i ), target ) > 0 )
{
return i;
}
}
}
else if ( searchOption == IConditionalExpression.OP_LT )
{
//if value is found
if ( high == low )
return high - 1;
for ( int i = high; i >= low; i
{
if ( ScriptEvalUtil.compare( sortedList.get( i ), target ) < 0 )
{
return i;
}
}
}
return -1; // key not found
}
private class Seg
{
private SoftReference<List> keys = new SoftReference( null );
private SoftReference<List<List<Integer>>> indexs = new SoftReference( null );
private RAInputStream raIn;
private long offset;
public Seg( RAInputStream raIn, long offset )
{
this.raIn = raIn;
this.offset = offset;
}
public int getSize( ) throws DataException
{
init( );
return this.keys.get( ).size( );
}
public List<Integer> seekAll( ) throws DataException
{
init( );
List<List<Integer>> indexList = this.indexs.get( );
List<Integer> result = new ArrayList<Integer>( );
for ( int i = 0; i < indexList.size( ); i++ )
{
result.addAll( indexList.get( i ) );
}
return result;
}
public List<Integer> seekG( Object value, boolean incEqual )
throws DataException
{
init( );
List keyList = this.keys.get( );
List<List<Integer>> indexList = this.indexs.get( );
int threshHold = binarySearch( value, keyList, incEqual
? IConditionalExpression.OP_GE : IConditionalExpression.OP_GT );
if ( threshHold < 0 || threshHold >= keyList.size( ) )
return new ArrayList( );
List<Integer> result = new ArrayList<Integer>( );
for ( int i = threshHold; i < keyList.size( ); i++ )
{
result.addAll( indexList.get( i ) );
}
return result;
}
public List<Integer> seekL( Object value, boolean incEqual )
throws DataException
{
init( );
List keyList = this.keys.get( );
List<List<Integer>> indexList = this.indexs.get( );
int threshHold = binarySearch( value, keyList, incEqual
? IConditionalExpression.OP_LE : IConditionalExpression.OP_LT );
if ( threshHold < 0 || threshHold >= keyList.size( ) )
return new ArrayList( );
List<Integer> result = new ArrayList<Integer>( );
for ( int i = 0; i <= threshHold; i++ )
{
result.addAll( indexList.get( i ) );
}
return result;
}
public List<Integer> seekBetween( Object value1, Object value2 )
throws DataException
{
init( );
List keyList = this.keys.get( );
List<List<Integer>> indexList = this.indexs.get( );
int threshHold1 = binarySearch( value1, keyList, IConditionalExpression.OP_GE );
int threshHold2 = binarySearch( value2, keyList, IConditionalExpression.OP_LE );
if ( threshHold1 > threshHold2 )
return new ArrayList( );
List<Integer> result = new ArrayList<Integer>( );
for ( int i = threshHold1; i <= threshHold2; i++ )
{
result.addAll( indexList.get( i ) );
}
return result;
}
public List<Integer> seek( Object value ) throws DataException
{
init( );
List keyList = this.keys.get( );
List<List<Integer>> indexList = this.indexs.get( );
int threshHold = binarySearch( value, keyList, IConditionalExpression.OP_EQ );
if ( threshHold < 0 || threshHold >= keyList.size( ) )
return new ArrayList( );
List<Integer> result = new ArrayList<Integer>( );
result.addAll( indexList.get( threshHold ) );
return result;
}
private void init( ) throws DataException
{
try
{
if ( this.keys.get( ) == null || this.indexs.get( ) == null )
{
List keyList = new LinkedList( );
List<List<Integer>> indexList = new LinkedList<List<Integer>>( );
this.raIn.seek( offset );
DataInputStream din = new DataInputStream( this.raIn );
int size = IOUtil.readInt( this.raIn );
for ( int i = 0; i < size; i++ )
{
keyList.add( IOUtil.readObject( din ) );
indexList.add( IOUtil.readList( din ) );
}
this.keys = new SoftReference( keyList );
this.indexs = new SoftReference( indexList );
}
}
catch ( Exception e )
{
throw new DataException( e.getLocalizedMessage( ), e );
}
}
}
public List<Integer> getKeyIndex( Object key, int searchType ) throws DataException
{
if( searchType == IConditionalExpression.OP_EQ )
{
return this.seekEQ( key );
}
else if( searchType == IConditionalExpression.OP_LE )
{
return this.seekL( key, true );
}
else if( searchType == IConditionalExpression.OP_LT )
{
return this.seekL( key, false );
}
else if( searchType == IConditionalExpression.OP_GE )
{
return this.seekG( key, true );
}
else if( searchType == IConditionalExpression.OP_GT )
{
return this.seekG( key, false );
}
else if( searchType == IConditionalExpression.OP_BETWEEN )
{
assert key instanceof List && ((List)key).size( ) == 2;
return this.seekBetween( ((List)key).get( 0 ), ((List)key).get( 1 ) );
}
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.impl.index.IDataSetIndex#supportFilter(int)
*/
public boolean supportFilter( int filterType ) throws DataException
{
if ( filterType != IConditionalExpression.OP_BETWEEN
&& filterType != IConditionalExpression.OP_EQ
&& filterType != IConditionalExpression.OP_LE
&& filterType != IConditionalExpression.OP_LT
&& filterType != IConditionalExpression.OP_GE
&& filterType != IConditionalExpression.OP_GT )
return false;
return true;
}
}
|
package de.unistuttgart.ims.drama.meta.vocabulary;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
public class QD {
/**
* <p>
* The RDF model that holds the vocabulary terms
* </p>
*/
private static final Model m_model = ModelFactory.createDefaultModel();
/**
* <p>
* The namespace of the vocabalary as a string ({@value})
* </p>
*/
public static final String NS = "http://github.com/quadrama/ontology/qdo.rdf
/**
* <p>
* The namespace of the vocabalary as a string
* </p>
*
* @see #NS
*/
public static String getURI() {
return NS;
}
/**
* <p>
* The namespace of the vocabalary as a resource
* </p>
*/
public static final Resource NAMESPACE = m_model.createResource(NS);
public static final Resource Premiere = m_model.createResource(NS + "Premiere");
public static final Resource GenreAssignment = m_model.createResource(NS + "GenreAssignment");
public static final Resource LiteraryGenre = m_model.createResource(NS + "LiteraryGenre");
public static final Resource Drama = m_model.createResource(NS + "Drama");
public static final Resource Tragedy = m_model.createResource(NS + "Tragedy");
public static final Property from = m_model.createProperty(NS + "From");
public static final Property isAnnotated = m_model.createProperty(NS + "isAnnotated");
public static final Property hasPremiere = m_model.createProperty(NS + "hasPremiere");
public static final Property hasGenre = m_model.createProperty(NS + "hasGenre");
public static final Property genreAssignment = m_model.createProperty(NS + "genreAssignment");
public static final Property certainty = m_model.createProperty(NS + "certainty");
}
|
package de.charite.compbio.exomiser.core.analysis.util;
import com.sun.javafx.scene.control.skin.VirtualFlow;
import de.charite.compbio.exomiser.core.model.Gene;
import de.charite.compbio.exomiser.core.model.TopologicalDomain;
import de.charite.compbio.exomiser.core.model.VariantEvaluation;
import de.charite.compbio.exomiser.core.prioritisers.PriorityType;
import de.charite.compbio.jannovar.annotation.Annotation;
import de.charite.compbio.jannovar.annotation.VariantEffect;
import de.charite.compbio.jannovar.reference.TranscriptModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static java.util.stream.Collectors.toList;
/**
* Reassigns regulatory non-coding variants to the gene with the best phenotype score in a topological domain
* (doi:10.1038/nature11082). 'Recent research shows that high-order chromosome structures make an important contribution
* to enhancer functionality by triggering their physical interactions with target genes.' (doi:10.1038/nature12753).
*
* @author Damian Smedley <damian.smedley@sanger.ac.uk>
* @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk>
*/
public class GeneReassigner {
private static final Logger logger = LoggerFactory.getLogger(GeneReassigner.class);
private final PriorityType priorityType;
private final ChromosomalRegionIndex<TopologicalDomain> tadIndex;
/**
* @param tadIndex
* @param priorityType
*/
public GeneReassigner(ChromosomalRegionIndex<TopologicalDomain> tadIndex, PriorityType priorityType) {
this.priorityType = priorityType;
this.tadIndex = tadIndex;
logger.info("Made new GeneReassigner for {}", priorityType);
}
public void reassignVariantToMostPhenotypicallySimilarGeneInTad(VariantEvaluation variantEvaluation, Map<String, Gene> allGenes) {
if (variantEvaluation.getVariantEffect() == VariantEffect.REGULATORY_REGION_VARIANT) {
logger.debug("Checking gene assignment for {} chr={} pos={}", variantEvaluation.getVariantEffect(), variantEvaluation.getChromosome(), variantEvaluation.getPosition());
assignVariantToGeneWithHighestPhenotypeScore(variantEvaluation, allGenes);
}
}
private void assignVariantToGeneWithHighestPhenotypeScore(VariantEvaluation variantEvaluation, Map<String, Gene> allGenes) {
Gene geneWithHighestPhenotypeScore = null;
Gene currentlyAssignedGene = allGenes.get(variantEvaluation.getGeneSymbol());
//assign this to the variant's current gene as we don't necessarily want ALL the regulatory region variants to clump into one gene.
float bestScore = prioritiserScore(currentlyAssignedGene);
List<String> genesInTad = getGenesInTadForVariant(variantEvaluation);
for (String geneSymbol : genesInTad) {
Gene gene = allGenes.get(geneSymbol);
logger.debug("Checking gene {}", gene);
if (gene != null && (gene.getPriorityResult(priorityType)) != null) {
float geneScore = prioritiserScore(gene);
logger.debug("Gene {} in TAD has score {}", geneSymbol, geneScore);
if (geneScore > bestScore) {
bestScore = geneScore;
geneWithHighestPhenotypeScore = gene;
}
}
}
if (prioritiserScore(currentlyAssignedGene) == bestScore) {
//don't move the assignment if there is nowhere better to go...
return;
}
if (geneWithHighestPhenotypeScore == null) {
return;
}
assignVariantToGene(variantEvaluation, geneWithHighestPhenotypeScore);
}
private float prioritiserScore(Gene gene) {
return gene.getPriorityResult(priorityType).getScore();
}
private List<String> getGenesInTadForVariant(VariantEvaluation variantEvaluation) {
List<TopologicalDomain> tadsContainingVariant = tadIndex.getRegionsContainingVariant(variantEvaluation);
return tadsContainingVariant.stream()
.map(TopologicalDomain::getGenes)
.flatMap(geneMap -> geneMap.keySet().stream())
.collect(toList());
}
private void assignVariantToGene(VariantEvaluation variantEvaluation, Gene gene) {
logger.debug("Reassigning {} {}:{} {}->{} from {} to {}", variantEvaluation.getVariantEffect(), variantEvaluation.getChromosome(), variantEvaluation.getPosition(), variantEvaluation.getRef(), variantEvaluation.getAlt(), variantEvaluation.getGeneSymbol(), gene.getGeneSymbol());
variantEvaluation.setEntrezGeneId(gene.getEntrezGeneID());
variantEvaluation.setGeneSymbol(gene.getGeneSymbol());
//given the physical ranges of topologically associated domains, the annotations are likely to be meaningless once reassigned
//TODO: check if the reassigned gene is actually in the annotation list and include this.
variantEvaluation.setAnnotations(Collections.emptyList());
}
//Ignore this for the time being it should be public - this is an attempt to fix Jannovar/Annotation issues.
public void reassignGeneToMostPhenotypicallySimilarGeneInAnnotations(VariantEvaluation variantEvaluation, Map<String, Gene> allGenes) {
List<Annotation> annotations = variantEvaluation.getAnnotations();
Gene geneWithHighestPhenotypeScore = null;
VariantEffect variantEffectForTopHit = null;
Gene currentlyAssignedGene = allGenes.get(variantEvaluation.getGeneSymbol());
float bestScore = prioritiserScore(currentlyAssignedGene);
List<String> geneSymbols = new ArrayList<>();
List<VariantEffect> variantEffects = new ArrayList<>();
List<Annotation> newAnnotations = new ArrayList<>();
Annotation bestAnnotation = null;
for (Annotation a : annotations) {
String geneSymbol = a.getGeneSymbol();
geneSymbols.add(geneSymbol);
variantEffects.add(a.getMostPathogenicVarType());
newAnnotations.add(a);
// hack to deal with fusion protein Jannovar nonsense - ? should the separate genes not be part of the annotation anyway - don't seem to be, should maybe not do this split
if (geneSymbol.contains("-")) {
String[] separateGeneSymbols = geneSymbol.split("-");
for (String separateGeneSymbol : separateGeneSymbols) {
geneSymbols.add(separateGeneSymbol);
variantEffects.add(VariantEffect.CUSTOM);// for - split entries do not know effect
newAnnotations.add(null);
}
}
}
int i = 0;
for (String geneSymbol : geneSymbols) {
Gene gene = allGenes.get(geneSymbol);
VariantEffect ve = variantEffects.get(i);
if (gene != null && (gene.getPriorityResult(priorityType)) != null) {
float geneScore = prioritiserScore(gene);
if (geneScore > bestScore) {
bestScore = geneScore;
geneWithHighestPhenotypeScore = gene;
variantEffectForTopHit = ve;
if (newAnnotations.get(i) != null) {
bestAnnotation = newAnnotations.get(i);
}
else{
bestAnnotation = null;
}
}
}
i++;
}
if (prioritiserScore(currentlyAssignedGene) == bestScore) {
//don't move the assignment if there is nowhere better to go...
return;
}
if (geneWithHighestPhenotypeScore == null) {
return;
}
/* Only reassign variant effect if it has not already been flagged by RegFeatureDao as a regulatory region variant.
Otherwise TAD reassignment and subsequent reg feature filter fail to work as expected
*/
if (variantEvaluation.getVariantEffect() != VariantEffect.REGULATORY_REGION_VARIANT){
variantEvaluation.setVariantEffect(variantEffectForTopHit);
}
// Keep original annotation if possible - used in RegFilter later on and for display
List<Annotation> finalAnnotations = new ArrayList<>();
if (bestAnnotation != null){
finalAnnotations.add(bestAnnotation);
}
variantEvaluation.setAnnotations(finalAnnotations);
variantEvaluation.setEntrezGeneId(geneWithHighestPhenotypeScore.getEntrezGeneID());
variantEvaluation.setGeneSymbol(geneWithHighestPhenotypeScore.getGeneSymbol());
}
}
|
package org.monarchinitiative.exomiser.core.writers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.datatype.jdk7.Jdk7Module;
import de.charite.compbio.jannovar.mendel.ModeOfInheritance;
import org.monarchinitiative.exomiser.core.analysis.Analysis;
import org.monarchinitiative.exomiser.core.analysis.AnalysisResults;
import org.monarchinitiative.exomiser.core.filters.FilterReport;
import org.monarchinitiative.exomiser.core.model.Gene;
import org.monarchinitiative.exomiser.core.model.VariantEvaluation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
/**
* @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk>
*/
public class HtmlResultsWriter implements ResultsWriter {
private static final Logger logger = LoggerFactory.getLogger(HtmlResultsWriter.class);
private final TemplateEngine templateEngine;
private static final OutputFormat OUTPUT_FORMAT = OutputFormat.HTML;
public HtmlResultsWriter() {
Locale.setDefault(Locale.UK);
this.templateEngine = ThymeleafConfig.coreTemplateEngine();
}
@Override
public void writeFile(ModeOfInheritance modeOfInheritance, Analysis analysis, AnalysisResults analysisResults, OutputSettings settings) {
logger.info("Writing HTML results");
String outFileName = ResultsWriterUtils.makeOutputFilename(analysis.getVcfPath(), settings.getOutputPrefix(), OUTPUT_FORMAT, modeOfInheritance);
Path outFile = Paths.get(outFileName);
try (BufferedWriter writer = Files.newBufferedWriter(outFile, StandardCharsets.UTF_8)) {
Context context = buildContext(modeOfInheritance, analysis, analysisResults, settings);
templateEngine.process("results", context, writer);
} catch (IOException ex) {
logger.error("Unable to write results to file {}", outFileName, ex);
}
logger.info("{} ALL results written to file {}", OUTPUT_FORMAT, outFileName);
}
@Override
public String writeString(ModeOfInheritance modeOfInheritance, Analysis analysis, AnalysisResults analysisResults, OutputSettings settings) {
logger.info("Writing HTML results");
Context context = buildContext(modeOfInheritance, analysis, analysisResults, settings);
return templateEngine.process("results", context);
}
private Context buildContext(ModeOfInheritance modeOfInheritance, Analysis analysis, AnalysisResults analysisResults, OutputSettings settings) {
Context context = new Context();
//write the settings
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
//required for correct output of Path types
mapper.registerModule(new Jdk7Module());
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
//avoids issues where there are oddities in the analysisSteps - none of these properly de/serialise at present
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
StringBuilder jsonSettings = new StringBuilder();
try {
jsonSettings.append(mapper.writeValueAsString(analysis));
jsonSettings.append(mapper.writeValueAsString(settings));
} catch (JsonProcessingException ex) {
logger.error("Unable to process JSON settings", ex);
}
context.setVariable("settings", jsonSettings.toString());
//make the user aware of any unanalysed variants
List<VariantEvaluation> unAnalysedVarEvals = analysisResults.getUnAnnotatedVariantEvaluations();
context.setVariable("unAnalysedVarEvals", unAnalysedVarEvals);
//write out the analysis reports section
List<FilterReport> analysisStepReports = ResultsWriterUtils.makeFilterReports(analysis, analysisResults);
context.setVariable("filterReports", analysisStepReports);
//write out the variant type counters
List<String> sampleNames = analysisResults.getSampleNames();
List<VariantEffectCount> variantTypeCounters = ResultsWriterUtils.makeVariantEffectCounters(sampleNames, analysisResults
.getVariantEvaluations());
String sampleName = "Anonymous";
if (!analysis.getProbandSampleName().isEmpty()) {
sampleName = analysis.getProbandSampleName();
}
context.setVariable("sampleName", sampleName);
context.setVariable("sampleNames", sampleNames);
context.setVariable("variantTypeCounters", variantTypeCounters);
context.setVariable("modeOfInheritance", modeOfInheritance);
List<Gene> passedGenes = ResultsWriterUtils.getMaxPassedGenes(analysisResults.getGenes(), settings.getNumberOfGenesToShow());
context.setVariable("genes", passedGenes);
//this will change the links to the relevant resource.
// For the time being we're going to maintain the original behaviour (UCSC)
// Need to wire it up through the system or it might be easiest to autodetect this from the transcripts of passed variants.
// One of UCSC, ENSEMBL or REFSEQ
context.setVariable("transcriptDb", "ENSEMBL");
context.setVariable("variantRankComparator", new VariantEvaluation.RankBasedComparator());
return context;
}
//TODO:
// /**
// * This function writes out a table representing the PED file of the family
// * being analysed (if a multisample VCF file is being analysed) or the name
// * of the sample (for a single-sample VCF file).
// * <P>
// * For multisample VCF files, a color code is used to mark the following
// * kinds of samples (individuals):
// * <ul>
// * <li>Unaffected parent: white</li>
// * <li>Affected (whether parent or not): dark grey</li>
// * <li>Unaffected sibling: light blue</li>
// * </ul>
// * The same color code will be used for showing the genotypes of the
// * individual variants, which hopefully will help in their interpretation.
// *
// * @param out An open file handle (can come from the command line or server
// * versions of Exomiser).
// */
// public void writePedigreeTable(Writer out) throws IOException {
// int n = this.pedigree.getNumberOfIndividualsInPedigree();
// if (n == 1) {
// String sampleName = this.pedigree.getSingleSampleName();
// out.write("<table class=\"pedigree\">\n");
// out.write(String.format("<tr><td>Sample name: %s</td></tr>\n", sampleName));
// out.write("</table>\n");
// } else { /* multiple samples */
// out.write("<h2>Analyzed samples</h2>\n");
// out.write("<p>affected: red, parent of affected: light blue, unaffected: white</p>\n");
// out.write("<table class=\"pedigree\">\n");
// for (int i = 0; i < n; ++i) {
// List<String> lst = this.pedigree.getPEDFileDatForNthPerson(i);
// String fam = lst.get(0);
// String id = lst.get(1);
// String fathID = lst.get(2);
// String mothID = lst.get(3);
// String sex = lst.get(4);
// String disease = lst.get(5);
// out.write("<tr><td>" + fam + "</td>");
// if (this.pedigree.isNthPersonAffected(i)) {
// out.write("<td id=\"g\">" + id + "</td>");
// } else if (this.pedigree.isNthPersonParentOfAffected(i)) {
// out.write("<td id=\"b\">" + id + "</td>");
// } else {
// out.write("<td id=\"w\">" + id + "</td>");
// out.write("<td>" + fathID + "</td><td>" + mothID + "</td><td>"
// + sex + "</td><td>" + disease + "</td></tr>\n");
// out.write("</table>\n");
// out.write("<br/>\n");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.