answer stringlengths 17 10.2M |
|---|
package com.speedment.runtime.core.internal.util.testing;
import static com.speedment.runtime.core.internal.util.testing.JavaVersionUtil.JavaVersion.*;
/**
*
* @author Per Minborg
*/
public final class JavaVersionUtil {
public enum JavaVersion {
UNKNOWN, EIGHT, NINE, TEN;
}
public static boolean is8() {
return getJavaVersion() == EIGHT;
}
public static boolean is9() {
return getJavaVersion() == NINE;
}
public static boolean is10() {
return getJavaVersion() == TEN;
}
public static JavaVersion getJavaVersion() {
final String version = System.getProperty("java.specification.version");
if (version == null) {
return UNKNOWN;
}
if (version.startsWith("1.8")) {
return EIGHT;
}
if (version.startsWith("9")) {
return NINE;
}
if (version.startsWith("10")) {
return TEN;
}
return UNKNOWN;
}
} |
package org.jboss.as.test.manualmode.ws;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.helpers.Operations;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.junit.After;
import org.junit.Assert;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xnio.IoUtils;
@RunWith(Arquillian.class)
@RunAsClient
public class ReloadWSDLPublisherTestCase {
private static final String DEFAULT_JBOSSAS = "default-jbossas";
private static final String DEPLOYMENT = "jaxws-manual-pojo";
private static final String keepAlive = System.getProperty("http.keepAlive") == null ? "true" : System.getProperty("http.keepAlive");
@ArquillianResource
ContainerController containerController;
@ArquillianResource
Deployer deployer;
@Deployment(name = DEPLOYMENT, testable = false, managed = false)
public static WebArchive deployment() {
WebArchive pojoWar = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war").addClasses(
EndpointIface.class, PojoEndpoint.class);
return pojoWar;
}
@Before
public void endpointLookup() throws Exception {
containerController.start(DEFAULT_JBOSSAS);
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
deployer.deploy(DEPLOYMENT);
}
}
@Test
@OperateOnDeployment(DEPLOYMENT)
public void testHelloStringAfterReload() throws Exception {
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
ManagementClient managementClient = new ManagementClient(TestSuiteEnvironment.getModelControllerClient(),
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "http-remoting");
QName serviceName = new QName("http://jbossws.org/basic", "POJOService");
URL wsdlURL = new URL(managementClient.getWebUri().toURL(), '/' + DEPLOYMENT + "/POJOService?wsdl");
checkWsdl(wsdlURL);
Service service = Service.create(wsdlURL, serviceName);
EndpointIface proxy = service.getPort(EndpointIface.class);
Assert.assertEquals("Hello World!", proxy.helloString("World"));
reloadServer(managementClient, 100000);
checkWsdl(wsdlURL);
serviceName = new QName("http://jbossws.org/basic", "POJOService");
service = Service.create(wsdlURL, serviceName);
proxy = service.getPort(EndpointIface.class);
Assert.assertEquals("Hello World!", proxy.helloString("World"));
Assert.assertTrue(containerController.isStarted(DEFAULT_JBOSSAS));
}
@After
public void stopContainer() {
System.setProperty("http.keepAlive", keepAlive);
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
deployer.undeploy(DEPLOYMENT);
}
if (containerController.isStarted(DEFAULT_JBOSSAS)) {
containerController.stop(DEFAULT_JBOSSAS);
}
}
private void reloadServer(ManagementClient managementClient, int timeout) throws Exception {
executeReload(managementClient.getControllerClient());
waitForLiveServerToReload(timeout);
}
private void executeReload(ModelControllerClient client) throws IOException {
ModelNode operation = new ModelNode();
operation.get(OP_ADDR).setEmptyList();
operation.get(OP).set("reload");
try {
Assert.assertTrue(Operations.isSuccessfulOutcome(client.execute(operation)));
} catch(IOException e) {
final Throwable cause = e.getCause();
if (cause instanceof ExecutionException) {
// ignore, this might happen if the channel gets closed before we got the response
} else {
throw e;
}
} finally {
client.close();
}
}
private void waitForLiveServerToReload(int timeout) throws Exception {
long start = System.currentTimeMillis();
ModelNode operation = new ModelNode();
operation.get(OP_ADDR).setEmptyList();
operation.get(OP).set(READ_ATTRIBUTE_OPERATION);
operation.get(NAME).set("server-state");
while (System.currentTimeMillis() - start < timeout) {
ModelControllerClient liveClient = ModelControllerClient.Factory.create(
TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort());
try {
ModelNode result = liveClient.execute(operation);
if ("running".equals(result.get(RESULT).asString())) {
return;
}
} catch (IOException e) {
} finally {
IoUtils.safeClose(liveClient);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
fail("Live Server did not reload in the imparted time.");
}
private void checkWsdl(URL wsdlURL) throws IOException {
System.setProperty("http.keepAlive", "false");
HttpURLConnection connection = (HttpURLConnection) wsdlURL.openConnection();
try {
connection.connect();
Assert.assertEquals(200, connection.getResponseCode());
} finally {
connection.disconnect();
}
}
} |
package org.xwiki.component.embed;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xwiki.component.annotation.ComponentAnnotationLoader;
import org.xwiki.component.descriptor.ComponentDependency;
import org.xwiki.component.descriptor.ComponentDescriptor;
import org.xwiki.component.descriptor.ComponentInstantiationStrategy;
import org.xwiki.component.internal.Composable;
import org.xwiki.component.internal.ReflectionUtils;
import org.xwiki.component.internal.RoleHint;
import org.xwiki.component.logging.VoidLogger;
import org.xwiki.component.manager.ComponentDescriptorAddedEvent;
import org.xwiki.component.manager.ComponentLifecycleException;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.manager.ComponentRepositoryException;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.LogEnabled;
import org.xwiki.observation.ObservationManager;
/**
* Simple implementation of {@link ComponentManager} to be used when using some XWiki modules standalone.
*
* @version $Id$
* @since 2.0M1
*/
public class EmbeddableComponentManager implements ComponentManager
{
private Map<RoleHint< ? >, ComponentDescriptor< ? >> descriptors = new HashMap<RoleHint< ? >, ComponentDescriptor< ? >>();
private Map<RoleHint< ? >, Object> components = new HashMap<RoleHint< ? >, Object>();
private ClassLoader classLoader;
public EmbeddableComponentManager(ClassLoader classLoader)
{
this.classLoader = classLoader;
}
/**
* Load all component annotations and register them as components.
*
* @param classLoader the class loader to use to look for component definitions
*/
public void initialize()
{
ComponentAnnotationLoader loader = new ComponentAnnotationLoader();
loader.initialize(this, this.classLoader);
}
/**
* {@inheritDoc}
* @see ComponentManager#lookup(Class)
*/
public <T> T lookup(Class< T > role) throws ComponentLookupException
{
return initialize(new RoleHint<T>(role));
}
/**
* {@inheritDoc}
* @see ComponentManager#lookup(Class, String)
*/
public <T> T lookup(Class< T > role, String roleHint) throws ComponentLookupException
{
return initialize(new RoleHint<T>(role, roleHint));
}
/**
* {@inheritDoc}
* @see ComponentManager#lookupList(Class)
*/
public <T> List< T > lookupList(Class< T > role) throws ComponentLookupException
{
return initializeList(role);
}
/**
* {@inheritDoc}
* @see ComponentManager#lookupMap(Class)
*/
public <T> Map<String, T> lookupMap(Class< T > role) throws ComponentLookupException
{
return initializeMap(role);
}
/**
* {@inheritDoc}
* @see ComponentManager#registerComponent(ComponentDescriptor)
*/
public <T> void registerComponent(ComponentDescriptor<T> componentDescriptor) throws ComponentRepositoryException
{
synchronized(this) {
this.descriptors.put(new RoleHint<T>(componentDescriptor.getRole(), componentDescriptor.getRoleHint()),
componentDescriptor);
}
}
/**
* Add ability to register a component instance. Useful for unit testing.
*/
public <T> void registerComponent(Class< T > role, String hint, Object component)
{
synchronized(this) {
this.components.put(new RoleHint<T>(role, hint), component);
}
}
/**
* Add ability to register a component instance. Useful for unit testing.
*/
public <T> void registerComponent(Class< T > role, Object component)
{
synchronized(this) {
this.components.put(new RoleHint<T>(role), component);
}
}
/**
* {@inheritDoc}
* @see ComponentManager#getComponentDescriptor(Class, String)
*/
@SuppressWarnings("unchecked")
public <T> ComponentDescriptor<T> getComponentDescriptor(Class< T > role, String roleHint)
{
synchronized(this) {
return (ComponentDescriptor<T>) this.descriptors.get(new RoleHint<T>(role, roleHint));
}
}
/**
* {@inheritDoc}
* @see ComponentManager#release(Object)
*/
public <T> void release(T component) throws ComponentLifecycleException
{
synchronized(this) {
for (Map.Entry<RoleHint<?>, Object> entry : this.components.entrySet()) {
if (entry.getValue() == component) {
this.components.remove(entry.getKey());
}
}
}
}
@SuppressWarnings("unchecked")
private <T> List<T> initializeList(Class< T > role) throws ComponentLookupException
{
List<T> objects = new ArrayList<T>();
synchronized(this) {
for (RoleHint<?> roleHint : this.descriptors.keySet()) {
if (roleHint.getRole().getName().equals(role.getName())) {
objects.add(initialize((RoleHint<T>)roleHint));
}
}
}
return objects;
}
@SuppressWarnings("unchecked")
private <T> Map<String, T> initializeMap(Class< ? > role) throws ComponentLookupException
{
Map<String, T> objects = new HashMap<String, T>();
synchronized(this) {
for (RoleHint<?> roleHint : this.descriptors.keySet()) {
if (roleHint.getRole().getName().equals(role.getName())) {
objects.put(roleHint.getHint(), initialize((RoleHint<T>)roleHint));
}
}
}
return objects;
}
@SuppressWarnings("unchecked")
private <T> T initialize(RoleHint<T> roleHint) throws ComponentLookupException
{
T instance;
synchronized(this) {
instance = (T) this.components.get(roleHint);
if (instance == null) {
try {
instance = createInstance(roleHint);
if (instance == null) {
throw new ComponentLookupException("Failed to lookup component [" + roleHint + "]");
} else if (this.descriptors.get(roleHint).getInstantiationStrategy()
== ComponentInstantiationStrategy.SINGLETON)
{
this.components.put(roleHint, instance);
}
} catch (Exception e) {
throw new ComponentLookupException("Failed to lookup component [" + roleHint + "]", e);
}
// Send an Observation event to listeners
ObservationManager om = lookup(ObservationManager.class);
ComponentDescriptor descriptor = this.descriptors.get(roleHint);
ComponentDescriptorAddedEvent event = new ComponentDescriptorAddedEvent(descriptor.getRole());
om.notify(event, this, descriptor);
}
}
return instance;
}
@SuppressWarnings("unchecked")
private <T> T createInstance(RoleHint<T> roleHint) throws Exception
{
T instance = null;
// Instantiate component
ComponentDescriptor<T> descriptor = (ComponentDescriptor<T>) this.descriptors.get(roleHint);
if (descriptor != null) {
Class<T> componentClass = (Class<T>) this.classLoader.loadClass(descriptor.getImplementation());
instance = componentClass.newInstance();
// Set each dependency
for (ComponentDependency<?> dependency : descriptor.getComponentDependencies()) {
// TODO: Handle dependency cycles
// Handle different field types
Object fieldValue;
if ((dependency.getMappingType() != null)
&& List.class.isAssignableFrom(dependency.getMappingType()))
{
fieldValue = lookupList(dependency.getRole());
} else if ((dependency.getMappingType() != null)
&& Map.class.isAssignableFrom(dependency.getMappingType()))
{
fieldValue = lookupMap(dependency.getRole());
} else {
fieldValue = lookup(dependency.getRole(), dependency.getRoleHint());
}
// Set the field by introspection
if (fieldValue != null) {
ReflectionUtils.setFieldValue(instance, dependency.getName(), fieldValue);
}
}
// Call Lifecycle
// LogEnabled
if (LogEnabled.class.isAssignableFrom(componentClass)) {
// TODO: Use a proper logger
((LogEnabled) instance).enableLogging(new VoidLogger());
}
// Composable
// Only support Composable for classes implementing ComponentManager since for all other components
// they should have ComponentManager injected.
if (ComponentManager.class.isAssignableFrom(componentClass)
&& Composable.class.isAssignableFrom(componentClass))
{
((Composable) instance).compose(this);
}
// Initializable
if (Initializable.class.isAssignableFrom(componentClass)) {
((Initializable) instance).initialize();
}
}
return instance;
}
} |
package im.actor.core.modules.internal.contacts;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import im.actor.core.api.ApiUser;
import im.actor.core.api.rpc.RequestGetContacts;
import im.actor.core.api.rpc.ResponseGetContacts;
import im.actor.core.entity.Contact;
import im.actor.core.entity.User;
import im.actor.core.modules.ModuleContext;
import im.actor.core.modules.utils.ModuleActor;
import im.actor.core.network.RpcCallback;
import im.actor.core.network.RpcException;
import im.actor.runtime.Crypto;
import im.actor.runtime.Log;
import im.actor.runtime.bser.DataInput;
import im.actor.runtime.bser.DataOutput;
public class ContactsSyncActor extends ModuleActor {
private static final String TAG = "ContactsServerSync";
private final boolean ENABLE_LOG;
private ArrayList<Integer> contacts = new ArrayList<Integer>();
private boolean isInProgress = false;
private boolean isInvalidated = false;
public ContactsSyncActor(ModuleContext context) {
super(context);
ENABLE_LOG = context.getConfiguration().isEnableContactsLogging();
}
@Override
public void preStart() {
super.preStart();
if (ENABLE_LOG) {
Log.d(TAG, "Loading contacts ids from storage...");
}
byte[] data = preferences().getBytes("contact_list");
if (data != null) {
try {
DataInput dataInput = new DataInput(data, 0, data.length);
int count = dataInput.readInt();
for (int i = 0; i < count; i++) {
contacts.add(dataInput.readInt());
}
} catch (IOException e) {
e.printStackTrace();
}
}
notifyState();
self().send(new PerformSync());
}
public void performSync() {
if (ENABLE_LOG) {
Log.d(TAG, "Checking sync");
}
if (isInProgress) {
if (ENABLE_LOG) {
Log.d(TAG, "Sync in progress, invalidating current sync");
}
isInvalidated = true;
return;
}
isInProgress = true;
isInvalidated = false;
if (ENABLE_LOG) {
Log.d(TAG, "Starting sync");
}
Integer[] uids = contacts.toArray(new Integer[contacts.size()]);
Arrays.sort(uids);
String hash = "";
for (long u : uids) {
if (hash.length() != 0) {
hash += ",";
}
hash += u;
}
byte[] hashData;
try {
hashData = hash.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return;
}
String hashValue = Crypto.hex(Crypto.SHA256(hashData));
Log.d(TAG, "Performing sync with hash: " + hashValue);
request(new RequestGetContacts(hashValue), new RpcCallback<ResponseGetContacts>() {
@Override
public void onResult(ResponseGetContacts response) {
updates().onUpdateReceived(
new im.actor.core.modules.updates.internal.ContactsLoaded(response));
}
@Override
public void onError(RpcException e) {
isInProgress = false;
e.printStackTrace();
}
});
}
public void onContactsLoaded(ResponseGetContacts result) {
if (ENABLE_LOG) {
Log.d(TAG, "Sync result received");
}
isInProgress = false;
context().getAppStateModule().onContactsLoaded();
if (result.isNotChanged()) {
Log.d(TAG, "Sync: Not changed");
if (isInvalidated) {
performSync();
} else {
// ProfileSyncState.onContactsLoaded(contactUsers.size() == 0);
}
return;
}
if (ENABLE_LOG) {
Log.d(TAG, "Sync received " + result.getUsers().size() + " contacts");
}
outer:
for (Integer uid : contacts.toArray(new Integer[contacts.size()])) {
for (ApiUser u : result.getUsers()) {
if (u.getId() == uid) {
continue outer;
}
}
if (ENABLE_LOG) {
Log.d(TAG, "Removing: #" + uid);
}
contacts.remove((Integer) uid);
if (getUser(uid) != null) {
getUserVM(uid).isContact().change(false);
}
context().getContactsModule().markNonContact(uid);
}
for (ApiUser u : result.getUsers()) {
if (contacts.contains(u.getId())) {
continue;
}
if (ENABLE_LOG) {
Log.d(TAG, "Adding: #" + u.getId());
}
contacts.add(u.getId());
if (getUser(u.getId()) != null) {
getUserVM(u.getId()).isContact().change(true);
}
context().getContactsModule().markContact(u.getId());
}
saveList();
updateEngineList();
if (isInvalidated) {
self().send(new PerformSync());
}
}
public void onContactsAdded(int[] uids) {
if (ENABLE_LOG) {
Log.d(TAG, "OnContactsAdded received");
}
for (int uid : uids) {
if (ENABLE_LOG) {
Log.d(TAG, "Adding: #" + uid);
}
contacts.add(uid);
context().getContactsModule().markContact(uid);
getUserVM(uid).isContact().change(true);
}
saveList();
updateEngineList();
self().send(new PerformSync());
}
public void onContactsRemoved(int[] uids) {
if (ENABLE_LOG) {
Log.d(TAG, "OnContactsRemoved received");
}
for (int uid : uids) {
Log.d(TAG, "Removing: #" + uid);
contacts.remove((Integer) uid);
context().getContactsModule().markNonContact(uid);
getUserVM(uid).isContact().change(false);
}
saveList();
updateEngineList();
self().send(new PerformSync());
}
public void onUserChanged(User user) {
if (ENABLE_LOG) {
Log.d(TAG, "OnUserChanged #" + user.getUid() + " received");
}
if (!contacts.contains(user.getUid())) {
return;
}
updateEngineList();
}
private void updateEngineList() {
if (ENABLE_LOG) {
Log.d(TAG, "Saving contact EngineList");
}
ArrayList<User> userList = new ArrayList<User>();
for (int u : contacts) {
userList.add(getUser(u));
}
Collections.sort(userList, new Comparator<User>() {
@Override
public int compare(User lhs, User rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
List<Contact> registeredContacts = new ArrayList<Contact>();
int index = -1;
for (User userModel : userList) {
Contact contact = new Contact(userModel.getUid(),
(long) index
userModel.getAvatar(),
userModel.getName());
registeredContacts.add(contact);
}
context().getContactsModule().getContacts().replaceItems(registeredContacts);
Integer[] sorted = new Integer[contacts.size()];
int sindex = 0;
for (User userModel : userList) {
sorted[sindex++] = userModel.getUid();
}
context().getSearchModule().onContactsChanged(sorted);
notifyState();
}
private void saveList() {
if (ENABLE_LOG) {
Log.d(TAG, "Saving contacts ids to storage");
}
DataOutput dataOutput = new DataOutput();
dataOutput.writeInt(contacts.size());
for (int l : contacts) {
dataOutput.writeInt(l);
}
preferences().putBytes("contact_list", dataOutput.toByteArray());
}
private void notifyState() {
context().getAppStateModule().onContactsUpdate(context().getContactsModule().getContacts().isEmpty());
}
@Override
public void onReceive(Object message) {
if (message instanceof ContactsLoaded) {
onContactsLoaded(((ContactsLoaded) message).getResult());
} else if (message instanceof ContactsAdded) {
onContactsAdded(((ContactsAdded) message).getUids());
} else if (message instanceof ContactsRemoved) {
onContactsRemoved(((ContactsRemoved) message).getUids());
} else if (message instanceof UserChanged) {
onUserChanged(((UserChanged) message).getUser());
} else if (message instanceof PerformSync) {
performSync();
} else {
drop(message);
}
}
private static class PerformSync {
}
public static class ContactsLoaded {
private ResponseGetContacts result;
public ContactsLoaded(ResponseGetContacts result) {
this.result = result;
}
public ResponseGetContacts getResult() {
return result;
}
}
public static class ContactsAdded {
private int[] uids;
public ContactsAdded(int[] uids) {
this.uids = uids;
}
public int[] getUids() {
return uids;
}
}
public static class ContactsRemoved {
private int[] uids;
public ContactsRemoved(int[] uids) {
this.uids = uids;
}
public int[] getUids() {
return uids;
}
}
public static class UserChanged {
private User user;
public UserChanged(User user) {
this.user = user;
}
public User getUser() {
return user;
}
}
} |
package com.sap.core.odata.processor.core.jpa.access.data;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sap.core.odata.api.edm.EdmEntitySet;
import com.sap.core.odata.api.edm.EdmEntityType;
import com.sap.core.odata.api.edm.EdmException;
import com.sap.core.odata.api.edm.EdmNavigationProperty;
import com.sap.core.odata.api.edm.EdmProperty;
import com.sap.core.odata.api.edm.EdmStructuralType;
import com.sap.core.odata.api.edm.EdmTypeKind;
import com.sap.core.odata.api.edm.EdmTyped;
import com.sap.core.odata.api.ep.entry.ODataEntry;
import com.sap.core.odata.api.ep.feed.ODataFeed;
import com.sap.core.odata.processor.api.jpa.exception.ODataJPARuntimeException;
import com.sap.core.odata.processor.api.jpa.model.JPAEdmMapping;
public class JPAEntity {
private Object jpaEntity = null;
private EdmEntityType oDataEntityType = null;
private EdmEntitySet oDataEntitySet = null;
private Class<?> jpaType = null;
private HashMap<String, Method> accessModifiersWrite = null;
private JPAEntityParser jpaEntityParser = null;
public HashMap<EdmNavigationProperty, EdmEntitySet> inlinedEntities = null;
public JPAEntity(EdmEntityType oDataEntityType, EdmEntitySet oDataEntitySet) {
this.oDataEntityType = oDataEntityType;
this.oDataEntitySet = oDataEntitySet;
try {
JPAEdmMapping mapping = (JPAEdmMapping) oDataEntityType.getMapping();
this.jpaType = mapping.getJPAType();
} catch (EdmException e) {
return;
}
jpaEntityParser = JPAEntityParser.create();
}
public void setAccessModifersWrite(HashMap<String, Method> accessModifiersWrite) {
this.accessModifiersWrite = accessModifiersWrite;
}
public Object getJPAEntity() {
return jpaEntity;
}
@SuppressWarnings("unchecked")
private void write(Map<String, Object> oDataEntryProperties, boolean isCreate) throws ODataJPARuntimeException {
try {
EdmStructuralType structuralType = null;
final List<String> keyNames = oDataEntityType.getKeyPropertyNames();
if (isCreate)
jpaEntity = instantiateJPAEntity();
else if (jpaEntity == null)
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.RESOURCE_NOT_FOUND, null);
if (accessModifiersWrite == null)
accessModifiersWrite = jpaEntityParser.getAccessModifiers(jpaEntity, oDataEntityType, JPAEntityParser.ACCESS_MODIFIER_SET);
if (oDataEntityType == null || oDataEntryProperties == null)
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL, null);
final HashMap<String, String> embeddableKeys = jpaEntityParser.getJPAEmbeddableKeyMap(jpaEntity.getClass().getName());
Set<String> propertyNames = null;
if (embeddableKeys != null)
{
setEmbeddableKeyProperty(embeddableKeys, oDataEntityType.getKeyProperties(), oDataEntryProperties, jpaEntity);
propertyNames = new HashSet<String>();
propertyNames.addAll(oDataEntryProperties.keySet());
for (String propertyName : oDataEntityType.getKeyPropertyNames())
propertyNames.remove(propertyName);
}
else
propertyNames = oDataEntryProperties.keySet();
for (String propertyName : propertyNames) {
EdmTyped edmTyped = (EdmTyped) oDataEntityType.getProperty(propertyName);
Method accessModifier = null;
switch (edmTyped.getType().getKind()) {
case SIMPLE:
if (isCreate == false) {
if (keyNames.contains(edmTyped.getName()))
continue;
}
accessModifier = accessModifiersWrite.get(propertyName);
setProperty(accessModifier, jpaEntity, oDataEntryProperties.get(propertyName));
break;
case COMPLEX:
structuralType = (EdmStructuralType) edmTyped.getType();
accessModifier = accessModifiersWrite.get(propertyName);
setComplexProperty(accessModifier, jpaEntity,
structuralType,
(HashMap<String, Object>) oDataEntryProperties.get(propertyName));
break;
case NAVIGATION:
case ENTITY:
structuralType = (EdmStructuralType) edmTyped.getType();
accessModifier = jpaEntityParser.getAccessModifier(jpaEntity, (EdmNavigationProperty) edmTyped, JPAEntityParser.ACCESS_MODIFIER_SET);
EdmEntitySet edmRelatedEntitySet = oDataEntitySet.getRelatedEntitySet((EdmNavigationProperty) edmTyped);
List<ODataEntry> relatedEntries = (List<ODataEntry>) oDataEntryProperties.get(propertyName);
List<Object> relatedJPAEntites = new ArrayList<Object>();
JPAEntity relatedEntity = new JPAEntity((EdmEntityType) structuralType, edmRelatedEntitySet);
for (ODataEntry oDataEntry : relatedEntries) {
relatedEntity.create(oDataEntry);
relatedJPAEntites.add(relatedEntity.getJPAEntity());
}
EdmNavigationProperty navProperty = (EdmNavigationProperty) edmTyped;
switch (navProperty.getMultiplicity()) {
case MANY:
accessModifier.invoke(jpaEntity, relatedJPAEntites);
break;
case ONE:
case ZERO_TO_ONE:
accessModifier.invoke(jpaEntity, relatedJPAEntites.get(0));
break;
}
if (inlinedEntities == null)
inlinedEntities = new HashMap<EdmNavigationProperty, EdmEntitySet>();
inlinedEntities.put((EdmNavigationProperty) edmTyped, edmRelatedEntitySet);
default:
continue;
}
}
} catch (Exception e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
}
public void create(ODataEntry oDataEntry) throws ODataJPARuntimeException {
if (oDataEntry == null)
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL, null);
Map<String, Object> oDataEntryProperties = oDataEntry.getProperties();
if (oDataEntry.containsInlineEntry()) {
try {
for (String navigationPropertyName : oDataEntityType.getNavigationPropertyNames()) {
ODataFeed feed = (ODataFeed) oDataEntry.getProperties().get(navigationPropertyName);
if (feed == null) continue;
List<ODataEntry> relatedEntries = feed.getEntries();
oDataEntryProperties.put(navigationPropertyName, relatedEntries);
}
} catch (EdmException e) {
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL
.addContent(e.getMessage()), e);
}
}
write(oDataEntryProperties, true);
}
public void create(Map<String, Object> oDataEntryProperties) throws ODataJPARuntimeException {
write(oDataEntryProperties, true);
}
public void update(ODataEntry oDataEntry) throws ODataJPARuntimeException {
if (oDataEntry == null)
throw ODataJPARuntimeException
.throwException(ODataJPARuntimeException.GENERAL, null);
Map<String, Object> oDataEntryProperties = oDataEntry.getProperties();
write(oDataEntryProperties, false);
}
public void update(Map<String, Object> oDataEntryProperties) throws ODataJPARuntimeException {
write(oDataEntryProperties, false);
}
@SuppressWarnings("unchecked")
protected void setComplexProperty(Method accessModifier, Object jpaEntity, EdmStructuralType edmComplexType, HashMap<String, Object> propertyValue)
throws EdmException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, ODataJPARuntimeException {
JPAEdmMapping mapping = (JPAEdmMapping) edmComplexType.getMapping();
Object embeddableObject = mapping.getJPAType().newInstance();
accessModifier.invoke(jpaEntity, embeddableObject);
HashMap<String, Method> accessModifiers = jpaEntityParser.getAccessModifiers(embeddableObject, edmComplexType, JPAEntityParser.ACCESS_MODIFIER_SET);
for (String edmPropertyName : edmComplexType.getPropertyNames()) {
EdmTyped edmTyped = (EdmTyped) edmComplexType.getProperty(edmPropertyName);
accessModifier = accessModifiers.get(edmPropertyName);
if (edmTyped.getType().getKind().toString().equals(EdmTypeKind.COMPLEX)) {
EdmStructuralType structualType = (EdmStructuralType) edmTyped.getType();
setComplexProperty(accessModifier, embeddableObject, structualType, (HashMap<String, Object>) propertyValue.get(edmPropertyName));
}
else
setProperty(accessModifier, embeddableObject, propertyValue.get(edmPropertyName));
}
}
protected void setProperty(Method method, Object entity, Object entityPropertyValue) throws
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (entityPropertyValue != null)
method.invoke(entity, entityPropertyValue);
}
protected void setEmbeddableKeyProperty(HashMap<String, String> embeddableKeys, List<EdmProperty> oDataEntryKeyProperties,
Map<String, Object> oDataEntryProperties, Object entity)
throws ODataJPARuntimeException, EdmException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
HashMap<String, Object> embeddableObjMap = new HashMap<String, Object>();
List<EdmProperty> leftODataEntryKeyProperties = new ArrayList<EdmProperty>();
HashMap<String, String> leftEmbeddableKeys = new HashMap<String, String>();
for (EdmProperty edmProperty : oDataEntryKeyProperties)
{
if (oDataEntryProperties.containsKey(edmProperty.getName()) == false)
continue;
String edmPropertyName = edmProperty.getName();
String embeddableKeyNameComposite = embeddableKeys.get(edmPropertyName);
String embeddableKeyNameSplit[] = embeddableKeyNameComposite.split("\\.");
String methodPartName = null;
Method method = null;
Object embeddableObj = null;
if (embeddableObjMap.containsKey(embeddableKeyNameSplit[0]) == false) {
methodPartName = embeddableKeyNameSplit[0];
method = jpaEntityParser.getAccessModifierSet(entity, methodPartName);
embeddableObj = method.getParameterTypes()[0].newInstance();
method.invoke(entity, embeddableObj);
embeddableObjMap.put(embeddableKeyNameSplit[0], embeddableObj);
}
else
embeddableObj = embeddableObjMap.get(embeddableKeyNameSplit[0]);
if (embeddableKeyNameSplit.length == 2) {
methodPartName = embeddableKeyNameSplit[1];
method = jpaEntityParser.getAccessModifierSet(embeddableObj, methodPartName);
Object simpleObj = oDataEntryProperties.get(edmProperty.getName());
method.invoke(embeddableObj, simpleObj);
}
else if (embeddableKeyNameSplit.length > 2) // Deeply nested
{
leftODataEntryKeyProperties.add(edmProperty);
leftEmbeddableKeys.put(edmPropertyName, embeddableKeyNameComposite.split(embeddableKeyNameSplit[0] + ".", 2)[1]);
setEmbeddableKeyProperty(leftEmbeddableKeys, leftODataEntryKeyProperties, oDataEntryProperties, embeddableObj);
}
}
}
protected Object instantiateEmbeddableKey(EdmProperty edmProperty, int nestingLevel) throws EdmException, InstantiationException, IllegalAccessException {
JPAEdmMapping propertyMapping = (JPAEdmMapping) edmProperty.getMapping();
if (propertyMapping == null || propertyMapping.getJPAType() == null) throw new InstantiationException();
Object key = propertyMapping.getJPATypeHierachy()[nestingLevel].newInstance();
return key;
}
protected Object instantiateJPAEntity() throws InstantiationException, IllegalAccessException {
if (jpaType == null) throw new InstantiationException();
return jpaType.newInstance();
}
public HashMap<EdmNavigationProperty, EdmEntitySet> getInlineJPAEntities() {
return this.inlinedEntities;
}
public void setJPAEntity(Object jpaEntity) {
this.jpaEntity = jpaEntity;
}
} |
package org.squonk.chemaxon.services;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.camel.model.rest.RestBindingMode;
import org.squonk.camel.chemaxon.processor.clustering.SphereExclusionClusteringProcessor;
import org.squonk.camel.chemaxon.processor.enumeration.ReactorProcessor;
import org.squonk.camel.chemaxon.processor.screening.MoleculeScreenerProcessor;
import org.squonk.camel.processor.DatasetToJsonProcessor;
import org.squonk.camel.processor.JsonToDatasetProcessor;
import org.squonk.camel.processor.MoleculeObjectRouteHttpProcessor;
import org.squonk.chemaxon.molecule.ChemTermsEvaluator;
import org.squonk.core.AccessMode;
import org.squonk.core.ServiceDescriptor;
import org.squonk.core.ServiceDescriptor.DataType;
import org.squonk.execution.steps.StepDefinitionConstants;
import org.squonk.mqueue.MessageQueueCredentials;
import org.squonk.options.MoleculeTypeDescriptor;
import org.squonk.options.OptionDescriptor;
import org.squonk.types.MoleculeObject;
import org.squonk.types.NumberRange;
import org.squonk.types.TypeResolver;
import org.squonk.util.CommonConstants;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import static org.squonk.mqueue.MessageQueueCredentials.MQUEUE_JOB_METRICS_EXCHANGE_NAME;
import static org.squonk.mqueue.MessageQueueCredentials.MQUEUE_JOB_METRICS_EXCHANGE_PARAMS;
/**
* @author timbo
*/
public class ChemaxonRestRouteBuilder extends RouteBuilder {
private static final Logger LOG = Logger.getLogger(ChemaxonRestRouteBuilder.class.getName());
private static final String ROUTE_STATS = "seda:post_stats";
private static final String HEADER = "header.";
private static final String KEY_SIM_CUTTOFF = HEADER + MoleculeScreenerProcessor.HEADER_THRESHOLD;
private static final String LABEL_SIM_CUTTOFF = "Similarity Cuttoff";
private static final String DESC_SIM_CUTTOFF = "Similarity score cuttoff between 0 and 1 (1 means identical)";
private static final String KEY_QMOL = HEADER + MoleculeScreenerProcessor.HEADER_QUERY_MOLECULE;
private static final String LABEL_QMOL = "Query Structure";
private static final String DESC_QMOL = "Structure to use as the query";
// private static final String KEY_CT_EXPR = "ct_expr";
// private static final String LABEL_CT_EXPR = "ChemTerms Expression";
// private static final String DESC_CT_EXPR = "Expression using the Chemical Terms language";
private static final String KEY_MIN_CLUSTERS = HEADER + SphereExclusionClusteringProcessor.HEADER_MIN_CLUSTER_COUNT;
private static final String LABEL_MIN_CLUSTERS = "Min clusters";
private static final String DESC_MIN_CLUSTERS = "Minimum number of clusters to generate";
private static final String KEY_MAX_CLUSTERS = HEADER + SphereExclusionClusteringProcessor.HEADER_MAX_CLUSTER_COUNT;
private static final String LABEL_MAX_CLUSTERS = "Max clusters";
private static final String DESC_MAX_CLUSTERS = "Target maximum number of clusters to generate";
private static final TypeResolver resolver = new TypeResolver();
private final String mqueueUrl = new MessageQueueCredentials().generateUrl(MQUEUE_JOB_METRICS_EXCHANGE_NAME, MQUEUE_JOB_METRICS_EXCHANGE_PARAMS) +
"&routingKey=tokens.chemaxon";
protected static final ServiceDescriptor[] SERVICE_DESCRIPTOR_CALCULATORS
= new ServiceDescriptor[]{
createServiceDescriptor(
"chemaxon.calculators.verify",
"Verify structure (ChemAxon)",
"Verify that the molecules are valid according to ChemAxon's Marvin",
new String[]{"verify", "chemaxon"},
"icons/properties_add.png",
new String[]{"/Chemistry/Toolkits/ChemAxon/Verify", "/Chemistry/Verify"},
"asyncHttp",
"verify",
0f,
new OptionDescriptor[] {OptionDescriptor.IS_FILTER, OptionDescriptor.FILTER_MODE}),
createServiceDescriptor(
"chemaxon.calculators.logp",
"LogP (CXN)",
"LogP using ChemAxon calculators. See http://www.chemaxon.com/products/calculator-plugins/property-predictors/#logp_logd",
new String[]{"logp", "partitioning", "molecularproperties", "chemaxon"},
"icons/properties_add.png",
new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/Partioning"},
"asyncHttp",
"logp",
0.001f,
null),
createServiceDescriptor(
"chemaxon.calculators.atomcount",
"Atom Count (CXN)",
"Atom Count using ChemAxon calculators. See http://www.chemaxon.com/products/calculator-plugins/property-calculations/#topology_analysis",
new String[]{"atomcount", "topology", "molecularproperties", "chemaxon"},
"icons/properties_add.png",
new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/Topological"},
"asyncHttp",
"atomCount",
0f,
null),
createServiceDescriptor(
"chemaxon.calculators.lipinski",
"Lipinski (CXN)",
"Lipinski rule of 5 filter using ChemAxon calculators",
new String[]{"lipinski", "filter", "druglike", "molecularproperties", "chemaxon"},
"icons/filter_molecules.png",
new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/DrugLike"},
"asyncHttp",
"lipinski",
0.002f,
createLipinskiOptionDescriptors()),
createServiceDescriptor(
"chemaxon.calculators.druglikefilter",
"Drug-like Filter (CXN)",
"Drug-like filter using ChemAxon calculators",
new String[]{"druglike", "filter", "molecularproperties", "chemaxon"},
"icons/filter_molecules.png",
new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/DrugLike"},
"asyncHttp",
"drugLikeFilter",
0.0025f,
createDrugLikeFilterOptionDescriptors()),
createServiceDescriptor(
"chemaxon.calculators.ghosefilter",
"Ghose Filter (CXN)",
"Ghose filter using ChemAxon calculators",
new String[]{"ghose", "filter", "druglike", "molecularproperties", "chemaxon"},
"icons/filter_molecules.png",
new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/GhoseFilter"},
"asyncHttp",
"ghosefilter",
0.0025f,
createGhoseFilterOptionDescriptors()),
createServiceDescriptor(
"chemaxon.calculators.ruleofthreefilter",
"Rule of 3 Filter (CXN)",
"Astex Rule of 3 filter using ChemAxon calculators",
new String[]{"ruleofthree", "ro3", "hbond", "donors", "acceptors", "logp", "molecularweight", "rotatablebonds", "leadlike", "molecularproperties", "filter", "chemaxon"},
"icons/filter_molecules.png",
new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/DrugLike"},
"asyncHttp",
"ruleOfThreeFilter",
0.0025f,
createRuleOfThreeOptionDescriptors()),
createServiceDescriptor(
"chemaxon.calculators.reosfilter",
"REOS (CXN)",
"Rapid Elimination Of Swill (REOS) using ChemAxon calculators",
new String[]{"reos", "hbond", "donors", "acceptors", "logp", "molecularweight", "rotatablebonds", "charge", "formalcharge", "leadlike", "molecularproperties", "filter", "chemaxon"},
"icons/filter_molecules.png",
new String[]{"/Vendors/ChemAxon/Calculators", "/Chemistry/Calculators/DrugLike"},
"asyncHttp",
"reosFilter",
0.0025f,
createReosFilterOptionDescriptors())
// createServiceDescriptor(
// "chemaxon.calculators.chemterms",
// "CXN Chemical Terms",
// new String[]{"molecularproperties", "chemaxon"},
// new String[]{"/Vendors/ChemAxon/Calculators", "Chemistry/Calculators/General"},
// "asyncHttp",
// "chemTerms",
// 0.01f,
// new ServicePropertyDescriptor[]{
// new ServicePropertyDescriptor(ServicePropertyDescriptor.Type.STRING, KEY_CT_EXPR, LABEL_CT_EXPR, DESC_CT_EXPR)
};
static private OptionDescriptor[] createLipinskiOptionDescriptors() {
List<OptionDescriptor> list = new ArrayList<>();
list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false));
list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results")
.withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS")
.withMinMaxValues(1,1));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT,
"Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(0f, 500f)));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP,
"LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(null, 5.0f)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT,
"HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT,
"HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 10)));
return list.toArray(new OptionDescriptor[0]);
}
static private OptionDescriptor[] createDrugLikeFilterOptionDescriptors() {
List<OptionDescriptor> list = new ArrayList<>();
list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false));
list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results")
.withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS")
.withMinMaxValues(1,1));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT,
"Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(0f, 400f)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.RING_COUNT,
"Ring count", "Ring count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(1, null)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ROTATABLE_BOND_COUNT,
"Rotatable bond count", "Rotatable bond count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT,
"HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT,
"HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 10)));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP,
"LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(null, 5.0f)));
return list.toArray(new OptionDescriptor[0]);
}
static private OptionDescriptor[] createGhoseFilterOptionDescriptors() {
List<OptionDescriptor> list = new ArrayList<>();
list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false));
list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results")
.withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS")
.withMinMaxValues(1,1));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP,
"LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(-0.4f, 5.6f)));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT,
"MolWeight", "molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(160f, 480f)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ATOM_COUNT,
"Atom count", "Atom count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(20, 70)));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLAR_REFRACTIVITY,
"Refractivity", "Molar Refractivity").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(40f, 130f)));
return list.toArray(new OptionDescriptor[0]);
}
static private OptionDescriptor[] createRuleOfThreeOptionDescriptors() {
List<OptionDescriptor> list = new ArrayList<>();
list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false));
list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results")
.withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS")
.withMinMaxValues(1,1));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP,
"LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(null, 3.0f)));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT,
"Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(0f, 300f)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT,
"HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 3)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT,
"HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 3)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ROTATABLE_BOND_COUNT,
"Rot bond count", "Rotatable bond count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 3)));
return list.toArray(new OptionDescriptor[0]);
}
static private OptionDescriptor[] createReosFilterOptionDescriptors() {
List<OptionDescriptor> list = new ArrayList<>();
list.add(new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false));
list.add(new OptionDescriptor<>(String.class, "query." + CommonConstants.OPTION_FILTER_MODE, "Filter mode", "How to filter results")
.withValues(new String[] {"INCLUDE_PASS", "INCLUDE_FAIL", "INCLUDE_ALL"}).withDefaultValue("INCLUDE_PASS")
.withMinMaxValues(1,1));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.MOLECULAR_WEIGHT,
"Mol weight", "Molecular weight").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(200f, 500f)));
list.add(new OptionDescriptor<>(NumberRange.Float.class, "query." + ChemTermsEvaluator.LOGP,
"LogP", "LogP partition coefficient").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Float(-5.0f, 5.0f)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_DONOR_COUNT,
"HBD count", "H-bond donor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 5)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HBOND_ACCEPTOR_COUNT,
"HBA count", "H-bond acceptor count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 10)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.FORMAL_CHARGE,
"Formal charge", "Formal charge").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(-2, 2)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.ROTATABLE_BOND_COUNT,
"Rot bond count", "Rotatable bond count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(0, 8)));
list.add(new OptionDescriptor<>(NumberRange.Integer.class, "query." + ChemTermsEvaluator.HEAVY_ATOM_COUNT,
"Heavy atom count", "Heavy atom count").withMinMaxValues(0,1).withDefaultValue(new NumberRange.Integer(15, 50)));
return list.toArray(new OptionDescriptor[0]);
}
private static final ServiceDescriptor[] SERVICE_DESCRIPTOR_DESCRIPTORS
= new ServiceDescriptor[]{
createServiceDescriptor(
"chemaxon.screening.ecpf4",
"ECFP4 Screen (CXN)",
"Virtual screening using ChemAxon ECFP4 fingerprints. See http:
new String[]{"virtualscreening", "screening", "ecfp", "ecfp4", "moleculardescriptors", "fingerprints", "chemaxon"},
"icons/filter_molecules.png",
new String[]{"/Vendors/ChemAxon/Screening", "Chemistry/Screening"},
"asyncHttp",
"screening/ecfp4",
0.001f,
new OptionDescriptor[]{
new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false),
new OptionDescriptor<>(new MoleculeTypeDescriptor(MoleculeTypeDescriptor.MoleculeType.DISCRETE, new String[]{"smiles"}), KEY_QMOL, LABEL_QMOL, DESC_QMOL),
new OptionDescriptor<>(Float.class, KEY_SIM_CUTTOFF, LABEL_SIM_CUTTOFF, DESC_SIM_CUTTOFF).withDefaultValue(0.7f)
}),
createServiceDescriptor(
"chemaxon.screening.pharmacophore",
"Pharmacophore Screen (CXN)",
"Virtual screening using ChemAxon 2D pharmacophore fingerprints. See http:
new String[]{"virtualscreening", "screening", "parmacophore", "moleculardescriptors", "fingerprints", "chemaxon"},
"icons/filter_molecules.png",
new String[]{"/Vendors/ChemAxon/Screening", "Chemistry/Screening"},
"asyncHttp",
"screening/pharmacophore",
0.004f,
new OptionDescriptor[]{
new OptionDescriptor<>(Boolean.class, "option.filter", "filter mode", "filter mode").withDefaultValue(true).withAccess(false, false),
new OptionDescriptor<>(new MoleculeTypeDescriptor(MoleculeTypeDescriptor.MoleculeType.DISCRETE, new String[]{"smiles"}), KEY_QMOL, LABEL_QMOL, DESC_QMOL),
new OptionDescriptor<>(Float.class, KEY_SIM_CUTTOFF, LABEL_SIM_CUTTOFF, DESC_SIM_CUTTOFF).withDefaultValue(0.7f)
}),
createServiceDescriptor(
"chemaxon.clustering.sperex",
"SpereEx Clustering (CXN)",
"Sphere exclusion clustering using ChemAxon ECFP4 fingerprints. See http:
new String[]{"clustering", "ecfp", "ecfp4", "chemaxon"},
"icons/clustering.png",
new String[]{"/Vendors/ChemAxon/Clustering", "Chemistry/Clustering"},
"asyncHttp",
"clustering/spherex/ecfp4",
0.002f,
new OptionDescriptor[]{
new OptionDescriptor<>(Integer.class, KEY_MIN_CLUSTERS, LABEL_MIN_CLUSTERS, DESC_MIN_CLUSTERS).withDefaultValue(5),
new OptionDescriptor<>(Integer.class, KEY_MAX_CLUSTERS, LABEL_MAX_CLUSTERS, DESC_MAX_CLUSTERS).withDefaultValue(10)
})
};
static ServiceDescriptor createServiceDescriptor(String serviceDescriptorId, String name, String desc, String[] tags, String icon,
String[] paths, String modeId, String endpoint, float cost, OptionDescriptor[] props) {
return new ServiceDescriptor(
serviceDescriptorId,
name,
desc,
tags,
null,
paths,
"Tim Dudgeon <tdudgeon@informaticsmatters.com>",
null,
new String[]{"public"},
MoleculeObject.class, // inputClass
MoleculeObject.class, // outputClass
DataType.STREAM, // inputType
DataType.STREAM, // outputType
icon,
new AccessMode[]{
new AccessMode(
modeId,
"Immediate execution",
"Execute as an asynchronous REST web service",
endpoint,
true, // a relative URL
null,
null,
cost,
new ServiceDescriptor.LicenseToken[]{ServiceDescriptor.LicenseToken.CHEMAXON},
props,
StepDefinitionConstants.MoleculeServiceThinExecutor.CLASSNAME)
}
);
}
@Override
public void configure() throws Exception {
restConfiguration().component("servlet").host("0.0.0.0");
// send usage metrics to the message queue
from(ROUTE_STATS)
.marshal().json(JsonLibrary.Jackson)
.to(mqueueUrl);
/* These are the REST endpoints - exposed as public web services
*/
rest("ping")
.get().description("Simple ping service to check things are running")
.produces("text/plain")
.route()
.transform(constant("OK\n")).endRest();
rest("v1/calculators").description("Property calculation services using ChemAxon")
.bindingMode(RestBindingMode.off)
.consumes("application/json")
.produces("application/json")
// service descriptor
.get().description("ServiceDescriptors for ChemAxon calculators")
.bindingMode(RestBindingMode.json)
.produces("application/json")
.route()
.process((Exchange exch) -> {
exch.getIn().setBody(SERVICE_DESCRIPTOR_CALCULATORS);
})
.endRest()
.post("verify").description("Verify as Marvin molecules")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_STRUCTURE_VERIFY, resolver, ROUTE_STATS))
.endRest()
.post("logp").description("Calculate the logP for the supplied MoleculeObjects")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_LOGP, resolver, ROUTE_STATS))
.endRest()
.post("atomCount").description("Calculate the atom count for the supplied MoleculeObjects")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_ATOM_COUNT, resolver, ROUTE_STATS))
.endRest()
.post("lipinski").description("Calculate the Lipinski properties for the supplied MoleculeObjects")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_LIPINSKI, resolver, ROUTE_STATS))
.endRest()
.post("drugLikeFilter").description("Apply a drug like filter to the supplied MoleculeObjects")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_DRUG_LIKE_FILTER, resolver, ROUTE_STATS))
.endRest()
.post("ghoseFilter").description("Apply a Ghose filter to the supplied MoleculeObjects")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_GHOSE_FILTER, resolver, ROUTE_STATS))
.endRest()
.post("ruleOfThreeFilter").description("Apply a Rule of 3 filter to the supplied MoleculeObjects")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_RULE_OF_THREE, resolver, ROUTE_STATS))
.endRest()
.post("reosFilter").description("Apply a REOS filter to the supplied MoleculeObjects")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_REOS, resolver, ROUTE_STATS))
.endRest()
.post("chemTerms").description("Calculate a chemical terms expression for the supplied MoleculeObjects")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonCalculatorsRouteBuilder.CHEMAXON_CHEMTERMS, resolver, ROUTE_STATS))
.endRest();
rest("v1/descriptors").description("Screening and clustering services using ChemAxon")
.bindingMode(RestBindingMode.off)
.consumes("application/json")
.produces("application/json")
// service descriptor
.get().description("ServiceDescriptors for ChemAxon descriptors")
.bindingMode(RestBindingMode.json)
.produces("application/json")
.route()
.process((Exchange exch) -> {
exch.getIn().setBody(SERVICE_DESCRIPTOR_DESCRIPTORS);
})
.endRest()
.post("screening/ecfp4").description("Screen using ECFP4 fingerprints")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonDescriptorsRouteBuilder.CHEMAXON_SCREENING_ECFP4, resolver, ROUTE_STATS))
.endRest()
.post("screening/pharmacophore").description("Screen using pharmacophore fingerprints")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonDescriptorsRouteBuilder.CHEMAXON_SCREENING_PHARMACOPHORE, resolver, ROUTE_STATS))
.endRest()
.post("clustering/spherex/ecfp4").description("Sphere exclusion clustering using ECFP4 fingerprints")
.route()
.process(new MoleculeObjectRouteHttpProcessor(ChemaxonDescriptorsRouteBuilder.CHEMAXON_CLUSTERING_SPHEREX_ECFP4, resolver, ROUTE_STATS))
.endRest();
rest("v1/reactor").description("Library enumeration using ChemAxon Reactor")
.bindingMode(RestBindingMode.off)
.consumes("application/json")
.produces("application/json")
.post("react").description("Simple enumeration")
.route()
.process(new JsonToDatasetProcessor(MoleculeObject.class))
.process(new ReactorProcessor("/chemaxon_reaction_library.zip", ROUTE_STATS))
.process(new DatasetToJsonProcessor(MoleculeObject.class))
.endRest();
}
} |
package org.phenotips.data.rest.internal;
import static org.mockito.Mockito.*;
import com.xpn.xwiki.XWikiContext;
import net.sf.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.phenotips.data.PatientRepository;
import org.phenotips.data.rest.DomainObjectFactory;
import org.phenotips.data.rest.PatientsResource;
import org.phenotips.data.rest.model.Patient;
import org.phenotips.data.rest.model.Patients;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.util.DefaultParameterizedType;
import org.xwiki.component.util.ReflectionUtils;
import org.xwiki.context.Execution;
import org.xwiki.context.ExecutionContext;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceResolver;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryManager;
import org.xwiki.query.internal.DefaultQuery;
import org.xwiki.rest.XWikiRestException;
import org.xwiki.security.authorization.AuthorizationManager;
import org.xwiki.security.authorization.Right;
import org.xwiki.test.mockito.MockitoComponentMockingRule;
import org.xwiki.users.User;
import org.xwiki.users.UserManager;
import javax.inject.Provider;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
public class DefaultPatientsResourceImplTest {
@Rule
public MockitoComponentMockingRule<PatientsResource> mocker =
new MockitoComponentMockingRule<PatientsResource>(DefaultPatientsResourceImpl.class);
@Mock
private User currentUser;
@Mock
private Logger logger;
private PatientRepository repository;
private QueryManager queries;
private AuthorizationManager access;
private UserManager users;
private EntityReferenceResolver<EntityReference> currentResolver;
private DomainObjectFactory factory;
@Mock
private Patient patient;
private URI uri;
@Mock
private UriInfo uriInfo;
private DefaultPatientsResourceImpl patientsResource;
private XWikiContext context;
@Before
public void setUp() throws ComponentLookupException, URISyntaxException {
MockitoAnnotations.initMocks(this);
Execution execution = mock(Execution.class);
ExecutionContext executionContext = mock(ExecutionContext.class);
ComponentManager compManager = this.mocker.getInstance(ComponentManager.class, "context");
when(compManager.getInstance(Execution.class)).thenReturn(execution);
doReturn(executionContext).when(execution).getContext();
doReturn(mock(XWikiContext.class)).when(executionContext).getProperty("xwikicontext");
this.repository = this.mocker.getInstance(PatientRepository.class);
this.users = this.mocker.getInstance(UserManager.class);
this.access = this.mocker.getInstance(AuthorizationManager.class);
this.patientsResource = (DefaultPatientsResourceImpl)this.mocker.getComponentUnderTest();
this.logger = this.mocker.getMockedLogger();
this.queries = this.mocker.getInstance(QueryManager.class);
this.uri = new URI("http://uri");
doReturn(this.uri).when(this.uriInfo).getBaseUri();
doReturn(this.uri).when(this.uriInfo).getRequestUri();
ReflectionUtils.setFieldValue(this.patientsResource, "uriInfo", this.uriInfo);
doReturn("00000001").when(this.patient).getId();
doReturn(this.currentUser).when(this.users).getCurrentUser();
doReturn(null).when(this.currentUser).getProfileDocument();
}
@Test
public void addPatientUserDoesNotHaveAccess() throws XWikiRestException {
WebApplicationException exception = new WebApplicationException();
doReturn(false).when(this.access).hasAccess(Right.EDIT, null, mock(EntityReference.class));
try {
Response response = this.patientsResource.addPatient("");
}
catch (WebApplicationException ex){
exception = ex;
}
Assert.assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), exception.getResponse().getStatus());
verify(this.logger).debug("Importing new patient from JSON via REST: {}", "");
}
@Test
public void addNullPatient() throws XWikiRestException {
doReturn(true).when(this.access).hasAccess(eq(Right.EDIT), any(DocumentReference.class), any(EntityReference.class));
Response response = this.patientsResource.addPatient(null);
Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
verify(this.logger).error(eq("Could not process remote matching request: {}"), anyString(), anyObject());
}
@Test
public void addPatientAsJSON() throws XWikiRestException {
doReturn(true).when(this.access).hasAccess(eq(Right.EDIT), any(DocumentReference.class), any(EntityReference.class));
JSONObject json = new JSONObject();
Response response = this.patientsResource.addPatient(json.toString());
verify(this.logger).debug("Importing new patient from JSON via REST: {}", json.toString());
}
@Test
public void listPatientsNullOrderField() throws XWikiRestException {
WebApplicationException exception = new WebApplicationException();
try {
Patients result = this.patientsResource.listPatients(0, 30, null, "asc");
}
catch (WebApplicationException ex){
exception = ex;
}
Assert.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), exception.getResponse().getStatus());
verify(this.logger).error(eq("Failed to list patients: {}"), anyString(), anyObject());
}
@Test
public void listPatientsNullOrder() throws XWikiRestException {
WebApplicationException exception = new WebApplicationException();
try {
Patients result = this.patientsResource.listPatients(0, 30, "id", null);
}
catch (WebApplicationException ex){
exception = ex;
}
Assert.assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), exception.getResponse().getStatus());
verify(this.logger).error(eq("Failed to list patients: {}"), anyString(), anyObject());
}
@Test
public void listPatientsDefaultBehaviour() throws WebApplicationException, XWikiRestException, QueryException
{
Query query = mock(DefaultQuery.class);
doReturn(query).when(this.queries).createQuery(anyString(), anyString());
doReturn(query).when(query).bindValue(anyString(), anyString());
doReturn(new ArrayList<Object[]>()).when(query).execute();
Patients result = this.patientsResource.listPatients(0, 30, "id", "asc");
verify(this.queries).createQuery("select doc.fullName, p.external_id, doc.creator, doc.creationDate, doc.version, doc.author, doc.date"
+ " from Document doc, doc.object(PhenoTips.PatientClass) p where doc.name <> :t order by "
+ "doc.name" + " asc", "xwql");
}
} |
package com.yahoo.vespa.hosted.controller.restapi.application;
import ai.vespa.hosted.api.Signatures;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;
import com.yahoo.component.Version;
import com.yahoo.config.application.api.DeploymentSpec;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.ClusterResources;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.zone.RoutingMethod;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.container.handler.metrics.JsonResponse;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.LoggingRequestHandler;
import com.yahoo.io.IOUtils;
import com.yahoo.restapi.ByteArrayResponse;
import com.yahoo.restapi.ErrorResponse;
import com.yahoo.restapi.MessageResponse;
import com.yahoo.restapi.Path;
import com.yahoo.restapi.ResourceResponse;
import com.yahoo.restapi.SlimeJsonResponse;
import com.yahoo.security.KeyUtils;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.Inspector;
import com.yahoo.slime.JsonParseException;
import com.yahoo.slime.Slime;
import com.yahoo.slime.SlimeUtils;
import com.yahoo.text.Text;
import com.yahoo.vespa.hosted.controller.Application;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.Instance;
import com.yahoo.vespa.hosted.controller.LockedTenant;
import com.yahoo.vespa.hosted.controller.NotExistsException;
import com.yahoo.vespa.hosted.controller.api.application.v4.EnvironmentResource;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.EndpointStatus;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.ProtonMetrics;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RefeedAction;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RestartAction;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.ServiceInfo;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.identifiers.Hostname;
import com.yahoo.vespa.hosted.controller.api.identifiers.TenantId;
import com.yahoo.vespa.hosted.controller.api.integration.aws.TenantRoles;
import com.yahoo.vespa.hosted.controller.api.integration.billing.Quota;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Cluster;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ConfigServerException;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Log;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeFilter;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeRepository;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.SourceRevision;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.RestartFilter;
import com.yahoo.vespa.hosted.controller.api.integration.resource.MeteringData;
import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceAllocation;
import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceSnapshot;
import com.yahoo.vespa.hosted.controller.api.integration.secrets.TenantSecretStore;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.RoleDefinition;
import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
import com.yahoo.vespa.hosted.controller.application.ActivateResult;
import com.yahoo.vespa.hosted.controller.application.AssignedRotation;
import com.yahoo.vespa.hosted.controller.application.Change;
import com.yahoo.vespa.hosted.controller.application.Deployment;
import com.yahoo.vespa.hosted.controller.application.DeploymentMetrics;
import com.yahoo.vespa.hosted.controller.application.Endpoint;
import com.yahoo.vespa.hosted.controller.application.EndpointList;
import com.yahoo.vespa.hosted.controller.application.QuotaUsage;
import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLoggingRequestHandler;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentStatus;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentSteps;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel;
import com.yahoo.vespa.hosted.controller.deployment.JobStatus;
import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.deployment.TestConfigSerializer;
import com.yahoo.vespa.hosted.controller.maintenance.ResourceMeterMaintainer;
import com.yahoo.vespa.hosted.controller.notification.Notification;
import com.yahoo.vespa.hosted.controller.notification.NotificationSource;
import com.yahoo.vespa.hosted.controller.persistence.SupportAccessSerializer;
import com.yahoo.vespa.hosted.controller.rotation.RotationId;
import com.yahoo.vespa.hosted.controller.rotation.RotationState;
import com.yahoo.vespa.hosted.controller.rotation.RotationStatus;
import com.yahoo.vespa.hosted.controller.routing.RoutingStatus;
import com.yahoo.vespa.hosted.controller.security.AccessControlRequests;
import com.yahoo.vespa.hosted.controller.security.Credentials;
import com.yahoo.vespa.hosted.controller.support.access.SupportAccess;
import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant;
import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
import com.yahoo.vespa.hosted.controller.tenant.DeletedTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfoAddress;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfoBillingContact;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
import com.yahoo.vespa.serviceview.bindings.ApplicationView;
import com.yahoo.yolean.Exceptions;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotAuthorizedException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.DigestInputStream;
import java.security.Principal;
import java.security.PublicKey;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Scanner;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.yahoo.jdisc.Response.Status.BAD_REQUEST;
import static com.yahoo.jdisc.Response.Status.CONFLICT;
import static com.yahoo.yolean.Exceptions.uncheck;
import static java.util.Map.Entry.comparingByKey;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toUnmodifiableList;
/**
* This implements the application/v4 API which is used to deploy and manage applications
* on hosted Vespa.
*
* @author bratseth
* @author mpolden
*/
@SuppressWarnings("unused")
public class ApplicationApiHandler extends AuditLoggingRequestHandler {
private static final ObjectMapper jsonMapper = new ObjectMapper();
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx, controller.auditLogger());
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20); // deploys may take a long time;
}
@Override
public HttpResponse auditAndHandle(HttpRequest request) {
try {
Path path = new Path(request.getUri());
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.code()) {
case NOT_FOUND:
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.code().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.code().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/info")) return tenantInfo(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/notifications")) return notifications(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}/validate")) return validateSecretStore(path.get("tenant"), path.get("name"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/diff/{number}")) return applicationPackageDiff(path.get("tenant"), path.get("application"), path.get("number"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)).descendingMap(), Optional.ofNullable(request.getProperty("limit")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/diff/{number}")) return devApplicationPackageDiff(runIdFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return getReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/content/{*}")) return content(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return supportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/node/{node}/service-dump")) return getServiceDump(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("node"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/info")) return updateTenantInfo(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/archive-access")) return allowArchiveAccess(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}")) return addSecretStore(path.get("tenant"), path.get("name"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); // legacy synonym of the above
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindex")) return reindex(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return enableReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspend")) return suspend(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return allowSupportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/node/{node}/service-dump")) return requestServiceDump(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("node"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); // legacy synonym of the above
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/archive-access")) return removeArchiveAccess(path.get("tenant"));
if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}")) return deleteSecretStore(path.get("tenant"), path.get("name"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return disableReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspend")) return suspend(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return disallowSupportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
// We implement this to avoid redirect loops on OPTIONS requests from browsers, but do not really bother
// spelling out the methods supported at each path, which we should
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
List<Application> applications = controller.applications().asList();
for (Tenant tenant : controller.tenants().asList(includeDeleted(request)))
toSlime(tenantArray.addObject(),
tenant,
applications.stream().filter(app -> app.id().tenant().equals(tenant.name())).collect(toList()),
request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList(includeDeleted(request)))
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName), includeDeleted(request))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, controller.applications().asList(tenant.name()), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse tenantInfo(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.filter(tenant -> tenant.type() == Tenant.Type.cloud)
.map(tenant -> tenantInfo(((CloudTenant)tenant).info(), request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist or does not support this"));
}
private SlimeJsonResponse tenantInfo(TenantInfo info, HttpRequest request) {
Slime slime = new Slime();
Cursor infoCursor = slime.setObject();
if (!info.isEmpty()) {
infoCursor.setString("name", info.name());
infoCursor.setString("email", info.email());
infoCursor.setString("website", info.website());
infoCursor.setString("invoiceEmail", info.invoiceEmail());
infoCursor.setString("contactName", info.contactName());
infoCursor.setString("contactEmail", info.contactEmail());
toSlime(info.address(), infoCursor);
toSlime(info.billingContact(), infoCursor);
}
return new SlimeJsonResponse(slime);
}
private void toSlime(TenantInfoAddress address, Cursor parentCursor) {
if (address.isEmpty()) return;
Cursor addressCursor = parentCursor.setObject("address");
addressCursor.setString("addressLines", address.addressLines());
addressCursor.setString("postalCodeOrZip", address.postalCodeOrZip());
addressCursor.setString("city", address.city());
addressCursor.setString("stateRegionProvince", address.stateRegionProvince());
addressCursor.setString("country", address.country());
}
private void toSlime(TenantInfoBillingContact billingContact, Cursor parentCursor) {
if (billingContact.isEmpty()) return;
Cursor addressCursor = parentCursor.setObject("billingContact");
addressCursor.setString("name", billingContact.name());
addressCursor.setString("email", billingContact.email());
addressCursor.setString("phone", billingContact.phone());
toSlime(billingContact.address(), addressCursor);
}
private HttpResponse updateTenantInfo(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.filter(tenant -> tenant.type() == Tenant.Type.cloud)
.map(tenant -> updateTenantInfo(((CloudTenant)tenant), request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist or does not support this"));
}
private String getString(Inspector field, String defaultVale) {
return field.valid() ? field.asString() : defaultVale;
}
private SlimeJsonResponse updateTenantInfo(CloudTenant tenant, HttpRequest request) {
TenantInfo oldInfo = tenant.info();
// Merge info from request with the existing info
Inspector insp = toSlime(request.getData()).get();
TenantInfo mergedInfo = TenantInfo.EMPTY
.withName(getString(insp.field("name"), oldInfo.name()))
.withEmail(getString(insp.field("email"), oldInfo.email()))
.withWebsite(getString(insp.field("website"), oldInfo.website()))
.withInvoiceEmail(getString(insp.field("invoiceEmail"), oldInfo.invoiceEmail()))
.withContactName(getString(insp.field("contactName"), oldInfo.contactName()))
.withContactEmail(getString(insp.field("contactEmail"), oldInfo.contactEmail()))
.withAddress(updateTenantInfoAddress(insp.field("address"), oldInfo.address()))
.withBillingContact(updateTenantInfoBillingContact(insp.field("billingContact"), oldInfo.billingContact()));
// Store changes
controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withInfo(mergedInfo);
controller.tenants().store(lockedTenant);
});
return new MessageResponse("Tenant info updated");
}
private TenantInfoAddress updateTenantInfoAddress(Inspector insp, TenantInfoAddress oldAddress) {
if (!insp.valid()) return oldAddress;
return TenantInfoAddress.EMPTY
.withCountry(getString(insp.field("country"), oldAddress.country()))
.withStateRegionProvince(getString(insp.field("stateRegionProvince"), oldAddress.stateRegionProvince()))
.withCity(getString(insp.field("city"), oldAddress.city()))
.withPostalCodeOrZip(getString(insp.field("postalCodeOrZip"), oldAddress.postalCodeOrZip()))
.withAddressLines(getString(insp.field("addressLines"), oldAddress.addressLines()));
}
private TenantInfoBillingContact updateTenantInfoBillingContact(Inspector insp, TenantInfoBillingContact oldContact) {
if (!insp.valid()) return oldContact;
return TenantInfoBillingContact.EMPTY
.withName(getString(insp.field("name"), oldContact.name()))
.withEmail(getString(insp.field("email"), oldContact.email()))
.withPhone(getString(insp.field("phone"), oldContact.phone()))
.withAddress(updateTenantInfoAddress(insp.field("address"), oldContact.address()));
}
private HttpResponse notifications(String tenantName, HttpRequest request) {
NotificationSource notificationSource = new NotificationSource(TenantName.from(tenantName),
Optional.ofNullable(request.getProperty("application")).map(ApplicationName::from),
Optional.ofNullable(request.getProperty("instance")).map(InstanceName::from),
Optional.empty(), Optional.empty(), Optional.empty(), OptionalLong.empty());
Slime slime = new Slime();
Cursor notificationsArray = slime.setObject().setArray("notifications");
controller.notificationsDb().listNotifications(notificationSource, showOnlyProductionInstances(request))
.forEach(notification -> toSlime(notificationsArray.addObject(), notification));
return new SlimeJsonResponse(slime);
}
private static void toSlime(Cursor cursor, Notification notification) {
cursor.setLong("at", notification.at().toEpochMilli());
cursor.setString("level", notificationLevelAsString(notification.level()));
cursor.setString("type", notificationTypeAsString(notification.type()));
Cursor messagesArray = cursor.setArray("messages");
notification.messages().forEach(messagesArray::addString);
notification.source().application().ifPresent(application -> cursor.setString("application", application.value()));
notification.source().instance().ifPresent(instance -> cursor.setString("instance", instance.value()));
notification.source().zoneId().ifPresent(zoneId -> {
cursor.setString("environment", zoneId.environment().value());
cursor.setString("region", zoneId.region().value());
});
notification.source().clusterId().ifPresent(clusterId -> cursor.setString("clusterId", clusterId.value()));
notification.source().jobType().ifPresent(jobType -> cursor.setString("jobName", jobType.jobName()));
notification.source().runNumber().ifPresent(runNumber -> cursor.setLong("runNumber", runNumber));
}
private static String notificationTypeAsString(Notification.Type type) {
switch (type) {
case applicationPackage: return "applicationPackage";
case deployment: return "deployment";
case feedBlock: return "feedBlock";
case reindex: return "reindex";
default: throw new IllegalArgumentException("No serialization defined for notification type " + type);
}
}
private static String notificationLevelAsString(Notification.Level level) {
switch (level) {
case info: return "info";
case warning: return "warning";
case error: return "error";
default: throw new IllegalArgumentException("No serialization defined for notification level " + level);
}
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
getTenantOrThrow(tenantName);
List<Application> applications = applicationName.isEmpty() ?
controller.applications().asList(tenant) :
controller.applications().getApplication(TenantAndApplicationId.from(tenantName, applicationName.get()))
.map(List::of)
.orElseThrow(() -> new NotExistsException("Application '" + applicationName.get() + "' does not exist"));
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (Application application : applications) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
ApplicationVersion version = controller.jobController().last(id, type).get().versions().targetApplication();
byte[] applicationPackage = controller.applications().applicationStore().get(new DeploymentId(id, zone), version);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse devApplicationPackageDiff(RunId runId) {
DeploymentId deploymentId = new DeploymentId(runId.application(), runId.job().type().zone(controller.system()));
return controller.applications().applicationStore().getDevDiff(deploymentId, runId.number())
.map(ByteArrayResponse::new)
.orElseThrow(() -> new NotExistsException("No application package diff found for " + runId));
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) { // Fall back to latest build
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse applicationPackageDiff(String tenant, String application, String number) {
TenantAndApplicationId tenantAndApplication = TenantAndApplicationId.from(tenant, application);
return controller.applications().applicationStore().getDiff(tenantAndApplication.tenant(), tenantAndApplication.application(), Long.parseLong(number))
.map(ByteArrayResponse::new)
.orElseThrow(() -> new NotExistsException("No application package diff found for '" + tenantAndApplication + "' with build number " + number));
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse validateSecretStore(String tenantName, String secretStoreName, HttpRequest request) {
var awsRegion = request.getProperty("aws-region");
var parameterName = request.getProperty("parameter-name");
var applicationId = ApplicationId.fromFullString(request.getProperty("application-id"));
var zoneId = ZoneId.from(request.getProperty("zone"));
var deploymentId = new DeploymentId(applicationId, zoneId);
var tenant = controller.tenants().require(applicationId.tenant(), CloudTenant.class);
var tenantSecretStore = tenant.tenantSecretStores()
.stream()
.filter(secretStore -> secretStore.getName().equals(secretStoreName))
.findFirst();
if (tenantSecretStore.isEmpty())
return ErrorResponse.notFoundError("No secret store '" + secretStoreName + "' configured for tenant '" + tenantName + "'");
var response = controller.serviceRegistry().configServer().validateSecretStore(deploymentId, tenantSecretStore.get(), awsRegion, parameterName);
try {
var responseRoot = new Slime();
var responseCursor = responseRoot.setObject();
responseCursor.setString("target", deploymentId.toString());
var responseResultCursor = responseCursor.setObject("result");
var responseSlime = SlimeUtils.jsonToSlime(response);
SlimeUtils.copyObject(responseSlime.get(), responseResultCursor);
return new SlimeJsonResponse(responseRoot);
} catch (JsonParseException e) {
return ErrorResponse.internalServerError(response);
}
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse addSecretStore(String tenantName, String name, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
var data = toSlime(request.getData()).get();
var awsId = mandatory("awsId", data).asString();
var externalId = mandatory("externalId", data).asString();
var role = mandatory("role", data).asString();
var tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class);
var tenantSecretStore = new TenantSecretStore(name, awsId, role);
if (!tenantSecretStore.isValid()) {
return ErrorResponse.badRequest("Secret store " + tenantSecretStore + " is invalid");
}
if (tenant.tenantSecretStores().contains(tenantSecretStore)) {
return ErrorResponse.badRequest("Secret store " + tenantSecretStore + " is already configured");
}
controller.serviceRegistry().roleService().createTenantPolicy(TenantName.from(tenantName), name, awsId, role);
controller.serviceRegistry().tenantSecretService().addSecretStore(tenant.name(), tenantSecretStore, externalId);
// Store changes
controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withSecretStore(tenantSecretStore);
controller.tenants().store(lockedTenant);
});
tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class);
var slime = new Slime();
toSlime(slime.setObject(), tenant.tenantSecretStores());
return new SlimeJsonResponse(slime);
}
private HttpResponse deleteSecretStore(String tenantName, String name, HttpRequest request) {
var tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class);
var optionalSecretStore = tenant.tenantSecretStores().stream()
.filter(secretStore -> secretStore.getName().equals(name))
.findFirst();
if (optionalSecretStore.isEmpty())
return ErrorResponse.notFoundError("Could not delete secret store '" + name + "': Secret store not found");
var tenantSecretStore = optionalSecretStore.get();
controller.serviceRegistry().tenantSecretService().deleteSecretStore(tenant.name(), tenantSecretStore);
controller.serviceRegistry().roleService().deleteTenantPolicy(tenant.name(), tenantSecretStore.getName(), tenantSecretStore.getRole());
controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withoutSecretStore(tenantSecretStore);
controller.tenants().store(lockedTenant);
});
tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class);
var slime = new Slime();
toSlime(slime.setObject(), tenant.tenantSecretStores());
return new SlimeJsonResponse(slime);
}
private HttpResponse allowArchiveAccess(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
var data = toSlime(request.getData()).get();
var role = mandatory("role", data).asString();
if (role.isBlank()) {
return ErrorResponse.badRequest("Archive access role can't be whitespace only");
}
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withArchiveAccessRole(Optional.of(role));
controller.tenants().store(lockedTenant);
});
return new MessageResponse("Archive access role set to '" + role + "' for tenant " + tenantName + ".");
}
private HttpResponse removeArchiveAccess(String tenantName) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withArchiveAccessRole(Optional.empty());
controller.tenants().store(lockedTenant);
});
return new MessageResponse("Archive access role removed for tenant " + tenantName + ".");
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
// TODO jonmv: Remove when clients are updated.
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, NodeFilter.all().applications(id));
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
node.flavor().ifPresent(flavor -> nodeObject.setString("flavor", flavor));
toSlime(node.resources(), nodeObject);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
nodeObject.setBool("down", node.history().stream().anyMatch(event -> "down".equals(event.name())));
nodeObject.setBool("retired", node.retired() || node.wantToRetire());
nodeObject.setBool("restarting", node.wantedRestartGeneration() > node.restartGeneration());
nodeObject.setBool("rebooting", node.wantedRebootGeneration() > node.rebootGeneration());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
com.yahoo.vespa.hosted.controller.api.integration.configserver.Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
clusterObject.setString("type", cluster.type().name());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
if (cluster.target().isPresent()
&& ! cluster.target().get().justNumbers().equals(cluster.current().justNumbers()))
toSlime(cluster.target().get(), clusterObject.setObject("target"));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
utilizationToSlime(cluster.utilization(), clusterObject.setObject("utilization"));
scalingEventsToSlime(cluster.scalingEvents(), clusterObject.setArray("scalingEvents"));
clusterObject.setString("autoscalingStatusCode", cluster.autoscalingStatusCode());
clusterObject.setString("autoscalingStatus", cluster.autoscalingStatus());
clusterObject.setLong("scalingDuration", cluster.scalingDuration().toMillis());
clusterObject.setDouble("maxQueryGrowthRate", cluster.maxQueryGrowthRate());
clusterObject.setDouble("currentQueryFractionOfMax", cluster.currentQueryFractionOfMax());
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case permanentlyDown: return "permanentlyDown";
case unorchestrated: return "unorchestrated";
case unknown: break;
}
return "unknown";
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
try (logStream) {
logStream.transferTo(outputStream);
}
}
};
}
private HttpResponse supportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
SupportAccess supportAccess = controller.supportAccess().forDeployment(deployment);
return new SlimeJsonResponse(SupportAccessSerializer.serializeCurrentState(supportAccess, controller.clock().instant()));
}
// TODO support access: only let tenants (not operators!) allow access
// TODO support access: configurable period of access?
private HttpResponse allowSupportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
Principal principal = requireUserPrincipal(request);
Instant now = controller.clock().instant();
SupportAccess allowed = controller.supportAccess().allow(deployment, now.plus(7, ChronoUnit.DAYS), principal.getName());
return new SlimeJsonResponse(SupportAccessSerializer.serializeCurrentState(allowed, now));
}
private HttpResponse disallowSupportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
Principal principal = requireUserPrincipal(request);
SupportAccess disallowed = controller.supportAccess().disallow(deployment, principal.getName());
controller.applications().deploymentTrigger().reTriggerOrAddToQueue(deployment);
return new SlimeJsonResponse(SupportAccessSerializer.serializeCurrentState(disallowed, controller.clock().instant()));
}
private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment);
return buildResponseFromProtonMetrics(protonMetrics);
}
private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) {
try {
var jsonObject = jsonMapper.createObjectNode();
var jsonArray = jsonMapper.createArrayNode();
for (ProtonMetrics metrics : protonMetrics) {
jsonArray.add(metrics.toJson());
}
jsonObject.set("metrics", jsonArray);
return new JsonResponse(200, jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject));
} catch (JsonProcessingException e) {
log.log(Level.WARNING, "Unable to build JsonResponse with Proton data: " + e.getMessage(), e);
return new JsonResponse(500, "");
}
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
// TODO jonmv: Remove this when users are updated.
application.instances().values().stream().findFirst().ifPresent(instance -> {
// Currently deploying change
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
// Outstanding change
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
// Metrics
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
// Activity
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
// TODO: Eliminate duplicated code in this and toSlime(Cursor, Instance, DeploymentStatus, HttpRequest)
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
// Jobs sorted according to deployment spec
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
// Outstanding change
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
// Change blockers
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
// Rotation ID
addRotationId(object, instance);
// Deployments sorted according to deployment spec
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
// Rotation status for this deployment
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request)) // List full deployment information when recursive.
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
// TODO(mpolden): Remove once MultiRegionTest stops expecting this field
private void addRotationId(Cursor object, Instance instance) {
// Legacy field. Identifies the first assigned rotation, if any.
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
// Jobs sorted according to deployment spec
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
// Outstanding change
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
// Change blockers
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
// Rotation ID
addRotationId(object, instance);
// Deployments sorted according to deployment spec
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
// Rotation status for this deployment
if (deployment.zone().environment() == Environment.prod) {
// 0 rotations: No fields written
// 1 rotation : Write legacy field and endpointStatus field
// >1 rotation : Write only endpointStatus field
if (instance.rotations().size() == 1) {
// TODO(mpolden): Stop writing this field once clients stop expecting it
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) { // TODO jonmv: clean up when clients have converged.
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request)) // List full deployment information when recursive.
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value()); // pointless
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
// Add dummy values for not-yet-existent prod deployments, and running dev/perf deployments.
Stream.concat(status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment()),
controller.jobController().active(instance.id()).stream()
.map(run -> run.id().job())
.filter(job -> job.type().environment().isManuallyDeployed()))
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
// TODO jonmv: Remove when clients are updated
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
// Metrics
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
// Activity
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment,
String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
requireZone(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, Cursor object) {
object.setString("cluster", endpoint.cluster().value());
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
object.setBool("legacy", endpoint.legacy());
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value()); // pointless
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
// Add zone endpoints
boolean legacyEndpoints = request.getBooleanProperty("includeLegacyEndpoints");
var endpointArray = response.setArray("endpoints");
EndpointList zoneEndpoints = controller.routing().readEndpointsOf(deploymentId)
.scope(Endpoint.Scope.zone);
if (!legacyEndpoints) {
zoneEndpoints = zoneEndpoints.not().legacy();
}
for (var endpoint : controller.routing().directEndpoints(zoneEndpoints, deploymentId.applicationId())) {
toSlime(endpoint, endpointArray.addObject());
}
// Add declared endpoints
EndpointList declaredEndpoints = controller.routing().declaredEndpointsOf(application)
.targets(deploymentId);
if (!legacyEndpoints) {
declaredEndpoints = declaredEndpoints.not().legacy();
}
for (var endpoint : controller.routing().directEndpoints(declaredEndpoints, deploymentId.applicationId())) {
toSlime(endpoint, endpointArray.addObject());
}
response.setString("clusters", withPath(toPath(deploymentId) + "/clusters", request.getUri()).toString());
response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
Instant lastDeploymentStart = lastDeploymentStart(deploymentId.applicationId(), deployment);
response.setLong("deployTimeEpochMs", lastDeploymentStart.toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", lastDeploymentStart.plus(deploymentTimeToLive).toEpochMilli()));
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
if (!deployment.zone().environment().isManuallyDeployed()) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
} else {
var deploymentRun = JobType.from(controller.system(), deploymentId.zoneId())
.flatMap(jobType -> controller.jobController().last(deploymentId.applicationId(), jobType));
deploymentRun.ifPresent(run -> {
response.setString("status", run.hasEnded() ? "complete" : "running");
});
}
}
response.setDouble("quota", deployment.quota().rate());
deployment.cost().ifPresent(cost -> response.setDouble("cost", cost));
controller.archiveBucketDb().archiveUriFor(deploymentId.zoneId(), deploymentId.applicationId().tenant())
.ifPresent(archiveUri -> response.setString("archiveUri", archiveUri.toString()));
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
// Metrics
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private Instant lastDeploymentStart(ApplicationId instanceId, Deployment deployment) {
return controller.jobController().jobStarts(new JobId(instanceId, JobType.from(controller.system(), deployment.zone()).get()))
.stream().findFirst().orElse(deployment.at());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.readVersionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = requireZone(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
// The order here matters because setGlobalRotationStatus involves an external request that may fail.
// TODO(mpolden): Set only one of these when only one kind of global endpoints are supported per zone.
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(Text.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? RoutingStatus.Agent.operator : RoutingStatus.Agent.tenant;
var status = inService ? RoutingStatus.Value.in : RoutingStatus.Value.out;
controller.routing().policies().setRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? RoutingStatus.Agent.operator : RoutingStatus.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = requireZone(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.forEach((applicationId, resources) -> {
String instanceName = applicationId.instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
resources.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ZoneId zone = requireZone(environment, region);
ServiceApiResponse response = new ServiceApiResponse(zone,
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
List.of(controller.zoneRegistry().getConfigServerVipUri(zone)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
if (restPath.contains("/status/")) {
String[] parts = restPath.split("/status/", 2);
String result = controller.serviceRegistry().configServer().getServiceStatusPage(deploymentId, serviceName, parts[0], parts[1]);
return new HtmlResponse(result);
}
String normalizedRestPath = URI.create(restPath).normalize().toString();
// Only state/v1 is allowed
if (! normalizedRestPath.startsWith("state/v1/")) {
return ErrorResponse.forbidden("Access denied");
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
List.of(controller.zoneRegistry().getConfigServerVipUri(deploymentId.zoneId())),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse content(String tenantName, String applicationName, String instanceName, String environment, String region, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
return controller.serviceRegistry().configServer().getApplicationPackageContent(deploymentId, "/" + restPath, request.getUri());
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
// TODO jonmv: Remove when clients are updated.
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
VersionStatus versionStatus = controller.readVersionStatus();
if (version.equals(Version.emptyVersion))
version = controller.systemVersion(versionStatus);
if (!versionStatus.isActive(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + versionStatus.versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule reindexing of an application, or a subset of clusters, possibly on a subset of documents. */
private HttpResponse reindex(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
List<String> clusterNames = Optional.ofNullable(request.getProperty("clusterId")).stream()
.flatMap(clusters -> Stream.of(clusters.split(",")))
.filter(cluster -> ! cluster.isBlank())
.collect(toUnmodifiableList());
List<String> documentTypes = Optional.ofNullable(request.getProperty("documentType")).stream()
.flatMap(types -> Stream.of(types.split(",")))
.filter(type -> ! type.isBlank())
.collect(toUnmodifiableList());
controller.applications().reindex(id, zone, clusterNames, documentTypes, request.getBooleanProperty("indexedOnly"));
return new MessageResponse("Requested reindexing of " + id + " in " + zone +
(clusterNames.isEmpty() ? "" : ", on clusters " + String.join(", ", clusterNames) +
(documentTypes.isEmpty() ? "" : ", for types " + String.join(", ", documentTypes))));
}
/** Gets reindexing status of an application in a zone. */
private HttpResponse getReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
ApplicationReindexing reindexing = controller.applications().applicationReindexing(id, zone);
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setBool("enabled", reindexing.enabled());
Cursor clustersArray = root.setArray("clusters");
reindexing.clusters().entrySet().stream().sorted(comparingByKey())
.forEach(cluster -> {
Cursor clusterObject = clustersArray.addObject();
clusterObject.setString("name", cluster.getKey());
Cursor pendingArray = clusterObject.setArray("pending");
cluster.getValue().pending().entrySet().stream().sorted(comparingByKey())
.forEach(pending -> {
Cursor pendingObject = pendingArray.addObject();
pendingObject.setString("type", pending.getKey());
pendingObject.setLong("requiredGeneration", pending.getValue());
});
Cursor readyArray = clusterObject.setArray("ready");
cluster.getValue().ready().entrySet().stream().sorted(comparingByKey())
.forEach(ready -> {
Cursor readyObject = readyArray.addObject();
readyObject.setString("type", ready.getKey());
setStatus(readyObject, ready.getValue());
});
});
return new SlimeJsonResponse(slime);
}
void setStatus(Cursor statusObject, ApplicationReindexing.Status status) {
status.readyAt().ifPresent(readyAt -> statusObject.setLong("readyAtMillis", readyAt.toEpochMilli()));
status.startedAt().ifPresent(startedAt -> statusObject.setLong("startedAtMillis", startedAt.toEpochMilli()));
status.endedAt().ifPresent(endedAt -> statusObject.setLong("endedAtMillis", endedAt.toEpochMilli()));
status.state().map(ApplicationApiHandler::toString).ifPresent(state -> statusObject.setString("state", state));
status.message().ifPresent(message -> statusObject.setString("message", message));
status.progress().ifPresent(progress -> statusObject.setDouble("progress", progress));
}
private static String toString(ApplicationReindexing.State state) {
switch (state) {
case PENDING: return "pending";
case RUNNING: return "running";
case FAILED: return "failed";
case SUCCESSFUL: return "successful";
default: return null;
}
}
/** Enables reindexing of an application in a zone. */
private HttpResponse enableReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
controller.applications().enableReindexing(id, zone);
return new MessageResponse("Enabled reindexing of " + id + " in " + zone);
}
/** Disables reindexing of an application in a zone. */
private HttpResponse disableReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
controller.applications().disableReindexing(id, zone);
return new MessageResponse("Disabled reindexing of " + id + " in " + zone);
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
RestartFilter restartFilter = new RestartFilter()
.withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from))
.withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from))
.withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from));
controller.applications().restart(deploymentId, restartFilter);
return new MessageResponse("Requested restart of " + deploymentId);
}
/** Set suspension status of the given deployment. */
private HttpResponse suspend(String tenantName, String applicationName, String instanceName, String environment, String region, boolean suspend) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
controller.applications().setSuspension(deploymentId, suspend);
return new MessageResponse((suspend ? "Suspended" : "Resumed") + " orchestration of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
ensureApplicationExists(TenantAndApplicationId.from(id), request);
boolean dryRun = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("dryRun", options))
.map(Boolean::valueOf)
.orElse(false);
controller.jobController().deploy(id, type, version, applicationPackage, dryRun);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
// Get deployOptions
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
// Resolve system application
Optional<SystemApplication> systemApplication = SystemApplication.matching(applicationId);
if (systemApplication.isEmpty() || !systemApplication.get().hasApplicationPackage()) {
return ErrorResponse.badRequest("Deployment of " + applicationId + " is not supported through this API");
}
// Make it explicit that version is not yet supported here
String vespaVersion = deployOptions.field("vespaVersion").asString();
if (!vespaVersion.isEmpty() && !vespaVersion.equals("null")) {
return ErrorResponse.badRequest("Specifying version for " + applicationId + " is not permitted");
}
// To avoid second guessing the orchestrated upgrades of system applications
// we don't allow to deploy these during an system upgrade (i.e when new vespa is being rolled out)
VersionStatus versionStatus = controller.readVersionStatus();
if (versionStatus.isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = versionStatus.systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(systemApplication.get(), zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
boolean forget = request.getBooleanProperty("forget");
if (forget && !isOperator(request))
return ErrorResponse.forbidden("Only operators can forget a tenant");
controller.tenants().delete(TenantName.from(tenantName),
() -> accessControlRequests.credentials(TenantName.from(tenantName),
toSlime(request.getData()).get(),
request.getJDiscRequest()),
forget);
return new MessageResponse("Deleted tenant " + tenantName);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
// Attempt to deactivate application even if the deployment is not known by the controller
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance if the given is not in deployment spec. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
Application application = controller.applications().requireApplication(TenantAndApplicationId.from(id));
ApplicationId prodInstanceId = application.deploymentSpec().instance(id.instance()).isPresent()
? id : TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(prodInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(prodInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
ZoneId testedZone = type.zone(controller.system());
// If a production job is specified, the production deployment of the orchestrated instance is the relevant one,
// as user instances should not exist in prod.
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().readZoneEndpointsOf(deployments),
controller.applications().reachableContentClustersByZone(deployments)));
}
private HttpResponse requestServiceDump(String tenant, String application, String instance, String environment,
String region, String hostname, HttpRequest request) {
NodeRepository nodeRepository = controller.serviceRegistry().configServer().nodeRepository();
ZoneId zone = requireZone(environment, region);
// Check that no other service dump is in progress
Slime report = getReport(nodeRepository, zone, tenant, application, instance, hostname).orElse(null);
if (report != null) {
Cursor cursor = report.get();
// Note: same behaviour for both value '0' and missing value.
boolean force = request.getBooleanProperty("force");
if (!force && cursor.field("failedAt").asLong() == 0 && cursor.field("completedAt").asLong() == 0) {
throw new IllegalArgumentException("Service dump already in progress for " + cursor.field("configId").asString());
}
}
Slime requestPayload;
try {
requestPayload = SlimeUtils.jsonToSlimeOrThrow(request.getData().readAllBytes());
} catch (Exception e) {
throw new IllegalArgumentException("Missing or invalid JSON in request content", e);
}
Cursor requestPayloadCursor = requestPayload.get();
String configId = requestPayloadCursor.field("configId").asString();
long expiresAt = requestPayloadCursor.field("expiresAt").asLong();
if (configId.isEmpty()) {
throw new IllegalArgumentException("Missing configId");
}
Cursor artifactsCursor = requestPayloadCursor.field("artifacts");
int artifactEntries = artifactsCursor.entries();
if (artifactEntries == 0) {
throw new IllegalArgumentException("Missing or empty 'artifacts'");
}
Slime dumpRequest = new Slime();
Cursor dumpRequestCursor = dumpRequest.setObject();
dumpRequestCursor.setLong("createdMillis", controller.clock().millis());
dumpRequestCursor.setString("configId", configId);
Cursor dumpRequestArtifactsCursor = dumpRequestCursor.setArray("artifacts");
for (int i = 0; i < artifactEntries; i++) {
dumpRequestArtifactsCursor.addString(artifactsCursor.entry(i).asString());
}
if (expiresAt > 0) {
dumpRequestCursor.setLong("expiresAt", expiresAt);
}
Cursor dumpOptionsCursor = requestPayloadCursor.field("dumpOptions");
if (dumpOptionsCursor.children() > 0) {
SlimeUtils.copyObject(dumpOptionsCursor, dumpRequestCursor.setObject("dumpOptions"));
}
var reportsUpdate = Map.of("serviceDump", new String(uncheck(() -> SlimeUtils.toJsonBytes(dumpRequest))));
nodeRepository.updateReports(zone, hostname, reportsUpdate);
boolean wait = request.getBooleanProperty("wait");
if (!wait) return new MessageResponse("Request created");
return waitForServiceDumpResult(nodeRepository, zone, tenant, application, instance, hostname);
}
private HttpResponse getServiceDump(String tenant, String application, String instance, String environment,
String region, String hostname, HttpRequest request) {
NodeRepository nodeRepository = controller.serviceRegistry().configServer().nodeRepository();
ZoneId zone = requireZone(environment, region);
Slime report = getReport(nodeRepository, zone, tenant, application, instance, hostname)
.orElseThrow(() -> new NotExistsException("No service dump for node " + hostname));
return new SlimeJsonResponse(report);
}
private HttpResponse waitForServiceDumpResult(NodeRepository nodeRepository, ZoneId zone, String tenant,
String application, String instance, String hostname) {
int pollInterval = 2;
Slime report;
while (true) {
report = getReport(nodeRepository, zone, tenant, application, instance, hostname).get();
Cursor cursor = report.get();
if (cursor.field("completedAt").asLong() > 0 || cursor.field("failedAt").asLong() > 0) {
break;
}
final Slime copyForLambda = report;
log.fine(() -> uncheck(() -> new String(SlimeUtils.toJsonBytes(copyForLambda))));
log.fine("Sleeping " + pollInterval + " seconds before checking report status again");
controller.sleeper().sleep(Duration.ofSeconds(pollInterval));
}
return new SlimeJsonResponse(report);
}
private Optional<Slime> getReport(NodeRepository nodeRepository, ZoneId zone, String tenant,
String application, String instance, String hostname) {
Node node;
try {
node = nodeRepository.getNode(zone, hostname);
} catch (IllegalArgumentException e) {
throw new NotExistsException(new Hostname(hostname));
}
ApplicationId app = ApplicationId.from(tenant, application, instance);
ApplicationId owner = node.owner().orElseThrow(() -> new IllegalArgumentException("Node has no owner"));
if (!app.equals(owner)) {
throw new IllegalArgumentException("Node is not owned by " + app.toFullString());
}
String json = node.reports().get("serviceDump");
if (json == null) return Optional.empty();
return Optional.of(SlimeUtils.jsonToSlimeOrThrow(json));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, List<Application> applications, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName()));
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
// TODO: remove this once console is updated
toSlime(object, cloudTenant.tenantSecretStores());
toSlime(object.setObject("integrations").setObject("aws"),
controller.serviceRegistry().roleService().getTenantRole(tenant.name()),
cloudTenant.tenantSecretStores());
try {
var tenantQuota = controller.serviceRegistry().billingController().getQuota(tenant.name());
var usedQuota = applications.stream()
.map(Application::quotaUsage)
.reduce(QuotaUsage.none, QuotaUsage::add);
toSlime(tenantQuota, usedQuota, object.setObject("quota"));
} catch (Exception e) {
log.warning(String.format("Failed to get quota for tenant %s: %s", tenant.name(), Exceptions.toMessageString(e)));
}
cloudTenant.archiveAccessRole().ifPresent(role -> object.setString("archiveAccessRole", role));
break;
}
case deleted: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
// TODO jonmv: This should list applications, not instances.
Cursor applicationArray = object.setArray("applications");
for (Application application : applications) {
DeploymentStatus status = null;
Collection<Instance> instances = showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values();
if (instances.isEmpty() && !showOnlyActiveInstances(request))
toSlime(application.id(), applicationArray.addObject(), request);
for (Instance instance : instances) {
if (showOnlyActiveInstances(request) && instance.deployments().isEmpty())
continue;
if (recurseOverApplications(request)) {
if (status == null) status = controller.jobController().deploymentStatus(application);
toSlime(applicationArray.addObject(), instance, status, request);
} else {
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
}
tenantMetaDataToSlime(tenant, applications, object.setObject("metaData"));
}
private void toSlime(Quota quota, QuotaUsage usage, Cursor object) {
quota.budget().ifPresentOrElse(
budget -> object.setDouble("budget", budget.doubleValue()),
() -> object.setNix("budget")
);
object.setDouble("budgetUsed", usage.rate());
// TODO: Retire when we no longer use maxClusterSize as a meaningful limit
quota.maxClusterSize().ifPresent(maxClusterSize -> object.setLong("clusterSize", maxClusterSize));
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
double cost = ResourceMeterMaintainer.cost(resources, controller.serviceRegistry().zoneRegistry().system());
object.setDouble("cost", cost);
}
private void utilizationToSlime(Cluster.Utilization utilization, Cursor utilizationObject) {
utilizationObject.setDouble("cpu", utilization.cpu());
utilizationObject.setDouble("idealCpu", utilization.idealCpu());
utilizationObject.setDouble("currentCpu", utilization.currentCpu());
utilizationObject.setDouble("memory", utilization.memory());
utilizationObject.setDouble("idealMemory", utilization.idealMemory());
utilizationObject.setDouble("currentMemory", utilization.currentMemory());
utilizationObject.setDouble("disk", utilization.disk());
utilizationObject.setDouble("idealDisk", utilization.idealDisk());
utilizationObject.setDouble("currentDisk", utilization.currentDisk());
}
private void scalingEventsToSlime(List<Cluster.ScalingEvent> scalingEvents, Cursor scalingEventsArray) {
for (Cluster.ScalingEvent scalingEvent : scalingEvents) {
Cursor scalingEventObject = scalingEventsArray.addObject();
toSlime(scalingEvent.from(), scalingEventObject.setObject("from"));
toSlime(scalingEvent.to(), scalingEventObject.setObject("to"));
scalingEventObject.setLong("at", scalingEvent.at().toEpochMilli());
scalingEvent.completion().ifPresent(completion -> scalingEventObject.setLong("completion", completion.toEpochMilli()));
}
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
// A tenant has different content when in a list ... antipattern, but not solvable before application/v5
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
case deleted: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
private void tenantMetaDataToSlime(Tenant tenant, List<Application> applications, Cursor object) {
Optional<Instant> lastDev = applications.stream()
.flatMap(application -> application.instances().values().stream())
.flatMap(instance -> instance.deployments().values().stream()
.filter(deployment -> deployment.zone().environment() == Environment.dev)
.map(deployment -> lastDeploymentStart(instance.id(), deployment)))
.max(Comparator.naturalOrder())
.or(() -> applications.stream()
.flatMap(application -> application.instances().values().stream())
.flatMap(instance -> JobType.allIn(controller.system()).stream()
.filter(job -> job.environment() == Environment.dev)
.flatMap(jobType -> controller.jobController().last(instance.id(), jobType).stream()))
.map(Run::start)
.max(Comparator.naturalOrder()));
Optional<Instant> lastSubmission = applications.stream()
.flatMap(app -> app.latestVersion().flatMap(ApplicationVersion::buildTime).stream())
.max(Comparator.naturalOrder());
object.setLong("createdAtMillis", tenant.createdAt().toEpochMilli());
if (tenant.type() == Tenant.Type.deleted)
object.setLong("deletedAtMillis", ((DeletedTenant) tenant).deletedAt().toEpochMilli());
lastDev.ifPresent(instant -> object.setLong("lastDeploymentToDevMillis", instant.toEpochMilli()));
lastSubmission.ifPresent(instant -> object.setLong("lastSubmissionToProdMillis", instant.toEpochMilli()));
tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.user)
.ifPresent(instant -> object.setLong("lastLoginByUserMillis", instant.toEpochMilli()));
tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.developer)
.ifPresent(instant -> object.setLong("lastLoginByDeveloperMillis", instant.toEpochMilli()));
tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.administrator)
.ifPresent(instant -> object.setLong("lastLoginByAdministratorMillis", instant.toEpochMilli()));
}
/** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/
private URI withPathAndQuery(String newPath, String newQuery, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
return withPathAndQuery(newPath, null, uri);
}
private String toPath(DeploymentId id) {
return path("/application", "v4",
"tenant", id.applicationId().tenant(),
"application", id.applicationId().application(),
"instance", id.applicationId().instance(),
"environment", id.zoneId().environment(),
"region", id.zoneId().region());
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private void toSlime(Cursor object, List<TenantSecretStore> tenantSecretStores) {
Cursor secretStore = object.setArray("secretStores");
tenantSecretStores.forEach(store -> {
toSlime(secretStore.addObject(), store);
});
}
private void toSlime(Cursor object, TenantRoles tenantRoles, List<TenantSecretStore> tenantSecretStores) {
object.setString("tenantRole", tenantRoles.containerRole());
var stores = object.setArray("accounts");
tenantSecretStores.forEach(secretStore -> {
toSlime(stores.addObject(), secretStore);
});
}
private void toSlime(Cursor object, TenantSecretStore secretStore) {
object.setString("name", secretStore.getName());
object.setString("awsId", secretStore.getAwsId());
object.setString("role", secretStore.getRole());
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static boolean showOnlyActiveInstances(HttpRequest request) {
return "true".equals(request.getProperty("activeInstances"));
}
private static boolean includeDeleted(HttpRequest request) {
return "true".equals(request.getProperty("includeDeleted"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
case deleted: return "DELETED";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong()); // Absence of this means it's not a prod app :/
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
ensureApplicationExists(TenantAndApplicationId.from(tenant, application), request);
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private ZoneId requireZone(String environment, String region) {
ZoneId zone = ZoneId.from(environment, region);
// TODO(mpolden): Find a way to not hardcode this. Some APIs allow this "virtual" zone, e.g. /logs
if (zone.environment() == Environment.prod && zone.region().value().equals("controller")) {
return zone;
}
if (!controller.zoneRegistry().hasZone(zone)) {
throw new IllegalArgumentException("Zone " + zone + " does not exist in this system");
}
return zone;
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("X-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case weighted: return "weighted";
case application: return "application";
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
private void ensureApplicationExists(TenantAndApplicationId id, HttpRequest request) {
if (controller.applications().getApplication(id).isEmpty()) {
log.fine("Application does not exist in public, creating: " + id);
var credentials = accessControlRequests.credentials(id.tenant(), null /* not used on public */ , request.getJDiscRequest());
controller.applications().createApplication(id, credentials);
}
}
} |
package com.yahoo.vespa.hosted.controller.restapi.application;
import ai.vespa.hosted.api.Signatures;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;
import com.yahoo.component.Version;
import com.yahoo.config.application.api.DeploymentSpec;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.ClusterResources;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.InstanceName;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.zone.RoutingMethod;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.container.handler.metrics.JsonResponse;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.LoggingRequestHandler;
import com.yahoo.io.IOUtils;
import com.yahoo.restapi.ByteArrayResponse;
import com.yahoo.restapi.ErrorResponse;
import com.yahoo.restapi.MessageResponse;
import com.yahoo.restapi.Path;
import com.yahoo.restapi.ResourceResponse;
import com.yahoo.restapi.SlimeJsonResponse;
import com.yahoo.security.KeyUtils;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.Inspector;
import com.yahoo.slime.JsonParseException;
import com.yahoo.slime.Slime;
import com.yahoo.slime.SlimeUtils;
import com.yahoo.text.Text;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.flags.ListFlag;
import com.yahoo.vespa.hosted.controller.Application;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.Instance;
import com.yahoo.vespa.hosted.controller.LockedTenant;
import com.yahoo.vespa.hosted.controller.NotExistsException;
import com.yahoo.vespa.hosted.controller.api.application.v4.EnvironmentResource;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.EndpointStatus;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.ProtonMetrics;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RefeedAction;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RestartAction;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.ServiceInfo;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.identifiers.Hostname;
import com.yahoo.vespa.hosted.controller.api.identifiers.TenantId;
import com.yahoo.vespa.hosted.controller.api.integration.aws.TenantRoles;
import com.yahoo.vespa.hosted.controller.api.integration.billing.Quota;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Cluster;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ConfigServerException;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Log;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeFilter;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeRepository;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.SourceRevision;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.RestartFilter;
import com.yahoo.vespa.hosted.controller.api.integration.resource.MeteringData;
import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceAllocation;
import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceSnapshot;
import com.yahoo.vespa.hosted.controller.api.integration.secrets.TenantSecretStore;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.RoleDefinition;
import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
import com.yahoo.vespa.hosted.controller.application.ActivateResult;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.application.AssignedRotation;
import com.yahoo.vespa.hosted.controller.application.Change;
import com.yahoo.vespa.hosted.controller.application.Deployment;
import com.yahoo.vespa.hosted.controller.application.DeploymentMetrics;
import com.yahoo.vespa.hosted.controller.application.Endpoint;
import com.yahoo.vespa.hosted.controller.application.EndpointList;
import com.yahoo.vespa.hosted.controller.application.QuotaUsage;
import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLoggingRequestHandler;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentStatus;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentSteps;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel;
import com.yahoo.vespa.hosted.controller.deployment.JobStatus;
import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.deployment.TestConfigSerializer;
import com.yahoo.vespa.hosted.controller.maintenance.ResourceMeterMaintainer;
import com.yahoo.vespa.hosted.controller.notification.Notification;
import com.yahoo.vespa.hosted.controller.notification.NotificationSource;
import com.yahoo.vespa.hosted.controller.persistence.SupportAccessSerializer;
import com.yahoo.vespa.hosted.controller.rotation.RotationId;
import com.yahoo.vespa.hosted.controller.rotation.RotationState;
import com.yahoo.vespa.hosted.controller.rotation.RotationStatus;
import com.yahoo.vespa.hosted.controller.routing.GlobalRouting;
import com.yahoo.vespa.hosted.controller.security.AccessControlRequests;
import com.yahoo.vespa.hosted.controller.security.Credentials;
import com.yahoo.vespa.hosted.controller.support.access.SupportAccess;
import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant;
import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
import com.yahoo.vespa.hosted.controller.tenant.DeletedTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfoAddress;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfoBillingContact;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
import com.yahoo.vespa.serviceview.bindings.ApplicationView;
import com.yahoo.yolean.Exceptions;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotAuthorizedException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.DigestInputStream;
import java.security.Principal;
import java.security.PublicKey;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Scanner;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.yahoo.jdisc.Response.Status.BAD_REQUEST;
import static com.yahoo.jdisc.Response.Status.CONFLICT;
import static com.yahoo.yolean.Exceptions.uncheck;
import static java.util.Map.Entry.comparingByKey;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toUnmodifiableList;
/**
* This implements the application/v4 API which is used to deploy and manage applications
* on hosted Vespa.
*
* @author bratseth
* @author mpolden
*/
@SuppressWarnings("unused")
public class ApplicationApiHandler extends AuditLoggingRequestHandler {
private static final ObjectMapper jsonMapper = new ObjectMapper();
private final Controller controller;
private final AccessControlRequests accessControlRequests;
private final TestConfigSerializer testConfigSerializer;
private final ListFlag<String> allowedServiceViewProxy;
@Inject
public ApplicationApiHandler(LoggingRequestHandler.Context parentCtx,
Controller controller,
AccessControlRequests accessControlRequests) {
super(parentCtx, controller.auditLogger());
this.controller = controller;
this.accessControlRequests = accessControlRequests;
this.testConfigSerializer = new TestConfigSerializer(controller.system());
allowedServiceViewProxy = Flags.ALLOWED_SERVICE_VIEW_APIS.bindTo(controller.flagSource());
}
@Override
public Duration getTimeout() {
return Duration.ofMinutes(20); // deploys may take a long time;
}
@Override
public HttpResponse auditAndHandle(HttpRequest request) {
try {
Path path = new Path(request.getUri());
switch (request.getMethod()) {
case GET: return handleGET(path, request);
case PUT: return handlePUT(path, request);
case POST: return handlePOST(path, request);
case PATCH: return handlePATCH(path, request);
case DELETE: return handleDELETE(path, request);
case OPTIONS: return handleOPTIONS();
default: return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is not supported");
}
}
catch (ForbiddenException e) {
return ErrorResponse.forbidden(Exceptions.toMessageString(e));
}
catch (NotAuthorizedException e) {
return ErrorResponse.unauthorized(Exceptions.toMessageString(e));
}
catch (NotExistsException e) {
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
}
catch (IllegalArgumentException e) {
return ErrorResponse.badRequest(Exceptions.toMessageString(e));
}
catch (ConfigServerException e) {
switch (e.code()) {
case NOT_FOUND:
return ErrorResponse.notFoundError(Exceptions.toMessageString(e));
case ACTIVATION_CONFLICT:
return new ErrorResponse(CONFLICT, e.code().name(), Exceptions.toMessageString(e));
case INTERNAL_SERVER_ERROR:
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
default:
return new ErrorResponse(BAD_REQUEST, e.code().name(), Exceptions.toMessageString(e));
}
}
catch (RuntimeException e) {
log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "'", e);
return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
}
}
private HttpResponse handleGET(Path path, HttpRequest request) {
if (path.matches("/application/v4/")) return root(request);
if (path.matches("/application/v4/tenant")) return tenants(request);
if (path.matches("/application/v4/tenant/{tenant}")) return tenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/info")) return tenantInfo(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/notifications")) return notifications(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}/validate")) return validateSecretStore(path.get("tenant"), path.get("name"), request);
if (path.matches("/application/v4/tenant/{tenant}/application")) return applications(path.get("tenant"), Optional.empty(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return application(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/compile-version")) return compileVersion(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return JobControllerApiHandlerHelper.overviewResponse(controller, TenantAndApplicationId.from(path.get("tenant"), path.get("application")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/package")) return applicationPackage(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/diff/{number}")) return applicationPackageDiff(path.get("tenant"), path.get("application"), path.get("number"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/metering")) return metering(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance")) return applications(path.get("tenant"), Optional.of(path.get("application")), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return instance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deploying(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job")) return JobControllerApiHandlerHelper.jobTypeResponse(controller, appIdFromPath(path), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.runResponse(controller.jobController().runs(appIdFromPath(path), jobTypeFromPath(path)).descendingMap(), Optional.ofNullable(request.getProperty("limit")), request.getUri());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/package")) return devApplicationPackage(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/diff/{number}")) return devApplicationPackageDiff(runIdFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/test-config")) return testConfig(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/run/{number}")) return JobControllerApiHandlerHelper.runDetailsResponse(controller.jobController(), runIdFromPath(path), request.getProperty("after"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return getReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/content/{*}")) return content(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return supportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/node/{node}/service-dump")) return getServiceDump(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("node"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/metrics")) return metrics(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deployment(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/suspended")) return suspended(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service")) return services(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/service/{service}/{*}")) return service(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("service"), path.getRest(), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/nodes")) return nodes(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/clusters")) return clusters(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/logs")) return logs(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request.propertyMap());
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation")) return rotationStatus(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), Optional.ofNullable(request.getProperty("endpointId")));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return getGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"));
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePUT(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return updateTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/info")) return updateTenantInfo(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/archive-access")) return allowArchiveAccess(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}")) return addSecretStore(path.get("tenant"), path.get("name"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePOST(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return createTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return addDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return createApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), "default", false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), "default", true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), "default", request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return addDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return createInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{jobtype}")) return jobDeploy(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/platform")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), false, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/pin")) return deployPlatform(path.get("tenant"), path.get("application"), path.get("instance"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/application")) return deployApplication(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/submit")) return submit(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return trigger(appIdFromPath(path), jobTypeFromPath(path), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return pause(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); // legacy synonym of the above
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindex")) return reindex(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return enableReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspend")) return suspend(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return allowSupportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/node/{node}/service-dump")) return requestServiceDump(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), path.get("node"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/deploy")) return deploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request); // legacy synonym of the above
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/restart")) return restart(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handlePATCH(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return patchApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return patchApplication(path.get("tenant"), path.get("application"), request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleDELETE(Path path, HttpRequest request) {
if (path.matches("/application/v4/tenant/{tenant}")) return deleteTenant(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/key")) return removeDeveloperKey(path.get("tenant"), request);
if (path.matches("/application/v4/tenant/{tenant}/archive-access")) return removeArchiveAccess(path.get("tenant"));
if (path.matches("/application/v4/tenant/{tenant}/secret-store/{name}")) return deleteSecretStore(path.get("tenant"), path.get("name"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}")) return deleteApplication(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deployment")) return removeAllProdDeployments(path.get("tenant"), path.get("application"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), "default", path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/key")) return removeDeployKey(path.get("tenant"), path.get("application"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}")) return deleteInstance(path.get("tenant"), path.get("application"), path.get("instance"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), "all");
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploying/{choice}")) return cancelDeploy(path.get("tenant"), path.get("application"), path.get("instance"), path.get("choice"));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}")) return JobControllerApiHandlerHelper.abortJobResponse(controller.jobController(), appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{jobtype}/pause")) return resume(appIdFromPath(path), jobTypeFromPath(path));
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/reindexing")) return disableReindexing(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/suspend")) return suspend(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), false);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/{environment}/region/{region}/access/support")) return disallowSupportAccess(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}")) return deactivate(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), request);
if (path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override")) return setGlobalRotationOverride(path.get("tenant"), path.get("application"), path.get("instance"), path.get("environment"), path.get("region"), true, request);
return ErrorResponse.notFoundError("Nothing at " + path);
}
private HttpResponse handleOPTIONS() {
// We implement this to avoid redirect loops on OPTIONS requests from browsers, but do not really bother
// spelling out the methods supported at each path, which we should
EmptyResponse response = new EmptyResponse();
response.headers().put("Allow", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
return response;
}
private HttpResponse recursiveRoot(HttpRequest request) {
Slime slime = new Slime();
Cursor tenantArray = slime.setArray();
List<Application> applications = controller.applications().asList();
for (Tenant tenant : controller.tenants().asList(includeDeleted(request)))
toSlime(tenantArray.addObject(),
tenant,
applications.stream().filter(app -> app.id().tenant().equals(tenant.name())).collect(toList()),
request);
return new SlimeJsonResponse(slime);
}
private HttpResponse root(HttpRequest request) {
return recurseOverTenants(request)
? recursiveRoot(request)
: new ResourceResponse(request, "tenant");
}
private HttpResponse tenants(HttpRequest request) {
Slime slime = new Slime();
Cursor response = slime.setArray();
for (Tenant tenant : controller.tenants().asList(includeDeleted(request)))
tenantInTenantsListToSlime(tenant, request.getUri(), response.addObject());
return new SlimeJsonResponse(slime);
}
private HttpResponse tenant(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName), includeDeleted(request))
.map(tenant -> tenant(tenant, request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist"));
}
private HttpResponse tenant(Tenant tenant, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), tenant, controller.applications().asList(tenant.name()), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse tenantInfo(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.filter(tenant -> tenant.type() == Tenant.Type.cloud)
.map(tenant -> tenantInfo(((CloudTenant)tenant).info(), request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist or does not support this"));
}
private SlimeJsonResponse tenantInfo(TenantInfo info, HttpRequest request) {
Slime slime = new Slime();
Cursor infoCursor = slime.setObject();
if (!info.isEmpty()) {
infoCursor.setString("name", info.name());
infoCursor.setString("email", info.email());
infoCursor.setString("website", info.website());
infoCursor.setString("invoiceEmail", info.invoiceEmail());
infoCursor.setString("contactName", info.contactName());
infoCursor.setString("contactEmail", info.contactEmail());
toSlime(info.address(), infoCursor);
toSlime(info.billingContact(), infoCursor);
}
return new SlimeJsonResponse(slime);
}
private void toSlime(TenantInfoAddress address, Cursor parentCursor) {
if (address.isEmpty()) return;
Cursor addressCursor = parentCursor.setObject("address");
addressCursor.setString("addressLines", address.addressLines());
addressCursor.setString("postalCodeOrZip", address.postalCodeOrZip());
addressCursor.setString("city", address.city());
addressCursor.setString("stateRegionProvince", address.stateRegionProvince());
addressCursor.setString("country", address.country());
}
private void toSlime(TenantInfoBillingContact billingContact, Cursor parentCursor) {
if (billingContact.isEmpty()) return;
Cursor addressCursor = parentCursor.setObject("billingContact");
addressCursor.setString("name", billingContact.name());
addressCursor.setString("email", billingContact.email());
addressCursor.setString("phone", billingContact.phone());
toSlime(billingContact.address(), addressCursor);
}
private HttpResponse updateTenantInfo(String tenantName, HttpRequest request) {
return controller.tenants().get(TenantName.from(tenantName))
.filter(tenant -> tenant.type() == Tenant.Type.cloud)
.map(tenant -> updateTenantInfo(((CloudTenant)tenant), request))
.orElseGet(() -> ErrorResponse.notFoundError("Tenant '" + tenantName + "' does not exist or does not support this"));
}
private String getString(Inspector field, String defaultVale) {
return field.valid() ? field.asString() : defaultVale;
}
private SlimeJsonResponse updateTenantInfo(CloudTenant tenant, HttpRequest request) {
TenantInfo oldInfo = tenant.info();
// Merge info from request with the existing info
Inspector insp = toSlime(request.getData()).get();
TenantInfo mergedInfo = TenantInfo.EMPTY
.withName(getString(insp.field("name"), oldInfo.name()))
.withEmail(getString(insp.field("email"), oldInfo.email()))
.withWebsite(getString(insp.field("website"), oldInfo.email()))
.withInvoiceEmail(getString(insp.field("invoiceEmail"), oldInfo.invoiceEmail()))
.withContactName(getString(insp.field("contactName"), oldInfo.contactName()))
.withContactEmail(getString(insp.field("contactEmail"), oldInfo.contactName()))
.withAddress(updateTenantInfoAddress(insp.field("address"), oldInfo.address()))
.withBillingContact(updateTenantInfoBillingContact(insp.field("billingContact"), oldInfo.billingContact()));
// Store changes
controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withInfo(mergedInfo);
controller.tenants().store(lockedTenant);
});
return new MessageResponse("Tenant info updated");
}
private TenantInfoAddress updateTenantInfoAddress(Inspector insp, TenantInfoAddress oldAddress) {
if (!insp.valid()) return oldAddress;
return TenantInfoAddress.EMPTY
.withCountry(getString(insp.field("country"), oldAddress.country()))
.withStateRegionProvince(getString(insp.field("stateRegionProvince"), oldAddress.stateRegionProvince()))
.withCity(getString(insp.field("city"), oldAddress.city()))
.withPostalCodeOrZip(getString(insp.field("postalCodeOrZip"), oldAddress.postalCodeOrZip()))
.withAddressLines(getString(insp.field("addressLines"), oldAddress.addressLines()));
}
private TenantInfoBillingContact updateTenantInfoBillingContact(Inspector insp, TenantInfoBillingContact oldContact) {
if (!insp.valid()) return oldContact;
return TenantInfoBillingContact.EMPTY
.withName(getString(insp.field("name"), oldContact.name()))
.withEmail(getString(insp.field("email"), oldContact.email()))
.withPhone(getString(insp.field("phone"), oldContact.phone()))
.withAddress(updateTenantInfoAddress(insp.field("address"), oldContact.address()));
}
private HttpResponse notifications(String tenantName, HttpRequest request) {
NotificationSource notificationSource = new NotificationSource(TenantName.from(tenantName),
Optional.ofNullable(request.getProperty("application")).map(ApplicationName::from),
Optional.ofNullable(request.getProperty("instance")).map(InstanceName::from),
Optional.empty(), Optional.empty(), Optional.empty(), OptionalLong.empty());
Slime slime = new Slime();
Cursor notificationsArray = slime.setObject().setArray("notifications");
controller.notificationsDb().listNotifications(notificationSource, showOnlyProductionInstances(request))
.forEach(notification -> toSlime(notificationsArray.addObject(), notification));
return new SlimeJsonResponse(slime);
}
private static void toSlime(Cursor cursor, Notification notification) {
cursor.setLong("at", notification.at().toEpochMilli());
cursor.setString("level", notificationLevelAsString(notification.level()));
cursor.setString("type", notificationTypeAsString(notification.type()));
Cursor messagesArray = cursor.setArray("messages");
notification.messages().forEach(messagesArray::addString);
notification.source().application().ifPresent(application -> cursor.setString("application", application.value()));
notification.source().instance().ifPresent(instance -> cursor.setString("instance", instance.value()));
notification.source().zoneId().ifPresent(zoneId -> {
cursor.setString("environment", zoneId.environment().value());
cursor.setString("region", zoneId.region().value());
});
notification.source().clusterId().ifPresent(clusterId -> cursor.setString("clusterId", clusterId.value()));
notification.source().jobType().ifPresent(jobType -> cursor.setString("jobName", jobType.jobName()));
notification.source().runNumber().ifPresent(runNumber -> cursor.setLong("runNumber", runNumber));
}
private static String notificationTypeAsString(Notification.Type type) {
switch (type) {
case applicationPackage: return "applicationPackage";
case deployment: return "deployment";
case feedBlock: return "feedBlock";
case reindex: return "reindex";
default: throw new IllegalArgumentException("No serialization defined for notification type " + type);
}
}
private static String notificationLevelAsString(Notification.Level level) {
switch (level) {
case info: return "info";
case warning: return "warning";
case error: return "error";
default: throw new IllegalArgumentException("No serialization defined for notification level " + level);
}
}
private HttpResponse applications(String tenantName, Optional<String> applicationName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
getTenantOrThrow(tenantName);
List<Application> applications = applicationName.isEmpty() ?
controller.applications().asList(tenant) :
controller.applications().getApplication(TenantAndApplicationId.from(tenantName, applicationName.get()))
.map(List::of)
.orElseThrow(() -> new NotExistsException("Application '" + applicationName.get() + "' does not exist"));
Slime slime = new Slime();
Cursor applicationArray = slime.setArray();
for (Application application : applications) {
Cursor applicationObject = applicationArray.addObject();
applicationObject.setString("tenant", application.id().tenant().value());
applicationObject.setString("application", application.id().application().value());
applicationObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value(),
request.getUri()).toString());
Cursor instanceArray = applicationObject.setArray("instances");
for (InstanceName instance : showOnlyProductionInstances(request) ? application.productionInstances().keySet()
: application.instances().keySet()) {
Cursor instanceObject = instanceArray.addObject();
instanceObject.setString("instance", instance.value());
instanceObject.setString("url", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/instance/" + instance.value(),
request.getUri()).toString());
}
}
return new SlimeJsonResponse(slime);
}
private HttpResponse devApplicationPackage(ApplicationId id, JobType type) {
if ( ! type.environment().isManuallyDeployed())
throw new IllegalArgumentException("Only manually deployed zones have dev packages");
ZoneId zone = type.zone(controller.system());
ApplicationVersion version = controller.jobController().last(id, type).get().versions().targetApplication();
byte[] applicationPackage = controller.applications().applicationStore().get(new DeploymentId(id, zone), version);
return new ZipResponse(id.toFullString() + "." + zone.value() + ".zip", applicationPackage);
}
private HttpResponse devApplicationPackageDiff(RunId runId) {
DeploymentId deploymentId = new DeploymentId(runId.application(), runId.job().type().zone(controller.system()));
return controller.applications().applicationStore().getDevDiff(deploymentId, runId.number())
.map(ByteArrayResponse::new)
.orElseThrow(() -> new NotExistsException("No application package diff found for " + runId));
}
private HttpResponse applicationPackage(String tenantName, String applicationName, HttpRequest request) {
var tenantAndApplication = TenantAndApplicationId.from(tenantName, applicationName);
long buildNumber;
var requestedBuild = Optional.ofNullable(request.getProperty("build")).map(build -> {
try {
return Long.parseLong(build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid build number", e);
}
});
if (requestedBuild.isEmpty()) { // Fall back to latest build
var application = controller.applications().requireApplication(tenantAndApplication);
var latestBuild = application.latestVersion().map(ApplicationVersion::buildNumber).orElse(OptionalLong.empty());
if (latestBuild.isEmpty()) {
throw new NotExistsException("No application package has been submitted for '" + tenantAndApplication + "'");
}
buildNumber = latestBuild.getAsLong();
} else {
buildNumber = requestedBuild.get();
}
var applicationPackage = controller.applications().applicationStore().find(tenantAndApplication.tenant(), tenantAndApplication.application(), buildNumber);
var filename = tenantAndApplication + "-build" + buildNumber + ".zip";
if (applicationPackage.isEmpty()) {
throw new NotExistsException("No application package found for '" +
tenantAndApplication +
"' with build number " + buildNumber);
}
return new ZipResponse(filename, applicationPackage.get());
}
private HttpResponse applicationPackageDiff(String tenant, String application, String number) {
TenantAndApplicationId tenantAndApplication = TenantAndApplicationId.from(tenant, application);
return controller.applications().applicationStore().getDiff(tenantAndApplication.tenant(), tenantAndApplication.application(), Long.parseLong(number))
.map(ByteArrayResponse::new)
.orElseThrow(() -> new NotExistsException("No application package diff found for '" + tenantAndApplication + "' with build number " + number));
}
private HttpResponse application(String tenantName, String applicationName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getApplication(tenantName, applicationName), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse compileVersion(String tenantName, String applicationName) {
Slime slime = new Slime();
slime.setObject().setString("compileVersion",
compileVersion(TenantAndApplicationId.from(tenantName, applicationName)).toFullString());
return new SlimeJsonResponse(slime);
}
private HttpResponse instance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Slime slime = new Slime();
toSlime(slime.setObject(), getInstance(tenantName, applicationName, instanceName),
controller.jobController().deploymentStatus(getApplication(tenantName, applicationName)), request);
return new SlimeJsonResponse(slime);
}
private HttpResponse addDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
Principal user = request.getJDiscRequest().getUserPrincipal();
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withDeveloperKey(developerKey, user);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private HttpResponse validateSecretStore(String tenantName, String secretStoreName, HttpRequest request) {
var awsRegion = request.getProperty("aws-region");
var parameterName = request.getProperty("parameter-name");
var applicationId = ApplicationId.fromFullString(request.getProperty("application-id"));
var zoneId = ZoneId.from(request.getProperty("zone"));
var deploymentId = new DeploymentId(applicationId, zoneId);
var tenant = controller.tenants().require(applicationId.tenant(), CloudTenant.class);
var tenantSecretStore = tenant.tenantSecretStores()
.stream()
.filter(secretStore -> secretStore.getName().equals(secretStoreName))
.findFirst();
if (tenantSecretStore.isEmpty())
return ErrorResponse.notFoundError("No secret store '" + secretStoreName + "' configured for tenant '" + tenantName + "'");
var response = controller.serviceRegistry().configServer().validateSecretStore(deploymentId, tenantSecretStore.get(), awsRegion, parameterName);
try {
var responseRoot = new Slime();
var responseCursor = responseRoot.setObject();
responseCursor.setString("target", deploymentId.toString());
var responseResultCursor = responseCursor.setObject("result");
var responseSlime = SlimeUtils.jsonToSlime(response);
SlimeUtils.copyObject(responseSlime.get(), responseResultCursor);
return new SlimeJsonResponse(responseRoot);
} catch (JsonParseException e) {
return ErrorResponse.internalServerError(response);
}
}
private HttpResponse removeDeveloperKey(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
String pemDeveloperKey = toSlime(request.getData()).get().field("key").asString();
PublicKey developerKey = KeyUtils.fromPemEncodedPublicKey(pemDeveloperKey);
Principal user = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class).developerKeys().get(developerKey);
Slime root = new Slime();
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, tenant -> {
tenant = tenant.withoutDeveloperKey(developerKey);
toSlime(root.setObject().setArray("keys"), tenant.get().developerKeys());
controller.tenants().store(tenant);
});
return new SlimeJsonResponse(root);
}
private void toSlime(Cursor keysArray, Map<PublicKey, Principal> keys) {
keys.forEach((key, principal) -> {
Cursor keyObject = keysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", principal.getName());
});
}
private HttpResponse addDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse removeDeployKey(String tenantName, String applicationName, HttpRequest request) {
String pemDeployKey = toSlime(request.getData()).get().field("key").asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
Slime root = new Slime();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
application = application.withoutDeployKey(deployKey);
application.get().deployKeys().stream()
.map(KeyUtils::toPem)
.forEach(root.setObject().setArray("keys")::addString);
controller.applications().store(application);
});
return new SlimeJsonResponse(root);
}
private HttpResponse addSecretStore(String tenantName, String name, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
var data = toSlime(request.getData()).get();
var awsId = mandatory("awsId", data).asString();
var externalId = mandatory("externalId", data).asString();
var role = mandatory("role", data).asString();
var tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class);
var tenantSecretStore = new TenantSecretStore(name, awsId, role);
if (!tenantSecretStore.isValid()) {
return ErrorResponse.badRequest("Secret store " + tenantSecretStore + " is invalid");
}
if (tenant.tenantSecretStores().contains(tenantSecretStore)) {
return ErrorResponse.badRequest("Secret store " + tenantSecretStore + " is already configured");
}
controller.serviceRegistry().roleService().createTenantPolicy(TenantName.from(tenantName), name, awsId, role);
controller.serviceRegistry().tenantSecretService().addSecretStore(tenant.name(), tenantSecretStore, externalId);
// Store changes
controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withSecretStore(tenantSecretStore);
controller.tenants().store(lockedTenant);
});
tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class);
var slime = new Slime();
toSlime(slime.setObject(), tenant.tenantSecretStores());
return new SlimeJsonResponse(slime);
}
private HttpResponse deleteSecretStore(String tenantName, String name, HttpRequest request) {
var tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class);
var optionalSecretStore = tenant.tenantSecretStores().stream()
.filter(secretStore -> secretStore.getName().equals(name))
.findFirst();
if (optionalSecretStore.isEmpty())
return ErrorResponse.notFoundError("Could not delete secret store '" + name + "': Secret store not found");
var tenantSecretStore = optionalSecretStore.get();
controller.serviceRegistry().tenantSecretService().deleteSecretStore(tenant.name(), tenantSecretStore);
controller.serviceRegistry().roleService().deleteTenantPolicy(tenant.name(), tenantSecretStore.getName(), tenantSecretStore.getRole());
controller.tenants().lockOrThrow(tenant.name(), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withoutSecretStore(tenantSecretStore);
controller.tenants().store(lockedTenant);
});
tenant = controller.tenants().require(TenantName.from(tenantName), CloudTenant.class);
var slime = new Slime();
toSlime(slime.setObject(), tenant.tenantSecretStores());
return new SlimeJsonResponse(slime);
}
private HttpResponse allowArchiveAccess(String tenantName, HttpRequest request) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
var data = toSlime(request.getData()).get();
var role = mandatory("role", data).asString();
if (role.isBlank()) {
return ErrorResponse.badRequest("Archive access role can't be whitespace only");
}
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withArchiveAccessRole(Optional.of(role));
controller.tenants().store(lockedTenant);
});
return new MessageResponse("Archive access role set to '" + role + "' for tenant " + tenantName + ".");
}
private HttpResponse removeArchiveAccess(String tenantName) {
if (controller.tenants().require(TenantName.from(tenantName)).type() != Tenant.Type.cloud)
throw new IllegalArgumentException("Tenant '" + tenantName + "' is not a cloud tenant");
controller.tenants().lockOrThrow(TenantName.from(tenantName), LockedTenant.Cloud.class, lockedTenant -> {
lockedTenant = lockedTenant.withArchiveAccessRole(Optional.empty());
controller.tenants().store(lockedTenant);
});
return new MessageResponse("Archive access role removed for tenant " + tenantName + ".");
}
private HttpResponse patchApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
StringJoiner messageBuilder = new StringJoiner("\n").setEmptyValue("No applicable changes.");
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(tenantName, applicationName), application -> {
Inspector majorVersionField = requestObject.field("majorVersion");
if (majorVersionField.valid()) {
Integer majorVersion = majorVersionField.asLong() == 0 ? null : (int) majorVersionField.asLong();
application = application.withMajorVersion(majorVersion);
messageBuilder.add("Set major version to " + (majorVersion == null ? "empty" : majorVersion));
}
// TODO jonmv: Remove when clients are updated.
Inspector pemDeployKeyField = requestObject.field("pemDeployKey");
if (pemDeployKeyField.valid()) {
String pemDeployKey = pemDeployKeyField.asString();
PublicKey deployKey = KeyUtils.fromPemEncodedPublicKey(pemDeployKey);
application = application.withDeployKey(deployKey);
messageBuilder.add("Added deploy key " + pemDeployKey);
}
controller.applications().store(application);
});
return new MessageResponse(messageBuilder.toString());
}
private Application getApplication(String tenantName, String applicationName) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
return controller.applications().getApplication(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private Instance getInstance(String tenantName, String applicationName, String instanceName) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
return controller.applications().getInstance(applicationId)
.orElseThrow(() -> new NotExistsException(applicationId + " not found"));
}
private HttpResponse nodes(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
List<Node> nodes = controller.serviceRegistry().configServer().nodeRepository().list(zone, NodeFilter.all().applications(id));
Slime slime = new Slime();
Cursor nodesArray = slime.setObject().setArray("nodes");
for (Node node : nodes) {
Cursor nodeObject = nodesArray.addObject();
nodeObject.setString("hostname", node.hostname().value());
nodeObject.setString("state", valueOf(node.state()));
node.reservedTo().ifPresent(tenant -> nodeObject.setString("reservedTo", tenant.value()));
nodeObject.setString("orchestration", valueOf(node.serviceState()));
nodeObject.setString("version", node.currentVersion().toString());
node.flavor().ifPresent(flavor -> nodeObject.setString("flavor", flavor));
toSlime(node.resources(), nodeObject);
nodeObject.setString("clusterId", node.clusterId());
nodeObject.setString("clusterType", valueOf(node.clusterType()));
nodeObject.setBool("down", node.history().stream().anyMatch(event -> "down".equals(event.name())));
nodeObject.setBool("retired", node.retired() || node.wantToRetire());
nodeObject.setBool("restarting", node.wantedRestartGeneration() > node.restartGeneration());
nodeObject.setBool("rebooting", node.wantedRebootGeneration() > node.rebootGeneration());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse clusters(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
com.yahoo.vespa.hosted.controller.api.integration.configserver.Application application = controller.serviceRegistry().configServer().nodeRepository().getApplication(zone, id);
Slime slime = new Slime();
Cursor clustersObject = slime.setObject().setObject("clusters");
for (Cluster cluster : application.clusters().values()) {
Cursor clusterObject = clustersObject.setObject(cluster.id().value());
clusterObject.setString("type", cluster.type().name());
toSlime(cluster.min(), clusterObject.setObject("min"));
toSlime(cluster.max(), clusterObject.setObject("max"));
toSlime(cluster.current(), clusterObject.setObject("current"));
if (cluster.target().isPresent()
&& ! cluster.target().get().justNumbers().equals(cluster.current().justNumbers()))
toSlime(cluster.target().get(), clusterObject.setObject("target"));
cluster.suggested().ifPresent(suggested -> toSlime(suggested, clusterObject.setObject("suggested")));
utilizationToSlime(cluster.utilization(), clusterObject.setObject("utilization"));
scalingEventsToSlime(cluster.scalingEvents(), clusterObject.setArray("scalingEvents"));
clusterObject.setString("autoscalingStatusCode", cluster.autoscalingStatusCode());
clusterObject.setString("autoscalingStatus", cluster.autoscalingStatus());
clusterObject.setLong("scalingDuration", cluster.scalingDuration().toMillis());
clusterObject.setDouble("maxQueryGrowthRate", cluster.maxQueryGrowthRate());
clusterObject.setDouble("currentQueryFractionOfMax", cluster.currentQueryFractionOfMax());
}
return new SlimeJsonResponse(slime);
}
private static String valueOf(Node.State state) {
switch (state) {
case failed: return "failed";
case parked: return "parked";
case dirty: return "dirty";
case ready: return "ready";
case active: return "active";
case inactive: return "inactive";
case reserved: return "reserved";
case provisioned: return "provisioned";
default: throw new IllegalArgumentException("Unexpected node state '" + state + "'.");
}
}
static String valueOf(Node.ServiceState state) {
switch (state) {
case expectedUp: return "expectedUp";
case allowedDown: return "allowedDown";
case permanentlyDown: return "permanentlyDown";
case unorchestrated: return "unorchestrated";
case unknown: break;
}
return "unknown";
}
private static String valueOf(Node.ClusterType type) {
switch (type) {
case admin: return "admin";
case content: return "content";
case container: return "container";
case combined: return "combined";
default: throw new IllegalArgumentException("Unexpected node cluster type '" + type + "'.");
}
}
private static String valueOf(NodeResources.DiskSpeed diskSpeed) {
switch (diskSpeed) {
case fast : return "fast";
case slow : return "slow";
case any : return "any";
default: throw new IllegalArgumentException("Unknown disk speed '" + diskSpeed.name() + "'");
}
}
private static String valueOf(NodeResources.StorageType storageType) {
switch (storageType) {
case remote : return "remote";
case local : return "local";
case any : return "any";
default: throw new IllegalArgumentException("Unknown storage type '" + storageType.name() + "'");
}
}
private HttpResponse logs(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
InputStream logStream = controller.serviceRegistry().configServer().getLogs(deployment, queryParameters);
return new HttpResponse(200) {
@Override
public void render(OutputStream outputStream) throws IOException {
try (logStream) {
logStream.transferTo(outputStream);
}
}
};
}
private HttpResponse supportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, Map<String, String> queryParameters) {
DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
SupportAccess supportAccess = controller.supportAccess().forDeployment(deployment);
return new SlimeJsonResponse(SupportAccessSerializer.serializeCurrentState(supportAccess, controller.clock().instant()));
}
// TODO support access: only let tenants (not operators!) allow access
// TODO support access: configurable period of access?
private HttpResponse allowSupportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
Principal principal = requireUserPrincipal(request);
Instant now = controller.clock().instant();
SupportAccess allowed = controller.supportAccess().allow(deployment, now.plus(7, ChronoUnit.DAYS), principal.getName());
return new SlimeJsonResponse(SupportAccessSerializer.serializeCurrentState(allowed, now));
}
private HttpResponse disallowSupportAccess(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deployment = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
Principal principal = requireUserPrincipal(request);
SupportAccess disallowed = controller.supportAccess().disallow(deployment, principal.getName());
controller.applications().deploymentTrigger().reTriggerOrAddToQueue(deployment);
return new SlimeJsonResponse(SupportAccessSerializer.serializeCurrentState(disallowed, controller.clock().instant()));
}
private HttpResponse metrics(String tenantName, String applicationName, String instanceName, String environment, String region) {
ApplicationId application = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
DeploymentId deployment = new DeploymentId(application, zone);
List<ProtonMetrics> protonMetrics = controller.serviceRegistry().configServer().getProtonMetrics(deployment);
return buildResponseFromProtonMetrics(protonMetrics);
}
private JsonResponse buildResponseFromProtonMetrics(List<ProtonMetrics> protonMetrics) {
try {
var jsonObject = jsonMapper.createObjectNode();
var jsonArray = jsonMapper.createArrayNode();
for (ProtonMetrics metrics : protonMetrics) {
jsonArray.add(metrics.toJson());
}
jsonObject.set("metrics", jsonArray);
return new JsonResponse(200, jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject));
} catch (JsonProcessingException e) {
log.log(Level.WARNING, "Unable to build JsonResponse with Proton data: " + e.getMessage(), e);
return new JsonResponse(500, "");
}
}
private HttpResponse trigger(ApplicationId id, JobType type, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
boolean requireTests = ! requestObject.field("skipTests").asBool();
boolean reTrigger = requestObject.field("reTrigger").asBool();
String triggered = reTrigger
? controller.applications().deploymentTrigger()
.reTrigger(id, type).type().jobName()
: controller.applications().deploymentTrigger()
.forceTrigger(id, type, request.getJDiscRequest().getUserPrincipal().getName(), requireTests)
.stream().map(job -> job.type().jobName()).collect(joining(", "));
return new MessageResponse(triggered.isEmpty() ? "Job " + type.jobName() + " for " + id + " not triggered"
: "Triggered " + triggered + " for " + id);
}
private HttpResponse pause(ApplicationId id, JobType type) {
Instant until = controller.clock().instant().plus(DeploymentTrigger.maxPause);
controller.applications().deploymentTrigger().pauseJob(id, type, until);
return new MessageResponse(type.jobName() + " for " + id + " paused for " + DeploymentTrigger.maxPause);
}
private HttpResponse resume(ApplicationId id, JobType type) {
controller.applications().deploymentTrigger().resumeJob(id, type);
return new MessageResponse(type.jobName() + " for " + id + " resumed");
}
private void toSlime(Cursor object, Application application, HttpRequest request) {
object.setString("tenant", application.id().tenant().value());
object.setString("application", application.id().application().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + application.id().tenant().value() +
"/application/" + application.id().application().value() +
"/job/",
request.getUri()).toString());
DeploymentStatus status = controller.jobController().deploymentStatus(application);
application.latestVersion().ifPresent(version -> toSlime(version, object.setObject("latestVersion")));
application.projectId().ifPresent(id -> object.setLong("projectId", id));
// TODO jonmv: Remove this when users are updated.
application.instances().values().stream().findFirst().ifPresent(instance -> {
// Currently deploying change
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
// Outstanding change
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
});
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
Cursor instancesArray = object.setArray("instances");
for (Instance instance : showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values())
toSlime(instancesArray.addObject(), status, instance, application.deploymentSpec(), request);
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
// Metrics
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
// Activity
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
// TODO: Eliminate duplicated code in this and toSlime(Cursor, Instance, DeploymentStatus, HttpRequest)
private void toSlime(Cursor object, DeploymentStatus status, Instance instance, DeploymentSpec deploymentSpec, HttpRequest request) {
object.setString("instance", instance.name().value());
if (deploymentSpec.instance(instance.name()).isPresent()) {
// Jobs sorted according to deployment spec
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(deploymentSpec.requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
// Outstanding change
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
// Change blockers
Cursor changeBlockers = object.setArray("changeBlockers");
deploymentSpec.instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
// Global endpoints
globalEndpointsToSlime(object, instance);
// Deployments sorted according to deployment spec
List<Deployment> deployments = deploymentSpec.instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor deploymentsArray = object.setArray("deployments");
for (Deployment deployment : deployments) {
Cursor deploymentObject = deploymentsArray.addObject();
// Rotation status for this deployment
if (deployment.zone().environment() == Environment.prod && ! instance.rotations().isEmpty())
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
if (recurseOverDeployments(request)) // List full deployment information when recursive.
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/instance/" + instance.name().value() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
}
// TODO(mpolden): Remove once legacy dashboard and integration tests stop expecting these fields
private void globalEndpointsToSlime(Cursor object, Instance instance) {
var globalEndpointUrls = new LinkedHashSet<String>();
// Add global endpoints backed by rotations
controller.routing().endpointsOf(instance.id())
.requiresRotation()
.not().legacy() // Hide legacy names
.asList().stream()
.map(Endpoint::url)
.map(URI::toString)
.forEach(globalEndpointUrls::add);
var globalRotationsArray = object.setArray("globalRotations");
globalEndpointUrls.forEach(globalRotationsArray::addString);
// Legacy field. Identifies the first assigned rotation, if any.
instance.rotations().stream()
.map(AssignedRotation::rotationId)
.findFirst()
.ifPresent(rotation -> object.setString("rotationId", rotation.asString()));
}
private void toSlime(Cursor object, Instance instance, DeploymentStatus status, HttpRequest request) {
Application application = status.application();
object.setString("tenant", instance.id().tenant().value());
object.setString("application", instance.id().application().value());
object.setString("instance", instance.id().instance().value());
object.setString("deployments", withPath("/application/v4" +
"/tenant/" + instance.id().tenant().value() +
"/application/" + instance.id().application().value() +
"/instance/" + instance.id().instance().value() + "/job/",
request.getUri()).toString());
application.latestVersion().ifPresent(version -> {
sourceRevisionToSlime(version.source(), object.setObject("source"));
version.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
version.commit().ifPresent(commit -> object.setString("commit", commit));
});
application.projectId().ifPresent(id -> object.setLong("projectId", id));
if (application.deploymentSpec().instance(instance.name()).isPresent()) {
// Jobs sorted according to deployment spec
List<JobStatus> jobStatus = controller.applications().deploymentTrigger()
.steps(application.deploymentSpec().requireInstance(instance.name()))
.sortedJobs(status.instanceJobs(instance.name()).values());
if ( ! instance.change().isEmpty())
toSlime(object.setObject("deploying"), instance.change());
// Outstanding change
if ( ! status.outstandingChange(instance.name()).isEmpty())
toSlime(object.setObject("outstandingChange"), status.outstandingChange(instance.name()));
// Change blockers
Cursor changeBlockers = object.setArray("changeBlockers");
application.deploymentSpec().instance(instance.name()).ifPresent(spec -> spec.changeBlocker().forEach(changeBlocker -> {
Cursor changeBlockerObject = changeBlockers.addObject();
changeBlockerObject.setBool("versions", changeBlocker.blocksVersions());
changeBlockerObject.setBool("revisions", changeBlocker.blocksRevisions());
changeBlockerObject.setString("timeZone", changeBlocker.window().zone().getId());
Cursor days = changeBlockerObject.setArray("days");
changeBlocker.window().days().stream().map(DayOfWeek::getValue).forEach(days::addLong);
Cursor hours = changeBlockerObject.setArray("hours");
changeBlocker.window().hours().forEach(hours::addLong);
}));
}
application.majorVersion().ifPresent(majorVersion -> object.setLong("majorVersion", majorVersion));
// Global endpoint
globalEndpointsToSlime(object, instance);
// Deployments sorted according to deployment spec
List<Deployment> deployments =
application.deploymentSpec().instance(instance.name())
.map(spec -> new DeploymentSteps(spec, controller::system))
.map(steps -> steps.sortedDeployments(instance.deployments().values()))
.orElse(List.copyOf(instance.deployments().values()));
Cursor instancesArray = object.setArray("instances");
for (Deployment deployment : deployments) {
Cursor deploymentObject = instancesArray.addObject();
// Rotation status for this deployment
if (deployment.zone().environment() == Environment.prod) {
// 0 rotations: No fields written
// 1 rotation : Write legacy field and endpointStatus field
// >1 rotation : Write only endpointStatus field
if (instance.rotations().size() == 1) {
// TODO(mpolden): Stop writing this field once clients stop expecting it
toSlime(instance.rotationStatus().of(instance.rotations().get(0).rotationId(), deployment),
deploymentObject);
}
if ( ! recurseOverDeployments(request) && ! instance.rotations().isEmpty()) { // TODO jonmv: clean up when clients have converged.
toSlime(instance.rotations(), instance.rotationStatus(), deployment, deploymentObject);
}
}
if (recurseOverDeployments(request)) // List full deployment information when recursive.
toSlime(deploymentObject, new DeploymentId(instance.id(), deployment.zone()), deployment, request);
else {
deploymentObject.setString("environment", deployment.zone().environment().value());
deploymentObject.setString("region", deployment.zone().region().value());
deploymentObject.setString("instance", instance.id().instance().value()); // pointless
deploymentObject.setString("url", withPath(request.getUri().getPath() +
"/environment/" + deployment.zone().environment().value() +
"/region/" + deployment.zone().region().value(),
request.getUri()).toString());
}
}
// Add dummy values for not-yet-existent prod deployments.
status.jobSteps().keySet().stream()
.filter(job -> job.application().instance().equals(instance.name()))
.filter(job -> job.type().isProduction() && job.type().isDeployment())
.map(job -> job.type().zone(controller.system()))
.filter(zone -> ! instance.deployments().containsKey(zone))
.forEach(zone -> {
Cursor deploymentObject = instancesArray.addObject();
deploymentObject.setString("environment", zone.environment().value());
deploymentObject.setString("region", zone.region().value());
});
// TODO jonmv: Remove when clients are updated
application.deployKeys().stream().findFirst().ifPresent(key -> object.setString("pemDeployKey", KeyUtils.toPem(key)));
application.deployKeys().stream().map(KeyUtils::toPem).forEach(object.setArray("pemDeployKeys")::addString);
// Metrics
Cursor metricsObject = object.setObject("metrics");
metricsObject.setDouble("queryServiceQuality", application.metrics().queryServiceQuality());
metricsObject.setDouble("writeServiceQuality", application.metrics().writeServiceQuality());
// Activity
Cursor activity = object.setObject("activity");
application.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried", instant.toEpochMilli()));
application.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten", instant.toEpochMilli()));
application.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
application.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
application.ownershipIssueId().ifPresent(issueId -> object.setString("ownershipIssueId", issueId.value()));
application.owner().ifPresent(owner -> object.setString("owner", owner.username()));
application.deploymentIssueId().ifPresent(issueId -> object.setString("deploymentIssueId", issueId.value()));
}
private HttpResponse deployment(String tenantName, String applicationName, String instanceName, String environment,
String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().getInstance(id)
.orElseThrow(() -> new NotExistsException(id + " not found"));
DeploymentId deploymentId = new DeploymentId(instance.id(),
requireZone(environment, region));
Deployment deployment = instance.deployments().get(deploymentId.zoneId());
if (deployment == null)
throw new NotExistsException(instance + " is not deployed in " + deploymentId.zoneId());
Slime slime = new Slime();
toSlime(slime.setObject(), deploymentId, deployment, request);
return new SlimeJsonResponse(slime);
}
private void toSlime(Cursor object, Change change) {
change.platform().ifPresent(version -> object.setString("version", version.toString()));
change.application()
.filter(version -> !version.isUnknown())
.ifPresent(version -> toSlime(version, object.setObject("revision")));
}
private void toSlime(Endpoint endpoint, Cursor object) {
object.setString("cluster", endpoint.cluster().value());
object.setBool("tls", endpoint.tls());
object.setString("url", endpoint.url().toString());
object.setString("scope", endpointScopeString(endpoint.scope()));
object.setString("routingMethod", routingMethodString(endpoint.routingMethod()));
object.setBool("legacy", endpoint.legacy());
}
private void toSlime(Cursor response, DeploymentId deploymentId, Deployment deployment, HttpRequest request) {
response.setString("tenant", deploymentId.applicationId().tenant().value());
response.setString("application", deploymentId.applicationId().application().value());
response.setString("instance", deploymentId.applicationId().instance().value()); // pointless
response.setString("environment", deploymentId.zoneId().environment().value());
response.setString("region", deploymentId.zoneId().region().value());
var application = controller.applications().requireApplication(TenantAndApplicationId.from(deploymentId.applicationId()));
// Add zone endpoints
boolean legacyEndpoints = request.getBooleanProperty("includeLegacyEndpoints");
var endpointArray = response.setArray("endpoints");
EndpointList zoneEndpoints = controller.routing().endpointsOf(deploymentId)
.scope(Endpoint.Scope.zone);
if (!legacyEndpoints) {
zoneEndpoints = zoneEndpoints.not().legacy();
}
for (var endpoint : controller.routing().directEndpoints(zoneEndpoints, deploymentId.applicationId())) {
toSlime(endpoint, endpointArray.addObject());
}
// Add global endpoints
EndpointList globalEndpoints = controller.routing().endpointsOf(application, deploymentId.applicationId().instance())
.targets(deploymentId.zoneId());
if (!legacyEndpoints) {
globalEndpoints = globalEndpoints.not().legacy();
}
for (var endpoint : controller.routing().directEndpoints(globalEndpoints, deploymentId.applicationId())) {
toSlime(endpoint, endpointArray.addObject());
}
response.setString("clusters", withPath(toPath(deploymentId) + "/clusters", request.getUri()).toString());
response.setString("nodes", withPathAndQuery("/zone/v2/" + deploymentId.zoneId().environment() + "/" + deploymentId.zoneId().region() + "/nodes/v2/node/", "recursive=true&application=" + deploymentId.applicationId().tenant() + "." + deploymentId.applicationId().application() + "." + deploymentId.applicationId().instance(), request.getUri()).toString());
response.setString("yamasUrl", monitoringSystemUri(deploymentId).toString());
response.setString("version", deployment.version().toFullString());
response.setString("revision", deployment.applicationVersion().id());
Instant lastDeploymentStart = lastDeploymentStart(deploymentId.applicationId(), deployment);
response.setLong("deployTimeEpochMs", lastDeploymentStart.toEpochMilli());
controller.zoneRegistry().getDeploymentTimeToLive(deploymentId.zoneId())
.ifPresent(deploymentTimeToLive -> response.setLong("expiryTimeEpochMs", lastDeploymentStart.plus(deploymentTimeToLive).toEpochMilli()));
application.projectId().ifPresent(i -> response.setString("screwdriverId", String.valueOf(i)));
sourceRevisionToSlime(deployment.applicationVersion().source(), response);
var instance = application.instances().get(deploymentId.applicationId().instance());
if (instance != null) {
if (!instance.rotations().isEmpty() && deployment.zone().environment() == Environment.prod)
toSlime(instance.rotations(), instance.rotationStatus(), deployment, response);
if (!deployment.zone().environment().isManuallyDeployed()) {
DeploymentStatus status = controller.jobController().deploymentStatus(application);
JobType.from(controller.system(), deployment.zone())
.map(type -> new JobId(instance.id(), type))
.map(status.jobSteps()::get)
.ifPresent(stepStatus -> {
JobControllerApiHandlerHelper.applicationVersionToSlime(
response.setObject("applicationVersion"), deployment.applicationVersion());
if (!status.jobsToRun().containsKey(stepStatus.job().get()))
response.setString("status", "complete");
else if (stepStatus.readyAt(instance.change()).map(controller.clock().instant()::isBefore).orElse(true))
response.setString("status", "pending");
else response.setString("status", "running");
});
} else {
var deploymentRun = JobType.from(controller.system(), deploymentId.zoneId())
.flatMap(jobType -> controller.jobController().last(deploymentId.applicationId(), jobType));
deploymentRun.ifPresent(run -> {
response.setString("status", run.hasEnded() ? "complete" : "running");
});
}
}
response.setDouble("quota", deployment.quota().rate());
deployment.cost().ifPresent(cost -> response.setDouble("cost", cost));
controller.archiveBucketDb().archiveUriFor(deploymentId.zoneId(), deploymentId.applicationId().tenant())
.ifPresent(archiveUri -> response.setString("archiveUri", archiveUri.toString()));
Cursor activity = response.setObject("activity");
deployment.activity().lastQueried().ifPresent(instant -> activity.setLong("lastQueried",
instant.toEpochMilli()));
deployment.activity().lastWritten().ifPresent(instant -> activity.setLong("lastWritten",
instant.toEpochMilli()));
deployment.activity().lastQueriesPerSecond().ifPresent(value -> activity.setDouble("lastQueriesPerSecond", value));
deployment.activity().lastWritesPerSecond().ifPresent(value -> activity.setDouble("lastWritesPerSecond", value));
// Metrics
DeploymentMetrics metrics = deployment.metrics();
Cursor metricsObject = response.setObject("metrics");
metricsObject.setDouble("queriesPerSecond", metrics.queriesPerSecond());
metricsObject.setDouble("writesPerSecond", metrics.writesPerSecond());
metricsObject.setDouble("documentCount", metrics.documentCount());
metricsObject.setDouble("queryLatencyMillis", metrics.queryLatencyMillis());
metricsObject.setDouble("writeLatencyMillis", metrics.writeLatencyMillis());
metrics.instant().ifPresent(instant -> metricsObject.setLong("lastUpdated", instant.toEpochMilli()));
}
private Instant lastDeploymentStart(ApplicationId instanceId, Deployment deployment) {
return controller.jobController().jobStarts(new JobId(instanceId, JobType.from(controller.system(), deployment.zone()).get()))
.stream().findFirst().orElse(deployment.at());
}
private void toSlime(ApplicationVersion applicationVersion, Cursor object) {
if ( ! applicationVersion.isUnknown()) {
object.setLong("buildNumber", applicationVersion.buildNumber().getAsLong());
object.setString("hash", applicationVersion.id());
sourceRevisionToSlime(applicationVersion.source(), object.setObject("source"));
applicationVersion.sourceUrl().ifPresent(url -> object.setString("sourceUrl", url));
applicationVersion.commit().ifPresent(commit -> object.setString("commit", commit));
}
}
private void sourceRevisionToSlime(Optional<SourceRevision> revision, Cursor object) {
if (revision.isEmpty()) return;
object.setString("gitRepository", revision.get().repository());
object.setString("gitBranch", revision.get().branch());
object.setString("gitCommit", revision.get().commit());
}
private void toSlime(RotationState state, Cursor object) {
Cursor bcpStatus = object.setObject("bcpStatus");
bcpStatus.setString("rotationStatus", rotationStateString(state));
}
private void toSlime(List<AssignedRotation> rotations, RotationStatus status, Deployment deployment, Cursor object) {
var array = object.setArray("endpointStatus");
for (var rotation : rotations) {
var statusObject = array.addObject();
var targets = status.of(rotation.rotationId());
statusObject.setString("endpointId", rotation.endpointId().id());
statusObject.setString("rotationId", rotation.rotationId().asString());
statusObject.setString("clusterId", rotation.clusterId().value());
statusObject.setString("status", rotationStateString(status.of(rotation.rotationId(), deployment)));
statusObject.setLong("lastUpdated", targets.lastUpdated().toEpochMilli());
}
}
private URI monitoringSystemUri(DeploymentId deploymentId) {
return controller.zoneRegistry().getMonitoringSystemUri(deploymentId);
}
private Version compileVersion(TenantAndApplicationId id) {
Version oldestPlatform = controller.applications().oldestInstalledPlatform(id);
VersionStatus versionStatus = controller.readVersionStatus();
return versionStatus.versions().stream()
.filter(version -> version.confidence().equalOrHigherThan(VespaVersion.Confidence.low))
.filter(VespaVersion::isReleased)
.map(VespaVersion::versionNumber)
.filter(version -> ! version.isAfter(oldestPlatform))
.max(Comparator.naturalOrder())
.orElseGet(() -> controller.mavenRepository().metadata().versions().stream()
.filter(version -> ! version.isAfter(oldestPlatform))
.filter(version -> ! versionStatus.versions().stream()
.map(VespaVersion::versionNumber)
.collect(Collectors.toSet()).contains(version))
.max(Comparator.naturalOrder())
.orElseThrow(() -> new IllegalStateException("No available releases of " +
controller.mavenRepository().artifactId())));
}
private HttpResponse setGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region, boolean inService, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
ZoneId zone = requireZone(environment, region);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
// The order here matters because setGlobalRotationStatus involves an external request that may fail.
// TODO(mpolden): Set only one of these when only one kind of global endpoints are supported per zone.
var deploymentId = new DeploymentId(instance.id(), zone);
setGlobalRotationStatus(deploymentId, inService, request);
setGlobalEndpointStatus(deploymentId, inService, request);
return new MessageResponse(Text.format("Successfully set %s in %s %s service",
instance.id().toShortString(), zone, inService ? "in" : "out of"));
}
/** Set the global endpoint status for given deployment. This only applies to global endpoints backed by a cloud service */
private void setGlobalEndpointStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
var status = inService ? GlobalRouting.Status.in : GlobalRouting.Status.out;
controller.routing().policies().setGlobalRoutingStatus(deployment, status, agent);
}
/** Set the global rotation status for given deployment. This only applies to global endpoints backed by a rotation */
private void setGlobalRotationStatus(DeploymentId deployment, boolean inService, HttpRequest request) {
var requestData = toSlime(request.getData()).get();
var reason = mandatory("reason", requestData).asString();
var agent = isOperator(request) ? GlobalRouting.Agent.operator : GlobalRouting.Agent.tenant;
long timestamp = controller.clock().instant().getEpochSecond();
var status = inService ? EndpointStatus.Status.in : EndpointStatus.Status.out;
var endpointStatus = new EndpointStatus(status, reason, agent.name(), timestamp);
controller.routing().setGlobalRotationStatus(deployment, endpointStatus);
}
private HttpResponse getGlobalRotationOverride(String tenantName, String applicationName, String instanceName, String environment, String region) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
Slime slime = new Slime();
Cursor array = slime.setObject().setArray("globalrotationoverride");
controller.routing().globalRotationStatus(deploymentId)
.forEach((endpoint, status) -> {
array.addString(endpoint.upstreamIdOf(deploymentId));
Cursor statusObject = array.addObject();
statusObject.setString("status", status.getStatus().name());
statusObject.setString("reason", status.getReason() == null ? "" : status.getReason());
statusObject.setString("agent", status.getAgent() == null ? "" : status.getAgent());
statusObject.setLong("timestamp", status.getEpoch());
});
return new SlimeJsonResponse(slime);
}
private HttpResponse rotationStatus(String tenantName, String applicationName, String instanceName, String environment, String region, Optional<String> endpointId) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
Instance instance = controller.applications().requireInstance(applicationId);
ZoneId zone = requireZone(environment, region);
RotationId rotation = findRotationId(instance, endpointId);
Deployment deployment = instance.deployments().get(zone);
if (deployment == null) {
throw new NotExistsException(instance + " has no deployment in " + zone);
}
Slime slime = new Slime();
Cursor response = slime.setObject();
toSlime(instance.rotationStatus().of(rotation, deployment), response);
return new SlimeJsonResponse(slime);
}
private HttpResponse metering(String tenant, String application, HttpRequest request) {
Slime slime = new Slime();
Cursor root = slime.setObject();
MeteringData meteringData = controller.serviceRegistry()
.meteringService()
.getMeteringData(TenantName.from(tenant), ApplicationName.from(application));
ResourceAllocation currentSnapshot = meteringData.getCurrentSnapshot();
Cursor currentRate = root.setObject("currentrate");
currentRate.setDouble("cpu", currentSnapshot.getCpuCores());
currentRate.setDouble("mem", currentSnapshot.getMemoryGb());
currentRate.setDouble("disk", currentSnapshot.getDiskGb());
ResourceAllocation thisMonth = meteringData.getThisMonth();
Cursor thismonth = root.setObject("thismonth");
thismonth.setDouble("cpu", thisMonth.getCpuCores());
thismonth.setDouble("mem", thisMonth.getMemoryGb());
thismonth.setDouble("disk", thisMonth.getDiskGb());
ResourceAllocation lastMonth = meteringData.getLastMonth();
Cursor lastmonth = root.setObject("lastmonth");
lastmonth.setDouble("cpu", lastMonth.getCpuCores());
lastmonth.setDouble("mem", lastMonth.getMemoryGb());
lastmonth.setDouble("disk", lastMonth.getDiskGb());
Map<ApplicationId, List<ResourceSnapshot>> history = meteringData.getSnapshotHistory();
Cursor details = root.setObject("details");
Cursor detailsCpu = details.setObject("cpu");
Cursor detailsMem = details.setObject("mem");
Cursor detailsDisk = details.setObject("disk");
history.forEach((applicationId, resources) -> {
String instanceName = applicationId.instance().value();
Cursor detailsCpuApp = detailsCpu.setObject(instanceName);
Cursor detailsMemApp = detailsMem.setObject(instanceName);
Cursor detailsDiskApp = detailsDisk.setObject(instanceName);
Cursor detailsCpuData = detailsCpuApp.setArray("data");
Cursor detailsMemData = detailsMemApp.setArray("data");
Cursor detailsDiskData = detailsDiskApp.setArray("data");
resources.forEach(resourceSnapshot -> {
Cursor cpu = detailsCpuData.addObject();
cpu.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
cpu.setDouble("value", resourceSnapshot.getCpuCores());
Cursor mem = detailsMemData.addObject();
mem.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
mem.setDouble("value", resourceSnapshot.getMemoryGb());
Cursor disk = detailsDiskData.addObject();
disk.setLong("unixms", resourceSnapshot.getTimestamp().toEpochMilli());
disk.setDouble("value", resourceSnapshot.getDiskGb());
});
});
return new SlimeJsonResponse(slime);
}
private HttpResponse deploying(String tenantName, String applicationName, String instanceName, HttpRequest request) {
Instance instance = controller.applications().requireInstance(ApplicationId.from(tenantName, applicationName, instanceName));
Slime slime = new Slime();
Cursor root = slime.setObject();
if ( ! instance.change().isEmpty()) {
instance.change().platform().ifPresent(version -> root.setString("platform", version.toString()));
instance.change().application().ifPresent(applicationVersion -> root.setString("application", applicationVersion.id()));
root.setBool("pinned", instance.change().isPinned());
}
return new SlimeJsonResponse(slime);
}
private HttpResponse suspended(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
boolean suspended = controller.applications().isSuspended(deploymentId);
Slime slime = new Slime();
Cursor response = slime.setObject();
response.setBool("suspended", suspended);
return new SlimeJsonResponse(slime);
}
private HttpResponse services(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationView applicationView = controller.getApplicationView(tenantName, applicationName, instanceName, environment, region);
ZoneId zone = requireZone(environment, region);
ServiceApiResponse response = new ServiceApiResponse(zone,
new ApplicationId.Builder().tenant(tenantName).applicationName(applicationName).instanceName(instanceName).build(),
List.of(controller.zoneRegistry().getConfigServerVipUri(zone)),
request.getUri());
response.setResponse(applicationView);
return response;
}
private HttpResponse service(String tenantName, String applicationName, String instanceName, String environment, String region, String serviceName, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
if (restPath.contains("/status/")) {
String[] parts = restPath.split("/status/", 2);
String result = controller.serviceRegistry().configServer().getServiceStatusPage(deploymentId, serviceName, parts[0], parts[1]);
return new HtmlResponse(result);
}
String normalizedRestPath = URI.create(restPath).normalize().toString();
if (allowedServiceViewProxy.value().stream().noneMatch(normalizedRestPath::startsWith)) {
return ErrorResponse.forbidden("Access denied");
}
Map<?,?> result = controller.serviceRegistry().configServer().getServiceApiResponse(deploymentId, serviceName, restPath);
ServiceApiResponse response = new ServiceApiResponse(deploymentId.zoneId(),
deploymentId.applicationId(),
List.of(controller.zoneRegistry().getConfigServerVipUri(deploymentId.zoneId())),
request.getUri());
response.setResponse(result, serviceName, restPath);
return response;
}
private HttpResponse content(String tenantName, String applicationName, String instanceName, String environment, String region, String restPath, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName), requireZone(environment, region));
return controller.serviceRegistry().configServer().getApplicationPackageContent(deploymentId, "/" + restPath, request.getUri());
}
private HttpResponse updateTenant(String tenantName, HttpRequest request) {
getTenantOrThrow(tenantName);
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().update(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createTenant(String tenantName, HttpRequest request) {
TenantName tenant = TenantName.from(tenantName);
Inspector requestObject = toSlime(request.getData()).get();
controller.tenants().create(accessControlRequests.specification(tenant, requestObject),
accessControlRequests.credentials(tenant, requestObject, request.getJDiscRequest()));
return tenant(controller.tenants().require(TenantName.from(tenantName)), request);
}
private HttpResponse createApplication(String tenantName, String applicationName, HttpRequest request) {
Inspector requestObject = toSlime(request.getData()).get();
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), requestObject, request.getJDiscRequest());
Application application = controller.applications().createApplication(id, credentials);
Slime slime = new Slime();
toSlime(id, slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
// TODO jonmv: Remove when clients are updated.
private HttpResponse createInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId applicationId = TenantAndApplicationId.from(tenantName, applicationName);
if (controller.applications().getApplication(applicationId).isEmpty())
createApplication(tenantName, applicationName, request);
controller.applications().createInstance(applicationId.instance(instanceName));
Slime slime = new Slime();
toSlime(applicationId.instance(instanceName), slime.setObject(), request);
return new SlimeJsonResponse(slime);
}
/** Trigger deployment of the given Vespa version if a valid one is given, e.g., "7.8.9". */
private HttpResponse deployPlatform(String tenantName, String applicationName, String instanceName, boolean pin, HttpRequest request) {
String versionString = readToString(request.getData());
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Version version = Version.fromString(versionString);
VersionStatus versionStatus = controller.readVersionStatus();
if (version.equals(Version.emptyVersion))
version = controller.systemVersion(versionStatus);
if (!versionStatus.isActive(version))
throw new IllegalArgumentException("Cannot trigger deployment of version '" + version + "': " +
"Version is not active in this system. " +
"Active versions: " + versionStatus.versions()
.stream()
.map(VespaVersion::versionNumber)
.map(Version::toString)
.collect(joining(", ")));
Change change = Change.of(version);
if (pin)
change = change.withPin();
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Trigger deployment to the last known application package for the given application. */
private HttpResponse deployApplication(String tenantName, String applicationName, String instanceName, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = Change.of(application.get().latestVersion().get());
controller.applications().deploymentTrigger().forceChange(id, change);
response.append("Triggered ").append(change).append(" for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Cancel ongoing change for given application, e.g., everything with {"cancel":"all"} */
private HttpResponse cancelDeploy(String tenantName, String applicationName, String instanceName, String choice) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
StringBuilder response = new StringBuilder();
controller.applications().lockApplicationOrThrow(TenantAndApplicationId.from(id), application -> {
Change change = application.get().require(id.instance()).change();
if (change.isEmpty()) {
response.append("No deployment in progress for ").append(id).append(" at this time");
return;
}
ChangesToCancel cancel = ChangesToCancel.valueOf(choice.toUpperCase());
controller.applications().deploymentTrigger().cancelChange(id, cancel);
response.append("Changed deployment from '").append(change).append("' to '").append(controller.applications().requireInstance(id).change()).append("' for ").append(id);
});
return new MessageResponse(response.toString());
}
/** Schedule reindexing of an application, or a subset of clusters, possibly on a subset of documents. */
private HttpResponse reindex(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
List<String> clusterNames = Optional.ofNullable(request.getProperty("clusterId")).stream()
.flatMap(clusters -> Stream.of(clusters.split(",")))
.filter(cluster -> ! cluster.isBlank())
.collect(toUnmodifiableList());
List<String> documentTypes = Optional.ofNullable(request.getProperty("documentType")).stream()
.flatMap(types -> Stream.of(types.split(",")))
.filter(type -> ! type.isBlank())
.collect(toUnmodifiableList());
controller.applications().reindex(id, zone, clusterNames, documentTypes, request.getBooleanProperty("indexedOnly"));
return new MessageResponse("Requested reindexing of " + id + " in " + zone +
(clusterNames.isEmpty() ? "" : ", on clusters " + String.join(", ", clusterNames) +
(documentTypes.isEmpty() ? "" : ", for types " + String.join(", ", documentTypes))));
}
/** Gets reindexing status of an application in a zone. */
private HttpResponse getReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
ApplicationReindexing reindexing = controller.applications().applicationReindexing(id, zone);
Slime slime = new Slime();
Cursor root = slime.setObject();
root.setBool("enabled", reindexing.enabled());
Cursor clustersArray = root.setArray("clusters");
reindexing.clusters().entrySet().stream().sorted(comparingByKey())
.forEach(cluster -> {
Cursor clusterObject = clustersArray.addObject();
clusterObject.setString("name", cluster.getKey());
Cursor pendingArray = clusterObject.setArray("pending");
cluster.getValue().pending().entrySet().stream().sorted(comparingByKey())
.forEach(pending -> {
Cursor pendingObject = pendingArray.addObject();
pendingObject.setString("type", pending.getKey());
pendingObject.setLong("requiredGeneration", pending.getValue());
});
Cursor readyArray = clusterObject.setArray("ready");
cluster.getValue().ready().entrySet().stream().sorted(comparingByKey())
.forEach(ready -> {
Cursor readyObject = readyArray.addObject();
readyObject.setString("type", ready.getKey());
setStatus(readyObject, ready.getValue());
});
});
return new SlimeJsonResponse(slime);
}
void setStatus(Cursor statusObject, ApplicationReindexing.Status status) {
status.readyAt().ifPresent(readyAt -> statusObject.setLong("readyAtMillis", readyAt.toEpochMilli()));
status.startedAt().ifPresent(startedAt -> statusObject.setLong("startedAtMillis", startedAt.toEpochMilli()));
status.endedAt().ifPresent(endedAt -> statusObject.setLong("endedAtMillis", endedAt.toEpochMilli()));
status.state().map(ApplicationApiHandler::toString).ifPresent(state -> statusObject.setString("state", state));
status.message().ifPresent(message -> statusObject.setString("message", message));
status.progress().ifPresent(progress -> statusObject.setDouble("progress", progress));
}
private static String toString(ApplicationReindexing.State state) {
switch (state) {
case PENDING: return "pending";
case RUNNING: return "running";
case FAILED: return "failed";
case SUCCESSFUL: return "successful";
default: return null;
}
}
/** Enables reindexing of an application in a zone. */
private HttpResponse enableReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
controller.applications().enableReindexing(id, zone);
return new MessageResponse("Enabled reindexing of " + id + " in " + zone);
}
/** Disables reindexing of an application in a zone. */
private HttpResponse disableReindexing(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId id = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
controller.applications().disableReindexing(id, zone);
return new MessageResponse("Disabled reindexing of " + id + " in " + zone);
}
/** Schedule restart of deployment, or specific host in a deployment */
private HttpResponse restart(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
RestartFilter restartFilter = new RestartFilter()
.withHostName(Optional.ofNullable(request.getProperty("hostname")).map(HostName::from))
.withClusterType(Optional.ofNullable(request.getProperty("clusterType")).map(ClusterSpec.Type::from))
.withClusterId(Optional.ofNullable(request.getProperty("clusterId")).map(ClusterSpec.Id::from));
controller.applications().restart(deploymentId, restartFilter);
return new MessageResponse("Requested restart of " + deploymentId);
}
/** Set suspension status of the given deployment. */
private HttpResponse suspend(String tenantName, String applicationName, String instanceName, String environment, String region, boolean suspend) {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
controller.applications().setSuspension(deploymentId, suspend);
return new MessageResponse((suspend ? "Suspended" : "Resumed") + " orchestration of " + deploymentId);
}
private HttpResponse jobDeploy(ApplicationId id, JobType type, HttpRequest request) {
if ( ! type.environment().isManuallyDeployed() && ! isOperator(request))
throw new IllegalArgumentException("Direct deployments are only allowed to manually deployed environments.");
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("applicationZip"))
throw new IllegalArgumentException("Missing required form part 'applicationZip'");
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP));
controller.applications().verifyApplicationIdentityConfiguration(id.tenant(),
Optional.of(id.instance()),
Optional.of(type.zone(controller.system())),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
Optional<Version> version = Optional.ofNullable(dataParts.get("deployOptions"))
.map(json -> SlimeUtils.jsonToSlime(json).get())
.flatMap(options -> optional("vespaVersion", options))
.map(Version::fromString);
controller.jobController().deploy(id, type, version, applicationPackage);
RunId runId = controller.jobController().last(id, type).get().id();
Slime slime = new Slime();
Cursor rootObject = slime.setObject();
rootObject.setString("message", "Deployment started in " + runId +
". This may take about 15 minutes the first time.");
rootObject.setLong("run", runId.number());
return new SlimeJsonResponse(slime);
}
private HttpResponse deploy(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
ApplicationId applicationId = ApplicationId.from(tenantName, applicationName, instanceName);
ZoneId zone = requireZone(environment, region);
// Get deployOptions
Map<String, byte[]> dataParts = parseDataParts(request);
if ( ! dataParts.containsKey("deployOptions"))
return ErrorResponse.badRequest("Missing required form part 'deployOptions'");
Inspector deployOptions = SlimeUtils.jsonToSlime(dataParts.get("deployOptions")).get();
// Resolve system application
Optional<SystemApplication> systemApplication = SystemApplication.matching(applicationId);
if (systemApplication.isEmpty() || !systemApplication.get().hasApplicationPackage()) {
return ErrorResponse.badRequest("Deployment of " + applicationId + " is not supported through this API");
}
// Make it explicit that version is not yet supported here
String vespaVersion = deployOptions.field("vespaVersion").asString();
if (!vespaVersion.isEmpty() && !vespaVersion.equals("null")) {
return ErrorResponse.badRequest("Specifying version for " + applicationId + " is not permitted");
}
// To avoid second guessing the orchestrated upgrades of system applications
// we don't allow to deploy these during an system upgrade (i.e when new vespa is being rolled out)
VersionStatus versionStatus = controller.readVersionStatus();
if (versionStatus.isUpgrading()) {
throw new IllegalArgumentException("Deployment of system applications during a system upgrade is not allowed");
}
Optional<VespaVersion> systemVersion = versionStatus.systemVersion();
if (systemVersion.isEmpty()) {
throw new IllegalArgumentException("Deployment of system applications is not permitted until system version is determined");
}
ActivateResult result = controller.applications()
.deploySystemApplicationPackage(systemApplication.get(), zone, systemVersion.get().versionNumber());
return new SlimeJsonResponse(toSlime(result));
}
private HttpResponse deleteTenant(String tenantName, HttpRequest request) {
boolean forget = request.getBooleanProperty("forget");
if (forget && !isOperator(request))
return ErrorResponse.forbidden("Only operators can forget a tenant");
controller.tenants().delete(TenantName.from(tenantName),
() -> accessControlRequests.credentials(TenantName.from(tenantName),
toSlime(request.getData()).get(),
request.getJDiscRequest()),
forget);
return new MessageResponse("Deleted tenant " + tenantName);
}
private HttpResponse deleteApplication(String tenantName, String applicationName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
return new MessageResponse("Deleted application " + id);
}
private HttpResponse deleteInstance(String tenantName, String applicationName, String instanceName, HttpRequest request) {
TenantAndApplicationId id = TenantAndApplicationId.from(tenantName, applicationName);
controller.applications().deleteInstance(id.instance(instanceName));
if (controller.applications().requireApplication(id).instances().isEmpty()) {
Credentials credentials = accessControlRequests.credentials(id.tenant(), toSlime(request.getData()).get(), request.getJDiscRequest());
controller.applications().deleteApplication(id, credentials);
}
return new MessageResponse("Deleted instance " + id.instance(instanceName).toFullString());
}
private HttpResponse deactivate(String tenantName, String applicationName, String instanceName, String environment, String region, HttpRequest request) {
DeploymentId id = new DeploymentId(ApplicationId.from(tenantName, applicationName, instanceName),
requireZone(environment, region));
// Attempt to deactivate application even if the deployment is not known by the controller
controller.applications().deactivate(id.applicationId(), id.zoneId());
return new MessageResponse("Deactivated " + id);
}
/** Returns test config for indicated job, with production deployments of the default instance. */
private HttpResponse testConfig(ApplicationId id, JobType type) {
// TODO jonmv: Support non-default instances as well; requires API change in clients.
ApplicationId defaultInstanceId = TenantAndApplicationId.from(id).defaultInstance();
HashSet<DeploymentId> deployments = controller.applications()
.getInstance(defaultInstanceId).stream()
.flatMap(instance -> instance.productionDeployments().keySet().stream())
.map(zone -> new DeploymentId(defaultInstanceId, zone))
.collect(Collectors.toCollection(HashSet::new));
var testedZone = type.zone(controller.system());
// If a production job is specified, the production deployment of the _default instance_ is the relevant one,
// as user instances should not exist in prod. TODO jonmv: Remove this when multiple instances are supported (above).
if ( ! type.isProduction())
deployments.add(new DeploymentId(id, testedZone));
return new SlimeJsonResponse(testConfigSerializer.configSlime(id,
type,
false,
controller.routing().zoneEndpointsOf(deployments),
controller.applications().reachableContentClustersByZone(deployments)));
}
private HttpResponse requestServiceDump(String tenant, String application, String instance, String environment,
String region, String hostname, HttpRequest request) {
NodeRepository nodeRepository = controller.serviceRegistry().configServer().nodeRepository();
ZoneId zone = requireZone(environment, region);
// Check that no other service dump is in progress
Slime report = getReport(nodeRepository, zone, tenant, application, instance, hostname).orElse(null);
if (report != null) {
Cursor cursor = report.get();
// Note: same behaviour for both value '0' and missing value.
boolean force = request.getBooleanProperty("force");
if (!force && cursor.field("failedAt").asLong() == 0 && cursor.field("completedAt").asLong() == 0) {
throw new IllegalArgumentException("Service dump already in progress for " + cursor.field("configId").asString());
}
}
Slime requestPayload;
try {
requestPayload = SlimeUtils.jsonToSlimeOrThrow(request.getData().readAllBytes());
} catch (Exception e) {
throw new IllegalArgumentException("Missing or invalid JSON in request content", e);
}
Cursor requestPayloadCursor = requestPayload.get();
String configId = requestPayloadCursor.field("configId").asString();
long expiresAt = requestPayloadCursor.field("expiresAt").asLong();
if (configId.isEmpty()) {
throw new IllegalArgumentException("Missing configId");
}
Cursor artifactsCursor = requestPayloadCursor.field("artifacts");
int artifactEntries = artifactsCursor.entries();
if (artifactEntries == 0) {
throw new IllegalArgumentException("Missing or empty 'artifacts'");
}
Slime dumpRequest = new Slime();
Cursor dumpRequestCursor = dumpRequest.setObject();
dumpRequestCursor.setLong("createdMillis", controller.clock().millis());
dumpRequestCursor.setString("configId", configId);
Cursor dumpRequestArtifactsCursor = dumpRequestCursor.setArray("artifacts");
for (int i = 0; i < artifactEntries; i++) {
dumpRequestArtifactsCursor.addString(artifactsCursor.entry(i).asString());
}
if (expiresAt > 0) {
dumpRequestCursor.setLong("expiresAt", expiresAt);
}
var reportsUpdate = Map.of("serviceDump", new String(uncheck(() -> SlimeUtils.toJsonBytes(dumpRequest))));
nodeRepository.updateReports(zone, hostname, reportsUpdate);
return new MessageResponse("Request created");
}
private HttpResponse getServiceDump(String tenant, String application, String instance, String environment,
String region, String hostname, HttpRequest request) {
NodeRepository nodeRepository = controller.serviceRegistry().configServer().nodeRepository();
ZoneId zone = requireZone(environment, region);
Slime report = getReport(nodeRepository, zone, tenant, application, instance, hostname)
.orElseThrow(() -> new NotExistsException("No service dump for node " + hostname));
return new SlimeJsonResponse(report);
}
private Optional<Slime> getReport(NodeRepository nodeRepository, ZoneId zone, String tenant,
String application, String instance, String hostname) {
Node node;
try {
node = nodeRepository.getNode(zone, hostname);
} catch (IllegalArgumentException e) {
throw new NotExistsException(new Hostname(hostname));
}
ApplicationId app = ApplicationId.from(tenant, application, instance);
ApplicationId owner = node.owner().orElseThrow(() -> new IllegalArgumentException("Node has no owner"));
if (!app.equals(owner)) {
throw new IllegalArgumentException("Node is not owned by " + app.toFullString());
}
String json = node.reports().get("serviceDump");
if (json == null) return Optional.empty();
return Optional.of(SlimeUtils.jsonToSlimeOrThrow(json));
}
private static SourceRevision toSourceRevision(Inspector object) {
if (!object.field("repository").valid() ||
!object.field("branch").valid() ||
!object.field("commit").valid()) {
throw new IllegalArgumentException("Must specify \"repository\", \"branch\", and \"commit\".");
}
return new SourceRevision(object.field("repository").asString(),
object.field("branch").asString(),
object.field("commit").asString());
}
private Tenant getTenantOrThrow(String tenantName) {
return controller.tenants().get(tenantName)
.orElseThrow(() -> new NotExistsException(new TenantId(tenantName)));
}
private void toSlime(Cursor object, Tenant tenant, List<Application> applications, HttpRequest request) {
object.setString("tenant", tenant.name().value());
object.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
object.setString("athensDomain", athenzTenant.domain().getName());
object.setString("property", athenzTenant.property().id());
athenzTenant.propertyId().ifPresent(id -> object.setString("propertyId", id.toString()));
athenzTenant.contact().ifPresent(c -> {
object.setString("propertyUrl", c.propertyUrl().toString());
object.setString("contactsUrl", c.url().toString());
object.setString("issueCreationUrl", c.issueTrackerUrl().toString());
Cursor contactsArray = object.setArray("contacts");
c.persons().forEach(persons -> {
Cursor personArray = contactsArray.addArray();
persons.forEach(personArray::addString);
});
});
break;
case cloud: {
CloudTenant cloudTenant = (CloudTenant) tenant;
cloudTenant.creator().ifPresent(creator -> object.setString("creator", creator.getName()));
Cursor pemDeveloperKeysArray = object.setArray("pemDeveloperKeys");
cloudTenant.developerKeys().forEach((key, user) -> {
Cursor keyObject = pemDeveloperKeysArray.addObject();
keyObject.setString("key", KeyUtils.toPem(key));
keyObject.setString("user", user.getName());
});
// TODO: remove this once console is updated
toSlime(object, cloudTenant.tenantSecretStores());
toSlime(object.setObject("integrations").setObject("aws"),
controller.serviceRegistry().roleService().getTenantRole(tenant.name()),
cloudTenant.tenantSecretStores());
try {
var tenantQuota = controller.serviceRegistry().billingController().getQuota(tenant.name());
var usedQuota = applications.stream()
.map(Application::quotaUsage)
.reduce(QuotaUsage.none, QuotaUsage::add);
toSlime(tenantQuota, usedQuota, object.setObject("quota"));
} catch (Exception e) {
log.warning(String.format("Failed to get quota for tenant %s: %s", tenant.name(), Exceptions.toMessageString(e)));
}
cloudTenant.archiveAccessRole().ifPresent(role -> object.setString("archiveAccessRole", role));
break;
}
case deleted: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
// TODO jonmv: This should list applications, not instances.
Cursor applicationArray = object.setArray("applications");
for (Application application : applications) {
DeploymentStatus status = null;
Collection<Instance> instances = showOnlyProductionInstances(request) ? application.productionInstances().values()
: application.instances().values();
if (instances.isEmpty() && !showOnlyActiveInstances(request))
toSlime(application.id(), applicationArray.addObject(), request);
for (Instance instance : instances) {
if (showOnlyActiveInstances(request) && instance.deployments().isEmpty())
continue;
if (recurseOverApplications(request)) {
if (status == null) status = controller.jobController().deploymentStatus(application);
toSlime(applicationArray.addObject(), instance, status, request);
} else {
toSlime(instance.id(), applicationArray.addObject(), request);
}
}
}
tenantMetaDataToSlime(tenant, applications, object.setObject("metaData"));
}
private void toSlime(Quota quota, QuotaUsage usage, Cursor object) {
quota.budget().ifPresentOrElse(
budget -> object.setDouble("budget", budget.doubleValue()),
() -> object.setNix("budget")
);
object.setDouble("budgetUsed", usage.rate());
// TODO: Retire when we no longer use maxClusterSize as a meaningful limit
quota.maxClusterSize().ifPresent(maxClusterSize -> object.setLong("clusterSize", maxClusterSize));
}
private void toSlime(ClusterResources resources, Cursor object) {
object.setLong("nodes", resources.nodes());
object.setLong("groups", resources.groups());
toSlime(resources.nodeResources(), object.setObject("nodeResources"));
double cost = ResourceMeterMaintainer.cost(resources, controller.serviceRegistry().zoneRegistry().system());
object.setDouble("cost", cost);
}
private void utilizationToSlime(Cluster.Utilization utilization, Cursor utilizationObject) {
utilizationObject.setDouble("cpu", utilization.cpu());
utilizationObject.setDouble("idealCpu", utilization.idealCpu());
utilizationObject.setDouble("currentCpu", utilization.currentCpu());
utilizationObject.setDouble("memory", utilization.memory());
utilizationObject.setDouble("idealMemory", utilization.idealMemory());
utilizationObject.setDouble("currentMemory", utilization.currentMemory());
utilizationObject.setDouble("disk", utilization.disk());
utilizationObject.setDouble("idealDisk", utilization.idealDisk());
utilizationObject.setDouble("currentDisk", utilization.currentDisk());
}
private void scalingEventsToSlime(List<Cluster.ScalingEvent> scalingEvents, Cursor scalingEventsArray) {
for (Cluster.ScalingEvent scalingEvent : scalingEvents) {
Cursor scalingEventObject = scalingEventsArray.addObject();
toSlime(scalingEvent.from(), scalingEventObject.setObject("from"));
toSlime(scalingEvent.to(), scalingEventObject.setObject("to"));
scalingEventObject.setLong("at", scalingEvent.at().toEpochMilli());
scalingEvent.completion().ifPresent(completion -> scalingEventObject.setLong("completion", completion.toEpochMilli()));
}
}
private void toSlime(NodeResources resources, Cursor object) {
object.setDouble("vcpu", resources.vcpu());
object.setDouble("memoryGb", resources.memoryGb());
object.setDouble("diskGb", resources.diskGb());
object.setDouble("bandwidthGbps", resources.bandwidthGbps());
object.setString("diskSpeed", valueOf(resources.diskSpeed()));
object.setString("storageType", valueOf(resources.storageType()));
}
// A tenant has different content when in a list ... antipattern, but not solvable before application/v5
private void tenantInTenantsListToSlime(Tenant tenant, URI requestURI, Cursor object) {
object.setString("tenant", tenant.name().value());
Cursor metaData = object.setObject("metaData");
metaData.setString("type", tenantType(tenant));
switch (tenant.type()) {
case athenz:
AthenzTenant athenzTenant = (AthenzTenant) tenant;
metaData.setString("athensDomain", athenzTenant.domain().getName());
metaData.setString("property", athenzTenant.property().id());
break;
case cloud: break;
case deleted: break;
default: throw new IllegalArgumentException("Unexpected tenant type '" + tenant.type() + "'.");
}
object.setString("url", withPath("/application/v4/tenant/" + tenant.name().value(), requestURI).toString());
}
private void tenantMetaDataToSlime(Tenant tenant, List<Application> applications, Cursor object) {
Optional<Instant> lastDev = applications.stream()
.flatMap(application -> application.instances().values().stream())
.flatMap(instance -> instance.deployments().values().stream()
.filter(deployment -> deployment.zone().environment() == Environment.dev)
.map(deployment -> lastDeploymentStart(instance.id(), deployment)))
.max(Comparator.naturalOrder())
.or(() -> applications.stream()
.flatMap(application -> application.instances().values().stream())
.flatMap(instance -> JobType.allIn(controller.system()).stream()
.filter(job -> job.environment() == Environment.dev)
.flatMap(jobType -> controller.jobController().last(instance.id(), jobType).stream()))
.map(Run::start)
.max(Comparator.naturalOrder()));
Optional<Instant> lastSubmission = applications.stream()
.flatMap(app -> app.latestVersion().flatMap(ApplicationVersion::buildTime).stream())
.max(Comparator.naturalOrder());
object.setLong("createdAtMillis", tenant.createdAt().toEpochMilli());
if (tenant.type() == Tenant.Type.deleted)
object.setLong("deletedAtMillis", ((DeletedTenant) tenant).deletedAt().toEpochMilli());
lastDev.ifPresent(instant -> object.setLong("lastDeploymentToDevMillis", instant.toEpochMilli()));
lastSubmission.ifPresent(instant -> object.setLong("lastSubmissionToProdMillis", instant.toEpochMilli()));
tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.user)
.ifPresent(instant -> object.setLong("lastLoginByUserMillis", instant.toEpochMilli()));
tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.developer)
.ifPresent(instant -> object.setLong("lastLoginByDeveloperMillis", instant.toEpochMilli()));
tenant.lastLoginInfo().get(LastLoginInfo.UserLevel.administrator)
.ifPresent(instant -> object.setLong("lastLoginByAdministratorMillis", instant.toEpochMilli()));
}
/** Returns a copy of the given URI with the host and port from the given URI, the path set to the given path and the query set to given query*/
private URI withPathAndQuery(String newPath, String newQuery, URI uri) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, newQuery, null);
}
catch (URISyntaxException e) {
throw new RuntimeException("Will not happen", e);
}
}
/** Returns a copy of the given URI with the host and port from the given URI and the path set to the given path */
private URI withPath(String newPath, URI uri) {
return withPathAndQuery(newPath, null, uri);
}
private String toPath(DeploymentId id) {
return path("/application", "v4",
"tenant", id.applicationId().tenant(),
"application", id.applicationId().application(),
"instance", id.applicationId().instance(),
"environment", id.zoneId().environment(),
"region", id.zoneId().region());
}
private long asLong(String valueOrNull, long defaultWhenNull) {
if (valueOrNull == null) return defaultWhenNull;
try {
return Long.parseLong(valueOrNull);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected an integer but got '" + valueOrNull + "'");
}
}
private void toSlime(Run run, Cursor object) {
object.setLong("id", run.id().number());
object.setString("version", run.versions().targetPlatform().toFullString());
if ( ! run.versions().targetApplication().isUnknown())
toSlime(run.versions().targetApplication(), object.setObject("revision"));
object.setString("reason", "unknown reason");
object.setLong("at", run.end().orElse(run.start()).toEpochMilli());
}
private Slime toSlime(InputStream jsonStream) {
try {
byte[] jsonBytes = IOUtils.readBytes(jsonStream, 1000 * 1000);
return SlimeUtils.jsonToSlime(jsonBytes);
} catch (IOException e) {
throw new RuntimeException();
}
}
private static Principal requireUserPrincipal(HttpRequest request) {
Principal principal = request.getJDiscRequest().getUserPrincipal();
if (principal == null) throw new InternalServerErrorException("Expected a user principal");
return principal;
}
private Inspector mandatory(String key, Inspector object) {
if ( ! object.field(key).valid())
throw new IllegalArgumentException("'" + key + "' is missing");
return object.field(key);
}
private Optional<String> optional(String key, Inspector object) {
return SlimeUtils.optionalString(object.field(key));
}
private static String path(Object... elements) {
return Joiner.on("/").join(elements);
}
private void toSlime(TenantAndApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value(),
request.getUri()).toString());
}
private void toSlime(ApplicationId id, Cursor object, HttpRequest request) {
object.setString("tenant", id.tenant().value());
object.setString("application", id.application().value());
object.setString("instance", id.instance().value());
object.setString("url", withPath("/application/v4" +
"/tenant/" + id.tenant().value() +
"/application/" + id.application().value() +
"/instance/" + id.instance().value(),
request.getUri()).toString());
}
private Slime toSlime(ActivateResult result) {
Slime slime = new Slime();
Cursor object = slime.setObject();
object.setString("revisionId", result.revisionId().id());
object.setLong("applicationZipSize", result.applicationZipSizeBytes());
Cursor logArray = object.setArray("prepareMessages");
if (result.prepareResponse().log != null) {
for (Log logMessage : result.prepareResponse().log) {
Cursor logObject = logArray.addObject();
logObject.setLong("time", logMessage.time);
logObject.setString("level", logMessage.level);
logObject.setString("message", logMessage.message);
}
}
Cursor changeObject = object.setObject("configChangeActions");
Cursor restartActionsArray = changeObject.setArray("restart");
for (RestartAction restartAction : result.prepareResponse().configChangeActions.restartActions) {
Cursor restartActionObject = restartActionsArray.addObject();
restartActionObject.setString("clusterName", restartAction.clusterName);
restartActionObject.setString("clusterType", restartAction.clusterType);
restartActionObject.setString("serviceType", restartAction.serviceType);
serviceInfosToSlime(restartAction.services, restartActionObject.setArray("services"));
stringsToSlime(restartAction.messages, restartActionObject.setArray("messages"));
}
Cursor refeedActionsArray = changeObject.setArray("refeed");
for (RefeedAction refeedAction : result.prepareResponse().configChangeActions.refeedActions) {
Cursor refeedActionObject = refeedActionsArray.addObject();
refeedActionObject.setString("name", refeedAction.name);
refeedActionObject.setString("documentType", refeedAction.documentType);
refeedActionObject.setString("clusterName", refeedAction.clusterName);
serviceInfosToSlime(refeedAction.services, refeedActionObject.setArray("services"));
stringsToSlime(refeedAction.messages, refeedActionObject.setArray("messages"));
}
return slime;
}
private void serviceInfosToSlime(List<ServiceInfo> serviceInfoList, Cursor array) {
for (ServiceInfo serviceInfo : serviceInfoList) {
Cursor serviceInfoObject = array.addObject();
serviceInfoObject.setString("serviceName", serviceInfo.serviceName);
serviceInfoObject.setString("serviceType", serviceInfo.serviceType);
serviceInfoObject.setString("configId", serviceInfo.configId);
serviceInfoObject.setString("hostName", serviceInfo.hostName);
}
}
private void stringsToSlime(List<String> strings, Cursor array) {
for (String string : strings)
array.addString(string);
}
private void toSlime(Cursor object, List<TenantSecretStore> tenantSecretStores) {
Cursor secretStore = object.setArray("secretStores");
tenantSecretStores.forEach(store -> {
toSlime(secretStore.addObject(), store);
});
}
private void toSlime(Cursor object, TenantRoles tenantRoles, List<TenantSecretStore> tenantSecretStores) {
object.setString("tenantRole", tenantRoles.containerRole());
var stores = object.setArray("accounts");
tenantSecretStores.forEach(secretStore -> {
toSlime(stores.addObject(), secretStore);
});
}
private void toSlime(Cursor object, TenantSecretStore secretStore) {
object.setString("name", secretStore.getName());
object.setString("awsId", secretStore.getAwsId());
object.setString("role", secretStore.getRole());
}
private String readToString(InputStream stream) {
Scanner scanner = new Scanner(stream).useDelimiter("\\A");
if ( ! scanner.hasNext()) return null;
return scanner.next();
}
private static boolean recurseOverTenants(HttpRequest request) {
return recurseOverApplications(request) || "tenant".equals(request.getProperty("recursive"));
}
private static boolean recurseOverApplications(HttpRequest request) {
return recurseOverDeployments(request) || "application".equals(request.getProperty("recursive"));
}
private static boolean recurseOverDeployments(HttpRequest request) {
return ImmutableSet.of("all", "true", "deployment").contains(request.getProperty("recursive"));
}
private static boolean showOnlyProductionInstances(HttpRequest request) {
return "true".equals(request.getProperty("production"));
}
private static boolean showOnlyActiveInstances(HttpRequest request) {
return "true".equals(request.getProperty("activeInstances"));
}
private static boolean includeDeleted(HttpRequest request) {
return "true".equals(request.getProperty("includeDeleted"));
}
private static String tenantType(Tenant tenant) {
switch (tenant.type()) {
case athenz: return "ATHENS";
case cloud: return "CLOUD";
case deleted: return "DELETED";
default: throw new IllegalArgumentException("Unknown tenant type: " + tenant.getClass().getSimpleName());
}
}
private static ApplicationId appIdFromPath(Path path) {
return ApplicationId.from(path.get("tenant"), path.get("application"), path.get("instance"));
}
private static JobType jobTypeFromPath(Path path) {
return JobType.fromJobName(path.get("jobtype"));
}
private static RunId runIdFromPath(Path path) {
long number = Long.parseLong(path.get("number"));
return new RunId(appIdFromPath(path), jobTypeFromPath(path), number);
}
private HttpResponse submit(String tenant, String application, HttpRequest request) {
Map<String, byte[]> dataParts = parseDataParts(request);
Inspector submitOptions = SlimeUtils.jsonToSlime(dataParts.get(EnvironmentResource.SUBMIT_OPTIONS)).get();
long projectId = Math.max(1, submitOptions.field("projectId").asLong()); // Absence of this means it's not a prod app :/
Optional<String> repository = optional("repository", submitOptions);
Optional<String> branch = optional("branch", submitOptions);
Optional<String> commit = optional("commit", submitOptions);
Optional<SourceRevision> sourceRevision = repository.isPresent() && branch.isPresent() && commit.isPresent()
? Optional.of(new SourceRevision(repository.get(), branch.get(), commit.get()))
: Optional.empty();
Optional<String> sourceUrl = optional("sourceUrl", submitOptions);
Optional<String> authorEmail = optional("authorEmail", submitOptions);
sourceUrl.map(URI::create).ifPresent(url -> {
if (url.getHost() == null || url.getScheme() == null)
throw new IllegalArgumentException("Source URL must include scheme and host");
});
ApplicationPackage applicationPackage = new ApplicationPackage(dataParts.get(EnvironmentResource.APPLICATION_ZIP), true);
controller.applications().verifyApplicationIdentityConfiguration(TenantName.from(tenant),
Optional.empty(),
Optional.empty(),
applicationPackage,
Optional.of(requireUserPrincipal(request)));
return JobControllerApiHandlerHelper.submitResponse(controller.jobController(),
tenant,
application,
sourceRevision,
authorEmail,
sourceUrl,
projectId,
applicationPackage,
dataParts.get(EnvironmentResource.APPLICATION_TEST_ZIP));
}
private HttpResponse removeAllProdDeployments(String tenant, String application) {
JobControllerApiHandlerHelper.submitResponse(controller.jobController(), tenant, application,
Optional.empty(), Optional.empty(), Optional.empty(), 1,
ApplicationPackage.deploymentRemoval(), new byte[0]);
return new MessageResponse("All deployments removed");
}
private ZoneId requireZone(String environment, String region) {
ZoneId zone = ZoneId.from(environment, region);
// TODO(mpolden): Find a way to not hardcode this. Some APIs allow this "virtual" zone, e.g. /logs
if (zone.environment() == Environment.prod && zone.region().value().equals("controller")) {
return zone;
}
if (!controller.zoneRegistry().hasZone(zone)) {
throw new IllegalArgumentException("Zone " + zone + " does not exist in this system");
}
return zone;
}
private static Map<String, byte[]> parseDataParts(HttpRequest request) {
String contentHash = request.getHeader("X-Content-Hash");
if (contentHash == null)
return new MultipartParser().parse(request);
DigestInputStream digester = Signatures.sha256Digester(request.getData());
var dataParts = new MultipartParser().parse(request.getHeader("Content-Type"), digester, request.getUri());
if ( ! Arrays.equals(digester.getMessageDigest().digest(), Base64.getDecoder().decode(contentHash)))
throw new IllegalArgumentException("Value of X-Content-Hash header does not match computed content hash");
return dataParts;
}
private static RotationId findRotationId(Instance instance, Optional<String> endpointId) {
if (instance.rotations().isEmpty()) {
throw new NotExistsException("global rotation does not exist for " + instance);
}
if (endpointId.isPresent()) {
return instance.rotations().stream()
.filter(r -> r.endpointId().id().equals(endpointId.get()))
.map(AssignedRotation::rotationId)
.findFirst()
.orElseThrow(() -> new NotExistsException("endpoint " + endpointId.get() +
" does not exist for " + instance));
} else if (instance.rotations().size() > 1) {
throw new IllegalArgumentException(instance + " has multiple rotations. Query parameter 'endpointId' must be given");
}
return instance.rotations().get(0).rotationId();
}
private static String rotationStateString(RotationState state) {
switch (state) {
case in: return "IN";
case out: return "OUT";
}
return "UNKNOWN";
}
private static String endpointScopeString(Endpoint.Scope scope) {
switch (scope) {
case region: return "region";
case global: return "global";
case zone: return "zone";
}
throw new IllegalArgumentException("Unknown endpoint scope " + scope);
}
private static String routingMethodString(RoutingMethod method) {
switch (method) {
case exclusive: return "exclusive";
case shared: return "shared";
case sharedLayer4: return "sharedLayer4";
}
throw new IllegalArgumentException("Unknown routing method " + method);
}
private static <T> T getAttribute(HttpRequest request, String attributeName, Class<T> cls) {
return Optional.ofNullable(request.getJDiscRequest().context().get(attributeName))
.filter(cls::isInstance)
.map(cls::cast)
.orElseThrow(() -> new IllegalArgumentException("Attribute '" + attributeName + "' was not set on request"));
}
/** Returns whether given request is by an operator */
private static boolean isOperator(HttpRequest request) {
var securityContext = getAttribute(request, SecurityContext.ATTRIBUTE_NAME, SecurityContext.class);
return securityContext.roles().stream()
.map(Role::definition)
.anyMatch(definition -> definition == RoleDefinition.hostedOperator);
}
} |
package io.debezium.connector.mongodb.transforms;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import io.debezium.data.Envelope;
import io.debezium.transforms.UnwrapFromEnvelope.DeleteHandling;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.connect.connector.ConnectRecord;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.transforms.ExtractField;
import org.apache.kafka.connect.transforms.Flatten;
import org.apache.kafka.connect.transforms.Transformation;
import org.bson.BsonBoolean;
import org.bson.BsonDocument;
import org.bson.BsonNull;
import org.bson.BsonValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.config.Configuration;
import io.debezium.config.EnumeratedValue;
import io.debezium.config.Field;
/**
* Debezium Mongo Connector generates the CDC records in String format. Sink connectors usually are not able to parse
* the string and insert the document as it is represented in the Source. so a user use this SMT to parse the String
* and insert the MongoDB document in the JSON format.
*
* @param <R> the subtype of {@link ConnectRecord} on which this transformation will operate
* @author Sairam Polavarapu
* @author Renato mefi
*/
public class UnwrapFromMongoDbEnvelope<R extends ConnectRecord<R>> implements Transformation<R> {
public enum ArrayEncoding implements EnumeratedValue {
ARRAY("array"),
DOCUMENT("document");
private final String value;
ArrayEncoding(String value) {
this.value = value;
}
@Override
public String getValue() {
return value;
}
/**
* Determine if the supplied value is one of the predefined options.
*
* @param value the configuration property value; may not be null
* @return the matching option, or null if no match is found
*/
public static ArrayEncoding parse(String value) {
if (value == null) return null;
value = value.trim();
for (ArrayEncoding option : ArrayEncoding.values()) {
if (option.getValue().equalsIgnoreCase(value)) return option;
}
return null;
}
/**
* Determine if the supplied value is one of the predefined options.
*
* @param value the configuration property value; may not be null
* @param defaultValue the default value; may be null
* @return the matching option, or null if no match is found and the non-null default is invalid
*/
public static ArrayEncoding parse(String value, String defaultValue) {
ArrayEncoding mode = parse(value);
if (mode == null && defaultValue != null) mode = parse(defaultValue);
return mode;
}
}
final static String DEBEZIUM_OPERATION_HEADER_KEY = "__debezium-operation";
private static final String DELETED_FIELD = "__deleted";
private static final Logger LOGGER = LoggerFactory.getLogger(UnwrapFromMongoDbEnvelope.class);
private static final Field ARRAY_ENCODING = Field.create("array.encoding")
.withDisplayName("Array encoding")
.withEnum(ArrayEncoding.class, ArrayEncoding.ARRAY)
.withWidth(ConfigDef.Width.SHORT)
.withImportance(ConfigDef.Importance.MEDIUM)
.withDescription("The arrays can be encoded using 'array' schema type (the default) or as a 'document' (similar to how BSON encodes arrays). "
+ "'array' is easier to consume but requires all elements in the array to be of the same type. "
+ "Use 'document' if the arrays in data source mix different types together.");
private static final Field FLATTEN_STRUCT = Field.create("flatten.struct")
.withDisplayName("Flatten struct")
.withType(ConfigDef.Type.BOOLEAN)
.withWidth(ConfigDef.Width.SHORT)
.withImportance(ConfigDef.Importance.LOW)
.withDefault(false)
.withDescription("Flattening structs by concatenating the fields into plain properties, using a "
+ "(configurable) delimiter.");
private static final Field DELIMITER = Field.create("flatten.struct.delimiter")
.withDisplayName("Delimiter for flattened struct")
.withType(ConfigDef.Type.STRING)
.withWidth(ConfigDef.Width.SHORT)
.withImportance(ConfigDef.Importance.LOW)
.withDefault("_")
.withDescription("Delimiter to concat between field names from the input record when generating field names for the"
+ "output record.");
private static final Field OPERATION_HEADER = Field.create("operation.header")
.withDisplayName("Adds a message header representing the applied operation")
.withType(ConfigDef.Type.BOOLEAN)
.withWidth(ConfigDef.Width.SHORT)
.withImportance(ConfigDef.Importance.LOW)
.withDefault(false)
.withDescription("Adds the operation {@link FieldName#OPERATION operation} as a header." +
"Its key is '" + DEBEZIUM_OPERATION_HEADER_KEY + "'");
private static final Field HANDLE_DELETES = Field.create("delete.handling.mode")
.withDisplayName("Handle delete records")
.withEnum(DeleteHandling.class, DeleteHandling.DROP)
.withWidth(ConfigDef.Width.MEDIUM)
.withImportance(ConfigDef.Importance.MEDIUM)
.withDescription("How to handle delete records. Options are: "
+ "none - records are passed,"
+ "drop - records are removed,"
+ "rewrite - __deleted field is added to records.");
private static final Field DROP_TOMBSTONES = Field.create("drop.tombstones")
.withDisplayName("Drop tombstones")
.withType(ConfigDef.Type.BOOLEAN)
.withWidth(ConfigDef.Width.SHORT)
.withImportance(ConfigDef.Importance.LOW)
.withDefault(true)
.withDescription("Debezium by default generates a tombstone record to enable Kafka compaction after "
+ "a delete record was generated. This record is usually filtered out to avoid duplicates "
+ "as a delete record is converted to a tombstone record, too");
private final ExtractField<R> afterExtractor = new ExtractField.Value<>();
private final ExtractField<R> patchExtractor = new ExtractField.Value<>();
private final ExtractField<R> keyExtractor = new ExtractField.Key<>();
private MongoDataConverter converter;
private final Flatten<R> recordFlattener = new Flatten.Value<>();
private boolean addOperationHeader;
private boolean flattenStruct;
private String delimiter;
private boolean dropTombstones;
private DeleteHandling handleDeletes;
@Override
public R apply(R record) {
final R afterRecord = afterExtractor.apply(record);
final R patchRecord = patchExtractor.apply(record);
final R keyRecord = keyExtractor.apply(record);
BsonDocument keyDocument = BsonDocument.parse("{ \"id\" : " + keyRecord.key().toString() + "}");
BsonDocument valueDocument = new BsonDocument();
// Tombstone message
if (record.value() == null) {
if (dropTombstones) {
LOGGER.trace("Tombstone {} arrived and requested to be dropped", record.key());
return null;
}
if (addOperationHeader) {
record.headers().addString(DEBEZIUM_OPERATION_HEADER_KEY, Envelope.Operation.DELETE.code());
}
return newRecord(record, keyDocument, valueDocument);
}
if (addOperationHeader) {
record.headers().addString(DEBEZIUM_OPERATION_HEADER_KEY, ((Struct) record.value()).get("op").toString());
}
// insert
if (afterRecord.value() != null) {
valueDocument = getInsertDocument(afterRecord, keyDocument);
}
// update
if (afterRecord.value() == null && patchRecord.value() != null) {
valueDocument = getUpdateDocument(patchRecord, keyDocument);
}
boolean isDeletion = false;
// delete
if (afterRecord.value() == null && patchRecord.value() == null) {
if (handleDeletes.equals(DeleteHandling.DROP)) {
LOGGER.trace("Delete {} arrived and requested to be dropped", record.key());
return null;
}
isDeletion = true;
}
if (handleDeletes.equals(DeleteHandling.REWRITE)) {
valueDocument.append(DELETED_FIELD, new BsonBoolean(isDeletion));
}
return newRecord(record, keyDocument, valueDocument);
}
private R newRecord(R record, BsonDocument keyDocument, BsonDocument valueDocument) {
SchemaBuilder keySchemaBuilder = SchemaBuilder.struct();
Set<Entry<String, BsonValue>> keyPairs = keyDocument.entrySet();
for (Entry<String, BsonValue> keyPairsForSchema : keyPairs) {
converter.addFieldSchema(keyPairsForSchema, keySchemaBuilder);
}
Schema finalKeySchema = keySchemaBuilder.build();
Struct finalKeyStruct = new Struct(finalKeySchema);
for (Entry<String, BsonValue> keyPairsForStruct : keyPairs) {
converter.convertRecord(keyPairsForStruct, finalKeySchema, finalKeyStruct);
}
Schema finalValueSchema = null;
Struct finalValueStruct = null;
if (valueDocument.size() > 0) {
String newValueSchemaName = record.valueSchema().name();
if (newValueSchemaName.endsWith(".Envelope")) {
newValueSchemaName = newValueSchemaName.substring(0, newValueSchemaName.length() - 9);
}
SchemaBuilder valueSchemaBuilder = SchemaBuilder.struct().name(newValueSchemaName);
Set<Entry<String, BsonValue>> valuePairs = valueDocument.entrySet();
for (Entry<String, BsonValue> valuePairsForSchema : valuePairs) {
if (valuePairsForSchema.getKey().equalsIgnoreCase("$set")) {
BsonDocument val1 = BsonDocument.parse(valuePairsForSchema.getValue().toString());
Set<Entry<String, BsonValue>> keyValuesForSetSchema = val1.entrySet();
for (Entry<String, BsonValue> keyValuesForSetSchemaEntry : keyValuesForSetSchema) {
converter.addFieldSchema(keyValuesForSetSchemaEntry, valueSchemaBuilder);
}
} else {
converter.addFieldSchema(valuePairsForSchema, valueSchemaBuilder);
}
}
finalValueSchema = valueSchemaBuilder.build();
finalValueStruct = new Struct(finalValueSchema);
for (Entry<String, BsonValue> valuePairsForStruct : valuePairs) {
if (valuePairsForStruct.getKey().equalsIgnoreCase("$set")) {
BsonDocument val1 = BsonDocument.parse(valuePairsForStruct.getValue().toString());
Set<Entry<String, BsonValue>> keyValueForSetStruct = val1.entrySet();
for (Entry<String, BsonValue> keyValueForSetStructEntry : keyValueForSetStruct) {
converter.convertRecord(keyValueForSetStructEntry, finalValueSchema, finalValueStruct);
}
} else {
converter.convertRecord(valuePairsForStruct, finalValueSchema, finalValueStruct);
}
}
}
R newRecord = record.newRecord(record.topic(), record.kafkaPartition(), finalKeySchema,
finalKeyStruct, finalValueSchema, finalValueStruct, record.timestamp());
if (flattenStruct) {
return recordFlattener.apply(newRecord);
}
return newRecord;
}
private BsonDocument getUpdateDocument(R patchRecord, BsonDocument keyDocument) {
BsonDocument valueDocument = new BsonDocument();
BsonDocument document = BsonDocument.parse(patchRecord.value().toString());
if (document.containsKey("$set")) {
valueDocument = document.getDocument("$set");
}
if (document.containsKey("$unset")) {
Set<Entry<String, BsonValue>> unsetDocumentEntry = document.getDocument("$unset").entrySet();
for (Entry<String, BsonValue> valueEntry : unsetDocumentEntry) {
// In case unset of a key is false we don't have to do anything with it,
// if it's true we want to set the value to null
if (!valueEntry.getValue().asBoolean().getValue()) {
continue;
}
valueDocument.append(valueEntry.getKey(), new BsonNull());
}
}
if (!document.containsKey("$set") && !document.containsKey("$unset")) {
if (!document.containsKey("_id")) {
throw new ConnectException("Unable to process Mongo Operation, a '$set' or '$unset' is necessary " +
"for partial updates or '_id' is expected for full Document replaces.");
}
// In case of a full update we can use the whole Document as it is
// see https://docs.mongodb.com/manual/reference/method/db.collection.update/#replace-a-document-entirely
valueDocument = document;
valueDocument.remove("_id");
}
if (!valueDocument.containsKey("id")) {
valueDocument.append("id", keyDocument.get("id"));
}
if (flattenStruct) {
final BsonDocument newDocument = new BsonDocument();
valueDocument.forEach((fKey, fValue) -> newDocument.put(fKey.replace(".", delimiter), fValue));
valueDocument = newDocument;
}
return valueDocument;
}
private BsonDocument getInsertDocument(R record, BsonDocument key) {
BsonDocument valueDocument = BsonDocument.parse(record.value().toString());
valueDocument.remove("_id");
valueDocument.append("id", key.get("id"));
return valueDocument;
}
@Override
public ConfigDef config() {
final ConfigDef config = new ConfigDef();
Field.group(config, null, ARRAY_ENCODING);
return config;
}
@Override
public void close() {
}
@Override
public void configure(final Map<String, ?> map) {
final Configuration config = Configuration.from(map);
final Field.Set configFields = Field.setOf(ARRAY_ENCODING, FLATTEN_STRUCT, DELIMITER, OPERATION_HEADER, HANDLE_DELETES, DROP_TOMBSTONES);
if (!config.validateAndRecord(configFields, LOGGER::error)) {
throw new ConnectException("Unable to validate config.");
}
converter = new MongoDataConverter(ArrayEncoding.parse(config.getString(ARRAY_ENCODING)));
addOperationHeader = config.getBoolean(OPERATION_HEADER);
flattenStruct = config.getBoolean(FLATTEN_STRUCT);
delimiter = config.getString(DELIMITER);
dropTombstones = config.getBoolean(DROP_TOMBSTONES);
handleDeletes = DeleteHandling.parse(config.getString(HANDLE_DELETES));
final Map<String, String> afterExtractorConfig = new HashMap<>();
afterExtractorConfig.put("field", "after");
final Map<String, String> patchExtractorConfig = new HashMap<>();
patchExtractorConfig.put("field", "patch");
final Map<String, String> keyExtractorConfig = new HashMap<>();
keyExtractorConfig.put("field", "id");
afterExtractor.configure(afterExtractorConfig);
patchExtractor.configure(patchExtractorConfig);
keyExtractor.configure(keyExtractorConfig);
final Map<String, String> delegateConfig = new HashMap<>();
delegateConfig.put("delimiter", delimiter);
recordFlattener.configure(delegateConfig);
}
} |
package nl.jqno.equalsverifier.integration.extended_contract;
import java.util.Map;
import java.util.Objects;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException;
import org.junit.jupiter.api.Test;
class MapEntrySubclassTest {
@Test
void fails_whenMapEntryHashCodeContractIsNotHonored() {
ExpectedException
.when(() -> EqualsVerifier.forClass(HashCodeContractNotHonored.class).verify())
.assertFailure()
.assertMessageContains("hashCode: value does not follow Map.Entry specification");
}
@Test
void succeeds_whenMapEntryHashCodeContractIsHonored() {
EqualsVerifier.forClass(HashCodeContractHonored.class).verify();
}
static final class HashCodeContractNotHonored<K, V> implements Map.Entry<K, V> {
private final K key;
private final V value;
HashCodeContractNotHonored(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
return Objects.equals(key, other.getKey()) && Objects.equals(value, other.getValue());
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
// CHECKSTYLE OFF: HiddenField
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
// CHECKSTYLE ON: HiddenField
}
static final class HashCodeContractHonored<K, V> implements Map.Entry<K, V> {
private final K key;
private final V value;
HashCodeContractHonored(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
return Objects.equals(key, other.getKey()) && Objects.equals(value, other.getValue());
}
@Override
public int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
// CHECKSTYLE OFF: HiddenField
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
// CHECKSTYLE ON: HiddenField
}
} |
package io.lumify.foodTruck;
import io.lumify.core.ingest.graphProperty.GraphPropertyWorkData;
import io.lumify.core.ingest.graphProperty.GraphPropertyWorker;
import io.lumify.core.model.properties.LumifyProperties;
import org.securegraph.*;
import java.io.InputStream;
public class FoodTruckHasTwitterAccountOnCreateGraphPropertyWorker extends GraphPropertyWorker {
private static final String MULTI_VALUE_KEY = FoodTruckHasTwitterAccountOnCreateGraphPropertyWorker.class.getName();
@Override
public void execute(InputStream in, GraphPropertyWorkData data) throws Exception {
Edge hasTwitterUserEdge = (Edge) data.getElement();
Vertex foodTruckVertex = hasTwitterUserEdge.getVertex(Direction.OUT, getAuthorizations());
Vertex twitterUserVertex = hasTwitterUserEdge.getVertex(Direction.IN, getAuthorizations());
String imageVertexId = LumifyProperties.ENTITY_IMAGE_VERTEX_ID.getPropertyValue(twitterUserVertex);
if (imageVertexId != null && imageVertexId.length() > 0) {
LumifyProperties.ENTITY_IMAGE_VERTEX_ID.addPropertyValue(foodTruckVertex, MULTI_VALUE_KEY, imageVertexId, new Visibility(data.getVisibilitySource()), getAuthorizations());
getGraph().flush();
getWorkQueueRepository().pushGraphPropertyQueue(foodTruckVertex, MULTI_VALUE_KEY, LumifyProperties.ENTITY_IMAGE_VERTEX_ID.getPropertyName());
}
}
@Override
public boolean isHandled(Element element, Property property) {
if (!(element instanceof Edge)) {
return false;
}
Edge edge = (Edge) element;
if (!edge.getLabel().equals(FoodTruckOntology.EDGE_LABEL_HAS_TWITTER_USER)) {
return false;
}
return true;
}
} |
package ca.uhn.fhir.jpa.provider.r4;
import ca.uhn.fhir.jpa.api.config.DaoConfig;
import ca.uhn.fhir.jpa.config.BaseConfig;
import ca.uhn.fhir.jpa.config.TestR4Config;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.PreferReturnEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.client.interceptor.CapturingInterceptor;
import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;
import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
import ca.uhn.fhir.rest.server.interceptor.consent.ConsentInterceptor;
import ca.uhn.fhir.rest.server.interceptor.consent.ConsentOperationStatusEnum;
import ca.uhn.fhir.rest.server.interceptor.consent.ConsentOutcome;
import ca.uhn.fhir.rest.server.interceptor.consent.DelegatingConsentService;
import ca.uhn.fhir.rest.server.interceptor.consent.IConsentContextServices;
import ca.uhn.fhir.rest.server.interceptor.consent.IConsentService;
import ca.uhn.fhir.util.BundleUtil;
import ca.uhn.fhir.util.UrlUtil;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.Validate;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.IdType;
import org.hl7.fhir.r4.model.Observation;
import org.hl7.fhir.r4.model.OperationOutcome;
import org.hl7.fhir.r4.model.Organization;
import org.hl7.fhir.r4.model.Patient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.leftPad;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.blankOrNullString;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {TestR4Config.class})
public class ConsentInterceptorResourceProviderR4Test extends BaseResourceProviderR4Test {
private static final Logger ourLog = LoggerFactory.getLogger(ConsentInterceptorResourceProviderR4Test.class);
private List<String> myObservationIds;
private List<String> myPatientIds;
private List<String> myObservationIdsOddOnly;
private List<String> myObservationIdsEvenOnly;
private List<String> myObservationIdsEvenOnlyBackwards;
private ConsentInterceptor myConsentInterceptor;
@Autowired
@Qualifier(BaseConfig.GRAPHQL_PROVIDER_NAME)
private Object myGraphQlProvider;
@Override
@AfterEach
public void after() throws Exception {
super.after();
Validate.notNull(myConsentInterceptor);
myDaoConfig.setSearchPreFetchThresholds(new DaoConfig().getSearchPreFetchThresholds());
ourRestServer.getInterceptorService().unregisterInterceptor(myConsentInterceptor);
ourRestServer.unregisterProvider(myGraphQlProvider);
}
@Override
@BeforeEach
public void before() throws Exception {
super.before();
myDaoConfig.setSearchPreFetchThresholds(Arrays.asList(20, 50, 190));
ourRestServer.registerProvider(myGraphQlProvider);
}
@Test
public void testSearchAndBlockSomeWithReject() {
create50Observations();
IConsentService consentService = new ConsentSvcCantSeeOddNumbered();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
// Perform a search
Bundle result = myClient
.search()
.forResource("Observation")
.sort()
.ascending(Observation.SP_IDENTIFIER)
.returnBundle(Bundle.class)
.count(15)
.execute();
List<IBaseResource> resources = BundleUtil.toListOfResources(myFhirCtx, result);
List<String> returnedIdValues = toUnqualifiedVersionlessIdValues(resources);
assertEquals(myObservationIdsEvenOnly.subList(0, 15), returnedIdValues);
// Fetch the next page
result = myClient
.loadPage()
.next(result)
.execute();
resources = BundleUtil.toListOfResources(myFhirCtx, result);
returnedIdValues = toUnqualifiedVersionlessIdValues(resources);
assertEquals(myObservationIdsEvenOnly.subList(15, 25), returnedIdValues);
}
/**
* Make sure that the query cache doesn't get used at all if the consent
* service wants to inspect a request
*/
@Test
public void testSearchAndBlockSome_DontReuseSearches() {
create50Observations();
CapturingInterceptor capture = new CapturingInterceptor();
myClient.registerInterceptor(capture);
DelegatingConsentService consentService = new DelegatingConsentService();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
// Perform a search and only allow even
consentService.setTarget(new ConsentSvcCantSeeOddNumbered());
Bundle result = myClient
.search()
.forResource("Observation")
.sort()
.ascending(Observation.SP_IDENTIFIER)
.returnBundle(Bundle.class)
.count(15)
.execute();
List<IBaseResource> resources = BundleUtil.toListOfResources(myFhirCtx, result);
List<String> returnedIdValues = toUnqualifiedVersionlessIdValues(resources);
assertEquals(myObservationIdsEvenOnly.subList(0, 15), returnedIdValues);
List<String> cacheOutcome = capture.getLastResponse().getHeaders(Constants.HEADER_X_CACHE);
assertEquals(0, cacheOutcome.size());
// Perform a search and only allow odd
consentService.setTarget(new ConsentSvcCantSeeEvenNumbered());
result = myClient
.search()
.forResource("Observation")
.sort()
.ascending(Observation.SP_IDENTIFIER)
.returnBundle(Bundle.class)
.count(15)
.execute();
resources = BundleUtil.toListOfResources(myFhirCtx, result);
returnedIdValues = toUnqualifiedVersionlessIdValues(resources);
assertEquals(myObservationIdsOddOnly.subList(0, 15), returnedIdValues);
cacheOutcome = capture.getLastResponse().getHeaders(Constants.HEADER_X_CACHE);
assertEquals(0, cacheOutcome.size());
// Perform a search and allow all with a PROCEED
consentService.setTarget(new ConsentSvcNop(ConsentOperationStatusEnum.PROCEED));
result = myClient
.search()
.forResource("Observation")
.sort()
.ascending(Observation.SP_IDENTIFIER)
.returnBundle(Bundle.class)
.count(15)
.execute();
resources = BundleUtil.toListOfResources(myFhirCtx, result);
returnedIdValues = toUnqualifiedVersionlessIdValues(resources);
assertEquals(myObservationIds.subList(0, 15), returnedIdValues);
cacheOutcome = capture.getLastResponse().getHeaders(Constants.HEADER_X_CACHE);
assertEquals(0, cacheOutcome.size());
// Perform a search and allow all with an AUTHORIZED (no further checking)
consentService.setTarget(new ConsentSvcNop(ConsentOperationStatusEnum.AUTHORIZED));
result = myClient
.search()
.forResource("Observation")
.sort()
.ascending(Observation.SP_IDENTIFIER)
.returnBundle(Bundle.class)
.count(15)
.execute();
resources = BundleUtil.toListOfResources(myFhirCtx, result);
returnedIdValues = toUnqualifiedVersionlessIdValues(resources);
assertEquals(myObservationIds.subList(0, 15), returnedIdValues);
cacheOutcome = capture.getLastResponse().getHeaders(Constants.HEADER_X_CACHE);
assertEquals(0, cacheOutcome.size());
// Perform a second search and allow all with an AUTHORIZED (no further checking)
// which means we should finally get one from the cache
consentService.setTarget(new ConsentSvcNop(ConsentOperationStatusEnum.AUTHORIZED));
result = myClient
.search()
.forResource("Observation")
.sort()
.ascending(Observation.SP_IDENTIFIER)
.returnBundle(Bundle.class)
.count(15)
.execute();
resources = BundleUtil.toListOfResources(myFhirCtx, result);
returnedIdValues = toUnqualifiedVersionlessIdValues(resources);
assertEquals(myObservationIds.subList(0, 15), returnedIdValues);
cacheOutcome = capture.getLastResponse().getHeaders(Constants.HEADER_X_CACHE);
assertThat(cacheOutcome.get(0), matchesPattern("^HIT from .*"));
myClient.unregisterInterceptor(capture);
}
@Test
public void testSearchMaskSubject() {
create50Observations();
ConsentSvcMaskObservationSubjects consentService = new ConsentSvcMaskObservationSubjects();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
// Perform a search
Bundle result = myClient
.search()
.forResource("Observation")
.sort()
.ascending(Observation.SP_IDENTIFIER)
.returnBundle(Bundle.class)
.count(15)
.execute();
List<IBaseResource> resources = BundleUtil.toListOfResources(myFhirCtx, result);
assertEquals(15, resources.size());
assertEquals(16, consentService.getSeeCount());
resources.forEach(t -> {
assertEquals(null, ((Observation) t).getSubject().getReference());
});
// Fetch the next page
result = myClient
.loadPage()
.next(result)
.execute();
resources = BundleUtil.toListOfResources(myFhirCtx, result);
assertEquals(15, resources.size());
assertEquals(32, consentService.getSeeCount());
resources.forEach(t -> {
assertEquals(null, ((Observation) t).getSubject().getReference());
});
}
@Test
public void testHistoryAndBlockSome() {
create50Observations();
IConsentService consentService = new ConsentSvcCantSeeOddNumbered();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
// Perform a search
Bundle result = myClient
.history()
.onServer()
.returnBundle(Bundle.class)
.count(10)
.execute();
List<IBaseResource> resources = BundleUtil.toListOfResources(myFhirCtx, result);
List<String> returnedIdValues = toUnqualifiedVersionlessIdValues(resources);
assertEquals(myObservationIdsEvenOnlyBackwards.subList(0, 5), returnedIdValues);
// Per #2012
assertNull(result.getTotalElement().getValue());
}
@Test
public void testReadAndBlockSome() {
create50Observations();
IConsentService consentService = new ConsentSvcCantSeeOddNumbered();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
myClient.read().resource("Observation").withId(new IdType(myObservationIdsEvenOnly.get(0))).execute();
myClient.read().resource("Observation").withId(new IdType(myObservationIdsEvenOnly.get(1))).execute();
try {
myClient.read().resource("Observation").withId(new IdType(myObservationIdsOddOnly.get(0))).execute();
fail();
} catch (ResourceNotFoundException e) {
// good
}
try {
myClient.read().resource("Observation").withId(new IdType(myObservationIdsOddOnly.get(1))).execute();
fail();
} catch (ResourceNotFoundException e) {
// good
}
}
@Test
public void testCreateBlockResponse() throws IOException {
create50Observations();
DelegatingConsentService consentService = new DelegatingConsentService();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
Patient patient = new Patient();
patient.setActive(true);
// Reject output
consentService.setTarget(new ConsentSvcRejectCanSeeAnything());
HttpPost post = new HttpPost(ourServerBase + "/Patient");
post.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION);
post.setEntity(toEntity(patient));
try (CloseableHttpResponse status = ourHttpClient.execute(post)) {
String id = status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue();
assertThat(id, matchesPattern("^.*/Patient/[0-9]+/_history/[0-9]+$"));
assertEquals(201, status.getStatusLine().getStatusCode());
String responseString = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8);
assertThat(responseString, blankOrNullString());
assertNull(status.getEntity().getContentType());
}
// Accept output
consentService.setTarget(new ConsentSvcNop(ConsentOperationStatusEnum.PROCEED));
post = new HttpPost(ourServerBase + "/Patient");
post.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION);
post.setEntity(toEntity(patient));
try (CloseableHttpResponse status = ourHttpClient.execute(post)) {
String id = status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue();
assertThat(id, matchesPattern("^.*/Patient/[0-9]+/_history/[0-9]+$"));
assertEquals(201, status.getStatusLine().getStatusCode());
assertNotNull(status.getEntity());
String responseString = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8);
assertThat(responseString, not(blankOrNullString()));
assertThat(status.getEntity().getContentType().getValue().toLowerCase(), matchesPattern(".*json.*"));
}
}
@Test
public void testUpdateBlockResponse() throws IOException {
create50Observations();
Patient patient = new Patient();
patient.setActive(true);
IIdType id = myClient.create().resource(patient).prefer(PreferReturnEnum.REPRESENTATION).execute().getId().toUnqualifiedVersionless();
DelegatingConsentService consentService = new DelegatingConsentService();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
// Reject output
consentService.setTarget(new ConsentSvcRejectCanSeeAnything());
patient = new Patient();
patient.setId(id);
patient.setActive(true);
patient.addIdentifier().setValue("VAL1");
HttpPut put = new HttpPut(ourServerBase + "/Patient/" + id.getIdPart());
put.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION);
put.setEntity(toEntity(patient));
try (CloseableHttpResponse status = ourHttpClient.execute(put)) {
String idVal = status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue();
assertThat(idVal, matchesPattern("^.*/Patient/[0-9]+/_history/[0-9]+$"));
assertEquals(200, status.getStatusLine().getStatusCode());
String responseString = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8);
assertThat(responseString, blankOrNullString());
assertNull(status.getEntity().getContentType());
}
// Accept output
consentService.setTarget(new ConsentSvcNop(ConsentOperationStatusEnum.PROCEED));
patient = new Patient();
patient.setId(id);
patient.setActive(true);
patient.addIdentifier().setValue("VAL2");
put = new HttpPut(ourServerBase + "/Patient/" + id.getIdPart());
put.addHeader(Constants.HEADER_PREFER, Constants.HEADER_PREFER_RETURN + '=' + Constants.HEADER_PREFER_RETURN_REPRESENTATION);
put.setEntity(toEntity(patient));
try (CloseableHttpResponse status = ourHttpClient.execute(put)) {
String idVal = status.getFirstHeader(Constants.HEADER_CONTENT_LOCATION).getValue();
assertThat(idVal, matchesPattern("^.*/Patient/[0-9]+/_history/[0-9]+$"));
assertEquals(200, status.getStatusLine().getStatusCode());
assertNotNull(status.getEntity());
String responseString = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8);
assertThat(responseString, not(blankOrNullString()));
assertThat(status.getEntity().getContentType().getValue().toLowerCase(), matchesPattern(".*json.*"));
}
}
@Test
public void testRejectWillSeeResource() throws IOException {
create50Observations();
ConsentSvcRejectWillSeeEvenNumbered consentService = new ConsentSvcRejectWillSeeEvenNumbered();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
// Search for all
String url = ourServerBase + "/Observation?_pretty=true&_count=10";
ourLog.info("HTTP GET {}", url);
HttpGet get = new HttpGet(url);
get.addHeader(Constants.HEADER_ACCEPT, Constants.CT_JSON);
try (CloseableHttpResponse status = ourHttpClient.execute(get)) {
String responseString = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8);
ourLog.info("Response: {}", responseString);
assertEquals(200, status.getStatusLine().getStatusCode());
Bundle result = myFhirCtx.newJsonParser().parseResource(Bundle.class, responseString);
List<IBaseResource> resources = BundleUtil.toListOfResources(myFhirCtx, result);
List<String> returnedIdValues = toUnqualifiedVersionlessIdValues(resources);
assertEquals(myObservationIdsOddOnly.subList(0, 5), returnedIdValues);
}
}
@Test
public void testGraphQL_Proceed() throws IOException {
createPatientAndOrg();
DelegatingConsentService consentService = new DelegatingConsentService();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
// Proceed everything
consentService.setTarget(new ConsentSvcNop(ConsentOperationStatusEnum.PROCEED));
String query = "{ name { family, given }, managingOrganization { reference, resource {name} } }";
String url = ourServerBase + "/" + myPatientIds.get(0) + "/$graphql?query=" + UrlUtil.escapeUrlParam(query);
ourLog.info("HTTP GET {}", url);
HttpGet get = new HttpGet(url);
get.addHeader(Constants.HEADER_ACCEPT, Constants.CT_JSON);
try (CloseableHttpResponse status = ourHttpClient.execute(get)) {
String responseString = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8);
ourLog.info("Response: {}", responseString);
assertEquals(200, status.getStatusLine().getStatusCode());
assertThat(responseString, containsString("\"family\":\"PATIENT_FAMILY\""));
assertThat(responseString, containsString("\"given\":[\"PATIENT_GIVEN1\",\"PATIENT_GIVEN2\"]"));
assertThat(responseString, containsString("\"name\":\"ORG_NAME\""));
}
}
@Test
public void testGraphQL_RejectResource() throws IOException {
createPatientAndOrg();
DelegatingConsentService consentService = new DelegatingConsentService();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
IConsentService svc = mock(IConsentService.class);
when(svc.startOperation(any(), any())).thenReturn(ConsentOutcome.PROCEED);
when(svc.canSeeResource(any(), any(), any())).thenReturn(ConsentOutcome.REJECT);
consentService.setTarget(svc);
String query = "{ name { family, given }, managingOrganization { reference, resource {name} } }";
String url = ourServerBase + "/" + myPatientIds.get(0) + "/$graphql?query=" + UrlUtil.escapeUrlParam(query);
ourLog.info("HTTP GET {}", url);
HttpGet get = new HttpGet(url);
get.addHeader(Constants.HEADER_ACCEPT, Constants.CT_JSON);
try (CloseableHttpResponse status = ourHttpClient.execute(get)) {
String responseString = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8);
ourLog.info("Response: {}", responseString);
assertEquals(404, status.getStatusLine().getStatusCode());
assertThat(responseString, not(containsString("\"family\":\"PATIENT_FAMILY\"")));
assertThat(responseString, not(containsString("\"given\":[\"PATIENT_GIVEN1\",\"PATIENT_GIVEN2\"]")));
assertThat(responseString, not(containsString("\"name\":\"ORG_NAME\"")));
OperationOutcome oo = myFhirCtx.newJsonParser().parseResource(OperationOutcome.class, responseString);
assertThat(oo.getIssueFirstRep().getDiagnostics(), matchesPattern("Unable to execute GraphQL Expression: HTTP 404 Resource Patient/[0-9]+ is not known"));
}
}
@Test
public void testGraphQL_RejectLinkedResource() throws IOException {
createPatientAndOrg();
DelegatingConsentService consentService = new DelegatingConsentService();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
IConsentService svc = mock(IConsentService.class);
when(svc.startOperation(any(), any())).thenReturn(ConsentOutcome.PROCEED);
when(svc.canSeeResource(any(RequestDetails.class), any(IBaseResource.class), any())).thenAnswer(t -> {
IBaseResource resource = t.getArgument(1, IBaseResource.class);
if (resource instanceof Organization) {
return ConsentOutcome.REJECT;
}
return ConsentOutcome.PROCEED;
});
when(svc.willSeeResource(any(), any(), any())).thenReturn(ConsentOutcome.PROCEED);
consentService.setTarget(svc);
String query = "{ name { family, given }, managingOrganization { reference, resource {name} } }";
String url = ourServerBase + "/" + myPatientIds.get(0) + "/$graphql?query=" + UrlUtil.escapeUrlParam(query);
ourLog.info("HTTP GET {}", url);
HttpGet get = new HttpGet(url);
get.addHeader(Constants.HEADER_ACCEPT, Constants.CT_JSON);
try (CloseableHttpResponse status = ourHttpClient.execute(get)) {
String responseString = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8);
ourLog.info("Response: {}", responseString);
assertEquals(404, status.getStatusLine().getStatusCode());
assertThat(responseString, not(containsString("\"family\":\"PATIENT_FAMILY\"")));
assertThat(responseString, not(containsString("\"given\":[\"PATIENT_GIVEN1\",\"PATIENT_GIVEN2\"]")));
assertThat(responseString, not(containsString("\"name\":\"ORG_NAME\"")));
OperationOutcome oo = myFhirCtx.newJsonParser().parseResource(OperationOutcome.class, responseString);
assertThat(oo.getIssueFirstRep().getDiagnostics(), matchesPattern("Unable to execute GraphQL Expression: HTTP 404 Resource Organization/[0-9]+ is not known"));
}
}
@Test
public void testGraphQL_MaskLinkedResource() throws IOException {
createPatientAndOrg();
DelegatingConsentService consentService = new DelegatingConsentService();
myConsentInterceptor = new ConsentInterceptor(consentService, IConsentContextServices.NULL_IMPL);
ourRestServer.getInterceptorService().registerInterceptor(myConsentInterceptor);
IConsentService svc = mock(IConsentService.class);
when(svc.startOperation(any(), any())).thenReturn(ConsentOutcome.PROCEED);
when(svc.canSeeResource(any(), any(), any())).thenReturn(ConsentOutcome.PROCEED);
when(svc.willSeeResource(any(RequestDetails.class), any(IBaseResource.class), any())).thenAnswer(t -> {
IBaseResource resource = t.getArgument(1, IBaseResource.class);
if (resource instanceof Organization) {
Organization org = new Organization();
org.addIdentifier().setSystem("ORG_SYSTEM").setValue("ORG_VALUE");
return new ConsentOutcome(ConsentOperationStatusEnum.PROCEED, org);
}
return ConsentOutcome.PROCEED;
});
consentService.setTarget(svc);
String query = "{ name { family, given }, managingOrganization { reference, resource {name, identifier { system } } } }";
String url = ourServerBase + "/" + myPatientIds.get(0) + "/$graphql?query=" + UrlUtil.escapeUrlParam(query);
ourLog.info("HTTP GET {}", url);
HttpGet get = new HttpGet(url);
get.addHeader(Constants.HEADER_ACCEPT, Constants.CT_JSON);
try (CloseableHttpResponse status = ourHttpClient.execute(get)) {
String responseString = IOUtils.toString(status.getEntity().getContent(), Charsets.UTF_8);
ourLog.info("Response: {}", responseString);
assertEquals(200, status.getStatusLine().getStatusCode());
assertThat(responseString, containsString("\"family\":\"PATIENT_FAMILY\""));
assertThat(responseString, containsString("\"given\":[\"PATIENT_GIVEN1\",\"PATIENT_GIVEN2\"]"));
assertThat(responseString, not(containsString("\"name\":\"ORG_NAME\"")));
assertThat(responseString, containsString("\"system\":\"ORG_SYSTEM\""));
}
}
private void createPatientAndOrg() {
myPatientIds = new ArrayList<>();
Organization org = new Organization();
org.setName("ORG_NAME");
IIdType orgId = myOrganizationDao.create(org).getId().toUnqualifiedVersionless();
Patient p = new Patient();
p.setActive(true);
p.addName().setFamily("PATIENT_FAMILY").addGiven("PATIENT_GIVEN1").addGiven("PATIENT_GIVEN2");
p.getManagingOrganization().setReference(orgId.getValue());
String pid = myPatientDao.create(p).getId().toUnqualifiedVersionless().getValue();
myPatientIds.add(pid);
}
private void create50Observations() {
myPatientIds = new ArrayList<>();
myObservationIds = new ArrayList<>();
Patient p = new Patient();
p.setActive(true);
String pid = myPatientDao.create(p).getId().toUnqualifiedVersionless().getValue();
myPatientIds.add(pid);
for (int i = 0; i < 50; i++) {
final Observation obs1 = new Observation();
obs1.setStatus(Observation.ObservationStatus.FINAL);
obs1.addIdentifier().setSystem("urn:system").setValue("I" + leftPad("" + i, 5, '0'));
obs1.getSubject().setReference(pid);
IIdType obs1id = myObservationDao.create(obs1).getId().toUnqualifiedVersionless();
myObservationIds.add(obs1id.toUnqualifiedVersionless().getValue());
}
myObservationIdsEvenOnly =
myObservationIds
.stream()
.filter(t -> Long.parseLong(t.substring(t.indexOf('/') + 1)) % 2 == 0)
.collect(Collectors.toList());
myObservationIdsOddOnly = ListUtils.removeAll(myObservationIds, myObservationIdsEvenOnly);
myObservationIdsEvenOnlyBackwards = Lists.reverse(myObservationIdsEvenOnly);
}
private HttpEntity toEntity(Patient thePatient) {
String encoded = myFhirCtx.newJsonParser().encodeResourceToString(thePatient);
ContentType cs = ContentType.create(Constants.CT_FHIR_JSON, Constants.CHARSET_UTF8);
return new StringEntity(encoded, cs);
}
private class ConsentSvcMaskObservationSubjects implements IConsentService {
private int mySeeCount = 0;
@Override
public ConsentOutcome startOperation(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
return ConsentOutcome.PROCEED;
}
@Override
public ConsentOutcome canSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
return ConsentOutcome.PROCEED;
}
int getSeeCount() {
return mySeeCount;
}
@Override
public ConsentOutcome willSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
mySeeCount++;
String resourceId = theResource.getIdElement().toUnqualifiedVersionless().getValue();
ourLog.info("** SEE: {}", resourceId);
if (theResource instanceof Observation) {
((Observation) theResource).getSubject().setReference("");
((Observation) theResource).getSubject().setResource(null);
return new ConsentOutcome(ConsentOperationStatusEnum.PROCEED, theResource);
}
return ConsentOutcome.PROCEED;
}
@Override
public void completeOperationSuccess(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
// nothing
}
@Override
public void completeOperationFailure(RequestDetails theRequestDetails, BaseServerResponseException theException, IConsentContextServices theContextServices) {
// nothing
}
}
private static class ConsentSvcCantSeeOddNumbered implements IConsentService {
@Override
public ConsentOutcome startOperation(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
return new ConsentOutcome(ConsentOperationStatusEnum.PROCEED);
}
@Override
public ConsentOutcome canSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
Long resIdLong = theResource.getIdElement().getIdPartAsLong();
if (resIdLong % 2 == 1) {
return new ConsentOutcome(ConsentOperationStatusEnum.REJECT);
}
return new ConsentOutcome(ConsentOperationStatusEnum.PROCEED);
}
@Override
public ConsentOutcome willSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
return ConsentOutcome.PROCEED;
}
@Override
public void completeOperationSuccess(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
// nothing
}
@Override
public void completeOperationFailure(RequestDetails theRequestDetails, BaseServerResponseException theException, IConsentContextServices theContextServices) {
// nothing
}
}
private static class ConsentSvcCantSeeEvenNumbered implements IConsentService {
@Override
public ConsentOutcome startOperation(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
return new ConsentOutcome(ConsentOperationStatusEnum.PROCEED);
}
@Override
public ConsentOutcome canSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
Long resIdLong = theResource.getIdElement().getIdPartAsLong();
if (resIdLong % 2 == 0) {
return new ConsentOutcome(ConsentOperationStatusEnum.REJECT);
}
return new ConsentOutcome(ConsentOperationStatusEnum.PROCEED);
}
@Override
public ConsentOutcome willSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
return ConsentOutcome.PROCEED;
}
@Override
public void completeOperationSuccess(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
// nothing
}
@Override
public void completeOperationFailure(RequestDetails theRequestDetails, BaseServerResponseException theException, IConsentContextServices theContextServices) {
// nothing
}
}
private static class ConsentSvcNop implements IConsentService {
private final ConsentOperationStatusEnum myOperationStatus;
private ConsentSvcNop(ConsentOperationStatusEnum theOperationStatus) {
myOperationStatus = theOperationStatus;
}
@Override
public ConsentOutcome startOperation(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
return new ConsentOutcome(myOperationStatus);
}
@Override
public ConsentOutcome canSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
return new ConsentOutcome(ConsentOperationStatusEnum.PROCEED);
}
@Override
public ConsentOutcome willSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
return ConsentOutcome.PROCEED;
}
@Override
public void completeOperationSuccess(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
// nothing
}
@Override
public void completeOperationFailure(RequestDetails theRequestDetails, BaseServerResponseException theException, IConsentContextServices theContextServices) {
// nothing
}
}
private static class ConsentSvcRejectCanSeeAnything implements IConsentService {
@Override
public ConsentOutcome startOperation(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
return ConsentOutcome.PROCEED;
}
@Override
public ConsentOutcome canSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
return ConsentOutcome.REJECT;
}
@Override
public ConsentOutcome willSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
return ConsentOutcome.PROCEED;
}
@Override
public void completeOperationSuccess(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
// nothing
}
@Override
public void completeOperationFailure(RequestDetails theRequestDetails, BaseServerResponseException theException, IConsentContextServices theContextServices) {
// nothing
}
}
private static class ConsentSvcRejectWillSeeEvenNumbered implements IConsentService {
@Override
public ConsentOutcome startOperation(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
return ConsentOutcome.PROCEED;
}
@Override
public ConsentOutcome canSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
return ConsentOutcome.PROCEED;
}
@Override
public ConsentOutcome willSeeResource(RequestDetails theRequestDetails, IBaseResource theResource, IConsentContextServices theContextServices) {
if (theResource.getIdElement().isIdPartValidLong()) {
Long resIdLong = theResource.getIdElement().getIdPartAsLong();
if (resIdLong % 2 == 0) {
return new ConsentOutcome(ConsentOperationStatusEnum.REJECT);
}
}
return new ConsentOutcome(ConsentOperationStatusEnum.PROCEED);
}
@Override
public void completeOperationSuccess(RequestDetails theRequestDetails, IConsentContextServices theContextServices) {
// nothing
}
@Override
public void completeOperationFailure(RequestDetails theRequestDetails, BaseServerResponseException theException, IConsentContextServices theContextServices) {
// nothing
}
}
} |
package com.worth.ifs.registration;
import com.worth.ifs.BaseControllerMockMVCTest;
import com.worth.ifs.commons.error.Error;
import com.worth.ifs.commons.error.exception.GeneralUnexpectedErrorException;
import com.worth.ifs.exception.ErrorControllerAdvice;
import com.worth.ifs.filter.CookieFlashMessageFilter;
import com.worth.ifs.user.resource.OrganisationResource;
import com.worth.ifs.user.resource.UserResource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import static com.worth.ifs.commons.error.CommonErrors.notFoundError;
import static com.worth.ifs.commons.error.CommonFailureKeys.USERS_EMAIL_VERIFICATION_TOKEN_EXPIRED;
import static com.worth.ifs.commons.error.CommonFailureKeys.USERS_EMAIL_VERIFICATION_TOKEN_NOT_FOUND;
import static com.worth.ifs.commons.rest.RestResult.restFailure;
import static com.worth.ifs.commons.rest.RestResult.restSuccess;
import static com.worth.ifs.user.builder.OrganisationResourceBuilder.newOrganisationResource;
import static com.worth.ifs.user.builder.RoleResourceBuilder.newRoleResource;
import static com.worth.ifs.user.builder.UserResourceBuilder.newUserResource;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.*;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(MockitoJUnitRunner.class)
@TestPropertySource(locations = "classpath:application.properties")
public class RegistrationControllerTest extends BaseControllerMockMVCTest<RegistrationController> {
@InjectMocks
private RegistrationController registrationController;
@Mock
private CookieFlashMessageFilter cookieFlashMessageFilter;
@Mock
private Validator validator;
private Cookie inviteHashCookie;
private Cookie usedInviteHashCookie;
private Cookie organisationCookie;
@Override
protected RegistrationController supplyControllerUnderTest() {
return new RegistrationController();
}
@Before
public void setUp() {
super.setUp();
MockitoAnnotations.initMocks(this);
setupUserRoles();
setupInvites();
registrationController.setValidator(new LocalValidatorFactoryBean());
when(userService.findUserByEmail(anyString())).thenReturn(restSuccess(new UserResource()));
when(userService.findUserByEmailForAnonymousUserFlow(anyString())).thenReturn(restSuccess(new UserResource()));
when(userService.createLeadApplicantForOrganisation(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyLong())).thenReturn(restSuccess(new UserResource()));
inviteHashCookie = new Cookie(AcceptInviteController.INVITE_HASH, INVITE_HASH);
usedInviteHashCookie = new Cookie(AcceptInviteController.INVITE_HASH, ACCEPTED_INVITE_HASH);
organisationCookie = new Cookie("organisationId", "1");
}
@Test
public void onGetRequestRegistrationViewIsReturned() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
mockMvc.perform(get("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
)
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration-register"));
}
@Test
public void onGetRequestRegistrationViewIsReturnedWithInviteEmail() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
mockMvc.perform(get("/registration/register")
.cookie(inviteHashCookie, organisationCookie)
)
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration-register"))
.andExpect(model().attribute("invitee", true))
;
}
@Test
public void onGetRequestRegistrationViewIsReturnedWithUsedInviteEmail() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
mockMvc.perform(get("/registration/register")
.cookie(usedInviteHashCookie, organisationCookie)
)
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/login"));
verify(cookieFlashMessageFilter).setFlashMessage(isA(HttpServletResponse.class), eq("inviteAlreadyAccepted"));
}
@Test
public void missingOrganisationGetParameterChangesViewWhenViewingForm() throws Exception {
mockMvc.perform(get("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
)
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/"));
}
@Test
public void testSuccessUrl() throws Exception {
mockMvc.perform(get("/registration/success").header("referer", "https://localhost/registration/register?organisationId=14"))
.andExpect(status().isOk())
.andExpect(view().name("registration/successful"))
;
}
@Test
public void testVerifiedUrlNotFoundOnDirectAccess() throws Exception {
mockMvc.perform(get("/registration/verified"))
.andExpect(status().isNotFound());
}
@Test
public void testVerifyEmail() throws Exception {
final String hash = UUID.randomUUID().toString();
when(userService.verifyEmail(eq(hash))).thenReturn(restSuccess());
mockMvc.perform(get("/registration/verify-email/" + hash))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/registration/verified"));
}
@Test
public void testVerifyEmailInvalid() throws Exception {
final String hash = UUID.randomUUID().toString();
when(userService.verifyEmail(eq(hash))).thenReturn(restFailure(new Error(USERS_EMAIL_VERIFICATION_TOKEN_NOT_FOUND)));
mockMvc.perform(get("/registration/verify-email/" + hash))
.andExpect(status().isAlreadyReported())
.andExpect(view().name(ErrorControllerAdvice.URL_HASH_INVALID_TEMPLATE));
}
@Test
public void testVerifyEmailExpired() throws Exception {
final String hash = UUID.randomUUID().toString();
when(userService.verifyEmail(eq(hash))).thenReturn(restFailure(new Error(USERS_EMAIL_VERIFICATION_TOKEN_EXPIRED)));
mockMvc.perform(get("/registration/verify-email/" + hash))
.andExpect(status().isForbidden())
.andExpect(view().name("registration-token-expired"));
}
@Test
public void organisationGetParameterOfANonExistentOrganisationChangesViewWhenViewingForm() throws Exception {
mockMvc.perform(get("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
)
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/"));
}
@Test
public void missingOrganisationGetParameterChangesViewWhenSubmittingForm() throws Exception {
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
)
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/"));
}
@Test
public void organisationGetParameterOfANonExistentOrganisationChangesViewWhenSubmittingForm() throws Exception {
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
)
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/"));
}
@Test
public void validButAlreadyExistingEmailInputShouldReturnErrorOnEmailField() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
String email = "alreadyexistingemail@test.test";
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
when(userService.findUserByEmailForAnonymousUserFlow(email)).thenReturn(restSuccess(new UserResource()));
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
.param("email", email)
)
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration-register"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "email"));
}
@Test
public void emptyFormInputsShouldReturnError() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
.param("email", "")
.param("password", "")
.param("retypedPassword", "")
.param("title", "")
.param("firstName", "")
.param("lastName", "")
.param("phoneNumber", "")
.param("termsAndConditions", "")
)
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration-register"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "password"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "email"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "retypedPassword"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "title"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "firstName"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "lastName"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "phoneNumber"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "termsAndConditions"));
}
@Test
public void invalidEmailFormatShouldReturnError() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
.param("email", "invalid email format")
)
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration-register"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "email"));
}
@Test
public void invalidCharactersInEmailShouldReturnError() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
.param("email", "{a|b}@test.test")
)
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration-register"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "email"));
verifyNoMoreInteractions(userService);
}
@Test
public void incorrectPasswordSizeShouldReturnError() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
.param("password", "12345")
.param("retypedPassword", "123456789012345678901234567890123")
)
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration-register"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "password"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "retypedPassword"));
}
@Test
public void unmatchedPasswordAndRetypePasswordShouldReturnError() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
.param("password", "12345678")
.param("retypedPassword", "123456789")
)
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration-register"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "retypedPassword"));
}
@Test
public void uncheckedTermsAndConditionsCheckboxShouldReturnError() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
)
.andExpect(status().is2xxSuccessful())
.andExpect(view().name("registration-register"))
.andExpect(model().attributeHasFieldErrors("registrationForm", "termsAndConditions"));
}
@Test
public void validRegisterPost() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
UserResource userResource = newUserResource()
.withPassword("password123")
.withFirstName("firstName")
.withLastName("lastName")
.withTitle("Mr")
.withPhoneNumber("0123456789")
.withEmail("test@test.test")
.withId(1L)
.build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
when(userService.createLeadApplicantForOrganisationWithCompetitionId(userResource.getFirstName(),
userResource.getLastName(),
userResource.getPassword(),
userResource.getEmail(),
userResource.getTitle(),
userResource.getPhoneNumber(),
1L,
null)).thenReturn(restSuccess(userResource));
when(userService.findUserByEmailForAnonymousUserFlow("test@test.test")).thenReturn(restFailure(notFoundError(UserResource.class, "test@test.test")));
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
.param("email", userResource.getEmail())
.param("password", userResource.getPassword())
.param("retypedPassword", userResource.getPassword())
.param("title", userResource.getTitle())
.param("firstName", userResource.getFirstName())
.param("lastName", userResource.getLastName())
.param("phoneNumber", userResource.getPhoneNumber())
.param("termsAndConditions", "1")
)
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/registration/success"));
}
@Test
public void validRegisterPostWithInvite() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
UserResource userResource = newUserResource()
.withPassword("password")
.withFirstName("firstName")
.withLastName("lastName")
.withTitle("Mr")
.withPhoneNumber("0123456789")
.withEmail("invited@email.com")
.withId(1L)
.build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
when(userService.createLeadApplicantForOrganisationWithCompetitionId(userResource.getFirstName(),
userResource.getLastName(),
userResource.getPassword(),
userResource.getEmail(),
userResource.getTitle(),
userResource.getPhoneNumber(),
1L,
null)).thenReturn(restSuccess(userResource));
when(userService.findUserByEmailForAnonymousUserFlow(eq("invited@email.com"))).thenReturn(restFailure(notFoundError(UserResource.class, "invited@email.com")));
when(inviteRestService.acceptInvite(eq(INVITE_HASH),anyLong())).thenReturn(restSuccess());
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(inviteHashCookie, organisationCookie)
.param("password", userResource.getPassword())
.param("retypedPassword", userResource.getPassword())
.param("title", userResource.getTitle())
.param("firstName", userResource.getFirstName())
.param("lastName", userResource.getLastName())
.param("phoneNumber", userResource.getPhoneNumber())
.param("termsAndConditions", "1")
)
.andExpect(view().name("redirect:/registration/success"))
.andExpect(status().is3xxRedirection());
}
@Test
public void correctOrganisationNameIsAddedToModel() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(4L).withName("uniqueOrganisationName").build();
when(organisationService.getOrganisationByIdForAnonymousUserFlow(4L)).thenReturn(organisation);
organisationCookie = new Cookie("organisationId", "4");
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
).andExpect(model().attribute("organisationName", "uniqueOrganisationName"));
}
@Test
public void gettingRegistrationPageWithLoggedInUserShouldResultInRedirectOnly() throws Exception {
when(userAuthenticationService.getAuthenticatedUser(isA(HttpServletRequest.class))).thenReturn(
newUserResource().withRolesGlobal(singletonList(
newRoleResource().withName("testrolename").withUrl("testrolename/dashboard").build()
)).build()
);
mockMvc.perform(get("/registration/register")
.cookie(organisationCookie)
).andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/testrolename/dashboard"));
}
@Test
public void postingRegistrationWithLoggedInUserShouldResultInRedirectOnly() throws Exception {
when(userAuthenticationService.getAuthenticatedUser(isA(HttpServletRequest.class))).thenReturn(
newUserResource().withRolesGlobal(singletonList(
newRoleResource().withName("testrolename").withUrl("testrolename/dashboard").build()
)).build()
);
mockMvc.perform(post("/registration/register")
.cookie(organisationCookie)
).andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/testrolename/dashboard"));
}
@Test
public void errorsReturnedInEnvelopeAreAddedToTheModel() throws Exception {
OrganisationResource organisation = newOrganisationResource().withId(1L).withName("Organisation 1").build();
UserResource userResource = newUserResource()
.withPassword("password")
.withFirstName("firstName")
.withLastName("lastName")
.withTitle("Mr")
.withPhoneNumber("0123456789")
.withEmail("test@test.test")
.withId(1L)
.build();
Error error = new Error("errorname", "errordescription", BAD_REQUEST);
when(organisationService.getOrganisationByIdForAnonymousUserFlow(1L)).thenReturn(organisation);
when(userService.createLeadApplicantForOrganisationWithCompetitionId(userResource.getFirstName(),
userResource.getLastName(),
userResource.getPassword(),
userResource.getEmail(),
userResource.getTitle(),
userResource.getPhoneNumber(),
1L, null)).thenReturn(restFailure(error));
mockMvc.perform(post("/registration/register")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(organisationCookie)
.param("email", userResource.getEmail())
.param("password", userResource.getPassword())
.param("retypedPassword", userResource.getPassword())
.param("title", userResource.getTitle())
.param("firstName", userResource.getFirstName())
.param("lastName", userResource.getLastName())
.param("phoneNumber", userResource.getPhoneNumber())
.param("termsAndConditions", "1")
)
.andExpect(model().hasErrors());
}
@Test
public void resendEmailVerification() throws Exception {
mockMvc.perform(get("/registration/resend-email-verification"))
.andExpect(status().isOk())
.andExpect(view().name("registration/resend-email-verification"));
}
@Test
public void validResendEmailVerificationForm() throws Exception {
mockMvc.perform(post("/registration/resend-email-verification")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("email", "a.b@test.test"))
.andExpect(status().isOk())
.andExpect(view().name("registration/resend-email-verification-send"));
}
@Test
public void invalidResendEmailVerificationFormShouldReturnError() throws Exception {
mockMvc.perform(post("/registration/resend-email-verification")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("email", "{a|b}@test.test"))
.andExpect(status().isOk())
.andExpect(view().name("registration/resend-email-verification"))
.andExpect(model().attributeHasFieldErrors("resendEmailVerificationForm", "email"));
}
@Test
public void validResendEmailVerificationFormWithOtherExceptionShouldByHandled() throws Exception {
final String emailAddress = "a.b@test.test";
doThrow(new GeneralUnexpectedErrorException("Other error occurred", asList())).when(userService).resendEmailVerificationNotification(emailAddress);
mockMvc.perform(post("/registration/resend-email-verification")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("email", emailAddress))
.andExpect(status().isInternalServerError())
.andExpect(view().name("error"));
}
} |
package org.eclipse.persistence.testing.tests.jpa.advanced;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Collection;
import java.util.Vector;
import java.util.Iterator;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.FlushModeType;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TransactionRequiredException;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceException;
import javax.persistence.OptimisticLockException;
import javax.persistence.RollbackException;
import junit.framework.*;
import org.eclipse.persistence.jpa.config.CacheUsage;
import org.eclipse.persistence.jpa.config.CascadePolicy;
import org.eclipse.persistence.jpa.config.PessimisticLock;
import org.eclipse.persistence.jpa.config.PersistenceUnitProperties;
import org.eclipse.persistence.jpa.config.EclipseLinkQueryHints;
import org.eclipse.persistence.internal.jpa.EJBQueryImpl;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl;
import org.eclipse.persistence.internal.helper.Helper;
import org.eclipse.persistence.queries.DatabaseQuery;
import org.eclipse.persistence.queries.ObjectLevelReadQuery;
import org.eclipse.persistence.queries.ReadAllQuery;
import org.eclipse.persistence.sequencing.NativeSequence;
import org.eclipse.persistence.sequencing.Sequence;
import org.eclipse.persistence.sessions.server.ReadConnectionPool;
import org.eclipse.persistence.sessions.server.ServerSession;
import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.tools.schemaframework.SequenceObjectDefinition;
import org.eclipse.persistence.jpa.PersistenceProvider;
import org.eclipse.persistence.exceptions.QueryException;
import org.eclipse.persistence.expressions.Expression;
import org.eclipse.persistence.expressions.ExpressionBuilder;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.changetracking.ChangeTracker;
import org.eclipse.persistence.internal.descriptors.PersistenceEntity;
import org.eclipse.persistence.internal.jpa.EntityManagerImpl;
import org.eclipse.persistence.internal.weaving.PersistenceWeaved;
import org.eclipse.persistence.internal.weaving.PersistenceWeavedLazy;
import org.eclipse.persistence.queries.FetchGroupTracker;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCaseHelper;
import org.eclipse.persistence.testing.models.jpa.advanced.*;
/**
* Test the EntityManager API using the advanced model.
*/
public class EntityManagerJUnitTestSuite extends JUnitTestCase {
/** The field length for the firstname */
public static final int MAX_FIRST_NAME_FIELD_LENGTH = 255;
public EntityManagerJUnitTestSuite() {
super();
}
public EntityManagerJUnitTestSuite(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("EntityManagerJUnitTestSuite");
suite.addTest(new EntityManagerJUnitTestSuite("testSetup"));
suite.addTest(new EntityManagerJUnitTestSuite("testWeaving"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearEntityManagerWithoutPersistenceContext"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllProjects"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateUsingTempStorage"));
suite.addTest(new EntityManagerJUnitTestSuite("testSequenceObjectDefinition"));
suite.addTest(new EntityManagerJUnitTestSuite("testFindDeleteAllPersist"));
suite.addTest(new EntityManagerJUnitTestSuite("testExtendedPersistenceContext"));
suite.addTest(new EntityManagerJUnitTestSuite("testRemoveFlushFind"));
suite.addTest(new EntityManagerJUnitTestSuite("testRemoveFlushPersistContains"));
suite.addTest(new EntityManagerJUnitTestSuite("testTransactionRequired"));
suite.addTest(new EntityManagerJUnitTestSuite("testSubString"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeOnUpdateQuery"));
suite.addTest(new EntityManagerJUnitTestSuite("testContainsRemoved"));
suite.addTest(new EntityManagerJUnitTestSuite("testRefreshRemoved"));
suite.addTest(new EntityManagerJUnitTestSuite("testRefreshNotManaged"));
suite.addTest(new EntityManagerJUnitTestSuite("testDoubleMerge"));
suite.addTest(new EntityManagerJUnitTestSuite("testDescriptorNamedQueryForMultipleQueries"));
suite.addTest(new EntityManagerJUnitTestSuite("testDescriptorNamedQuery"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearEntityManagerWithoutPersistenceContextSimulateJTA"));
suite.addTest(new EntityManagerJUnitTestSuite("testMultipleEntityManagerFactories"));
suite.addTest(new EntityManagerJUnitTestSuite("testOneToManyDefaultJoinTableName"));
suite.addTest(new EntityManagerJUnitTestSuite("testClosedEmShouldThrowException"));
suite.addTest(new EntityManagerJUnitTestSuite("testRollbackOnlyOnException"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllLargeProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllSmallProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllProjectsWithName"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllLargeProjectsWithName"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllSmallProjectsWithName"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllLargeProjects"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllSmallProjects"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateUsingTempStorageWithParameter"));
suite.addTest(new EntityManagerJUnitTestSuite("testDeleteAllLargeProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testDeleteAllSmallProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testDeleteAllProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testDeleteAllPhonesWithNullOwner"));
suite.addTest(new EntityManagerJUnitTestSuite("testSetFieldForPropertyAccessWithNewEM"));
suite.addTest(new EntityManagerJUnitTestSuite("testSetFieldForPropertyAccessWithRefresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testSetFieldForPropertyAccess"));
suite.addTest(new EntityManagerJUnitTestSuite("testInitializeFieldForPropertyAccess"));
suite.addTest(new EntityManagerJUnitTestSuite("testCascadePersistToNonEntitySubclass"));
suite.addTest(new EntityManagerJUnitTestSuite("testCascadeMergeManaged"));
suite.addTest(new EntityManagerJUnitTestSuite("testCascadeMergeDetached"));
suite.addTest(new EntityManagerJUnitTestSuite("testPrimaryKeyUpdatePKFK"));
suite.addTest(new EntityManagerJUnitTestSuite("testPrimaryKeyUpdateSameValue"));
suite.addTest(new EntityManagerJUnitTestSuite("testPrimaryKeyUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testRemoveNull"));
suite.addTest(new EntityManagerJUnitTestSuite("testContainsNull"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistNull"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNull"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeRemovedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeDetachedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testSerializedLazy"));
suite.addTest(new EntityManagerJUnitTestSuite("testCloneable"));
suite.addTest(new EntityManagerJUnitTestSuite("testLeftJoinOneToOneQuery"));
suite.addTest(new EntityManagerJUnitTestSuite("testNullifyAddressIn"));
suite.addTest(new EntityManagerJUnitTestSuite("testQueryOnClosedEM"));
suite.addTest(new EntityManagerJUnitTestSuite("testIncorrectBatchQueryHint"));
suite.addTest(new EntityManagerJUnitTestSuite("testFetchQueryHint"));
suite.addTest(new EntityManagerJUnitTestSuite("testBatchQueryHint"));
suite.addTest(new EntityManagerJUnitTestSuite("testQueryHints"));
suite.addTest(new EntityManagerJUnitTestSuite("testParallelMultipleFactories"));
suite.addTest(new EntityManagerJUnitTestSuite("testMultipleFactories"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistenceProperties"));
suite.addTest(new EntityManagerJUnitTestSuite("testBeginTransactionCloseCommitTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testBeginTransactionClose"));
suite.addTest(new EntityManagerJUnitTestSuite("testClose"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistOnNonEntity"));
suite.addTest(new EntityManagerJUnitTestSuite("testWRITELock"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_UpdateAll_Refresh_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_UpdateAll_Refresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_UpdateAll_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_UpdateAll"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_CustomUpdate_Refresh_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_CustomUpdate_Refresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_CustomUpdate_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_CustomUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_UpdateAll_Refresh_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_UpdateAll_Refresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_UpdateAll_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_UpdateAll"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_CustomUpdate_Refresh_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_CustomUpdate_Refresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_CustomUpdate_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_CustomUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearInTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearWithFlush"));
suite.addTest(new EntityManagerJUnitTestSuite("testClear"));
suite.addTest(new EntityManagerJUnitTestSuite("testCheckVersionOnMerge"));
suite.addTest(new EntityManagerJUnitTestSuite("testFindWithNullPk"));
suite.addTest(new EntityManagerJUnitTestSuite("testFindWithWrongTypePk"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistManagedNoException"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistManagedException"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistRemoved"));
suite.addTest(new EntityManagerJUnitTestSuite("testREADLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testIgnoreRemovedObjectsOnDatabaseSync"));
suite.addTest(new EntityManagerJUnitTestSuite("testIdentityOutsideTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testIdentityInsideTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testDatabaseSyncNewObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testSetRollbackOnly"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmCommitQueryAuto"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmCommit"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmCommitQueryCommit"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmAutoQueryAuto"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmAuto"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmAutoQueryCommit"));
suite.addTest(new EntityManagerJUnitTestSuite("testCacheUsage"));
suite.addTest(new EntityManagerJUnitTestSuite("testSequencePreallocationUsingCallbackTest"));
suite.addTest(new EntityManagerJUnitTestSuite("testForceSQLExceptionFor219097"));
suite.addTest(new EntityManagerJUnitTestSuite("testRefreshInvalidateDeletedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearWithFlush2"));
suite.addTest(new EntityManagerJUnitTestSuite("testEMFWrapValidationException"));
suite.addTest(new EntityManagerJUnitTestSuite("testEMDefaultTxType"));
suite.addTest(new EntityManagerJUnitTestSuite("testCloneable"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNewObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNewObject2"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNewObject3_UseSequencing"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNewObject3_DontUseSequencing"));
suite.addTest(new EntityManagerJUnitTestSuite("testCreateEntityManagerFactory"));
suite.addTest(new EntityManagerJUnitTestSuite("testCreateEntityManagerFactory2"));
suite.addTest(new EntityManagerJUnitTestSuite("testPessimisticLockHintStartsTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testManyToOnePersistCascadeOnFlush"));
suite.addTest(new EntityManagerJUnitTestSuite("testDiscoverNewReferencedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testManagedEmployeesMassInsertUseSequencing"));
suite.addTest(new EntityManagerJUnitTestSuite("testManagedEmployeesMassInsertDoNotUseSequencing"));
suite.addTest(new EntityManagerJUnitTestSuite("testManagedEmployeesMassMergeUseSequencing"));
suite.addTest(new EntityManagerJUnitTestSuite("testManagedEmployeesMassMergeDoNotUseSequencing"));
suite.addTest(new EntityManagerJUnitTestSuite("testBulkDeleteThenMerge"));
suite.addTest(new EntityManagerJUnitTestSuite("testNativeSequences"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetReference"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetReferenceUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetReferenceUsedInUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testClassInstanceConverter"));
return suite;
}
public void testSetup() {
new AdvancedTableCreator().replaceTables(JUnitTestCase.getServerSession());
}
/**
* Bug# 219097
* This test would normally pass, but we purposely invoke an SQLException on the firstName field
* so that we can test that an UnsupportedOperationException is not thrown as part of the
* roll-back exception handling code for an SQLException.
*/
public void testForceSQLExceptionFor219097() {
boolean exceptionThrown = false;
// Set an immutable properties Map on the em to test addition of properties to this map in the roll-back exception handler
EntityManager em = createEntityManager(Collections.emptyMap());
beginTransaction(em);
Employee emp = new Employee();
/*
* Provoke an SQL exception by setting a field with a value greater than field length.
* 1 - This test will not throw an exception without the Collections$emptyMap() set on the EntityhManager
* or the exceeded field length set on firstName.
* 2 - This test will throw an UnsupportedOperationException if the map on AbstractSession is not cloned when immutable - bug fix
* 3 - This test will throw an SQLException when operating normally due to the field length exception
*/
StringBuffer firstName = new StringBuffer("firstName_maxfieldLength_");
for(int i=0; i<MAX_FIRST_NAME_FIELD_LENGTH + 100; i++) {
firstName.append("0");
}
emp.setFirstName(firstName.toString());
em.persist(emp);
try {
commitTransaction(em);
} catch (Exception e) {
Throwable cause = e.getCause();
if(cause instanceof UnsupportedOperationException) {
exceptionThrown = true;
fail(cause.getClass() + " Exception was thrown in error instead of expected SQLException.");
} else {
exceptionThrown = true;
}
} finally {
closeEntityManager(em);
}
if(!exceptionThrown) {
fail("An expected SQLException was not thrown.");
}
}
// JUnit framework will automatically execute all methods starting with test...
public void testRefreshNotManaged() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("testRefreshNotManaged");
try {
em.refresh(emp);
fail("entityManager.refresh(notManagedObject) didn't throw exception");
} catch (IllegalArgumentException illegalArgumentException) {
// expected behavior
} catch (Exception exception ) {
fail("entityManager.refresh(notManagedObject) threw a wrong exception: " + exception.getMessage());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testRefreshRemoved() {
// find an existing or create a new Employee
String firstName = "testRefreshRemoved";
Employee emp;
EntityManager em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
if(!result.isEmpty()) {
emp = (Employee)result.get(0);
} else {
emp = new Employee();
emp.setFirstName(firstName);
// persist the Employee
try{
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
try{
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
// delete the Employee from the db
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
// refresh the Employee - should fail with EntityNotFoundException
em.refresh(emp);
fail("entityManager.refresh(removedObject) didn't throw exception");
} catch (EntityNotFoundException entityNotFoundException) {
rollbackTransaction(em);
// expected behavior
} catch (Exception exception ) {
rollbackTransaction(em);
fail("entityManager.refresh(removedObject) threw a wrong exception: " + exception.getMessage());
}
}
//Bug5955326, refresh should invalidate the shared cached object that was deleted outside of JPA.
public void testRefreshInvalidateDeletedObject(){
EntityManager em1 = createEntityManager();
EntityManager em2 = createEntityManager();
Address address = new Address();
address.setCity("Kanata");
// persist the Address
try {
//Ensure shared cache being used.
boolean isIsolated = ((EntityManagerImpl)em1).getServerSession().getClassDescriptorForAlias("Address").isIsolated();
if(isIsolated){
throw new Exception("This test should use non-isolated cache setting class descriptor for test.");
}
em1.getTransaction().begin();
em1.persist(address);
em1.getTransaction().commit();
//Cache the Address
em1 = createEntityManager();
em1.getTransaction().begin();
address = em1.find(Address.class, address.getId());
// Delete Address outside of JPA so that the object still stored in the cache.
em2 = createEntityManager();
em2.getTransaction().begin();
em2.createNativeQuery("DELETE FROM CMP3_ADDRESS where address_id = ?1").setParameter(1, address.getId()).executeUpdate();
em2.getTransaction().commit();
//Call refresh to invalidate the object
em1.refresh(address);
}catch (Exception e){
//expected exception
} finally{
if (em1.getTransaction().isActive()) {
em1.getTransaction().rollback();
}
}
//Verify
em1.getTransaction().begin();
address=em1.find(Address.class, address.getId());
em1.getTransaction().commit();
assertNull("The deleted object is still valid in share cache", address);
}
public void testCacheUsage() {
EntityManager em = createEntityManager();
Employee emp = new Employee();
emp.setFirstName("Mark");
// persist the Employee
try {
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
}
clearCache();
// Create new entity manager to avoid extended uow of work cache hits.
em = createEntityManager();
beginTransaction(em);
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e").getResultList();
commitTransaction(em);
Object obj = ((org.eclipse.persistence.jpa.JpaEntityManager)em).getServerSession().getIdentityMapAccessor().getFromIdentityMap(result.get(0));
assertTrue("Failed to load the object into the shared cache when there were no changes in the UOW", obj != null);
try{
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
commitTransaction(em);
} catch (RuntimeException exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw exception;
}
}
public void testContainsRemoved() {
// find an existing or create a new Employee
String firstName = "testContainsRemoved";
Employee emp;
EntityManager em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
if(!result.isEmpty()) {
emp = (Employee)result.get(0);
} else {
emp = new Employee();
emp.setFirstName(firstName);
// persist the Employee
try{
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
boolean containsRemoved = true;
try{
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
containsRemoved = em.contains(emp);
commitTransaction(em);
}catch (RuntimeException t){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw t;
}
assertFalse("entityManager.contains(removedObject)==true ", containsRemoved);
}
public void testFlushModeEmAutoQueryCommit() {
internalTestFlushMode(FlushModeType.AUTO, FlushModeType.COMMIT);
}
public void testFlushModeEmAuto() {
internalTestFlushMode(FlushModeType.AUTO, null);
}
public void testFlushModeEmAutoQueryAuto() {
internalTestFlushMode(FlushModeType.AUTO, FlushModeType.AUTO);
}
public void testFlushModeEmCommitQueryCommit() {
internalTestFlushMode(FlushModeType.COMMIT, FlushModeType.COMMIT);
}
public void testFlushModeEmCommit() {
internalTestFlushMode(FlushModeType.COMMIT, null);
}
public void testFlushModeEmCommitQueryAuto() {
internalTestFlushMode(FlushModeType.COMMIT, FlushModeType.AUTO);
}
public void internalTestFlushMode(FlushModeType emFlushMode, FlushModeType queryFlushMode) {
// create a new Employee
String firstName = "testFlushMode";
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
try{
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
clearCache();
Employee emp;
FlushModeType emFlushModeOriginal = em.getFlushMode();
// create a new Employee
emp = new Employee();
emp.setFirstName(firstName);
boolean flushed = true;
Employee result = null;
try{
beginTransaction(em);
Query query = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName like '"+firstName+"'");
if(queryFlushMode != null) {
query.setFlushMode(queryFlushMode);
}
emFlushModeOriginal = em.getFlushMode();
em.setFlushMode(emFlushMode);
em.persist(emp);
result = (Employee) query.getSingleResult();
} catch (javax.persistence.NoResultException ex) {
// failed to flush to database
flushed = false;
} finally {
rollbackTransaction(em);
em.setFlushMode(emFlushModeOriginal);
}
boolean shouldHaveFlushed;
if(queryFlushMode != null) {
shouldHaveFlushed = queryFlushMode == FlushModeType.AUTO;
} else {
shouldHaveFlushed = emFlushMode == FlushModeType.AUTO;
}
if(shouldHaveFlushed != flushed) {
if(flushed) {
fail("Flushed to database");
} else {
fail("Failed to flush to database");
}
}
}
public void testFlushModeOnUpdateQuery() {
// find an existing or create a new Employee
String firstName = "testFlushModeOnUpdateQuery";
Employee emp;
EntityManager em = createEntityManager();
emp = new Employee();
emp.setFirstName(firstName);
try{
try{
beginTransaction(em);
Query readQuery = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.phoneNumbers IS EMPTY and e.firstName like '"+firstName+"'");
Query updateQuery = em.createQuery("UPDATE Employee e set e.salary = 100 where e.firstName like '" + firstName + "'");
updateQuery.setFlushMode(FlushModeType.AUTO);
em.persist(emp);
updateQuery.executeUpdate();
Employee result = (Employee) readQuery.getSingleResult();
}catch (javax.persistence.EntityNotFoundException ex){
rollbackTransaction(em);
fail("Failed to flush to database");
}
em.refresh(emp);
assertTrue("Failed to flush to Database", emp.getSalary() == 100);
em.remove(emp);
commitTransaction(em);
}catch(RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
public void testSetRollbackOnly(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Bob");
emp.setLastName("Fisher");
em.persist(emp);
emp = new Employee();
emp.setFirstName("Anthony");
emp.setLastName("Walace");
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
List result = em.createQuery("SELECT e FROM Employee e").getResultList();
Employee emp = (Employee)result.get(0);
Employee emp2 = (Employee)result.get(1);
String newName = ""+System.currentTimeMillis();
emp2.setFirstName(newName);
em.flush();
emp2.setLastName("Whatever");
emp2.setVersion(0);
try{
em.flush();
}catch (Exception ex){
em.clear(); //prevent the flush again
String eName = (String)em.createQuery("SELECT e.firstName FROM Employee e where e.id = " + emp2.getId()).getSingleResult();
assertTrue("Failed to keep txn open for set RollbackOnly", eName.equals(newName));
}
try{
if (isOnServer()) {
assertTrue("Failed to mark txn rollback only", !isTransactionActive(em));
} else {
assertTrue("Failed to mark txn rollback only", em.getTransaction().getRollbackOnly());
}
} finally{
try{
commitTransaction(em);
}catch (RollbackException ex){
return;
}catch (RuntimeException ex){
if (ex.getCause() instanceof javax.transaction.RollbackException) {
return;
}
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
fail("Failed to throw rollback exception");
}
public void testSubString() {
// find an existing or create a new Employee
String firstName = "testSubString";
Employee emp;
EntityManager em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
if(!result.isEmpty()) {
emp = (Employee)result.get(0);
} else {
emp = new Employee();
emp.setFirstName(firstName);
// persist the Employee
try{
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
int firstIndex = 1;
int lastIndex = firstName.length();
List employees = em.createQuery("SELECT object(e) FROM Employee e where e.firstName = substring(:p1, :p2, :p3)").
setParameter("p1", firstName).
setParameter("p2", new Integer(firstIndex)).
setParameter("p3", new Integer(lastIndex)).
getResultList();
// clean up
try{
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
assertFalse("employees.isEmpty()==true ", employees.isEmpty());
}
public void testDatabaseSyncNewObject() {
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Project project = new LargeProject();
em.persist(project);
project.setName("Blah");
project.setTeamLeader(new Employee());
project.getTeamLeader().addProject(project);
em.flush();
}catch (IllegalStateException ex){
rollbackTransaction(em);
return;
}
fail("Failed to throw illegal argument when finding unregistered new object cascading on database sync");
}
public void testTransactionRequired() {
String firstName = "testTransactionRequired";
Employee emp = new Employee();
emp.setFirstName(firstName);
String noException = "";
String wrongException = "";
try {
createEntityManager().flush();
noException = noException + " flush;";
} catch (TransactionRequiredException transactionRequiredException) {
// expected behavior
} catch (RuntimeException ex) {
wrongException = wrongException + " flush: " + ex.getMessage() +";";
}
String errorMsg = "";
if(noException.length() > 0) {
errorMsg = "No exception thrown: " + noException;
}
if(wrongException.length() > 0) {
if(errorMsg.length() > 0) {
errorMsg = errorMsg + " ";
}
errorMsg = errorMsg + "Wrong exception thrown: " + wrongException;
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
public void testIdentityInsideTransaction() {
EntityManager em = createEntityManager();
beginTransaction(em);
Query query = em.createQuery("SELECT e FROM PhoneNumber e");
List<PhoneNumber> phoneNumbers = query.getResultList();
for (PhoneNumber phoneNumber : phoneNumbers) {
Employee emp = phoneNumber.getOwner();
Collection<PhoneNumber> numbers = emp.getPhoneNumbers();
assertTrue(numbers.contains(phoneNumber));
}
commitTransaction(em);
closeEntityManager(em);
}
public void testIdentityOutsideTransaction() {
EntityManager em = createEntityManager();
Query query = em.createQuery("SELECT e FROM PhoneNumber e");
List<PhoneNumber> phoneNumbers = query.getResultList();
for (PhoneNumber phoneNumber : phoneNumbers) {
Employee emp = phoneNumber.getOwner();
Collection<PhoneNumber> numbers = emp.getPhoneNumbers();
assertTrue(numbers.contains(phoneNumber));
}
closeEntityManager(em);
}
public void testIgnoreRemovedObjectsOnDatabaseSync() {
EntityManager em = createEntityManager();
beginTransaction(em);
Query phoneQuery = em.createQuery("Select p from PhoneNumber p where p.owner.lastName like 'Dow%'");
Query empQuery = em.createQuery("Select e FROM Employee e where e.lastName like 'Dow%'");
//--setup
try{
Employee emp = new Employee();
emp.setLastName("Dowder");
PhoneNumber phone = new PhoneNumber("work", "613", "5555555");
emp.addPhoneNumber(phone);
phone = new PhoneNumber("home", "613", "4444444");
emp.addPhoneNumber(phone);
Address address = new Address("SomeStreet", "somecity", "province", "country", "postalcode");
emp.setAddress(address);
em.persist(emp);
em.flush();
emp = new Employee();
emp.setLastName("Dows");
phone = new PhoneNumber("work", "613", "2222222");
emp.addPhoneNumber(phone);
phone = new PhoneNumber("home", "613", "1111111");
emp.addPhoneNumber(phone);
address = new Address("street1", "city1", "province1", "country1", "postalcode1");
emp.setAddress(address);
em.persist(emp);
em.flush();
//--end setup
List<Employee> emps = empQuery.getResultList();
List phones = phoneQuery.getResultList();
for (Iterator iterator = phones.iterator(); iterator.hasNext();){
em.remove(iterator.next());
}
em.flush();
for (Iterator<Employee> iterator = emps.iterator(); iterator.hasNext();){
em.remove(iterator.next());
}
}catch (RuntimeException ex){
rollbackTransaction(em);
throw ex;
}
try{
em.flush();
}catch (IllegalStateException ex){
rollbackTransaction(em);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
try{
phoneQuery = em.createQuery("Select p from PhoneNumber p where p.owner.lastName like 'Dow%'");
empQuery = em.createQuery("Select e from Employee e where e.lastName like 'Dow%'");
List<Employee> emps = empQuery.getResultList();
List phones = phoneQuery.getResultList();
for (Iterator iterator = phones.iterator(); iterator.hasNext();){
em.remove(iterator.next());
}
for (Iterator<Employee> iterator = emps.iterator(); iterator.hasNext();){
em.remove(iterator.next());
}
commitTransaction(em);
}catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
fail("Failed to ignore the removedobject when cascading on database sync");
}
commitTransaction(em);
}
public void testREADLock(){
// Cannot create parallel entity managers in the server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = null;
try{
employee = new Employee();
employee.setFirstName("Mark");
employee.setLastName("Madsen");
em.persist(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
EntityManager em2 = createEntityManager();
Exception optimisticLockException = null;
beginTransaction(em);
try{
employee = em.find(Employee.class, employee.getId());
em.lock(employee, LockModeType.READ);
em2.getTransaction().begin();
try{
Employee employee2 = em2.find(Employee.class, employee.getId());
employee2.setFirstName("Michael");
em2.getTransaction().commit();
em2.close();
}catch (RuntimeException ex){
em2.getTransaction().rollback();
em2.close();
throw ex;
}
try{
em.flush();
} catch (PersistenceException exception) {
if (exception instanceof OptimisticLockException){
optimisticLockException = exception;
}else{
throw exception;
}
}
rollbackTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
beginTransaction(em);
try{
employee = em.find(Employee.class, employee.getId());
em.remove(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
if (optimisticLockException == null){
fail("Proper exception not thrown when EntityManager.lock(object, READ) is used.");
}
}
// test for bug 4676587:
// CTS: AFTER A REMOVE THEN A PERSIST ON THE SAME ENTITY, CONTAINS RETURNS FALSE
// The test performs persist, remove, persist sequence on a single object
// in different "flavours":
// doTransaction - the first persist happens in a separate transaction;
// doFirstFlush - perform flush after the first persist;
// doSecondFlush - perform flush after the remove;
// doThirdFlush - perform flush after the second persist;
// doRollback - rollbacks transaction that contains remove and the second persist.
public void testPersistRemoved() {
// create an Employee
String firstName = "testPesistRemoved";
Employee emp = new Employee();
emp.setFirstName(firstName);
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
String errorMsg = "";
for (int i=0; i < 32; i++) {
int j = i;
boolean doRollback = j % 2 == 0;
j = j/2;
boolean doThirdFlush = j % 2 == 0;
j = j/2;
boolean doSecondFlush = j % 2 == 0;
j = j/2;
boolean doFirstFlush = j % 2 == 0;
j = j/2;
boolean doTransaction = j % 2 == 0;
if(doTransaction && doFirstFlush) {
continue;
}
String msg = "";
if(doTransaction) {
msg = "Transaction ";
}
if(doFirstFlush) {
msg = msg + "firstFlush ";
}
if(doSecondFlush) {
msg = msg + "secondFlush ";
}
if(doThirdFlush) {
msg = msg + "thirdFlush ";
}
if(doRollback) {
msg = msg + "RolledBack ";
}
String localErrorMsg = msg;
boolean exceptionWasThrown = false;
Integer empId = null;
beginTransaction(em);
try {
emp = new Employee();
emp.setFirstName(firstName);
// persist the Employee
em.persist(emp);
if(doTransaction) {
commitTransaction(em);
empId = emp.getId();
beginTransaction(em);
} else {
if(doFirstFlush) {
em.flush();
}
}
if(doTransaction) {
emp = em.find(Employee.class, empId);
}
// remove the Employee
em.remove(emp);
if(doSecondFlush) {
em.flush();
}
// persist the Employee
em.persist(emp);
if(doThirdFlush) {
em.flush();
}
} catch (RuntimeException ex) {
rollbackTransaction(em);
localErrorMsg = localErrorMsg + " " + ex.getMessage() + ";";
exceptionWasThrown = true;
}
boolean employeeShouldExist = doTransaction || !doRollback;
boolean employeeExists = false;
try{
if(!exceptionWasThrown) {
if(doRollback) {
rollbackTransaction(em);
} else {
commitTransaction(em);
}
if(doTransaction) {
Employee employeeReadFromCache = em.find(Employee.class, empId);
if(employeeReadFromCache == null) {
localErrorMsg = localErrorMsg + " employeeReadFromCache == null;";
}
}
List resultList = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
employeeExists = resultList.size() > 0;
if(employeeShouldExist) {
if(resultList.size() > 1) {
localErrorMsg = localErrorMsg + " resultList.size() > 1";
}
if(!employeeExists) {
localErrorMsg = localErrorMsg + " employeeReadFromDB == null;";
}
} else {
if(resultList.size() > 0) {
localErrorMsg = localErrorMsg + " employeeReadFromDB != null;";
}
}
}
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
// clean up
if(employeeExists || exceptionWasThrown) {
em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
rollbackTransaction(em);
throw ex;
}
}
if(!msg.equals(localErrorMsg)) {
errorMsg = errorMsg + "i="+Integer.toString(i)+": "+ localErrorMsg + " ";
}
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
public void testPersistManagedException(){
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
em.persist(emp);
em.flush();
Integer id = emp.getId();
emp = new Employee();
emp.setId(id);
boolean caughtException = false;
try{
em.persist(emp);
} catch (EntityExistsException e){
caughtException = true;
}
emp = em.find(Employee.class, id);
em.remove(emp);
rollbackTransaction(em);
assertTrue("EntityExistsException was not thrown for an existing Employee.", caughtException);
}
public void testPersistManagedNoException(){
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
em.persist(emp);
em.flush();
Integer id = emp.getId();
Address address = new Address();
emp.setAddress(address);
boolean caughtException = false;
try{
em.persist(emp);
} catch (EntityExistsException e){
caughtException = true;
}
emp = em.find(Employee.class, id);
em.remove(emp);
commitTransaction(em);
assertFalse("EntityExistsException was thrown for a registered Employee.", caughtException);
}
// test for bug 4676587:
// CTS: AFTER A REMOVE THEN A PERSIST ON THE SAME ENTITY, CONTAINS RETURNS FALSE
public void testRemoveFlushPersistContains() {
// create an Employee
String firstName = "testRemoveFlushPersistContains";
Employee emp = new Employee();
emp.setFirstName(firstName);
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// persist
beginTransaction(em);
try{
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// remove, flush, persist, contains
boolean contains = false;
beginTransaction(em);
try{
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
em.flush();
em.persist(emp);
contains = em.contains(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// clean up
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
assertTrue("contains==false", contains);
}
// test for bug 4742161:
// CTS: OBJECTS REMOVED AND THEN FLUSHED ARE RETURNED BY QUERIES AFTER THE FLUSH
public void testRemoveFlushFind() {
// create an Employee
String firstName = "testRemoveFlushFind";
Employee emp = new Employee();
emp.setFirstName(firstName);
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// persist
beginTransaction(em);
try{
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// remove, flush, persist, contains
boolean foundAfterFlush = true;
boolean foundBeforeFlush = true;
beginTransaction(em);
try{
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
Employee empFound = em.find(Employee.class, emp.getId());
foundBeforeFlush = empFound != null;
em.flush();
empFound = em.find(Employee.class, emp.getId());
foundAfterFlush = empFound != null;
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// clean up
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
assertFalse("removed object found", foundBeforeFlush);
assertFalse("removed object found after flush", foundAfterFlush);
}
// test for bug 4681287:
// CTS: EXCEPTION EXPECTED ON FIND() IF PK PASSED IN != ATTRIBUTE TYPE
public void testFindWithWrongTypePk() {
EntityManager em = createEntityManager();
try {
em.find(Employee.class, "1");
} catch (IllegalArgumentException ilEx) {
return;
} catch (Exception ex) {
fail("Wrong exception thrown: " + ex.getMessage());
return;
}finally{
closeEntityManager(em);
}
fail("No exception thrown");
}
public void testFindWithNullPk() {
EntityManager em = createEntityManager();
try {
em.find(Employee.class, null);
} catch (IllegalArgumentException iae) {
return;
} catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally{
closeEntityManager(em);
}
fail("No exception thrown when null PK used in find operation.");
}
public void testCheckVersionOnMerge() {
Employee employee = new Employee();
employee.setFirstName("Marc");
EntityManager em = createEntityManager();
try{
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
em.clear();
beginTransaction(em);
Employee empClone = em.find(Employee.class, employee.getId());
empClone.setFirstName("Guy");
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
fail("Exception caught during test setup " + ex);
}
try {
beginTransaction(em);
em.merge(employee);
commitTransaction(em);
} catch (OptimisticLockException e) {
rollbackTransaction(em);
closeEntityManager(em);
return;
} catch (RuntimeException ex) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
fail("Wrong exception thrown: " + ex.getMessage());
}
fail("No exception thrown");
}
public void testClear(){
Employee employee = new Employee();
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.persist(employee);
commitTransaction(em);
em.clear();
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
boolean cleared = !em.contains(employee);
closeEntityManager(em);
assertTrue("EntityManager not properly cleared", cleared);
}
public void testClearWithFlush(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Douglas");
emp.setLastName("McRae");
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
EntityManager localEm = createEntityManager();
localEm.getTransaction().begin();
Employee emp = null;
String originalName = "";
boolean cleared, updated, reset = false;
try{
Query query = localEm.createQuery("Select e from Employee e where e.firstName is not null");
emp = (Employee)query.getResultList().get(0);
originalName = emp.getFirstName();
emp.setFirstName("Bobster");
localEm.flush();
localEm.clear();
//this test is testing the cache not the database
localEm.getTransaction().commit();
cleared = !localEm.contains(emp);
emp = localEm.find(Employee.class, emp.getId());
updated = emp.getFirstName().equals("Bobster");
localEm.close();
}catch (RuntimeException ex){
localEm.getTransaction().rollback();
localEm.close();
throw ex;
}finally{
//now clean up
localEm = createEntityManager();
localEm.getTransaction().begin();
emp = localEm.find(Employee.class, emp.getId());
emp.setFirstName(originalName);
localEm.getTransaction().commit();
emp = localEm.find(Employee.class, emp.getId());
reset = emp.getFirstName().equals(originalName);
localEm.close();
}
assertTrue("EntityManager not properly cleared", cleared);
assertTrue("flushed data not merged", updated);
assertTrue("unable to reset", reset);
}
// gf3596: transactions never release memory until commit, so JVM eventually crashes
// The test verifies that there's no stale data read after transaction.
// Because there were no TopLinkProperties.FLUSH_CLEAR_CACHE property passed
// while creating either EM or EMF the tested behavior corresponds to
// the default property value FlushClearCache.DropInvalidate.
// Note that the same test would pass with FlushClearCache.Merge
// (in that case all changes are merges into the shared cache after transaction committed),
// but the test would fail with FlushClearCache.Drop - that mode just drops em cache
// without doing any invalidation of the shared cache.
public void testClearWithFlush2() {
String firstName = "testClearWithFlush2";
// setup
// create employee and manager - and then remove them from the shared cache
EntityManager em = createEntityManager();
int employee_1_NotInCache_id = 0;
int employee_2_NotInCache_id = 0;
int manager_NotInCache_id = 0;
beginTransaction(em);
try {
Employee employee_1_NotInCache = new Employee();
employee_1_NotInCache.setFirstName(firstName);
employee_1_NotInCache.setLastName("Employee_1_NotInCache");
Employee employee_2_NotInCache = new Employee();
employee_2_NotInCache.setFirstName(firstName);
employee_2_NotInCache.setLastName("Employee_2_NotInCache");
Employee manager_NotInCache = new Employee();
manager_NotInCache.setFirstName(firstName);
manager_NotInCache.setLastName("Manager_NotInCache");
// employee_1 is manager, employee_2 is not
manager_NotInCache.addManagedEmployee(employee_1_NotInCache);
// persist
em.persist(manager_NotInCache);
em.persist(employee_1_NotInCache);
em.persist(employee_2_NotInCache);
commitTransaction(em);
employee_1_NotInCache_id = employee_1_NotInCache.getId();
employee_2_NotInCache_id = employee_2_NotInCache.getId();
manager_NotInCache_id = manager_NotInCache.getId();
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// remove both manager_NotInCache and employee_NotInCache from the shared cache
clearCache();
// setup
// create employee and manager - and keep them in the shared cache
em = createEntityManager();
int employee_1_InCache_id = 0;
int employee_2_InCache_id = 0;
int manager_InCache_id = 0;
beginTransaction(em);
try {
Employee employee_1_InCache = new Employee();
employee_1_InCache.setFirstName(firstName);
employee_1_InCache.setLastName("Employee_1_InCache");
Employee employee_2_InCache = new Employee();
employee_2_InCache.setFirstName(firstName);
employee_2_InCache.setLastName("Employee_2_InCache");
Employee manager_InCache = new Employee();
manager_InCache.setFirstName(firstName);
manager_InCache.setLastName("Manager_InCache");
// employee_1 is manager, employee_2 is not
manager_InCache.addManagedEmployee(employee_1_InCache);
// persist
em.persist(manager_InCache);
em.persist(employee_1_InCache);
em.persist(employee_2_InCache);
commitTransaction(em);
employee_1_InCache_id = employee_1_InCache.getId();
employee_2_InCache_id = employee_2_InCache.getId();
manager_InCache_id = manager_InCache.getId();
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// test
// create new employee and manager, change existing ones, flush, clear
em = createEntityManager();
int employee_1_New_id = 0;
int employee_2_New_id = 0;
int employee_3_New_id = 0;
int employee_4_New_id = 0;
int manager_New_id = 0;
beginTransaction(em);
try {
Employee employee_1_New = new Employee();
employee_1_New.setFirstName(firstName);
employee_1_New.setLastName("Employee_1_New");
em.persist(employee_1_New);
employee_1_New_id = employee_1_New.getId();
Employee employee_2_New = new Employee();
employee_2_New.setFirstName(firstName);
employee_2_New.setLastName("Employee_2_New");
em.persist(employee_2_New);
employee_2_New_id = employee_2_New.getId();
Employee employee_3_New = new Employee();
employee_3_New.setFirstName(firstName);
employee_3_New.setLastName("Employee_3_New");
em.persist(employee_3_New);
employee_3_New_id = employee_3_New.getId();
Employee employee_4_New = new Employee();
employee_4_New.setFirstName(firstName);
employee_4_New.setLastName("Employee_4_New");
em.persist(employee_4_New);
employee_4_New_id = employee_4_New.getId();
Employee manager_New = new Employee();
manager_New.setFirstName(firstName);
manager_New.setLastName("Manager_New");
em.persist(manager_New);
manager_New_id = manager_New.getId();
// find and update all objects created during setup
Employee employee_1_NotInCache = em.find(Employee.class, employee_1_NotInCache_id);
employee_1_NotInCache.setLastName(employee_1_NotInCache.getLastName() + "_Updated");
Employee employee_2_NotInCache = em.find(Employee.class, employee_2_NotInCache_id);
employee_2_NotInCache.setLastName(employee_2_NotInCache.getLastName() + "_Updated");
Employee manager_NotInCache = em.find(Employee.class, manager_NotInCache_id);
manager_NotInCache.setLastName(manager_NotInCache.getLastName() + "_Updated");
Employee employee_1_InCache = em.find(Employee.class, employee_1_InCache_id);
employee_1_InCache.setLastName(employee_1_InCache.getLastName() + "_Updated");
Employee employee_2_InCache = em.find(Employee.class, employee_2_InCache_id);
employee_2_InCache.setLastName(employee_2_InCache.getLastName() + "_Updated");
Employee manager_InCache = em.find(Employee.class, manager_InCache_id);
manager_InCache.setLastName(manager_InCache.getLastName() + "_Updated");
manager_NotInCache.addManagedEmployee(employee_1_New);
manager_InCache.addManagedEmployee(employee_2_New);
manager_New.addManagedEmployee(employee_3_New);
manager_New.addManagedEmployee(employee_2_NotInCache);
manager_New.addManagedEmployee(employee_2_InCache);
// flush
em.flush();
// clear and commit
em.clear();
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// verify
String errorMsg = "";
em = createEntityManager();
// find and verify all objects created during setup and test
Employee manager_NotInCache = em.find(Employee.class, manager_NotInCache_id);
if(!manager_NotInCache.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "manager_NotInCache lastName NOT updated; ";
}
Iterator it = manager_NotInCache.getManagedEmployees().iterator();
while(it.hasNext()) {
Employee emp = (Employee)it.next();
if(emp.getId() == employee_1_NotInCache_id) {
if(!emp.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "employee_1_NotInCache lastName NOT updated; ";
}
} else if(emp.getId() == employee_1_New_id) {
if(!emp.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "employee_1_New lastName wrong; ";
}
} else {
errorMsg = errorMsg + "manager_NotInCache has unexpected employee: lastName = " + emp.getLastName();
}
}
if(manager_NotInCache.getManagedEmployees().size() != 2) {
errorMsg = errorMsg + "manager_NotInCache.getManagedEmployees().size() != 2; size = " + manager_NotInCache.getManagedEmployees().size();
}
Employee manager_InCache = em.find(Employee.class, manager_InCache_id);
if(!manager_InCache.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "manager_InCache lastName NOT updated; ";
}
it = manager_InCache.getManagedEmployees().iterator();
while(it.hasNext()) {
Employee emp = (Employee)it.next();
if(emp.getId() == employee_1_InCache_id) {
if(!emp.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "employee_1_InCache lastName NOT updated; ";
}
} else if(emp.getId() == employee_2_New_id) {
if(!emp.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "employee_2_New lastName wrong; ";
}
} else {
errorMsg = errorMsg + "manager_InCache has unexpected employee: lastName = " + emp.getLastName();
}
}
if(manager_InCache.getManagedEmployees().size() != 2) {
errorMsg = errorMsg + "manager_InCache.getManagedEmployees().size() != 2; size = " + manager_InCache.getManagedEmployees().size();
}
Employee manager_New = em.find(Employee.class, manager_New_id);
if(!manager_New.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "manager_New lastName wrong; ";
}
it = manager_New.getManagedEmployees().iterator();
while(it.hasNext()) {
Employee emp = (Employee)it.next();
if(emp.getId() == employee_2_NotInCache_id) {
if(!emp.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "employee_2_NotInCache_id lastName NOT updated; ";
}
} else if(emp.getId() == employee_2_InCache_id) {
if(!emp.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "employee_2_InCache_id lastName NOT updated; ";
}
} else if(emp.getId() == employee_3_New_id) {
if(!emp.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "employee_3_New lastName wrong; ";
}
} else {
errorMsg = errorMsg + "manager_New has unexpected employee: lastName = " + emp.getLastName();
}
}
if(manager_New.getManagedEmployees().size() != 3) {
errorMsg = errorMsg + "manager_InCache.getManagedEmployees().size() != 3; size = " + manager_InCache.getManagedEmployees().size();
}
Employee employee_4_New = em.find(Employee.class, employee_4_New_id);
if(!employee_4_New.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "employee_4_New lastName wrong; ";
}
closeEntityManager(em);
// clean up
// remove all objects created during this test and clear the cache.
em = createEntityManager();
try {
beginTransaction(em);
List<Employee> list = em.createQuery("Select e from Employee e where e.firstName = '"+firstName+"'").getResultList();
Iterator<Employee> i = list.iterator();
while (i.hasNext()){
Employee e = i.next();
if (e.getManager() != null){
e.getManager().removeManagedEmployee(e);
e.setManager(null);
}
em.remove(e);
}
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
// ignore exception in clean up in case there's an error in test
if(errorMsg.length() == 0) {
throw ex;
}
}
clearCache();
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
/** ToDo: move these to a memory test suite.
// gf3596: transactions never release memory until commit, so JVM eventually crashes.
// Attempts to compare memory consumption between the two FlushClearCache modes.
// If the values changed to be big enough (in TopLink I tried nFlashes = 30 , nInsertsPerFlush = 10000)
// internalMassInsertFlushClear(FlushClearCache.Merge, 30, 10000) will run out of memory,
// but internalMassInsertFlushClear(null, 30, 10000) will still be ok.
public void testMassInsertFlushClear() {
int nFlushes = 20;
int nPersistsPerFlush = 50;
long[] defaultFreeMemoryDelta = internalMassInsertFlushClear(null, nFlushes, nPersistsPerFlush);
long[] mergeFreeMemoryDelta = internalMassInsertFlushClear(FlushClearCache.Merge, nFlushes, nPersistsPerFlush);
// disregard the flush if any of the two FreeMemoryDeltas is negative - clearly that's gc artefact.
int nEligibleFlushes = 0;
long diff = 0;
for(int nFlush = 0; nFlush < nFlushes; nFlush++) {
if(defaultFreeMemoryDelta[nFlush] >= 0 && mergeFreeMemoryDelta[nFlush] >= 0) {
nEligibleFlushes++;
diff = diff + mergeFreeMemoryDelta[nFlush] - defaultFreeMemoryDelta[nFlush];
}
}
long lowEstimateOfBytesPerObject = 200;
long diffPerObject = diff / (nEligibleFlushes * nPersistsPerFlush);
if(diffPerObject < lowEstimateOfBytesPerObject) {
fail("difference in freememory per object persisted " + diffPerObject + " is lower than lowEstimateOfBytesPerObject " + lowEstimateOfBytesPerObject);
}
}
// memory usage with different FlushClearCache modes.
protected long[] internalMassInsertFlushClear(String propValue, int nFlushes, int nPersistsPerFlush) {
// set logDebug to true to output the freeMemory values after each flush/clear
boolean logDebug = false;
String firstName = "testMassInsertFlushClear";
EntityManager em;
if(propValue == null) {
// default value FlushClearCache.DropInvalidate will be used
em = createEntityManager();
if(logDebug) {
System.out.println(FlushClearCache.DEFAULT);
}
} else {
HashMap map = new HashMap(1);
map.put(PersistenceUnitProperties.FLUSH_CLEAR_CACHE, propValue);
em = getEntityManagerFactory().createEntityManager(map);
if(logDebug) {
System.out.println(propValue);
}
}
// For enhance accuracy of memory measuring allocate everything first:
// make a first run and completely disregard its results - somehow
// that get freeMemory function to report more accurate results in the second run -
// which is the only one used to calculate results.
if(logDebug) {
System.out.println("The first run is ignored");
}
long freeMemoryOld;
long freeMemoryNew;
long[] freeMemoryDelta = new long[nFlushes];
beginTransaction(em);
try {
// Try to force garbage collection NOW.
System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();
freeMemoryOld = Runtime.getRuntime().freeMemory();
if(logDebug) {
System.out.println("initial freeMemory = " + freeMemoryOld);
}
for(int nFlush = 0; nFlush < nFlushes; nFlush++) {
for(int nPersist = 0; nPersist < nPersistsPerFlush; nPersist++) {
Employee emp = new Employee();
emp.setFirstName(firstName);
int nEmployee = nFlush * nPersistsPerFlush + nPersist;
emp.setLastName("lastName_" + Integer.toString(nEmployee));
em.persist(emp);
}
em.flush();
em.clear();
// Try to force garbage collection NOW.
System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();
freeMemoryNew = Runtime.getRuntime().freeMemory();
freeMemoryDelta[nFlush] = freeMemoryOld - freeMemoryNew;
freeMemoryOld = freeMemoryNew;
if(logDebug) {
System.out.println(nFlush +": after flush/clear freeMemory = " + freeMemoryNew);
}
}
} finally {
rollbackTransaction(em);
em = null;
}
if(logDebug) {
System.out.println("The second run");
}
// now allocate again - with gc and memory measuring
if(propValue == null) {
// default value FlushClearCache.DropInvalidate will be used
em = createEntityManager();
} else {
HashMap map = new HashMap(1);
map.put(PersistenceUnitProperties.FLUSH_CLEAR_CACHE, propValue);
em = getEntityManagerFactory().createEntityManager(map);
}
beginTransaction(em);
try {
// Try to force garbage collection NOW.
System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();
freeMemoryOld = Runtime.getRuntime().freeMemory();
if(logDebug) {
System.out.println("initial freeMemory = " + freeMemoryOld);
}
for(int nFlush = 0; nFlush < nFlushes; nFlush++) {
for(int nPersist = 0; nPersist < nPersistsPerFlush; nPersist++) {
Employee emp = new Employee();
emp.setFirstName(firstName);
int nEmployee = nFlush * nPersistsPerFlush + nPersist;
emp.setLastName("lastName_" + Integer.toString(nEmployee));
em.persist(emp);
}
em.flush();
em.clear();
// Try to force garbage collection NOW.
System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();
freeMemoryNew = Runtime.getRuntime().freeMemory();
freeMemoryDelta[nFlush] = freeMemoryOld - freeMemoryNew;
freeMemoryOld = freeMemoryNew;
if(logDebug) {
System.out.println(nFlush +": after flush/clear freeMemory = " + freeMemoryNew);
}
}
return freeMemoryDelta;
} finally {
rollbackTransaction(em);
}
}*/
public void testClearInTransaction(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Tommy");
emp.setLastName("Marsh");
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
Employee emp = null;
String originalName = "";
try {
Query query = em.createQuery("Select e FROM Employee e where e.firstName is not null");
emp = (Employee)query.getResultList().get(0);
originalName = emp.getFirstName();
emp.setFirstName("Bobster");
em.clear();
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
boolean cleared = !em.contains(emp);
emp = em.find(Employee.class, emp.getId());
closeEntityManager(em);
assertTrue("EntityManager not properly cleared", cleared);
assertTrue("Employee was updated although EM was cleared", emp.getFirstName().equals(originalName));
}
public void testExtendedPersistenceContext() {
// Extended persistence context are not supported in the server.
// TODO: make this test use an extended entity manager in the server by creating from the factory and joining transaction.
if (isOnServer()) {
return;
}
String firstName = "testExtendedPersistenceContext";
int originalSalary = 0;
Employee empNew = new Employee();
empNew.setFirstName(firstName);
empNew.setLastName("new");
empNew.setSalary(originalSalary);
Employee empToBeRemoved = new Employee();
empToBeRemoved.setFirstName(firstName);
empToBeRemoved.setLastName("toBeRemoved");
empToBeRemoved.setSalary(originalSalary);
Employee empToBeRefreshed = new Employee();
empToBeRefreshed.setFirstName(firstName);
empToBeRefreshed.setLastName("toBeRefreshed");
empToBeRefreshed.setSalary(originalSalary);
Employee empToBeMerged = new Employee();
empToBeMerged.setFirstName(firstName);
empToBeMerged.setLastName("toBeMerged");
empToBeMerged.setSalary(originalSalary);
// setup: make sure no Employee with the specified firstName exists and create the existing employees.
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
beginTransaction(em);
em.persist(empToBeRemoved);
em.persist(empToBeRefreshed);
em.persist(empToBeMerged);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
closeEntityManager(em);
clearCache();
// create entityManager with extended Persistence Context.
em = createEntityManager();
try {
// first test
// without starting transaction persist, remove, refresh, merge
em.persist(empNew);
Employee empToBeRemovedExtended = em.find(Employee.class, empToBeRemoved.getId());
em.remove(empToBeRemovedExtended);
Employee empToBeRefreshedExtended = em.find(Employee.class, empToBeRefreshed.getId());
int newSalary = 100;
// Use another EntityManager to alter empToBeRefreshed in the db
beginTransaction(em);
empToBeRefreshed = em.find(Employee.class, empToBeRefreshed.getId());
empToBeRefreshed.setSalary(newSalary);
commitTransaction(em);
// now refesh
em.refresh(empToBeRefreshedExtended);
Employee empToBeMergedExtended = em.find(Employee.class, empToBeMerged.getId());
// alter empToBeRefreshed
empToBeMerged.setSalary(newSalary);
// now merge
em.merge(empToBeMerged);
// begin and commit transaction
beginTransaction(em);
commitTransaction(em);
// verify objects are correct in the PersistenceContext after transaction
if(!em.contains(empNew)) {
fail("empNew gone from extended PersistenceContext after transaction committed");
}
if(em.contains(empToBeRemovedExtended)) {
fail("empToBeRemovedExtended still in extended PersistenceContext after transaction committed");
}
if(!em.contains(empToBeRefreshedExtended)) {
fail("empToBeRefreshedExtended gone from extended PersistenceContext after transaction committed");
} else if(empToBeRefreshedExtended.getSalary() != newSalary) {
fail("empToBeRefreshedExtended still has the original salary after transaction committed");
}
if(!em.contains(empToBeMergedExtended)) {
fail("empToBeMergedExtended gone from extended PersistenceContext after transaction committed");
} else if(empToBeMergedExtended.getSalary() != newSalary) {
fail("empToBeMergedExtended still has the original salary after transaction committed");
}
// verify objects are correct in the db after transaction
clearCache();
Employee empNewFound = em.find(Employee.class, empNew.getId());
if(empNewFound == null) {
fail("empNew not in the db after transaction committed");
}
Employee empToBeRemovedFound = em.find(Employee.class, empToBeRemoved.getId());
if(empToBeRemovedFound != null) {
fail("empToBeRemoved is still in the db after transaction committed");
}
Employee empToBeRefreshedFound = em.find(Employee.class, empToBeRefreshed.getId());
if(empToBeRefreshedFound == null) {
fail("empToBeRefreshed not in the db after transaction committed");
} else if(empToBeRefreshedFound.getSalary() != newSalary) {
fail("empToBeRefreshed still has the original salary in the db after transaction committed");
}
Employee empToBeMergedFound = em.find(Employee.class, empToBeMerged.getId());
if(empToBeMergedFound == null) {
fail("empToBeMerged not in the db after transaction committed");
} else if(empToBeMergedFound.getSalary() != newSalary) {
fail("empToBeMerged still has the original salary in the db after transaction committed");
}
// second test
// without starting transaction persist, remove, refresh, merge for the second time:
// now return to the original state of the objects:
// remove empNew, persist empToBeRemoved, set empToBeRefreshed and empToBeMerged the original salary.
em.persist(empToBeRemoved);
em.remove(empNew);
// Use another EntityManager to alter empToBeRefreshed in the db
beginTransaction(em);
empToBeRefreshed = em.find(Employee.class, empToBeRefreshed.getId());
empToBeRefreshed.setSalary(originalSalary);
commitTransaction(em);
// now refesh
em.refresh(empToBeRefreshedExtended);
// alter empToBeRefreshedFound - can't use empToBeRefreshed here because of its older version().
empToBeMergedFound.setSalary(originalSalary);
// now merge
em.merge(empToBeMergedFound);
// begin and commit the second transaction
beginTransaction(em);
commitTransaction(em);
// verify objects are correct in the PersistenceContext
if(em.contains(empNew)) {
fail("empNew not gone from extended PersistenceContext after the second transaction committed");
}
if(!em.contains(empToBeRemoved)) {
fail("empToBeRemoved is not in extended PersistenceContext after the second transaction committed");
}
if(!em.contains(empToBeRefreshedExtended)) {
fail("empToBeRefreshedExtended gone from extended PersistenceContext after the second transaction committed");
} else if(empToBeRefreshedExtended.getSalary() != originalSalary) {
fail("empToBeRefreshedExtended still doesn't have the original salary after the second transaction committed");
}
if(!em.contains(empToBeMergedExtended)) {
fail("empToBeMergedExtended gone from extended PersistenceContext after the second transaction committed");
} else if(empToBeMergedExtended.getSalary() != originalSalary) {
fail("empToBeMergedExtended doesn't have the original salary after the second transaction committed");
}
// verify objects are correct in the db
clearCache();
Employee empNewFound2 = em.find(Employee.class, empNew.getId());
if(empNewFound2 != null) {
fail("empNew still in the db after the second transaction committed");
}
Employee empToBeRemovedFound2 = em.find(Employee.class, empToBeRemoved.getId());
if(empToBeRemovedFound2 == null) {
fail("empToBeRemoved is not in the db after the second transaction committed");
}
Employee empToBeRefreshedFound2 = em.find(Employee.class, empToBeRefreshed.getId());
if(empToBeRefreshedFound2 == null) {
fail("empToBeRefreshed not in the db after the second transaction committed");
} else if(empToBeRefreshedFound2.getSalary() != originalSalary) {
fail("empToBeRefreshed doesn't have the original salary in the db after the second transaction committed");
}
Employee empToBeMergedFound2 = em.find(Employee.class, empToBeMerged.getId());
if(empToBeMergedFound2 == null) {
fail("empToBeMerged not in the db after the second transaction committed");
} else if(empToBeMergedFound2.getSalary() != originalSalary) {
fail("empToBeMerged doesn't have the original salary in the db after the second transaction committed");
}
// third test
// without starting transaction persist, remove, refresh, merge
// The same as the first test - but now we'll rollback.
// The objects should be detached.
beginTransaction(em);
em.persist(empNew);
em.remove(empToBeRemoved);
// Use another EntityManager to alter empToBeRefreshed in the db
EntityManager em2 = createEntityManager();
em2.getTransaction().begin();
try{
empToBeRefreshed = em2.find(Employee.class, empToBeRefreshed.getId());
empToBeRefreshed.setSalary(newSalary);
em2.getTransaction().commit();
}catch (RuntimeException ex){
if (em2.getTransaction().isActive()){
em2.getTransaction().rollback();
}
throw ex;
}finally{
em2.close();
}
// now refesh
em.refresh(empToBeRefreshedExtended);
// alter empToBeRefreshed
empToBeMergedFound2.setSalary(newSalary);
// now merge
em.merge(empToBeMergedFound2);
// flush and ROLLBACK the third transaction
em.flush();
rollbackTransaction(em);
// verify objects are correct in the PersistenceContext after the third transaction rolled back
if(em.contains(empNew)) {
fail("empNew is still in extended PersistenceContext after the third transaction rolled back");
}
if(em.contains(empToBeRemoved)) {
fail("empToBeRemoved is still in extended PersistenceContext after the third transaction rolled back");
}
if(em.contains(empToBeRefreshedExtended)) {
fail("empToBeRefreshedExtended is still in extended PersistenceContext after the third transaction rolled back");
} else if(empToBeRefreshedExtended.getSalary() != newSalary) {
fail("empToBeRefreshedExtended still has the original salary after third transaction rolled back");
}
if(em.contains(empToBeMergedExtended)) {
fail("empToBeMergedExtended is still in extended PersistenceContext after the third transaction rolled back");
} else if(empToBeMergedExtended.getSalary() != newSalary) {
fail("empToBeMergedExtended still has the original salary after third transaction rolled back");
}
// verify objects are correct in the db after the third transaction rolled back
clearCache();
Employee empNewFound3 = em.find(Employee.class, empNew.getId());
if(empNewFound3 != null) {
fail("empNew is in the db after the third transaction rolled back");
}
Employee empToBeRemovedFound3 = em.find(Employee.class, empToBeRemoved.getId());
if(empToBeRemovedFound3 == null) {
fail("empToBeRemoved not in the db after the third transaction rolled back");
}
Employee empToBeRefreshedFound3 = em.find(Employee.class, empToBeRefreshed.getId());
if(empToBeRefreshedFound3 == null) {
fail("empToBeRefreshed not in the db after the third transaction rolled back");
} else if(empToBeRefreshedFound3.getSalary() != newSalary) {
fail("empToBeRefreshed has the original salary in the db after the third transaction rolled back");
}
Employee empToBeMergedFound3 = em.find(Employee.class, empToBeMerged.getId());
if(empToBeMergedFound3 == null) {
fail("empToBeMerged not in the db after the third transaction rolled back");
} else if(empToBeMergedFound3.getSalary() != originalSalary) {
fail("empToBeMerged still doesn't have the original salary in the db after the third transaction rolled back");
}
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
public void testReadTransactionIsolation_CustomUpdate() {
internalTestReadTransactionIsolation(false, false, false, false);
}
public void testReadTransactionIsolation_CustomUpdate_Flush() {
internalTestReadTransactionIsolation(false, false, false, true);
}
public void testReadTransactionIsolation_CustomUpdate_Refresh() {
internalTestReadTransactionIsolation(false, false, true, false);
}
public void testReadTransactionIsolation_CustomUpdate_Refresh_Flush() {
internalTestReadTransactionIsolation(false, false, true, true);
}
public void testReadTransactionIsolation_UpdateAll() {
internalTestReadTransactionIsolation(false, true, false, false);
}
public void testReadTransactionIsolation_UpdateAll_Flush() {
internalTestReadTransactionIsolation(false, true, false, true);
}
public void testReadTransactionIsolation_UpdateAll_Refresh() {
internalTestReadTransactionIsolation(false, true, true, false);
}
public void testReadTransactionIsolation_UpdateAll_Refresh_Flush() {
internalTestReadTransactionIsolation(false, true, true, true);
}
public void testReadTransactionIsolation_OriginalInCache_CustomUpdate() {
internalTestReadTransactionIsolation(true, false, false, false);
}
public void testReadTransactionIsolation_OriginalInCache_CustomUpdate_Flush() {
internalTestReadTransactionIsolation(true, false, false, true);
}
public void testReadTransactionIsolation_OriginalInCache_CustomUpdate_Refresh() {
internalTestReadTransactionIsolation(true, false, true, false);
}
public void testReadTransactionIsolation_OriginalInCache_CustomUpdate_Refresh_Flush() {
internalTestReadTransactionIsolation(true, false, true, true);
}
public void testReadTransactionIsolation_OriginalInCache_UpdateAll() {
internalTestReadTransactionIsolation(true, true, false, false);
}
public void testReadTransactionIsolation_OriginalInCache_UpdateAll_Flush() {
internalTestReadTransactionIsolation(true, true, false, true);
}
public void testReadTransactionIsolation_OriginalInCache_UpdateAll_Refresh() {
internalTestReadTransactionIsolation(true, true, true, false);
}
public void testReadTransactionIsolation_OriginalInCache_UpdateAll_Refresh_Flush() {
internalTestReadTransactionIsolation(true, true, true, true);
}
protected void internalTestReadTransactionIsolation(boolean shouldOriginalBeInParentCache, boolean shouldUpdateAll, boolean shouldRefresh, boolean shouldFlush) {
//setup
String firstName = "testReadTransactionIsolation";
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
Query deleteQuery = em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'");
beginTransaction(em);
try{
deleteQuery.executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
em.clear();
// create and persist the object
String lastNameOriginal = "Original";
int salaryOriginal = 0;
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName(lastNameOriginal);
employee.setSalary(salaryOriginal);
beginTransaction(em);
try{
em.persist(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
if(!shouldOriginalBeInParentCache) {
clearCache();
}
em.clear();
Employee employeeUOW = null;
int salaryNew = 100;
String lastNameNew = "New";
beginTransaction(em);
Query selectQuery = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'");
try{
if(shouldRefresh) {
String lastNameAlternative = "Alternative";
int salaryAlternative = 50;
employeeUOW = (Employee)selectQuery.getSingleResult();
employeeUOW.setLastName(lastNameAlternative);
employeeUOW.setSalary(salaryAlternative);
}
int nUpdated;
if(shouldUpdateAll) {
nUpdated = em.createQuery("UPDATE Employee e set e.lastName = '" + lastNameNew + "' where e.firstName like '" + firstName + "'").setFlushMode(FlushModeType.AUTO).executeUpdate();
} else {
nUpdated = em.createNativeQuery("UPDATE CMP3_EMPLOYEE SET L_NAME = '" + lastNameNew + "', VERSION = VERSION + 1 WHERE F_NAME LIKE '" + firstName + "'").setFlushMode(FlushModeType.AUTO).executeUpdate();
}
assertTrue("nUpdated=="+ nUpdated +"; 1 was expected", nUpdated == 1);
if(shouldFlush) {
selectQuery.setFlushMode(FlushModeType.AUTO);
} else {
selectQuery.setFlushMode(FlushModeType.COMMIT);
}
if(shouldRefresh) {
selectQuery.setHint("eclipselink.refresh", Boolean.TRUE);
employeeUOW = (Employee)selectQuery.getSingleResult();
selectQuery.setHint("eclipselink.refresh", Boolean.FALSE);
} else {
employeeUOW = (Employee)selectQuery.getSingleResult();
}
assertTrue("employeeUOW.getLastName()=="+ employeeUOW.getLastName() +"; " + lastNameNew + " was expected", employeeUOW.getLastName().equals(lastNameNew));
employeeUOW.setSalary(salaryNew);
employeeUOW = (Employee)selectQuery.getSingleResult();
assertTrue("employeeUOW.getSalary()=="+ employeeUOW.getSalary() +"; " + salaryNew + " was expected", employeeUOW.getSalary() == salaryNew);
commitTransaction(em);
}catch (Throwable ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
if (Error.class.isAssignableFrom(ex.getClass())){
throw (Error)ex;
}else{
throw (RuntimeException)ex;
}
}
Employee employeeFoundAfterTransaction = em.find(Employee.class, employeeUOW.getId());
assertTrue("employeeFoundAfterTransaction().getLastName()=="+ employeeFoundAfterTransaction.getLastName() +"; " + lastNameNew + " was expected", employeeFoundAfterTransaction.getLastName().equals(lastNameNew));
assertTrue("employeeFoundAfterTransaction().getSalary()=="+ employeeFoundAfterTransaction.getSalary() +"; " + salaryNew + " was expected", employeeFoundAfterTransaction.getSalary() == salaryNew);
// The cache should be invalidated because the commit should detect a jump in the version number and invalidate the object.
EntityManager em2 = createEntityManager();
employeeFoundAfterTransaction = em2.find(Employee.class, employeeUOW.getId());
assertTrue("employeeFoundAfterTransaction().getLastName()=="+ employeeFoundAfterTransaction.getLastName() +"; " + lastNameNew + " was expected", employeeFoundAfterTransaction.getLastName().equals(lastNameNew));
assertTrue("employeeFoundAfterTransaction().getSalary()=="+ employeeFoundAfterTransaction.getSalary() +"; " + salaryNew + " was expected", employeeFoundAfterTransaction.getSalary() == salaryNew);
em2.close();
// clean up
beginTransaction(em);
try{
deleteQuery.executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
closeEntityManager(em);
}
// test for bug 4755392:
// AFTER DELETEALL OBJECT STILL DEEMED EXISTING
public void testFindDeleteAllPersist() {
String firstName = "testFindDeleteAllPersist";
// create Employees
Employee empWithAddress = new Employee();
empWithAddress.setFirstName(firstName);
empWithAddress.setLastName("WithAddress");
empWithAddress.setAddress(new Address());
Employee empWithoutAddress = new Employee();
empWithoutAddress.setFirstName(firstName);
empWithoutAddress.setLastName("WithoutAddress");
EntityManager em = createEntityManager();
Query deleteQuery = em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'");
// make sure no Employee with the specified firstName exists.
beginTransaction(em);
try{
deleteQuery.executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// persist
beginTransaction(em);
try{
em.persist(empWithAddress);
em.persist(empWithoutAddress);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// clear cache
clearCache();
em.clear();
// Find both to bring into the cache, delete empWithoutAddress.
// Because the address VH is not triggered both objects should be invalidated.
beginTransaction(em);
try{
Employee empWithAddressFound = em.find(Employee.class, empWithAddress.getId());
Employee empWithoutAddressFound = em.find(Employee.class, empWithoutAddress.getId());
int nDeleted = em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"' and e.address IS NULL").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// we can no longer rely on the query above to clear the Employee from the persistence context.
// Clearling the context to allow us to proceed.
em.clear();
// persist new empWithoutAddress - the one that has been deleted from the db.
beginTransaction(em);
try{
Employee newEmpWithoutAddress = new Employee();
newEmpWithoutAddress.setFirstName(firstName);
newEmpWithoutAddress.setLastName("newWithoutAddress");
newEmpWithoutAddress.setId(empWithoutAddress.getId());
em.persist(newEmpWithoutAddress);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// persist new empWithAddress - the one still in the db.
beginTransaction(em);
try{
Employee newEmpWithAddress = new Employee();
newEmpWithAddress.setFirstName(firstName);
newEmpWithAddress.setLastName("newWithAddress");
newEmpWithAddress.setId(empWithAddress.getId());
em.persist(newEmpWithAddress);
fail("EntityExistsException was expected");
} catch (EntityExistsException ex) {
// "cant_persist_detatched_object" - ignore the expected exception
} finally {
rollbackTransaction(em);
}
// clean up
beginTransaction(em);
deleteQuery.executeUpdate();
commitTransaction(em);
}
public void testWRITELock(){
// Cannot create parallel transactions.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setFirstName("Mark");
employee.setLastName("Madsen");
beginTransaction(em);
try{
em.persist(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
EntityManager em2 = createEntityManager();
Exception optimisticLockException = null;
beginTransaction(em);
try{
employee = em.find(Employee.class, employee.getId());
em.lock(employee, LockModeType.WRITE);
em2.getTransaction().begin();
try{
Employee employee2 = em2.find(Employee.class, employee.getId());
employee2.setFirstName("Michael");
em2.getTransaction().commit();
}catch (RuntimeException ex){
em2.getTransaction().rollback();
em2.close();
throw ex;
}
commitTransaction(em);
} catch (RollbackException exception) {
if (exception.getCause() instanceof OptimisticLockException){
optimisticLockException = exception;
}
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
beginTransaction(em);
try{
employee = em.find(Employee.class, employee.getId());
em.remove(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
if (optimisticLockException == null){
fail("Proper exception not thrown when EntityManager.lock(object, WRITE) is used.");
}
}
/*This test case uses the "default2" PU defined in the persistence.xml
located at tltest/resource/essentials/broken-testmodels/META-INF
and included in essentials_testmodels_broken.jar */
public void testEMFWrapValidationException()
{
EntityManagerFactory factory = null;
try {
factory = Persistence.createEntityManagerFactory("broken-PU", JUnitTestCaseHelper.getDatabaseProperties());
EntityManager em = factory.createEntityManager();
} catch (javax.persistence.PersistenceException e) {
// Ignore - it's expected exception type
} finally {
factory.close();
}
}
/**
* At the time this test case was added, the problem it was designed to test for would cause a failure during deployement
* and therefore this tests case would likely always pass if there is a successful deployment.
* But it is anticipated that that may not always be the case and therefore we are adding a test case
*/
public void testEMDefaultTxType()
{
EntityManagerFactory factory = null;
try {
factory = Persistence.createEntityManagerFactory("default1", JUnitTestCaseHelper.getDatabaseProperties());
EntityManager em = factory.createEntityManager();
} catch (Exception e) {
fail("Exception caught while creating EM with no \"transaction-type\" specified in persistence.xml");
} finally {
factory.close();
}
Assert.assertTrue(true);
}
public void testPersistOnNonEntity()
{
boolean testPass = false;
Object nonEntity = new Object();
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.persist(nonEntity);
} catch (IllegalArgumentException e) {
testPass = true;
} finally {
rollbackTransaction(em);
}
Assert.assertTrue(testPass);
}
public void testClose() {
// Close is not used on server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
if(!em.isOpen()) {
fail("Created EntityManager is not open");
}
closeEntityManager(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open");
}
}
public void testBeginTransactionClose() {
// Close is not used on server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
beginTransaction(em);
try{
closeEntityManager(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open before transaction complete");
}
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
if(em.isOpen()) {
closeEntityManager(em);
}
throw ex;
}
rollbackTransaction(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open after transaction rollback");
}
}
public void testBeginTransactionCloseCommitTransaction() {
// EntityManager is always open in server.
if (isOnServer()) {
return;
}
String firstName = "testBeginTrCloseCommitTr";
EntityManager em = createEntityManager();
// make sure there is no employees with this firstName
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
// create a new Employee
Employee employee = new Employee();
employee.setFirstName(firstName);
// persist the new Employee and close the entity manager
beginTransaction(em);
try{
em.persist(employee);
closeEntityManager(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open before transaction complete");
}
}catch (RuntimeException ex){
rollbackTransaction(em);
if(em.isOpen()) {
closeEntityManager(em);
}
throw ex;
}
commitTransaction(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open after transaction commit");
}
// verify that the employee has been persisted
em = createEntityManager();
RuntimeException exception = null;
try {
Employee persistedEmployee = (Employee)em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getSingleResult();
} catch (RuntimeException runtimeException) {
exception = runtimeException;
}
// clean up
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
if(exception != null) {
if(exception instanceof EntityNotFoundException) {
fail("object has not been persisted");
} else {
// unexpected exception - rethrow.
throw exception;
}
}
}
// The test removed because we moved back to binding literals
// on platforms other than DB2 and Derby
/* public void testDontBindLiteral() {
EntityManager em = createEntityManager();
Query controlQuery = em.createQuery("SELECT OBJECT(p) FROM SmallProject p WHERE p.name = CONCAT(:param1, :param2)");
controlQuery.setParameter("param1", "A").setParameter("param2", "B");
List controlResults = controlQuery.getResultList();
int nControlParams = ((ExpressionQueryMechanism)((EJBQueryImpl)controlQuery).getDatabaseQuery().getQueryMechanism()).getCall().getParameters().size();
if(nControlParams != 2) {
fail("controlQuery has wrong number of parameters = "+nControlParams+"; 2 is expected");
}
Query query = em.createQuery("SELECT OBJECT(p) FROM SmallProject p WHERE p.name = CONCAT('A', 'B')");
List results = query.getResultList();
int nParams = ((ExpressionQueryMechanism)((EJBQueryImpl)query).getDatabaseQuery().getQueryMechanism()).getCall().getParameters().size();
if(nParams > 0) {
fail("Query processed literals as parameters");
}
closeEntityManager(em);
}*/
public void testPersistenceProperties() {
// Different properties are used on the server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
ServerSession ss = ((org.eclipse.persistence.internal.jpa.EntityManagerImpl)em).getServerSession();
// these properties were set in persistence unit
// and overridden in CMP3TestModel.setup - the values should be overridden.
boolean isReadShared = (ss.getReadConnectionPool() instanceof ReadConnectionPool);
if(isReadShared != Boolean.parseBoolean((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_SHARED))) {
fail("isReadShared is wrong");
}
int writeMin = ss.getDefaultConnectionPool().getMinNumberOfConnections();
if(writeMin != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN))) {
fail("writeMin is wrong");
}
int writeMax = ss.getDefaultConnectionPool().getMaxNumberOfConnections();
if(writeMax != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MAX))) {
fail("writeMax is wrong");
}
int readMin = ss.getReadConnectionPool().getMinNumberOfConnections();
if(readMin != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN))) {
fail("readMin is wrong");
}
int readMax = ss.getReadConnectionPool().getMaxNumberOfConnections();
if(readMax != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MAX))) {
fail("readMax is wrong");
}
// these properties were set in persistence unit - the values should be the same as in persistence.xml
/*
<property name="eclipselink.session-name" value="default-session"/>
<property name="eclipselink.cache.size.default" value="500"/>
<property name="eclipselink.cache.size.Employee" value="550"/>
<property name="eclipselink.cache.size.org.eclipse.persistence.testing.models.jpa.advanced.Address" value="555"/>
<property name="eclipselink.cache.type.default" value="Full"/>
<property name="eclipselink.cache.type.Employee" value="Weak"/>
<property name="eclipselink.cache.type.org.eclipse.persistence.testing.models.jpa.advanced.Address" value="HardWeak"/>
<property name="eclipselink.session.customizer" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
<property name="eclipselink.descriptor.customizer.Employee" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
<property name="eclipselink.descriptor.customizer.org.eclipse.persistence.testing.models.jpa.advanced.Address" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
*/
String sessionName = ss.getName();
if(!sessionName.equals("default-session")) {
fail("sessionName is wrong");
}
int defaultCacheSize = ss.getDescriptor(Project.class).getIdentityMapSize();
if(defaultCacheSize != 500) {
fail("defaultCacheSize is wrong");
}
int employeeCacheSize = ss.getDescriptor(Employee.class).getIdentityMapSize();
if(employeeCacheSize != 550) {
fail("employeeCacheSize is wrong");
}
int addressCacheSize = ss.getDescriptor(Address.class).getIdentityMapSize();
if(addressCacheSize != 555) {
fail("addressCacheSize is wrong");
}
Class defaultCacheType = ss.getDescriptor(Project.class).getIdentityMapClass();
if(! Helper.getShortClassName(defaultCacheType).equals("FullIdentityMap")) {
fail("defaultCacheType is wrong");
}
Class employeeCacheType = ss.getDescriptor(Employee.class).getIdentityMapClass();
if(! Helper.getShortClassName(employeeCacheType).equals("WeakIdentityMap")) {
fail("employeeCacheType is wrong");
}
Class addressCacheType = ss.getDescriptor(Address.class).getIdentityMapClass();
if(! Helper.getShortClassName(addressCacheType).equals("HardCacheWeakIdentityMap")) {
fail("addressCacheType is wrong");
}
int numSessionCalls = Customizer.getNumberOfCallsForSession(ss.getName());
if(numSessionCalls == 0) {
fail("session customizer hasn't been called");
}
int numProjectCalls = Customizer.getNumberOfCallsForClass(Project.class.getName());
if(numProjectCalls > 0) {
fail("Project customizer has been called");
}
int numEmployeeCalls = Customizer.getNumberOfCallsForClass(Employee.class.getName());
if(numEmployeeCalls == 0) {
fail("Employee customizer hasn't been called");
}
int numAddressCalls = Customizer.getNumberOfCallsForClass(Address.class.getName());
if(numAddressCalls == 0) {
fail("Address customizer hasn't been called");
}
closeEntityManager(em);
}
public void testMultipleFactories() {
getEntityManagerFactory();
closeEntityManagerFactory();
boolean isOpen = getEntityManagerFactory().isOpen();
if(!isOpen) {
fail("Close factory 1; open factory 2 - it's not open");
} else {
// Get entity manager just to login back the session, then close em
getEntityManagerFactory().createEntityManager().close();
}
}
public void testParallelMultipleFactories() {
EntityManagerFactory factory1 = Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
factory1.createEntityManager();
EntityManagerFactory factory2 = Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
factory2.createEntityManager();
factory1.close();
if(factory1.isOpen()) {
fail("after factory1.close() factory1 is not closed");
}
if(!factory2.isOpen()) {
fail("after factory1.close() factory2 is closed");
}
factory2.close();
if(factory2.isOpen()) {
fail("after factory2.close() factory2 is not closed");
}
EntityManagerFactory factory3 = Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
if(!factory3.isOpen()) {
fail("factory3 is closed");
}
factory3.createEntityManager();
factory3.close();
if(factory3.isOpen()) {
fail("after factory3.close() factory3 is open");
}
}
public void testQueryHints() {
EntityManager em = createEntityManager();
Query query = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = 'testQueryHints'");
ObjectLevelReadQuery olrQuery = (ObjectLevelReadQuery)((EJBQueryImpl)query).getDatabaseQuery();
// binding
// original state = default state
assertTrue(olrQuery.shouldIgnoreBindAllParameters());
// set boolean true
query.setHint(EclipseLinkQueryHints.BIND_PARAMETERS, true);
// Parse cached query may be cloned when hint set, so re-get.
olrQuery = (ObjectLevelReadQuery)((EJBQueryImpl)query).getDatabaseQuery();
assertTrue("Binding not set.", olrQuery.shouldBindAllParameters());
// reset to original state
query.setHint(EclipseLinkQueryHints.BIND_PARAMETERS, "");
assertTrue("Binding not set.", olrQuery.shouldIgnoreBindAllParameters());
// set "false"
query.setHint(EclipseLinkQueryHints.BIND_PARAMETERS, "false");
assertFalse("Binding not set.", olrQuery.shouldBindAllParameters());
// reset to the original state
query.setHint(EclipseLinkQueryHints.BIND_PARAMETERS, "");
assertTrue("Binding not set.", olrQuery.shouldIgnoreBindAllParameters());
// cache usage
query.setHint(EclipseLinkQueryHints.CACHE_USAGE, CacheUsage.DoNotCheckCache);
assertTrue("Cache usage not set.", olrQuery.getCacheUsage()==ObjectLevelReadQuery.DoNotCheckCache);
query.setHint(EclipseLinkQueryHints.CACHE_USAGE, CacheUsage.CheckCacheOnly);
assertTrue("Cache usage not set.", olrQuery.shouldCheckCacheOnly());
query.setHint(EclipseLinkQueryHints.CACHE_USAGE, CacheUsage.ConformResultsInUnitOfWork);
assertTrue("Cache usage not set.", olrQuery.shouldConformResultsInUnitOfWork());
// reset to the original state
query.setHint(EclipseLinkQueryHints.CACHE_USAGE, "");
assertTrue("Cache usage not set.", olrQuery.shouldCheckDescriptorForCacheUsage());
// pessimistic lock
query.setHint(EclipseLinkQueryHints.PESSIMISTIC_LOCK, PessimisticLock.Lock);
assertTrue("Lock not set.", olrQuery.getLockMode()==ObjectLevelReadQuery.LOCK);
query.setHint(EclipseLinkQueryHints.PESSIMISTIC_LOCK, PessimisticLock.NoLock);
assertTrue("Lock not set.", olrQuery.getLockMode()==ObjectLevelReadQuery.NO_LOCK);
query.setHint(EclipseLinkQueryHints.PESSIMISTIC_LOCK, PessimisticLock.LockNoWait);
assertTrue("Lock not set.", olrQuery.getLockMode()==ObjectLevelReadQuery.LOCK_NOWAIT);
// default state
query.setHint(EclipseLinkQueryHints.PESSIMISTIC_LOCK, "");
assertTrue("Lock not set.", olrQuery.getLockMode()==ObjectLevelReadQuery.NO_LOCK);
//refresh
// set to original state - don't refresh.
// the previously run LOCK and LOCK_NOWAIT have swithed it to true
query.setHint(EclipseLinkQueryHints.REFRESH, false);
assertFalse("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
// set boolean true
query.setHint(EclipseLinkQueryHints.REFRESH, true);
assertTrue("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
assertTrue("CascadeByMapping not set.", olrQuery.shouldCascadeByMapping()); // check if cascade refresh is enabled
// set "false"
query.setHint(EclipseLinkQueryHints.REFRESH, "false");
assertFalse("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
// set Boolean.TRUE
query.setHint(EclipseLinkQueryHints.REFRESH, Boolean.TRUE);
assertTrue("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
assertTrue("CascadeByMapping not set.", olrQuery.shouldCascadeByMapping()); // check if cascade refresh is enabled
// reset to original state
query.setHint(EclipseLinkQueryHints.REFRESH, "");
assertFalse("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
query.setHint(EclipseLinkQueryHints.RETURN_SHARED, "false");
assertFalse("Read-only not set.", olrQuery.isReadOnly());
query.setHint(EclipseLinkQueryHints.RETURN_SHARED, Boolean.TRUE);
assertTrue("Read-only not set.", olrQuery.isReadOnly());
query.setHint(EclipseLinkQueryHints.RETURN_SHARED, Boolean.FALSE);
assertFalse("Read-only not set.", olrQuery.isReadOnly());
query.setHint(EclipseLinkQueryHints.JDBC_TIMEOUT, new Integer(100));
assertTrue("Timeout not set.", olrQuery.getQueryTimeout() == 100);
query.setHint(EclipseLinkQueryHints.JDBC_FETCH_SIZE, new Integer(101));
assertTrue("Fetch-size not set.", olrQuery.getFetchSize() == 101);
query.setHint(EclipseLinkQueryHints.JDBC_MAX_ROWS, new Integer(103));
assertTrue("Max-rows not set.", olrQuery.getMaxRows() == 103);
query.setHint(EclipseLinkQueryHints.REFRESH_CASCADE, CascadePolicy.NoCascading);
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.NoCascading);
query.setHint(EclipseLinkQueryHints.REFRESH_CASCADE, CascadePolicy.CascadeByMapping);
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.CascadeByMapping);
query.setHint(EclipseLinkQueryHints.REFRESH_CASCADE, CascadePolicy.CascadeAllParts);
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.CascadeAllParts);
query.setHint(EclipseLinkQueryHints.REFRESH_CASCADE, CascadePolicy.CascadePrivateParts);
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.CascadePrivateParts);
// reset to the original state
query.setHint(EclipseLinkQueryHints.REFRESH_CASCADE, "");
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.CascadeByMapping);
query.setHint(EclipseLinkQueryHints.RESULT_COLLECTION_TYPE, java.util.ArrayList.class);
assertTrue("ArrayList not set.", ((ReadAllQuery)olrQuery).getContainerPolicy().getContainerClassName().equals(java.util.ArrayList.class.getName()));
query.setHint(EclipseLinkQueryHints.RESULT_COLLECTION_TYPE, "java.util.Vector");
assertTrue("Vector not set.", ((ReadAllQuery)olrQuery).getContainerPolicy().getContainerClassName().equals(java.util.Vector.class.getName()));
closeEntityManager(em);
}
/**
* This test ensures that the eclipselink.batch query hint works.
* It tests two things.
*
* 1. That the batch read attribute is properly added to the queyr
* 2. That the query will execute
*
* It does not do any verification that the batch reading feature actually works. That is
* left for the batch reading testing to do.
*/
public void testBatchQueryHint(){
int id1 = 0;
EntityManager em = createEntityManager();
beginTransaction(em);
Employee manager = new Employee();
manager.setFirstName("Marvin");
manager.setLastName("Malone");
PhoneNumber number = new PhoneNumber("cell", "613", "888-8888");
manager.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-8880");
manager.addPhoneNumber(number);
em.persist(manager);
id1 = manager.getId();
Employee emp = new Employee();
emp.setFirstName("Melvin");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9888");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0880");
emp.addPhoneNumber(number);
em.persist(emp);
emp = new Employee();
emp.setFirstName("David");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9988");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0980");
emp.addPhoneNumber(number);
em.persist(emp);
commitTransaction(em);
em.clear();
org.eclipse.persistence.jpa.JpaQuery query = (org.eclipse.persistence.jpa.JpaQuery)em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(EclipseLinkQueryHints.BATCH, "e.phoneNumbers");
query.setHint(EclipseLinkQueryHints.BATCH, "e.manager.phoneNumbers");
ReadAllQuery raq = (ReadAllQuery)query.getDatabaseQuery();
List expressions = raq.getBatchReadAttributeExpressions();
assertTrue(expressions.size() == 2);
Expression exp = (Expression)expressions.get(0);
assertTrue(exp.isQueryKeyExpression());
assertTrue(exp.getName().equals("phoneNumbers"));
exp = (Expression)expressions.get(1);
assertTrue(exp.isQueryKeyExpression());
assertTrue(exp.getName().equals("phoneNumbers"));
List resultList = query.getResultList();
emp = (Employee)resultList.get(0);
emp.getPhoneNumbers().hashCode();
emp.getManager().getPhoneNumbers().hashCode();
emp = (Employee)resultList.get(1);
emp.getPhoneNumbers().hashCode();
beginTransaction(em);
emp = em.find(Employee.class, id1);
Iterator it = emp.getManagedEmployees().iterator();
while (it.hasNext()){
Employee managedEmp = (Employee)it.next();
it.remove();
managedEmp.setManager(null);
em.remove(managedEmp);
}
em.remove(emp);
commitTransaction(em);
}
/**
* This test ensures that the eclipselink.fetch query hint works.
* It tests two things.
*
* 1. That the jined attribute is properly added to the query
* 2. That the query will execute
*
* It does not do any verification that the joining feature actually works. That is
* left for the joining testing to do.
*/
public void testFetchQueryHint(){
int id1 = 0;
EntityManager em = createEntityManager();
beginTransaction(em);
Employee manager = new Employee();
manager.setFirstName("Marvin");
manager.setLastName("Malone");
PhoneNumber number = new PhoneNumber("cell", "613", "888-8888");
manager.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-8880");
manager.addPhoneNumber(number);
em.persist(manager);
id1 = manager.getId();
Employee emp = new Employee();
emp.setFirstName("Melvin");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9888");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0880");
emp.addPhoneNumber(number);
em.persist(emp);
emp = new Employee();
emp.setFirstName("David");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9988");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0980");
emp.addPhoneNumber(number);
em.persist(emp);
commitTransaction(em);
em.clear();
org.eclipse.persistence.jpa.JpaQuery query = (org.eclipse.persistence.jpa.JpaQuery)em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(EclipseLinkQueryHints.FETCH, "e.manager");
ReadAllQuery raq = (ReadAllQuery)query.getDatabaseQuery();
List expressions = raq.getJoinedAttributeExpressions();
assertTrue(expressions.size() == 1);
Expression exp = (Expression)expressions.get(0);
assertTrue(exp.getName().equals("manager"));
query.setHint(EclipseLinkQueryHints.FETCH, "e.manager.phoneNumbers");
assertTrue(expressions.size() == 2);
List resultList = query.getResultList();
emp = (Employee)resultList.get(0);
beginTransaction(em);
emp = em.find(Employee.class, id1);
Iterator it = emp.getManagedEmployees().iterator();
while (it.hasNext()){
Employee managedEmp = (Employee)it.next();
it.remove();
managedEmp.setManager(null);
em.remove(managedEmp);
}
em.remove(emp);
commitTransaction(em);
}
/**
* Test that the proper exception is thrown when an incorrect batch or fetch query hint is set on the queyr.
*/
public void testIncorrectBatchQueryHint(){
EntityManager em = createEntityManager();
QueryException exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(EclipseLinkQueryHints.BATCH, "e");
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown on an incorrect BATCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_DID_NOT_CONTAIN_ENOUGH_TOKENS);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(EclipseLinkQueryHints.BATCH, "e.abcdef");
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown on an incorrect BATCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_NAVIGATED_NON_EXISTANT_RELATIONSHIP);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(EclipseLinkQueryHints.BATCH, "e.firstName");
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown when an incorrect relationship was navigated in a BATCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_NAVIGATED_ILLEGAL_RELATIONSHIP);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(EclipseLinkQueryHints.FETCH, "e");
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown on an incorrect FETCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_DID_NOT_CONTAIN_ENOUGH_TOKENS);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(EclipseLinkQueryHints.FETCH, "e.abcdef");
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown on an incorrect FETCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_NAVIGATED_NON_EXISTANT_RELATIONSHIP);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(EclipseLinkQueryHints.FETCH, "e.firstName");
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown when an incorrect relationship was navigated in a FETCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_NAVIGATED_ILLEGAL_RELATIONSHIP);
}
public void testQueryOnClosedEM() {
// Server entity managers are not closed.
if (isOnServer()) {
return;
}
boolean exceptionWasThrown = false;
EntityManager em = createEntityManager();
Query q = em.createQuery("SELECT e FROM Employee e ");
closeEntityManager(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open");
}
try{
q.getResultList();
}catch(java.lang.IllegalStateException e){
exceptionWasThrown=true;
}
if (!exceptionWasThrown){
fail("Query on Closed EntityManager did not throw an exception");
}
}
public void testNullifyAddressIn() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("UPDATE Employee e SET e.address = null WHERE e.address.country IN ('Canada', 'US')").executeUpdate();
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
//test for bug 5234283: WRONG =* SQL FOR LEFT JOIN ON DERBY AND DB2 PLATFORMS
public void testLeftJoinOneToOneQuery() {
EntityManager em = createEntityManager();
List results = em.createQuery("SELECT a FROM Employee e LEFT JOIN e.address a").getResultList();
closeEntityManager(em);
}
// Test the clone method works correctly with lazy attributes.
public void testCloneable() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = new Employee();
employee.setFirstName("Owen");
employee.setLastName("Hargreaves");
employee.getAddress();
Employee clone = employee.clone();
Address address = new Address();
address.setCity("Munich");
clone.setAddress(address);
clone.getAddress();
em.persist(clone);
if (employee.getAddress() == clone.getAddress()) {
fail("Changing clone address changed original.");
}
commitTransaction(em);
clearCache();
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, clone.getId());
clone = employee.clone();
address = new Address();
address.setCity("Not Munich");
clone.setAddress(address);
clone.getAddress();
if (employee.getAddress() == clone.getAddress()) {
fail("Changing clone address changed original.");
}
if (employee.getAddress() == null) {
fail("Changing clone address reset original to null.");
}
if (clone.getAddress() != address) {
fail("Changing clone did not work.");
}
em.remove(employee);
commitTransaction(em);
closeEntityManager(em);
}
// test for GlassFish bug 711 - throw a descriptive exception when an uninstantiated valueholder is serialized and then accessed
public void testSerializedLazy(){
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Owen");
emp.setLastName("Hargreaves");
emp.setId(40);
Address address = new Address();
address.setCity("Munich");
emp.setAddress(address);
em.persist(emp);
em.flush();
commitTransaction(em);
closeEntityManager(em);
clearCache();
em = createEntityManager();
String ejbqlString = "SELECT e FROM Employee e WHERE e.firstName = 'Owen' and e.lastName = 'Hargreaves'";
List result = em.createQuery(ejbqlString).getResultList();
emp = (Employee)result.get(0);
Exception exception = null;
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(byteStream);
stream.writeObject(emp);
stream.flush();
byte arr[] = byteStream.toByteArray();
ByteArrayInputStream inByteStream = new ByteArrayInputStream(arr);
ObjectInputStream inObjStream = new ObjectInputStream(inByteStream);
emp = (Employee) inObjStream.readObject();
emp.getAddress();
} catch (ValidationException e) {
if (e.getErrorCode() == ValidationException.INSTANTIATING_VALUEHOLDER_WITH_NULL_SESSION){
exception = e;
} else {
fail("An unexpected exception was thrown while testing serialization of ValueHolders: " + e.toString());
}
} catch (Exception e){
fail("An unexpected exception was thrown while testing serialization of ValueHolders: " + e.toString());
}
// Only throw error if weaving was used.
if (System.getProperty("TEST_NO_WEAVING") == null) {
assertNotNull("The correct exception was not thrown while traversing an uninstantiated lazy relationship on a serialized object: " + exception, exception);
}
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
commitTransaction(em);
}
//test for bug 5170395: GET THE SEQUENCING EXCEPTION WHEN RUNNING FOR THE FIRST TIME ON A CLEAR SCHEMA
public void testSequenceObjectDefinition() {
EntityManager em = createEntityManager();
ServerSession ss = ((org.eclipse.persistence.internal.jpa.EntityManagerImpl)em).getServerSession();
if(!ss.getLogin().getPlatform().supportsSequenceObjects()) {
// platform that supports sequence objects is required for this test
closeEntityManager(em);
return;
}
String seqName = "testSequenceObjectDefinition";
try {
// first param is preallocationSize, second is startValue
// both should be positive
internalTestSequenceObjectDefinition(10, 1, seqName, em, ss);
internalTestSequenceObjectDefinition(10, 5, seqName, em, ss);
internalTestSequenceObjectDefinition(10, 15, seqName, em, ss);
} finally {
closeEntityManager(em);
}
}
protected void internalTestSequenceObjectDefinition(int preallocationSize, int startValue, String seqName, EntityManager em, ServerSession ss) {
NativeSequence sequence = new NativeSequence(seqName, preallocationSize, startValue, false);
sequence.onConnect(ss.getPlatform());
SequenceObjectDefinition def = new SequenceObjectDefinition(sequence);
// create sequence
String createStr = def.buildCreationWriter(ss, new StringWriter()).toString();
beginTransaction(em);
em.createNativeQuery(createStr).executeUpdate();
commitTransaction(em);
try {
// sequence value preallocated
Vector seqValues = sequence.getGeneratedVector(null, ss);
int firstSequenceValue = ((Number)seqValues.elementAt(0)).intValue();
if(firstSequenceValue != startValue) {
fail(seqName + " sequence with preallocationSize = "+preallocationSize+" and startValue = " + startValue + " produced wrong firstSequenceValue =" + firstSequenceValue);
}
} finally {
sequence.onDisconnect(ss.getPlatform());
// drop sequence
String dropStr = def.buildDeletionWriter(ss, new StringWriter()).toString();
beginTransaction(em);
em.createNativeQuery(dropStr).executeUpdate();
commitTransaction(em);
}
}
public void testMergeDetachedObject() {
// Step 1 - read a department and clear the cache.
clearCache();
EntityManager em = createEntityManager();
EJBQueryImpl query = (EJBQueryImpl) em.createNamedQuery("findAllSQLDepartments");
Collection departments = query.getResultCollection();
Department detachedDepartment;
// This test seems to get called twice. Once with departments populated
// and a second time with the department table empty.
if (departments.isEmpty()) {
beginTransaction(em);
detachedDepartment = new Department();
detachedDepartment.setName("Department X");
em.persist(detachedDepartment);
commitTransaction(em);
} else {
detachedDepartment = (Department) departments.iterator().next();
}
closeEntityManager(em);
clearCache();
// Step 2 - create a new em, create a new employee with the
// detached department and then query the departments again.
em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Crazy");
emp.setLastName("Kid");
emp.setId(41);
emp.setDepartment(detachedDepartment);
em.persist(emp);
commitTransaction(em);
try {
((EJBQueryImpl) em.createNamedQuery("findAllSQLDepartments")).getResultCollection();
} catch (NullPointerException e) {
assertTrue("The detached department caused a null pointer on the query execution.", false);
}
closeEntityManager(em);
}
public void testMergeRemovedObject() {
//create an Employee
Employee emp = new Employee();
emp.setFirstName("testMergeRemovedObjectEmployee");
emp.setId(42);
//persist the Employee
EntityManager em = createEntityManager();
try{
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
beginTransaction(em);
em.remove(em.find(Employee.class, emp.getId())); //attempt to remove the Employee
try{
em.merge(emp); //then attempt to merge the Employee
fail("No exception thrown when merging a removed entity is attempted.");
}catch (IllegalArgumentException iae){
//expected
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
//clean up - ensure removal of employee
beginTransaction(em);
em.remove(em.find(Employee.class, emp.getId()));
commitTransaction(em);
closeEntityManager(em);
}
}
//bug6167431: tests calling merge on a new object puts it in the cache, and that all new objects in the tree get IDs generated
public void testMergeNewObject() {
//create an Employee
Employee emp = new Employee();
emp.setFirstName("testMergeNewObjectEmployee");
emp.setAddress(new Address("45 O'Connor", "Ottawa", "Ont", "Canada", "K1P1A4"));
//persist the Employee
EntityManager em = createEntityManager();
try{
beginTransaction(em);
Employee managedEmp = em.merge(emp);
this.assertNotNull("merged Employee doesn't have its ID generated", managedEmp.getId());
this.assertNotNull("merged Employee cannot be found using find", em.find(Employee.class, managedEmp.getId()));
//this won't work till bug:6193761 is fixed
//this.assertTrue("referenced Address doesn't have its ID generated", managedEmp.getAddress().getId()!=0);
}finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
}
}
//bug6180972: Tests calling merge on a new Entity that uses int as its ID, verifying it is set and cached correctly
public void testMergeNewObject2() {
//create an Equipment
Equipment equip = new Equipment();
equip.setDescription("New Equipment");
EntityManager em = createEntityManager();
try{
beginTransaction(em);
Equipment managedEquip = em.merge(equip);
this.assertTrue("merged Equipment doesn't have its ID generated", managedEquip.getId()!=0);
this.assertNotNull("merged Equipment cannot be found using find", em.find(Equipment.class, managedEquip.getId()));
}finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
}
}
//bug6342382: NEW OBJECT MERGE THROWS OPTIMISTICLOCKEXCEPTION
public void testMergeNewObject3_UseSequencing() {
internalTestMergeNewObject3(true);
}
//bug6342382: NEW OBJECT MERGE THROWS OPTIMISTICLOCKEXCEPTION
public void testMergeNewObject3_DontUseSequencing() {
internalTestMergeNewObject3(false);
}
// shouldUseSequencing == false indicates that PKs should be explicitly assigned to the objects
// rather than generated by sequencing.
protected void internalTestMergeNewObject3(boolean shouldUseSequencing) {
int id = 0;
if(!shouldUseSequencing) {
// obtain the last used sequence number
Employee emp = new Employee();
EntityManager em = createEntityManager();
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
id = emp.getId();
beginTransaction(em);
em.remove(emp);
commitTransaction(em);
closeEntityManager(em);
}
//create two Employees:
String firstName = "testMergeNewObjectEmployee3";
Employee manager = new Employee();
manager.setFirstName(firstName);
manager.setLastName("Manager");
if(!shouldUseSequencing) {
manager.setId(id++);
}
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName("Employee");
if(!shouldUseSequencing) {
employee.setId(id++);
}
manager.addManagedEmployee(employee);
//persist the Employee
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Employee managedEmp = em.merge(manager);
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
public void testMergeNull(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.merge(null);
}catch (IllegalArgumentException iae){
return;
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager.merge(null) attempted.");
}
public void testPersistNull(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.persist(null);
}catch (IllegalArgumentException iae){
return;
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager.persist(null) attempted.");
}
public void testContainsNull(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.contains(null);
}catch (IllegalArgumentException iae){
return;
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager.contains(null) attempted.");
}
public void testRemoveNull(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.remove(null);
}catch (IllegalArgumentException iae){
return;
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager.remove(null) attempted.");
}
/**
* GlassFish Bug854, originally calling with null caused a null-pointer exception.
*/
public void testCreateEntityManagerFactory() {
EntityManagerFactory factory = null;
try {
// First call with correct properties, to ensure test does not corrupt factory.
Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
factory = Persistence.createEntityManagerFactory("default", null);
factory = Persistence.createEntityManagerFactory("default");
} finally {
if (factory != null) {
factory.close();
}
}
}
//GlassFish Bug854 PU name doesn't exist or PU with the wrong name
public void testCreateEntityManagerFactory2() {
EntityManagerFactory emf = null;
PersistenceProvider provider = new PersistenceProvider();
try{
try {
emf = provider.createEntityManagerFactory("default123", null);
} catch (Exception e) {
fail("Exception is not expected, but thrown:" + e);
}
assertNull(emf);
try {
emf = Persistence.createEntityManagerFactory("default123");
fail("PersistenceException is expected");
} catch (Exception e) {
assertTrue("The exception should be a PersistenceException", e instanceof PersistenceException);
}
} finally{
if (emf != null) {
emf.close();
}
}
}
//Glassfish bug 702 - prevent primary key updates
public void testPrimaryKeyUpdate() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Groucho");
emp.setLastName("Marx");
em.persist(emp);
Integer id = emp.getId();
commitTransaction(em);
beginTransaction(em);
emp = em.merge(emp);
emp.setId(id + 1);
try {
commitTransaction(em);
} catch (Exception exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
Throwable persistenceException = exception;
if (exception.getCause() instanceof javax.transaction.RollbackException) {
// In the server this is always a rollback exception, need to get nested exception.
persistenceException = exception.getCause().getCause();
}
if (!(persistenceException instanceof PersistenceException)) {
AssertionFailedError failure = new AssertionFailedError("Wrong exception type thrown: " + persistenceException.getClass());
failure.initCause(exception);
throw failure;
}
if (persistenceException.getCause() instanceof ValidationException) {
ValidationException ve = (ValidationException) persistenceException.getCause();
if (ve.getErrorCode() == ValidationException.PRIMARY_KEY_UPDATE_DISALLOWED) {
return;
} else {
fail("Wrong error code for ValidationException: " + ve.getErrorCode());
}
} else {
fail("ValiationException expected, thrown: " + persistenceException.getCause());
}
} finally {
closeEntityManager(em);
}
fail("No exception thrown when primary key update attempted.");
}
//Glassfish bug 702 - prevent primary key updates, same value is ok
public void testPrimaryKeyUpdateSameValue() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Harpo");
emp.setLastName("Marx");
em.persist(emp);
Integer id = emp.getId();
commitTransaction(em);
beginTransaction(em);
emp.setId(id);
try {
commitTransaction(em);
} catch (Exception e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("Unexpected exception thrown: " + e.getClass());
} finally {
closeEntityManager(em);
}
}
//Glassfish bug 702 - prevent primary key updates, overlapping PK/FK
public void testPrimaryKeyUpdatePKFK() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Groucho");
emp.setLastName("Marx");
em.persist(emp);
Employee emp2 = new Employee();
emp2.setFirstName("Harpo");
emp2.setLastName("Marx");
em.persist(emp2);
PhoneNumber phone = new PhoneNumber("home", "415", "0007");
phone.setOwner(emp);
em.persist(phone);
commitTransaction(em);
beginTransaction(em);
phone.setOwner(emp2);
try {
commitTransaction(em);
} catch (Exception exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
Throwable persistenceException = exception;
if (exception.getCause() instanceof javax.transaction.RollbackException) {
// In the server this is always a rollback exception, need to get nested exception.
persistenceException = exception.getCause().getCause();
}
if (!(persistenceException instanceof PersistenceException)) {
AssertionFailedError failure = new AssertionFailedError("Wrong exception type thrown: " + persistenceException.getClass());
failure.initCause(exception);
throw failure;
}
if (persistenceException.getCause() instanceof ValidationException) {
ValidationException ve = (ValidationException) persistenceException.getCause();
if (ve.getErrorCode() == ValidationException.PRIMARY_KEY_UPDATE_DISALLOWED) {
return;
} else {
AssertionFailedError failure = new AssertionFailedError("Wrong error code for ValidationException: " + ve.getErrorCode());
failure.initCause(ve);
throw failure;
}
} else {
AssertionFailedError failure = new AssertionFailedError("ValiationException expected, thrown: " + persistenceException.getCause());
failure.initCause(persistenceException);
throw failure;
}
} finally {
closeEntityManager(em);
}
fail("No exception thrown when primary key update attempted.");
}
// Test cascade merge on a detached entity
public void testCascadeMergeDetached() {
// setup
Project p1 = new Project();
p1.setName("Project1");
Project p2 = new Project();
p1.setName("Project2");
Employee e1 = new Employee();
e1.setFirstName("Employee1");
Employee e2 = new Employee();
e2.setFirstName("Employee2");
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.persist(p1);
em.persist(p2);
em.persist(e1);
em.persist(e2);
commitTransaction(em);
} catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
closeEntityManager(em);
// end of setup
//p1,p2,e1,e2 are detached
// associate relationships
//p1 -> e1 (one-to-one)
p1.setTeamLeader(e1);
//e1 -> e2 (one-to-many)
e1.addManagedEmployee(e2);
//e2 -> p2 (many-to-many)
e2.addProject(p2);
p2.addTeamMember(e2);
em = createEntityManager();
beginTransaction(em);
try {
Project mp1 = em.merge(p1); // cascade merge
assertTrue(em.contains(mp1));
assertTrue("Managed instance and detached instance must not be same", mp1 != p1);
Employee me1 = mp1.getTeamLeader();
assertTrue("Cascade merge failed", em.contains(me1));
assertTrue("Managed instance and detached instance must not be same", me1 != e1);
Employee me2 = me1.getManagedEmployees().iterator().next();
assertTrue("Cascade merge failed", em.contains(me2));
assertTrue("Managed instance and detached instance must not be same", me2 != e2);
Project mp2 = me2.getProjects().iterator().next();
assertTrue("Cascade merge failed", em.contains(mp2));
assertTrue("Managed instance and detached instance must not be same", mp2 != p2);
commitTransaction(em);
} catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
closeEntityManager(em);
}
// Test cascade merge on a managed entity
// Test for GF#1139 - Cascade doesn't work when merging managed entity
public void testCascadeMergeManaged() {
// setup
Project p1 = new Project();
p1.setName("Project1");
Project p2 = new Project();
p1.setName("Project2");
Employee e1 = new Employee();
e1.setFirstName("Employee1");
Employee e2 = new Employee();
e2.setFirstName("Employee2");
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.persist(p1);
em.persist(p2);
em.persist(e1);
em.persist(e2);
commitTransaction(em);
} catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
closeEntityManager(em);
// end of setup
//p1,p2,e1,e2 are detached
em = createEntityManager();
beginTransaction(em);
try {
Project mp1 = em.merge(p1);
assertTrue(em.contains(mp1));
assertTrue("Managed instance and detached instance must not be same", mp1 != p1);
//p1 -> e1 (one-to-one)
mp1.setTeamLeader(e1);
mp1 = em.merge(mp1); // merge again - trigger cascade merge
Employee me1 = mp1.getTeamLeader();
assertTrue("Cascade merge failed", em.contains(me1));
assertTrue("Managed instance and detached instance must not be same", me1 != e1);
//e1 -> e2 (one-to-many)
me1.addManagedEmployee(e2);
me1 = em.merge(me1); // merge again - trigger cascade merge
Employee me2 = me1.getManagedEmployees().iterator().next();
assertTrue("Cascade merge failed", em.contains(me2));
assertTrue("Managed instance and detached instance must not be same", me2 != e2);
//e2 -> p2 (many-to-many)
me2.addProject(p2);
p2.addTeamMember(me2);
me2 = em.merge(me2); // merge again - trigger cascade merge
Project mp2 = me2.getProjects().iterator().next();
assertTrue("Cascade merge failed", em.contains(mp2));
assertTrue("Managed instance and detached instance must not be same", mp2 != p2);
commitTransaction(em);
} catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
closeEntityManager(em);
}
//Glassfish bug 1021 - allow cascading persist operation to non-entities
public void testCascadePersistToNonEntitySubclass() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Albert");
emp.setLastName("Einstein");
SuperLargeProject s1 = new SuperLargeProject("Super 1");
Collection projects = new ArrayList();
projects.add(s1);
emp.setProjects(projects);
em.persist(emp);
try {
commitTransaction(em);
} catch (Exception e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("Persist operation was not cascaded to related non-entity, thrown: " + e);
} finally {
closeEntityManager(em);
}
}
/**
* Bug 801
* Test to ensure when property access is used and the underlying variable is changed the change
* is correctly reflected in the database
*
* In this test we test making the change before the object is managed
*/
public void testInitializeFieldForPropertyAccess(){
Employee employee = new Employee();
employee.setFirstName("Andy");
employee.setLastName("Dufresne");
Address address = new Address();
address.setCity("Shawshank");
employee.setAddressField(address);
EntityManager em = createEntityManager();
beginTransaction(em);
em.persist(employee);
try{
commitTransaction(em);
} catch (RuntimeException e){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
}
int id = employee.getId();
clearCache();
em = createEntityManager();
beginTransaction(em);
try {
employee = em.find(Employee.class, new Integer(id));
address = employee.getAddress();
assertTrue("The address was not persisted.", employee.getAddress() != null);
assertTrue("The address was not correctly persisted.", employee.getAddress().getCity().equals("Shawshank"));
} finally {
employee.setAddress((Address)null);
em.remove(address);
em.remove(employee);
commitTransaction(em);
}
}
/**
* Bug 801
* Test to ensure when property access is used and the underlying variable is changed the change
* is correctly reflected in the database
*
* In this test we test making the change after the object is managed
*/
public void testSetFieldForPropertyAccess(){
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setFirstName("Andy");
employee.setLastName("Dufresne");
Address address = new Address();
address.setCity("Shawshank");
employee.setAddress(address);
Employee manager = new Employee();
manager.setFirstName("Bobby");
manager.setLastName("Dufresne");
employee.setManager(manager);
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
int id = employee.getId();
int addressId = address.getId();
int managerId = manager.getId();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
employee.getAddress();
address = new Address();
address.setCity("Metropolis");
employee.setAddress(address);
manager = new Employee();
manager.setFirstName("Metro");
manager.setLastName("Dufresne");
employee.setManagerField(manager);
try {
commitTransaction(em);
} catch (RuntimeException e){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
address = employee.getAddress();
manager = employee.getManager();
assertTrue("The address was not persisted.", employee.getAddress() != null);
assertTrue("The address was not correctly persisted.", employee.getAddress().getCity().equals("Metropolis"));
assertTrue("The manager was not persisted.", employee.getManager() != null);
assertTrue("The manager was not correctly persisted.", employee.getManager().getFirstName().equals("Metro"));
Address initialAddress = em.find(Address.class, new Integer(addressId));
Employee initialManager = em.find(Employee.class, new Integer(managerId));
employee.setAddress((Address)null);
em.remove(address);
em.remove(employee);
em.remove(manager);
em.remove(initialAddress);
em.remove(initialManager);
commitTransaction(em);
}
/**
* Bug 801
* Test to ensure when property access is used and the underlying variable is changed the change
* is correctly reflected in the database
*
* In this test we test making the change after the object is refreshed
*/
public void testSetFieldForPropertyAccessWithRefresh(){
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setFirstName("Andy");
employee.setLastName("Dufresne");
Address address = new Address();
address.setCity("Shawshank");
employee.setAddress(address);
Employee manager = new Employee();
manager.setFirstName("Bobby");
manager.setLastName("Dufresne");
employee.setManager(manager);
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
int id = employee.getId();
int addressId = address.getId();
int managerId = manager.getId();
beginTransaction(em);
employee = em.getReference(Employee.class, employee.getId());
em.refresh(employee);
employee.getAddress();
address = new Address();
address.setCity("Metropolis");
employee.setAddress(address);
manager = new Employee();
manager.setFirstName("Metro");
manager.setLastName("Dufresne");
employee.setManagerField(manager);
try{
commitTransaction(em);
} catch (RuntimeException e){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
address = employee.getAddress();
manager = employee.getManager();
assertTrue("The address was not persisted.", employee.getAddress() != null);
assertTrue("The address was not correctly persisted.", employee.getAddress().getCity().equals("Metropolis"));
assertTrue("The manager was not persisted.", employee.getManager() != null);
assertTrue("The manager was not correctly persisted.", employee.getManager().getFirstName().equals("Metro"));
Address initialAddress = em.find(Address.class, new Integer(addressId));
Employee initialManager = em.find(Employee.class, new Integer(managerId));
employee.setAddress((Address)null);
em.remove(address);
em.remove(employee);
em.remove(manager);
em.remove(initialAddress);
em.remove(initialManager);
commitTransaction(em);
}
/**
* Bug 801
* Test to ensure when property access is used and the underlying variable is changed the change
* is correctly reflected in the database
*
* In this test we test making the change when an existing object is read into a new EM
*/
public void testSetFieldForPropertyAccessWithNewEM(){
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setFirstName("Andy");
employee.setLastName("Dufresne");
Employee manager = new Employee();
manager.setFirstName("Bobby");
manager.setLastName("Dufresne");
employee.setManager(manager);
Address address = new Address();
address.setCity("Shawshank");
employee.setAddress(address);
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
int id = employee.getId();
int addressId = address.getId();
int managerId = manager.getId();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
employee.getAddress();
employee.getManager();
address = new Address();
address.setCity("Metropolis");
employee.setAddress(address);
manager = new Employee();
manager.setFirstName("Metro");
manager.setLastName("Dufresne");
employee.setManagerField(manager);
try {
commitTransaction(em);
} catch (RuntimeException e){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
address = employee.getAddress();
manager = employee.getManager();
assertTrue("The address was not persisted.", employee.getAddress() != null);
assertTrue("The address was not correctly persisted.", employee.getAddress().getCity().equals("Metropolis"));
assertTrue("The manager was not persisted.", employee.getManager() != null);
assertTrue("The manager was not correctly persisted.", employee.getManager().getFirstName().equals("Metro"));
Address initialAddress = em.find(Address.class, new Integer(addressId));
Employee initialManager = em.find(Employee.class, new Integer(managerId));
employee.setAddress((Address)null);
em.remove(address);
em.remove(employee);
em.remove(manager);
em.remove(initialAddress);
em.remove(initialManager);
commitTransaction(em);
}
//bug gf674 - EJBQL delete query with IS NULL in WHERE clause produces wrong sql
public void testDeleteAllPhonesWithNullOwner() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("DELETE FROM PhoneNumber ph WHERE ph.owner IS NULL").executeUpdate();
} catch (Exception e) {
fail("Exception thrown: " + e.getClass());
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
public void testDeleteAllProjectsWithNullTeamLeader() {
internalDeleteAllProjectsWithNullTeamLeader("Project");
}
public void testDeleteAllSmallProjectsWithNullTeamLeader() {
internalDeleteAllProjectsWithNullTeamLeader("SmallProject");
}
public void testDeleteAllLargeProjectsWithNullTeamLeader() {
internalDeleteAllProjectsWithNullTeamLeader("LargeProject");
}
protected void internalDeleteAllProjectsWithNullTeamLeader(String className) {
String name = "testDeleteAllProjectsWithNull";
// setup
SmallProject sp = new SmallProject();
sp.setName(name);
LargeProject lp = new LargeProject();
lp.setName(name);
EntityManager em = createEntityManager();
try {
beginTransaction(em);
// make sure there are no pre-existing objects with this name
em.createQuery("DELETE FROM "+className+" p WHERE p.name = '"+name+"'").executeUpdate();
em.persist(sp);
em.persist(lp);
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// test
em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("DELETE FROM "+className+" p WHERE p.name = '"+name+"' AND p.teamLeader IS NULL").executeUpdate();
commitTransaction(em);
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
// verify
String error = null;
em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(p) FROM Project p WHERE p.name = '"+name+"'").getResultList();
if(result.isEmpty()) {
if(!className.equals("Project")) {
error = "Target Class " + className +": no objects left";
}
} else {
if(result.size() > 1) {
error = "Target Class " + className +": too many objects left: " + result.size();
} else {
Project p = (Project)result.get(0);
if(p.getClass().getName().endsWith(className)) {
error = "Target Class " + className +": object of wrong type left: " + p.getClass().getName();
}
}
}
// clean up
try {
beginTransaction(em);
// make sure there are no pre-existing objects with this name
em.createQuery("DELETE FROM "+className+" p WHERE p.name = '"+name+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
if(error != null) {
fail(error);
}
}
// gf1408: DeleteAll and UpdateAll queries broken on some db platforms;
// gf1451: Complex updates to null using temporary storage do not work on Derby;
// gf1860: TopLink provides too few values.
// The tests forces the use of temporary storage to test null assignment to an integer field
// on all platforms.
public void testUpdateUsingTempStorage() {
internalUpdateUsingTempStorage(false);
}
public void testUpdateUsingTempStorageWithParameter() {
internalUpdateUsingTempStorage(true);
}
protected void internalUpdateUsingTempStorage(boolean useParameter) {
String firstName = "testUpdateUsingTempStorage";
int n = 3;
// setup
EntityManager em = createEntityManager();
try {
beginTransaction(em);
// make sure there are no pre-existing objects with this name
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
em.createQuery("DELETE FROM Address a WHERE a.country = '"+firstName+"'").executeUpdate();
// populate Employees
for(int i=1; i<=n; i++) {
Employee emp = new Employee();
emp.setFirstName(firstName);
emp.setLastName(Integer.toString(i));
emp.setSalary(i*100);
emp.setRoomNumber(i);
Address address = new Address();
address.setCountry(firstName);
address.setCity(Integer.toString(i));
emp.setAddress(address);
em.persist(emp);
}
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// test
em = createEntityManager();
beginTransaction(em);
int nUpdated = 0;
try {
if(useParameter) {
nUpdated = em.createQuery("UPDATE Employee e set e.salary = e.roomNumber, e.roomNumber = e.salary, e.address = :address where e.firstName = '" + firstName + "'").setParameter("address", null).executeUpdate();
} else {
nUpdated = em.createQuery("UPDATE Employee e set e.salary = e.roomNumber, e.roomNumber = e.salary, e.address = null where e.firstName = '" + firstName + "'").executeUpdate();
}
commitTransaction(em);
} catch (Exception e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("Exception thrown: " + e.getClass());
} finally {
closeEntityManager(em);
}
// verify
String error = null;
em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
closeEntityManager(em);
int nReadBack = result.size();
if(n != nUpdated) {
error = "n = "+n+", but nUpdated ="+nUpdated+";";
}
if(n != nReadBack) {
error = " n = "+n+", but nReadBack ="+nReadBack+";";
}
for(int i=0; i<nReadBack; i++) {
Employee emp = (Employee)result.get(i);
if(emp.getAddress() != null) {
error = " Employee "+emp.getLastName()+" still has address;";
}
int ind = Integer.valueOf(emp.getLastName()).intValue();
if(emp.getSalary() != ind) {
error = " Employee "+emp.getLastName()+" has wrong salary "+emp.getSalary()+";";
}
if(emp.getRoomNumber() != ind*100) {
error = " Employee "+emp.getLastName()+" has wrong roomNumber "+emp.getRoomNumber()+";";
}
}
// clean up
em = createEntityManager();
try {
beginTransaction(em);
// make sure there are no objects left with this name
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
em.createQuery("DELETE FROM Address a WHERE a.country = '"+firstName+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
if(error != null) {
fail(error);
}
}
protected void createProjectsWithName(String name, Employee teamLeader) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
SmallProject sp = new SmallProject();
sp.setName(name);
LargeProject lp = new LargeProject();
lp.setName(name);
em.persist(sp);
em.persist(lp);
if(teamLeader != null) {
SmallProject sp2 = new SmallProject();
sp2.setName(name);
sp2.setTeamLeader(teamLeader);
LargeProject lp2 = new LargeProject();
lp2.setName(name);
lp2.setTeamLeader(teamLeader);
em.persist(sp2);
em.persist(lp2);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
protected void deleteProjectsWithName(String name) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.createQuery("DELETE FROM Project p WHERE p.name = '"+name+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
public void testUpdateAllSmallProjects() {
internalTestUpdateAllProjects(SmallProject.class);
}
public void testUpdateAllLargeProjects() {
internalTestUpdateAllProjects(LargeProject.class);
}
public void testUpdateAllProjects() {
internalTestUpdateAllProjects(Project.class);
}
protected void internalTestUpdateAllProjects(Class cls) {
String className = Helper.getShortClassName(cls);
String name = "testUpdateAllProjects";
String newName = "testUpdateAllProjectsNEW";
HashMap map = null;
boolean ok = false;
try {
// setup
// populate Projects - necessary only if no SmallProject and/or LargeProject objects already exist.
createProjectsWithName(name, null);
// save the original names of projects: will set them back in cleanup
// to restore the original state.
EntityManager em = createEntityManager();
List projects = em.createQuery("SELECT OBJECT(p) FROM Project p").getResultList();
map = new HashMap(projects.size());
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
map.put(p.getId(), p.getName());
}
// test
beginTransaction(em);
try {
em.createQuery("UPDATE "+className+" p set p.name = '"+newName+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// verify
em = createEntityManager();
String errorMsg = "";
projects = em.createQuery("SELECT OBJECT(p) FROM Project p").getResultList();
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
String readName = p.getName();
if(cls.isInstance(p)) {
if(!newName.equals(readName)) {
errorMsg = errorMsg + "haven't updated name: " + p + "; ";
}
} else {
if(newName.equals(readName)) {
errorMsg = errorMsg + "have updated name: " + p + "; ";
}
}
}
closeEntityManager(em);
if(errorMsg.length() > 0) {
fail(errorMsg);
} else {
ok = true;
}
} finally {
// clean-up
try {
if(map != null) {
EntityManager em = createEntityManager();
beginTransaction(em);
List projects = em.createQuery("SELECT OBJECT(p) FROM Project p").getResultList();
try {
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
String oldName = (String)map.get(((Project)projects.get(i)).getId());
p.setName(oldName);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
// delete projects that createProjectsWithName has created in setup
deleteProjectsWithName(name);
} catch (RuntimeException ex) {
// eat clean-up exception in case the test failed
if(ok) {
throw ex;
}
}
}
}
public void testUpdateAllSmallProjectsWithName() {
internalTestUpdateAllProjectsWithName(SmallProject.class);
}
public void testUpdateAllLargeProjectsWithName() {
internalTestUpdateAllProjectsWithName(LargeProject.class);
}
public void testUpdateAllProjectsWithName() {
internalTestUpdateAllProjectsWithName(Project.class);
}
protected void internalTestUpdateAllProjectsWithName(Class cls) {
String className = Helper.getShortClassName(cls);
String name = "testUpdateAllProjects";
String newName = "testUpdateAllProjectsNEW";
boolean ok = false;
try {
// setup
// make sure no projects with the specified names exist
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
// populate Projects
createProjectsWithName(name, null);
// test
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("UPDATE "+className+" p set p.name = '"+newName+"' WHERE p.name = '"+name+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// verify
em = createEntityManager();
String errorMsg = "";
List projects = em.createQuery("SELECT OBJECT(p) FROM Project p WHERE p.name = '"+newName+"' OR p.name = '"+name+"'").getResultList();
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
String readName = p.getName();
if(cls.isInstance(p)) {
if(!readName.equals(newName)) {
errorMsg = errorMsg + "haven't updated name: " + p + "; ";
}
} else {
if(readName.equals(newName)) {
errorMsg = errorMsg + "have updated name: " + p + "; ";
}
}
}
closeEntityManager(em);
if(errorMsg.length() > 0) {
fail(errorMsg);
} else {
ok = true;
}
} finally {
// clean-up
// make sure no projects with the specified names left
try {
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
} catch (RuntimeException ex) {
// eat clean-up exception in case the test failed
if(ok) {
throw ex;
}
}
}
}
public void testUpdateAllSmallProjectsWithNullTeamLeader() {
internalTestUpdateAllProjectsWithNullTeamLeader(SmallProject.class);
}
public void testUpdateAllLargeProjectsWithNullTeamLeader() {
internalTestUpdateAllProjectsWithNullTeamLeader(LargeProject.class);
}
public void testUpdateAllProjectsWithNullTeamLeader() {
internalTestUpdateAllProjectsWithNullTeamLeader(Project.class);
}
protected void internalTestUpdateAllProjectsWithNullTeamLeader(Class cls) {
String className = Helper.getShortClassName(cls);
String name = "testUpdateAllProjects";
String newName = "testUpdateAllProjectsNEW";
Employee empTemp = null;
boolean ok = false;
try {
// setup
// make sure no projects with the specified names exist
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
EntityManager em = createEntityManager();
Employee emp = null;
List employees = em.createQuery("SELECT OBJECT(e) FROM Employee e").getResultList();
if(employees.size() > 0) {
emp = (Employee)employees.get(0);
} else {
beginTransaction(em);
try {
emp = new Employee();
emp.setFirstName(name);
emp.setLastName("TeamLeader");
em.persist(emp);
commitTransaction(em);
empTemp = emp;
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
}
closeEntityManager(em);
// populate Projects
createProjectsWithName(name, emp);
// test
em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("UPDATE "+className+" p set p.name = '"+newName+"' WHERE p.name = '"+name+"' AND p.teamLeader IS NULL").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// verify
em = createEntityManager();
String errorMsg = "";
List projects = em.createQuery("SELECT OBJECT(p) FROM Project p WHERE p.name = '"+newName+"' OR p.name = '"+name+"'").getResultList();
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
String readName = p.getName();
if(cls.isInstance(p) && p.getTeamLeader()==null) {
if(!readName.equals(newName)) {
errorMsg = errorMsg + "haven't updated name: " + p + "; ";
}
} else {
if(readName.equals(newName)) {
errorMsg = errorMsg + "have updated name: " + p + "; ";
}
}
}
closeEntityManager(em);
if(errorMsg.length() > 0) {
fail(errorMsg);
} else {
ok = true;
}
} finally {
// clean-up
// make sure no projects with the specified names exist
try {
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
if(empTemp != null) {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("DELETE FROM Employee e WHERE e.id = '"+empTemp.getId()+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
} catch (RuntimeException ex) {
// eat clean-up exception in case the test failed
if(ok) {
throw ex;
}
}
}
}
public void testRollbackOnlyOnException() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
Employee emp = em.find(Employee.class, "");
fail("IllegalArgumentException has not been thrown");
} catch(IllegalArgumentException ex) {
if (isOnServer()) {
assertTrue("Transaction is not roll back only", !isTransactionActive(em));
} else {
assertTrue("Transaction is not roll back only", em.getTransaction().getRollbackOnly());
}
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testClosedEmShouldThrowException() {
// Close is not used on server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
closeEntityManager(em);
String errorMsg = "";
try {
em.clear();
errorMsg = errorMsg + "; em.clear() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.clear() threw wrong exception: " + ex.getMessage();
}
try {
closeEntityManager(em);
errorMsg = errorMsg + "; closeEntityManager(em) didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; closeEntityManager(em) threw wrong exception: " + ex.getMessage();
}
try {
em.contains(null);
errorMsg = errorMsg + "; em.contains() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.contains threw() wrong exception: " + ex.getMessage();
}
try {
em.getDelegate();
errorMsg = errorMsg + "; em.getDelegate() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.getDelegate() threw wrong exception: " + ex.getMessage();
}
try {
em.getReference(Employee.class, new Integer(1));
errorMsg = errorMsg + "; em.getReference() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.getReference() threw wrong exception: " + ex.getMessage();
}
try {
em.joinTransaction();
errorMsg = errorMsg + "; em.joinTransaction() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.joinTransaction() threw wrong exception: " + ex.getMessage();
}
try {
em.lock(null, null);
errorMsg = errorMsg + "; em.lock() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.lock() threw wrong exception: " + ex.getMessage();
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
//gf 1217 - Ensure join table defaults correctly when 'mappedby' not specified
public void testOneToManyDefaultJoinTableName() {
Department dept = new Department();
Employee manager = new Employee();
dept.addManager(manager);
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.persist(dept);
commitTransaction(em);
}catch (RuntimeException e) {
throw e;
}finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
// gf1732
public void testMultipleEntityManagerFactories() {
// close the original factory
closeEntityManagerFactory();
// create the new one - not yet deployed
EntityManagerFactory factory1 = getEntityManagerFactory();
// create the second one
EntityManagerFactory factory2 = Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
// deploy
factory2.createEntityManager();
// close
factory2.close();
try {
// now try to getEM from the first one - this used to throw exception
factory1.createEntityManager();
// don't close factory1 if all is well
} catch (PersistenceException ex) {
fail("factory1.createEM threw exception: " + ex.getMessage());
factory1.close();
}
}
// gf2074: EM.clear throws NPE
public void testClearEntityManagerWithoutPersistenceContext() {
EntityManager em = createEntityManager();
try {
em.clear();
}finally {
closeEntityManager(em);
}
}
// Used by testClearEntityManagerWithoutPersistenceContextSimulateJTA().
// At first tried to use JTATransactionController class, but that introduced dependencies
// on javax.transaction package (and therefore failed in gf entity persistence tests).
static class DummyExternalTransactionController extends org.eclipse.persistence.transaction.AbstractTransactionController {
public boolean isRolledBack_impl(Object status){return false;}
protected void registerSynchronization_impl(org.eclipse.persistence.transaction.AbstractSynchronizationListener listener, Object txn) throws Exception{}
protected Object getTransaction_impl() throws Exception {return null;}
protected Object getTransactionKey_impl(Object transaction) throws Exception {return null;}
protected Object getTransactionStatus_impl() throws Exception {return null;}
protected void beginTransaction_impl() throws Exception{}
protected void commitTransaction_impl() throws Exception{}
protected void rollbackTransaction_impl() throws Exception{}
protected void markTransactionForRollback_impl() throws Exception{}
protected boolean canBeginTransaction_impl(Object status){return false;}
protected boolean canCommitTransaction_impl(Object status){return false;}
protected boolean canRollbackTransaction_impl(Object status){return false;}
protected boolean canIssueSQLToDatabase_impl(Object status){return false;}
protected boolean canMergeUnitOfWork_impl(Object status){return false;}
protected String statusToString_impl(Object status){return "";}
}
// gf2074: EM.clear throws NPE (JTA case)
public void testClearEntityManagerWithoutPersistenceContextSimulateJTA() {
EntityManager em = createEntityManager();
ServerSession ss = ((org.eclipse.persistence.jpa.JpaEntityManager)em).getServerSession();
closeEntityManager(em);
// in non-JTA case session doesn't have external transaction controller
boolean hasExternalTransactionController = ss.hasExternalTransactionController();
if(!hasExternalTransactionController) {
// simulate JTA case
ss.setExternalTransactionController(new DummyExternalTransactionController());
}
try {
testClearEntityManagerWithoutPersistenceContext();
}finally {
if(!hasExternalTransactionController) {
// remove the temporary set TransactionController
ss.setExternalTransactionController(null);
}
}
}
public void testDescriptorNamedQuery(){
ReadAllQuery query = new ReadAllQuery(Employee.class);
ExpressionBuilder builder = new ExpressionBuilder();
Expression exp = builder.get("firstName").equal(builder.getParameter("fName"));
exp = exp.and(builder.get("lastName").equal(builder.getParameter("lName")));
query.setSelectionCriteria(exp);
query.addArgument("fName", String.class);
query.addArgument("lName", String.class);
EntityManager em = createEntityManager();
Session session = ((EntityManagerImpl)em.getDelegate()).getServerSession();
ClassDescriptor descriptor = session.getDescriptor(Employee.class);
descriptor.getQueryManager().addQuery("findByFNameLName", query);
beginTransaction(em);
try {
Employee emp = new Employee();
emp.setFirstName("Melvin");
emp.setLastName("Malone");
em.persist(emp);
em.flush();
Query ejbQuery = ((org.eclipse.persistence.jpa.JpaEntityManager)em).createDescriptorNamedQuery("findByFNameLName", Employee.class);
List results = ejbQuery.setParameter("fName", "Melvin").setParameter("lName", "Malone").getResultList();
assertTrue(results.size() == 1);
emp = (Employee)results.get(0);
assertTrue(emp.getFirstName().equals("Melvin"));
assertTrue(emp.getLastName().equals("Malone"));
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
descriptor.getQueryManager().removeQuery("findByFNameLName");
}
public void testDescriptorNamedQueryForMultipleQueries(){
ReadAllQuery query = new ReadAllQuery(Employee.class);
ExpressionBuilder builder = new ExpressionBuilder();
Expression exp = builder.get("firstName").equal(builder.getParameter("fName"));
exp = exp.and(builder.get("lastName").equal(builder.getParameter("lName")));
query.setSelectionCriteria(exp);
query.addArgument("fName", String.class);
query.addArgument("lName", String.class);
ReadAllQuery query2 = new ReadAllQuery(Employee.class);
EntityManager em = createEntityManager();
Session session = ((EntityManagerImpl)em.getDelegate()).getServerSession();
ClassDescriptor descriptor = session.getDescriptor(Employee.class);
descriptor.getQueryManager().addQuery("findEmployees", query);
descriptor.getQueryManager().addQuery("findEmployees", query2);
beginTransaction(em);
try {
Employee emp = new Employee();
emp.setFirstName("Melvin");
emp.setLastName("Malone");
em.persist(emp);
em.flush();
Vector args = new Vector(2);
args.addElement(String.class);
args.addElement(String.class);
Query ejbQuery = ((org.eclipse.persistence.jpa.JpaEntityManager)em).createDescriptorNamedQuery("findEmployees", Employee.class, args);
List results = ejbQuery.setParameter("fName", "Melvin").setParameter("lName", "Malone").getResultList();
assertTrue(results.size() == 1);
emp = (Employee)results.get(0);
assertTrue(emp.getFirstName().equals("Melvin"));
assertTrue(emp.getLastName().equals("Malone"));
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
descriptor.getQueryManager().removeQuery("findEmployees");
}
// GF 2621
public void testDoubleMerge(){
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setId(44);
employee.setVersion(0);
employee.setFirstName("Alfie");
Employee employee2 = new Employee();
employee2.setId(44);
employee2.setVersion(0);
employee2.setFirstName("Phillip");
try {
beginTransaction(em);
em.merge(employee);
em.merge(employee2);
em.flush();
} catch (PersistenceException e){
fail("A double merge of an object with the same key, caused two inserts instead of one.");
} finally {
rollbackTransaction(em);
}
}
// gf 3032
public void testPessimisticLockHintStartsTransaction(){
Assert.assertFalse("Warning: DerbyPlatform does not currently support pessimistic locking", ((Session)JUnitTestCase.getServerSession()).getPlatform().isDerby());
Assert.assertFalse("Warning: PostgreSQLPlatform. does not currently support pessimistic locking", ((Session)JUnitTestCase.getServerSession()).getPlatform().isPostgreSQL());
EntityManagerImpl em = (EntityManagerImpl)createEntityManager();
beginTransaction(em);
Query query = em.createNamedQuery("findAllEmployeesByFirstName");
query.setHint("eclipselink.pessimistic-lock", PessimisticLock.Lock);
query.setParameter("firstname", "Sarah");
List results = query.getResultList();
assertTrue("The extended persistence context is not in a transaction after a pessmimistic lock query", em.getActivePersistenceContext(em.getTransaction()).getParent().isInTransaction());
rollbackTransaction(em);
}
/**
* Test that all of the classes in the advanced model were weaved as expected.
*/
public void testWeaving() {
// Only test if weaving was on, test runs without weaving must set this system property.
if (System.getProperty("TEST_NO_WEAVING") == null) {
internalTestWeaving(new Employee(), true, true);
internalTestWeaving(new FormerEmployment(), true, false);
internalTestWeaving(new Address(), true, false);
internalTestWeaving(new PhoneNumber(), true, false);
internalTestWeaving(new EmploymentPeriod(), true, false);
internalTestWeaving(new Buyer(), false, false); // field-locking
internalTestWeaving(new GoldBuyer(), false, false); // field-locking
internalTestWeaving(new PlatinumBuyer(), false, false); // field-locking
internalTestWeaving(new Department(), false, false); // eager 1-m
internalTestWeaving(new Golfer(), true, false);
internalTestWeaving(new GolferPK(), true, false);
internalTestWeaving(new SmallProject(), true, false);
internalTestWeaving(new LargeProject(), true, false);
internalTestWeaving(new SuperLargeProject(), true, false);
internalTestWeaving(new Man(), true, false);
internalTestWeaving(new Woman(), true, false);
internalTestWeaving(new Vegetable(), false, false); // serialized
internalTestWeaving(new VegetablePK(), false, false);
internalTestWeaving(new WorldRank(), true, false);
internalTestWeaving(new Equipment(), true, false);
internalTestWeaving(new EquipmentCode(), true, false);
internalTestWeaving(new PartnerLink(), true, false);
}
}
/**
* Test that the object was weaved.
*/
public void internalTestWeaving(Object object, boolean changeTracking, boolean indirection) {
if (!(object instanceof PersistenceWeaved)) {
fail("Object not weaved:" + object);
}
if (indirection && (!(object instanceof PersistenceWeavedLazy))) {
fail("Object not weaved for indirection:" + object);
}
if (changeTracking && (!(object instanceof ChangeTracker))) {
fail("Object not weaved for ChangeTracker:" + object);
}
ClassDescriptor descriptor = getServerSession().getDescriptor(object);
if (!descriptor.isAggregateDescriptor()) {
if (changeTracking != descriptor.getObjectChangePolicy().isAttributeChangeTrackingPolicy()) {
fail("Descriptor not set to use change tracking policy correctly:" + object);
}
if (!(object instanceof PersistenceEntity)) {
fail("Object not weaved for PersistenceEntity:" + object);
}
if (!(object instanceof FetchGroupTracker)) {
fail("Object not weaved for FetchGroupTracker:" + object);
}
}
}
// this test was failing after transaction ailitche_main_6333458_070821
public void testManyToOnePersistCascadeOnFlush() {
boolean pass = false;
EntityManager em = createEntityManager();
beginTransaction(em);
try {
String firstName = "testManyToOneContains";
Address address = new Address();
address.setCountry(firstName);
Employee employee = new Employee();
employee.setFirstName(firstName);
em.persist(employee);
employee.setAddress(address);
em.flush();
pass = em.contains(address);
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
if(!pass) {
fail("em.contains(address) returned false");
}
}
// This test weaving works with over-writing methods in subclasses, and overloading methods.
public void testOverwrittingAndOverLoadingMethods() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
Address address = new Address();
address.setCity("Ottawa");
Employee employee = new Employee();
employee.setAddress(address);
LargeProject project = new LargeProject();
project.setTeamLeader(employee);
em.persist(employee);
em.persist(project);
commitTransaction(em);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
project = em.find(LargeProject.class, project.getId());
if ((employee.getAddress("Home") == null) || (!employee.getAddress("Home").getCity().equals("Ottawa"))) {
fail("Get address did not work.");
}
employee.setAddress("Toronto");
if (!employee.getAddress().getCity().equals("Toronto")) {
fail("Set address did not work.");
}
if (project.getTeamLeader() != employee) {
fail("Get team leader did not work, team is: " + project.getTeamLeader() + " but should be:" + employee);
}
em.remove(employee.getAddress());
em.remove(employee);
em.remove(project);
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
// This tests that new objects referenced by new objects are found on commit.
public void testDiscoverNewReferencedObject() {
String firstName = "testDiscoverNewReferencedObject";
// setup: create and persist Employee
EntityManager em = createEntityManager();
int employeeId = 0;
beginTransaction(em);
try {
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName("Employee");
em.persist(employee);
commitTransaction(em);
employeeId = employee.getId();
} finally {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
// test: add to the exsisting Employee a new Manager with new Phones
em = createEntityManager();
int managerId = 0;
beginTransaction(em);
try {
Employee manager = new Employee();
manager.setFirstName(firstName);
manager.setLastName("Manager");
PhoneNumber phoneNumber1 = new PhoneNumber("home", "613", "1111111");
manager.addPhoneNumber(phoneNumber1);
PhoneNumber phoneNumber2 = new PhoneNumber("work", "613", "2222222");
manager.addPhoneNumber(phoneNumber2);
Employee employee = em.find(Employee.class, employeeId);
manager.addManagedEmployee(employee);
commitTransaction(em);
managerId = manager.getId();
} finally {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
// verify: were all the new objects written to the data base?
String errorMsg = "";
em = createEntityManager();
try {
Employee manager = (Employee)em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.id = "+managerId).setHint("eclipselink.refresh", "true").getSingleResult();
if(manager == null) {
errorMsg = "Manager hasn't been written into the db";
} else {
if(manager.getPhoneNumbers().size() != 2) {
errorMsg = "Manager has a wrong number of Phones = "+manager.getPhoneNumbers().size()+"; should be 2";
}
}
} finally {
closeEntityManager(em);
}
// clean up: delete Manager - all other object will be cascade deleted.
em = createEntityManager();
beginTransaction(em);
try {
if(managerId != 0) {
Employee manager = em.find(Employee.class, managerId);
em.remove(manager);
} else if(employeeId != 0) {
// if Manager hasn't been created - delete Employee
Employee employee = em.find(Employee.class, employeeId);
em.remove(employee);
}
} finally {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
public void testManagedEmployeesMassInsertUseSequencing() throws Exception {
internalTestManagedEmployeesMassInsertOrMerge(true, true);
}
public void testManagedEmployeesMassInsertDoNotUseSequencing() throws Exception {
internalTestManagedEmployeesMassInsertOrMerge(true, false);
}
public void testManagedEmployeesMassMergeUseSequencing() throws Exception {
internalTestManagedEmployeesMassInsertOrMerge(false, true);
}
public void testManagedEmployeesMassMergeDoNotUseSequencing() throws Exception {
internalTestManagedEmployeesMassInsertOrMerge(false, false);
}
// gf3152: toplink goes into a 2^n loop and comes to a halt on two cascade.
// before the fix this method took almost 10 minutes to complete on my local Oracle db.
// The test
// shouldInsert == true indicate that em.persist should be used,
// otherwise em.merge.
// shouldUseSequencing == true indicates that the pk value will be assigned by sequencing,
// otherwise the test generates ids and directly assignes them into the newly created objects.
protected void internalTestManagedEmployeesMassInsertOrMerge(boolean shouldInsert, boolean shouldUseSequencing) throws Exception {
// Example: nLevels == 3; nDirects = 4.
// First all the Employees corresponding to nLevels and nDirects values are created:
// There is always the single (highest ranking) topEmployee on Level_0;
// He/she has 4 Level_1 direct subordinates;
// each of those has 4 Level_2 directs,
// each of those has 4 Level_3 directs.
// For debugging:
// Employee's firstName is always his level (in "Level_2" format);
// Employee's lastName is his number in his level (from 0 to number of employees of this level - 1)
// in "Number_3" format.
// number of management levels
int nLevels = 2;
// number of direct employees each manager has
int nDirects = 50;
// used to keep ids in case sequencing is not used
int id = 0;
EntityManager em = null;
if(!shouldUseSequencing) {
// obtain the first unused sequence number
Employee emp = new Employee();
em = createEntityManager();
beginTransaction(em);
em.persist(emp);
id = emp.getId();
rollbackTransaction(em);
closeEntityManager(em);
}
// topEmployee - the only one on level 0.
Employee topEmployee = new Employee();
topEmployee.setFirstName("Level_0");
topEmployee.setLastName("Number_0");
if(!shouldUseSequencing) {
topEmployee.setId(id++);
}
// During each nLevel loop iterartion
// this array contains direct managers for the Employees to be created -
// all the Employees of nLevel - 1 level.
ArrayList<Employee> employeesForHigherLevel = new ArrayList<Employee>(1);
// In the end of each nLevel loop iterartion
// this array contains all Employees created during this iteration -
// all the Employees of nLevel level.
ArrayList<Employee> employeesForCurrentLevel;
employeesForHigherLevel.add(topEmployee);
// total number of employees
int nEmployeesTotal = 1;
for (int nLevel = 1; nLevel <= nLevels; nLevel++) {
employeesForCurrentLevel = new ArrayList<Employee>(employeesForHigherLevel.size() * nDirects);
Iterator<Employee> it = employeesForHigherLevel.iterator();
while(it.hasNext()) {
Employee mgr = it.next();
for(int nCurrent = 0; nCurrent < nDirects; nCurrent++) {
Employee employee = new Employee();
employee.setFirstName("Level_" + nLevel);
employee.setLastName("Number_" + employeesForCurrentLevel.size());
if(!shouldUseSequencing) {
employee.setId(id++);
}
employeesForCurrentLevel.add(employee);
mgr.addManagedEmployee(employee);
}
}
employeesForHigherLevel = employeesForCurrentLevel;
nEmployeesTotal = nEmployeesTotal + employeesForCurrentLevel.size();
}
em = createEntityManager();
beginTransaction(em);
try {
if(shouldInsert) {
em.persist(topEmployee);
} else {
em.merge(topEmployee);
}
commitTransaction(em);
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
// cleanup
em = createEntityManager();
beginTransaction(em);
try {
List<Employee> employees = em.createQuery("Select e FROM Employee e WHERE e.firstName LIKE 'Level_%'").getResultList();
Iterator<Employee> i = employees.iterator();
while(i.hasNext()){
Employee emp = i.next();
emp.setManager(null);
emp.setManagedEmployees(null);
em.remove(emp);
}
commitTransaction(em);
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
((EntityManagerImpl)em).getServerSession().getIdentityMapAccessor().initializeAllIdentityMaps();
closeEntityManager(em);
}
}
// bug 6006423: BULK DELETE QUERY FOLLOWED BY A MERGE RETURNS DELETED OBJECT
public void testBulkDeleteThenMerge() {
String firstName = "testBulkDeleteThenMerge";
// setup - create Employee
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName(firstName);
emp.setLastName("Original");
em.persist(emp);
commitTransaction(em);
closeEntityManager(em);
int id = emp.getId();
// test
// delete the Employee using bulk delete
em = createEntityManager();
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
closeEntityManager(em);
// then re-create and merge the Employee using the same pk
em = createEntityManager();
beginTransaction(em);
emp = new Employee();
emp.setId(id);
emp.setFirstName(firstName);
emp.setLastName("New");
em.merge(emp);
try {
commitTransaction(em);
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
// verify
String errorMsg = "";
em = createEntityManager();
// is the right Employee in the cache?
emp = (Employee)em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.id = " + id).getSingleResult();
if(emp == null) {
errorMsg = "Cache: Employee is not found; ";
} else {
if(!emp.getLastName().equals("New")) {
errorMsg = "Cache: wrong lastName = "+emp.getLastName()+"; should be New; ";
}
}
// is the right Employee in the db?
emp = (Employee)em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.id = " + id).setHint("eclipselink.refresh", Boolean.TRUE).getSingleResult();
if(emp == null) {
errorMsg = errorMsg + "DB: Employee is not found";
} else {
if(!emp.getLastName().equals("New")) {
errorMsg = "DB: wrong lastName = "+emp.getLastName()+"; should be New";
}
// clean up in case the employee is in the db
beginTransaction(em);
em.remove(emp);
commitTransaction(em);
}
closeEntityManager(em);
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
public void testNativeSequences() {
ServerSession ss = JUnitTestCase.getServerSession();
boolean doesPlatformSupportIdentity = ss.getPlatform().supportsIdentity();
boolean doesPlatformSupportSequenceObjects = ss.getPlatform().supportsSequenceObjects();
String errorMsg = "";
// SEQ_GEN_IDENTITY sequence defined by
// @GeneratedValue(strategy=IDENTITY)
boolean isIdentity = ss.getPlatform().getSequence("SEQ_GEN_IDENTITY").shouldAcquireValueAfterInsert();
if(doesPlatformSupportIdentity != isIdentity) {
errorMsg = "SEQ_GEN_IDENTITY: doesPlatformSupportIdentity = " + doesPlatformSupportIdentity +", but isIdentity = " + isIdentity +"; ";
}
// ADDRESS_SEQ sequence defined by
// @GeneratedValue(generator="ADDRESS_SEQ")
// @SequenceGenerator(name="ADDRESS_SEQ", allocationSize=25)
boolean isSequenceObject = !ss.getPlatform().getSequence("ADDRESS_SEQ").shouldAcquireValueAfterInsert();
if(doesPlatformSupportSequenceObjects != isSequenceObject) {
errorMsg = errorMsg +"ADDRESS_SEQ: doesPlatformSupportSequenceObjects = " + doesPlatformSupportSequenceObjects +", but isSequenceObject = " + isSequenceObject;
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
/**
* Test that sequence numbers allocated but unused in the transaction
* kept after transaction commits
* in case SequencingCallback used (that happens if TableSequence is used without
* using sequencing connection pool).
*/
public void testSequencePreallocationUsingCallbackTest() {
// setup
ServerSession ss = ((EntityManagerFactoryImpl)getEntityManagerFactory()).getServerSession();
// make sure the sequence has both preallocation and callback
// (the latter means not using sequencing connection pool,
// acquiring values before insert and requiring transaction).
if(ss.getSequencingControl().shouldUseSeparateConnection()) {
fail("setup failure: the test requires serverSession.getSequencingControl().shouldUseSeparateConnection()==false");
}
String seqName = ss.getDescriptor(Employee.class).getSequenceNumberName();
Sequence sequence = getServerSession().getLogin().getSequence(seqName);
if(sequence.getPreallocationSize() < 2) {
fail("setup failure: the test requires sequence preallocation size greater than 1");
}
if(sequence.shouldAcquireValueAfterInsert()) {
fail("setup failure: the test requires sequence that acquires value before insert, like TableSequence");
}
if(!sequence.shouldUseTransaction()) {
fail("setup failure: the test requires sequence that uses transaction, like TableSequence");
}
// clear all already allocated sequencing values for seqName
getServerSession().getSequencingControl().initializePreallocated(seqName);
// test
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp1 = new Employee();
emp1.setFirstName("testSequencePreallocation");
emp1.setLastName("1");
em.persist(emp1);
int assignedSequenceNumber = emp1.getId();
commitTransaction(em);
// verify
em = createEntityManager();
beginTransaction(em);
Employee emp2 = new Employee();
emp2.setFirstName("testSequencePreallocation");
emp2.setLastName("2");
em.persist(emp2);
int nextSequenceNumber = emp2.getId();
// only need nextSequenceNumber, no need to commit
rollbackTransaction(em);
// cleanup
// remove the object that has been created in setup
em = createEntityManager();
beginTransaction(em);
emp1 = em.find(Employee.class, assignedSequenceNumber);
em.remove(emp1);
commitTransaction(em);
// report result
if(assignedSequenceNumber + 1 != nextSequenceNumber) {
fail("Transaction that assigned sequence number committed, assignedSequenceNumber = " + assignedSequenceNumber +", but nextSequenceNumber = "+ nextSequenceNumber +"("+Integer.toString(assignedSequenceNumber+1)+" was expected)");
}
}
/**
* Create a test employee.
*/
protected Employee createEmployee(String name) {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = new Employee();
employee.setFirstName(name);
em.persist(employee);
commitTransaction(em);
return employee;
}
/**
* Test getReference() API.
*/
public void testGetReference() {
int id = createEmployee("testGetReference").getId();
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = em.getReference(Employee.class, id);
if (!employee.getFirstName().equals("testGetReference")) {
fail("getReference returned the wrong object");
}
commitTransaction(em);
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.getReference(Employee.class, id);
if (!employee.getFirstName().equals("testGetReference")) {
fail("getReference returned the wrong object");
}
commitTransaction(em);
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, id);
if (!employee.getFirstName().equals("testGetReference")) {
fail("find returned the wrong object");
}
commitTransaction(em);
}
/**
* Test getReference() with update.
*/
public void testGetReferenceUpdate() {
int id = createEmployee("testGetReference").getId();
clearCache();
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = em.getReference(Employee.class, id);
employee.setFirstName("changed");
commitTransaction(em);
verifyObject(employee);
clearCache();
verifyObject(employee);
}
/**
* Test getReference() used in update.
*/
public void testGetReferenceUsedInUpdate() {
int id = createEmployee("testGetReference").getId();
clearCache();
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = em.getReference(Employee.class, id);
Employee newEmployee = new Employee();
newEmployee.setFirstName("new");
newEmployee.setManager(employee);
em.persist(newEmployee);
commitTransaction(em);
verifyObject(newEmployee);
verifyObject(employee);
clearCache();
verifyObject(newEmployee);
verifyObject(employee);
}
public void testClassInstanceConverter(){
EntityManager em = createEntityManager();
beginTransaction(em);
Address add = new Address();
add.setCity("St. Louis");
add.setType(new Bungalow());
em.persist(add);
commitTransaction(em);
int assignedSequenceNumber = add.getId();
em.clear();
getServerSession().getIdentityMapAccessor().initializeAllIdentityMaps();
add = em.find(Address.class, assignedSequenceNumber);
assertTrue("Did not correctly persist a mapping using a class-instance converter", (add.getType() instanceof Bungalow));
beginTransaction(em);
em.remove(add);
commitTransaction(em);
}
} |
package jsettlers.main.android.mainmenu.presenters.setup;
import java.util.ArrayList;
import java.util.List;
import jsettlers.common.ai.EPlayerType;
import jsettlers.common.player.ECivilisation;
import jsettlers.logic.map.loading.EMapStartResources;
import jsettlers.logic.map.loading.MapLoader;
import jsettlers.logic.player.PlayerSetting;
import jsettlers.main.android.core.GameStarter;
import jsettlers.main.android.mainmenu.presenters.setup.playeritem.Civilisation;
import jsettlers.main.android.mainmenu.presenters.setup.playeritem.PlayerSlotPresenter;
import jsettlers.main.android.mainmenu.presenters.setup.playeritem.PlayerType;
import jsettlers.main.android.mainmenu.presenters.setup.playeritem.PositionChangedListener;
import jsettlers.main.android.mainmenu.presenters.setup.playeritem.StartPosition;
import jsettlers.main.android.mainmenu.presenters.setup.playeritem.Team;
import jsettlers.main.android.mainmenu.views.MapSetupView;
import java8.util.J8Arrays;
public abstract class MapSetupPresenterImpl implements MapSetupPresenter, PositionChangedListener {
private final MapSetupView view;
private final GameStarter gameStarter;
private final MapLoader mapLoader;
private final List<PlayerSlotPresenter> playerSlotPresenters = new ArrayList<>();
private PlayerCount playerCount;
private StartResources startResources;
public MapSetupPresenterImpl(MapSetupView view, GameStarter gameStarter, MapLoader mapLoader) {
this.view = view;
this.gameStarter = gameStarter;
this.mapLoader = mapLoader;
createComputerPlayerSlots();
}
@Override
public void initView() {
view.setNumberOfPlayersOptions(allowedPlayerCounts());
view.setPlayerCount(playerCount);
view.setStartResourcesOptions(startResourcesOptions());
view.setStartResources(new StartResources(EMapStartResources.MEDIUM_GOODS));
view.setPeaceTimeOptions(peaceTimeOptions());
view.setMapImage(mapLoader.getImage());
}
@Override
public void updateViewTitle() {
view.setMapName(mapLoader.getMapName());
}
@Override
public void viewFinished() {
if (gameStarter.getStartingGame() == null) {
abort();
}
}
@Override
public void dispose() {
}
protected void abort() {
}
@Override
public void playerCountSelected(PlayerCount item) {
playerCount = item;
updateViewItems();
}
@Override
public void startResourcesSelected(StartResources item) {
startResources = item;
}
protected void updateViewItems() {
view.setItems(getPlayerSlotPresenters(), playerCount.getNumberOfPlayers());
}
protected List<PlayerSlotPresenter> getPlayerSlotPresenters() {
return playerSlotPresenters;
}
protected PlayerCount getPlayerCount() {
return playerCount;
}
/**
* Get items for the main map options
*/
private PlayerCount[] allowedPlayerCounts() {
int maxPlayers = mapLoader.getMaxPlayers();
int minPlayers = mapLoader.getMinPlayers();
int numberOfOptions = maxPlayers - minPlayers + 1;
PlayerCount[] allowedPlayerCounts = new PlayerCount[numberOfOptions];
for (int i = 0; i < numberOfOptions; i++) {
allowedPlayerCounts[i] = new PlayerCount(minPlayers + i);
}
return allowedPlayerCounts;
}
private StartResources[] startResourcesOptions() {
return J8Arrays.stream(EMapStartResources.values())
.map(StartResources::new)
.toArray(StartResources[]::new);
}
private Peacetime[] peaceTimeOptions() {
return new Peacetime[] { new Peacetime("Without") };
}
/**
* Player slots setup
* Sets up the player slots as computer players. Subclasses can then modify the slots for any single or multi player human players.
*/
private void createComputerPlayerSlots() {
playerCount = new PlayerCount(mapLoader.getMaxPlayers());
PlayerSetting[] playerSettings = mapLoader.getFileHeader().getPlayerSettings();
for (byte i = 0; i < playerCount.getNumberOfPlayers(); i++) {
PlayerSlotPresenter playerSlotPresenter = new PlayerSlotPresenter(this);
PlayerSetting playerSetting = playerSettings[i];
playerSlotPresenter.setName("Computer " + i);
playerSlotPresenter.setShowReadyControl(false);
setComputerSlotPlayerTypes(playerSlotPresenter);
setSlotCivilisations(playerSlotPresenter, playerSetting);
setSlotStartPositions(playerSlotPresenter, playerCount.getNumberOfPlayers(), i);
setSlotTeams(playerSlotPresenter, playerSetting, playerCount.getNumberOfPlayers(), i);
playerSlotPresenters.add(playerSlotPresenter);
}
}
protected static void setHumanSlotPlayerTypes(PlayerSlotPresenter playerSlotPresenter) {
playerSlotPresenter.setPossiblePlayerTypes(new PlayerType[] {
new PlayerType(EPlayerType.HUMAN),
new PlayerType(EPlayerType.AI_VERY_HARD),
new PlayerType(EPlayerType.AI_HARD),
new PlayerType(EPlayerType.AI_EASY),
new PlayerType(EPlayerType.AI_VERY_EASY)
});
playerSlotPresenter.setPlayerType(new PlayerType(EPlayerType.HUMAN));
}
protected static void setComputerSlotPlayerTypes(PlayerSlotPresenter playerSlotPresenter) {
playerSlotPresenter.setPossiblePlayerTypes(new PlayerType[] {
new PlayerType(EPlayerType.AI_VERY_HARD),
new PlayerType(EPlayerType.AI_HARD),
new PlayerType(EPlayerType.AI_EASY),
new PlayerType(EPlayerType.AI_VERY_EASY)
});
playerSlotPresenter.setPlayerType(new PlayerType(EPlayerType.AI_VERY_HARD));
}
private static void setSlotCivilisations(PlayerSlotPresenter playerSlotPresenter, PlayerSetting playerSetting) {
playerSlotPresenter.setPossibleCivilisations(new Civilisation[] { new Civilisation(ECivilisation.ROMAN) });
if (playerSetting.getCivilisation() != null) {
playerSlotPresenter.setCivilisation(new Civilisation(playerSetting.getCivilisation()));
} else {
playerSlotPresenter.setCivilisation(new Civilisation(ECivilisation.ROMAN));
}
}
private static void setSlotStartPositions(PlayerSlotPresenter playerSlotPresenter, int numberOfPlayers, byte orderNumber) {
playerSlotPresenter.setPossibleStartPositions(numberOfPlayers);
playerSlotPresenter.setStartPosition(new StartPosition(orderNumber));
}
private static void setSlotTeams(PlayerSlotPresenter playerSlotPresenter, PlayerSetting playerSetting, int numberOfPlayers, byte orderNumber) {
playerSlotPresenter.setPossibleTeams(numberOfPlayers);
if (playerSetting.getTeamId() != null) {
playerSlotPresenter.setTeam(new Team(playerSetting.getTeamId()));
} else {
playerSlotPresenter.setTeam(new Team(orderNumber));
}
}
/**
* PositionChangedListener implementation
*/
@Override
public void positionChanged(PlayerSlotPresenter updatedPlayerSlotPresenter, StartPosition oldPosition, StartPosition newPosition) {
for (PlayerSlotPresenter playerSlotPresenter : playerSlotPresenters) {
if (playerSlotPresenter != updatedPlayerSlotPresenter && playerSlotPresenter.getStartPosition().equals(newPosition)) {
playerSlotPresenter.setStartPosition(oldPosition);
}
}
}
} |
package org.eclipse.kura.net.admin.monitor;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.eclipse.kura.KuraException;
import org.eclipse.kura.core.net.EthernetInterfaceConfigImpl;
import org.eclipse.kura.core.net.NetworkConfiguration;
import org.eclipse.kura.linux.net.dhcp.DhcpServerManager;
import org.eclipse.kura.linux.net.route.RouteService;
import org.eclipse.kura.linux.net.route.RouteServiceImpl;
import org.eclipse.kura.linux.net.util.LinuxNetworkUtil;
import org.eclipse.kura.net.EthernetMonitorService;
import org.eclipse.kura.net.IP4Address;
import org.eclipse.kura.net.IPAddress;
import org.eclipse.kura.net.NetConfig;
import org.eclipse.kura.net.NetConfigIP4;
import org.eclipse.kura.net.NetInterfaceAddressConfig;
import org.eclipse.kura.net.NetInterfaceConfig;
import org.eclipse.kura.net.NetInterfaceStatus;
import org.eclipse.kura.net.NetInterfaceType;
import org.eclipse.kura.net.NetworkAdminService;
import org.eclipse.kura.net.NetworkPair;
import org.eclipse.kura.net.NetworkService;
import org.eclipse.kura.net.admin.NetworkConfigurationService;
import org.eclipse.kura.net.admin.event.NetworkConfigurationChangeEvent;
import org.eclipse.kura.net.admin.event.NetworkStatusChangeEvent;
import org.eclipse.kura.net.dhcp.DhcpServerConfig4;
import org.eclipse.kura.net.firewall.FirewallAutoNatConfig;
import org.eclipse.kura.net.route.RouteConfig;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EthernetMonitorServiceImpl implements EthernetMonitorService, EventHandler {
private static final Logger s_logger = LoggerFactory.getLogger(EthernetMonitorServiceImpl.class);
private final static String[] EVENT_TOPICS = new String[] {
NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC,
};
private final static long THREAD_INTERVAL = 30000;
private final static long THREAD_TERMINATION_TOUT = 1; // in seconds
private static Map<String, Future<?>> tasks;
private static Map<String, Boolean> stopThreads;
private NetworkService m_networkService;
private EventAdmin m_eventAdmin;
private NetworkAdminService m_netAdminService;
private NetworkConfigurationService m_netConfigService;
private RouteService m_routeService;
private Map<String, InterfaceState> m_interfaceState = new HashMap<String, InterfaceState>();
private Map<String, EthernetInterfaceConfigImpl> m_networkConfiguration = new HashMap<String, EthernetInterfaceConfigImpl>();
private Map<String, EthernetInterfaceConfigImpl> m_newNetworkConfiguration = new HashMap<String, EthernetInterfaceConfigImpl>();
private ExecutorService m_executor;
// Dependencies
public void setNetworkService(NetworkService networkService) {
m_networkService = networkService;
}
public void unsetNetworkService(NetworkService networkService) {
m_networkService = null;
}
public void setEventAdmin(EventAdmin eventAdmin) {
m_eventAdmin = eventAdmin;
}
public void unsetEventAdmin(EventAdmin eventAdmin) {
m_eventAdmin = null;
}
public void setNetworkAdminService(NetworkAdminService netAdminService) {
m_netAdminService = netAdminService;
}
public void unsetNetworkAdminService(NetworkAdminService netAdminService) {
m_netAdminService = null;
}
public void setNetworkConfigurationService(NetworkConfigurationService netConfigService) {
m_netConfigService = netConfigService;
}
public void unsetNetworkConfigurationService(NetworkConfigurationService netConfigService) {
m_netConfigService = null;
}
// Activation APIs
protected void activate(ComponentContext componentContext) {
s_logger.debug("Activating EthernetMonitor Service...");
Dictionary<String, String[]> d = new Hashtable<String, String[]>();
d.put(EventConstants.EVENT_TOPIC, EVENT_TOPICS);
componentContext.getBundleContext().registerService(EventHandler.class.getName(), this, d);
m_routeService = RouteServiceImpl.getInstance();
m_executor = Executors.newFixedThreadPool(2);
// Get initial configurations
try {
NetworkConfiguration netConfiguration = m_netConfigService.getNetworkConfiguration();
if (netConfiguration != null) {
for (NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig: netConfiguration.getNetInterfaceConfigs()) {
if (netInterfaceConfig instanceof EthernetInterfaceConfigImpl) {
s_logger.debug("Adding initial ethernet config for " + netInterfaceConfig.getName());
EthernetInterfaceConfigImpl newEthernetConfig = (EthernetInterfaceConfigImpl) netInterfaceConfig;
m_newNetworkConfiguration.put(netInterfaceConfig.getName(), newEthernetConfig);
m_networkConfiguration.put(netInterfaceConfig.getName(), newEthernetConfig);
}
}
}
} catch (KuraException e) {
s_logger.error("Could not update list of interfaces", e);
}
// Initialize monitors
initializeMonitors();
s_logger.debug("Done Activating EthernetMonitor Service...");
}
protected void deactivate(ComponentContext componentContext) {
for (String key : tasks.keySet()) {
stopMonitor(key);
}
if (m_executor != null) {
s_logger.debug("Terminating EthernetMonitor Thread ...");
m_executor.shutdownNow();
try {
m_executor.awaitTermination(THREAD_TERMINATION_TOUT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
s_logger.warn("Interrupted", e);
}
s_logger.info("EthernetMonitor Thread terminated? - {}", m_executor.isTerminated());
m_executor = null;
}
}
private void monitor(String interfaceName) {
while (!stopThreads.get(interfaceName)) {
try {
List <? extends NetInterfaceAddressConfig> new_niacs = null;
List <? extends NetInterfaceAddressConfig> cur_niacs = null;
InterfaceState currentInterfaceState = null;
boolean interfaceEnabled = false;
boolean isDhcpClient = false;
IP4Address staticGateway = null;
boolean dhcpServerEnabled = false;
IPAddress dhcpServerSubnet = null;
short dhcpServerPrefix = -1;
boolean postStatusChangeEvent = false;
EthernetInterfaceConfigImpl currentInterfaceConfig = m_networkConfiguration.get(interfaceName);
EthernetInterfaceConfigImpl newInterfaceConfig = m_newNetworkConfiguration.get(interfaceName);
// Make sure the Ethernet Controllers are powered
if(!LinuxNetworkUtil.isEthernetControllerPowered(interfaceName)) {
LinuxNetworkUtil.powerOnEthernetController(interfaceName);
}
// If a new configuration exists, compare it to the existing configuration
if (newInterfaceConfig != null) {
// Get all configurations for the interface
new_niacs = newInterfaceConfig.getNetInterfaceAddresses();
if (currentInterfaceConfig != null) {
cur_niacs = currentInterfaceConfig.getNetInterfaceAddresses();
}
if (isConfigChanged(new_niacs, cur_niacs)) {
s_logger.debug("Found a new network configuration for " + interfaceName);
// Disable the interface to be reconfigured below
disableInterface(interfaceName);
// Set the current config to the new config
m_networkConfiguration.put(interfaceName, newInterfaceConfig);
currentInterfaceConfig = newInterfaceConfig;
postStatusChangeEvent = true;
}
m_newNetworkConfiguration.remove(interfaceName);
}
// Monitor for status changes and ensure dhcp server is running when enabled
interfaceEnabled = isEthernetEnabled(currentInterfaceConfig);
InterfaceState prevInterfaceState = m_interfaceState.get(interfaceName);
currentInterfaceState = new InterfaceState(interfaceName);
if(!currentInterfaceState.equals(prevInterfaceState)) {
postStatusChangeEvent = true;
}
// Find if DHCP server or DHCP client mode is enabled
if (currentInterfaceConfig != null) {
NetInterfaceStatus netInterfaceStatus = getStatus(currentInterfaceConfig);
cur_niacs = currentInterfaceConfig.getNetInterfaceAddresses();
if ((cur_niacs != null) && cur_niacs.size() > 0) {
for (NetInterfaceAddressConfig niac : cur_niacs) {
List<NetConfig> netConfigs = niac.getConfigs();
if ((netConfigs != null) && netConfigs.size() > 0) {
for (NetConfig netConfig : netConfigs) {
if (netConfig instanceof DhcpServerConfig4) {
// only enable if Enabled for LAN
if(netInterfaceStatus.equals(NetInterfaceStatus.netIPv4StatusEnabledLAN)) {
dhcpServerEnabled = ((DhcpServerConfig4) netConfig).isEnabled();
dhcpServerSubnet = ((DhcpServerConfig4) netConfig).getSubnet();
dhcpServerPrefix = ((DhcpServerConfig4) netConfig).getPrefix();
} else {
s_logger.trace("Not enabling DHCP server for " + interfaceName + " since it is set to " + netInterfaceStatus);
}
} else if (netConfig instanceof NetConfigIP4) {
isDhcpClient = ((NetConfigIP4) netConfig).isDhcp();
staticGateway = ((NetConfigIP4) netConfig).getGateway();
}
}
}
}
} else {
s_logger.debug("No current net interface addresses for " + interfaceName);
}
} else {
s_logger.debug("Current interface config is null for " + interfaceName);
}
// Enable/disable based on configuration and current status
if(interfaceEnabled) {
if(currentInterfaceState.isUp()) {
if(!currentInterfaceState.isLinkUp()) {
s_logger.debug("link is down - disabling " + interfaceName);
disableInterface(interfaceName);
}
} else {
// State is currently down
if(currentInterfaceState.isLinkUp()) {
s_logger.debug("link is up - enabling " + interfaceName);
m_netAdminService.enableInterface(interfaceName, isDhcpClient);
}
}
} else {
if(currentInterfaceState.isUp()) {
s_logger.debug(interfaceName + " is currently up - disable interface");
disableInterface(interfaceName);
}
}
// Get the status after all ifdowns and ifups
currentInterfaceState = new InterfaceState(interfaceName);
// Manage the DHCP server and validate routes
if (currentInterfaceState != null && currentInterfaceState.isUp() && currentInterfaceState.isLinkUp()) {
NetInterfaceStatus netInterfaceStatus = getStatus(currentInterfaceConfig);
if(netInterfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) {
// This should be the default gateway - make sure it is
boolean found = false;
RouteConfig[] routes = m_routeService.getRoutes();
if(routes != null && routes.length > 0) {
for(RouteConfig route : routes) {
if(route.getInterfaceName().equals(interfaceName) &&
route.getDestination().equals(IPAddress.parseHostAddress("0.0.0.0")) &&
!route.getGateway().equals(IPAddress.parseHostAddress("0.0.0.0"))) {
found = true;
break;
}
}
}
if(!found) {
if (isDhcpClient || (staticGateway != null)) {
//disable the interface and reenable - something didn't happen at initialization as it was supposed to
s_logger.error("WAN interface " + interfaceName + " did not have a route setting it as the default gateway, restarting it");
m_netAdminService.disableInterface(interfaceName);
m_netAdminService.enableInterface(interfaceName, isDhcpClient);
}
}
} else if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledLAN) {
if (isDhcpClient) {
RouteService rs = RouteServiceImpl.getInstance();
RouteConfig rconf = rs.getDefaultRoute(interfaceName);
if (rconf != null) {
s_logger.debug("{} is configured for LAN/DHCP - removing GATEWAY route ...", rconf.getInterfaceName());
rs.removeStaticRoute(rconf.getDestination(), rconf.getGateway(), rconf.getNetmask(), rconf.getInterfaceName());
}
}
}
if(dhcpServerEnabled && !DhcpServerManager.isRunning(interfaceName)) {
s_logger.debug("Starting DHCP server for " + interfaceName);
m_netAdminService.manageDhcpServer(interfaceName, true);
}
} else if(DhcpServerManager.isRunning(interfaceName)) {
s_logger.debug("Stopping DHCP server for " + interfaceName);
m_netAdminService.manageDhcpServer(interfaceName, false);
}
// post event if there were any changes
if(postStatusChangeEvent) {
s_logger.debug("Posting NetworkStatusChangeEvent for " + interfaceName + ": " + currentInterfaceState);
m_eventAdmin.postEvent(new NetworkStatusChangeEvent(interfaceName, currentInterfaceState, null));
m_interfaceState.put(interfaceName, currentInterfaceState);
}
// If the interface is disabled in Denali, stop the monitor
if(!interfaceEnabled) {
s_logger.debug(interfaceName + " is disabled - stopping monitor");
stopMonitor(interfaceName);
}
Thread.sleep(30000);
} catch (KuraException kuraException) {
s_logger.debug(kuraException.getMessage());
} catch (Exception e) {
s_logger.debug(e.getMessage());
}
}
}
// On a network config change event, verify the change was for ethernet and add a new ethernet config
@Override
public void handleEvent(Event event) {
String topic = event.getTopic();
s_logger.debug("handleEvent - topic: " + topic);
if (topic.equals(NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC)) {
NetworkConfigurationChangeEvent netConfigChangedEvent = (NetworkConfigurationChangeEvent)event;
String [] propNames = netConfigChangedEvent.getPropertyNames();
if ((propNames != null) && (propNames.length > 0)) {
Map<String, Object> props = new HashMap<String, Object>();
for (String propName : propNames) {
Object prop = netConfigChangedEvent.getProperty(propName);
if (prop != null) {
props.put(propName, prop);
}
else {
}
}
try {
NetworkConfiguration newNetworkConfig = new NetworkConfiguration(props);
if (newNetworkConfig != null) {
for (NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig: newNetworkConfig.getNetInterfaceConfigs()) {
if (netInterfaceConfig instanceof EthernetInterfaceConfigImpl) {
s_logger.debug("Adding new ethernet config for " + netInterfaceConfig.getName());
EthernetInterfaceConfigImpl newEthernetConfig = (EthernetInterfaceConfigImpl) netInterfaceConfig;
m_newNetworkConfiguration.put(netInterfaceConfig.getName(), newEthernetConfig);
if (isEthernetEnabled(newEthernetConfig)) {
startMonitor(netInterfaceConfig.getName());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// Compare configurations
private boolean isConfigChanged(List <? extends NetInterfaceAddressConfig> newConfig, List <? extends NetInterfaceAddressConfig> currentConfig) {
if(newConfig == null && currentConfig == null) {
return false;
}
if ((newConfig == null || currentConfig == null) || (newConfig.size() != currentConfig.size())) {
return true;
}
for (int i = 0; i < newConfig.size(); i++) {
List<NetConfig> newNetConfigs = newConfig.get(i).getConfigs();
List<NetConfig> currentNetConfigs = currentConfig.get(i).getConfigs();
if(newNetConfigs == null && currentNetConfigs == null) {
continue;
}
if((newNetConfigs == null || currentNetConfigs == null) || (newNetConfigs.size() != currentNetConfigs.size())) {
s_logger.debug("Config changed current - " + currentNetConfigs);
s_logger.debug("Config changed new - " + newNetConfigs);
return true;
}
for(int j = 0; j < newNetConfigs.size(); j++) {
boolean foundMatch = false;
NetConfig newNetConfig = newNetConfigs.get(j);
for(int k = 0; k < currentNetConfigs.size(); k++) {
NetConfig currentNetConfig = currentNetConfigs.get(k);
if(newNetConfig.getClass() == currentNetConfig.getClass()) {
foundMatch = true;
if(!newNetConfig.equals(currentNetConfig) && newNetConfig.getClass() != FirewallAutoNatConfig.class) {
s_logger.debug("\tConfig changed - Current config: " + currentNetConfig.toString());
s_logger.debug("\tConfig changed - New config: " + newNetConfig.toString());
return true;
}
break;
}
}
if(!foundMatch) {
return true;
}
}
/*
if (!newConfig.get(i).equals(currentConfig.get(i))) {
s_logger.debug("\tConfig changed - Old config: " + currentConfig.get(i).toString());
s_logger.debug("\tConfig changed - New config: " + newConfig.get(i).toString());
return true;
}*/
}
return false;
}
// Very the interface is enabled in Denali
private boolean isEthernetEnabled(EthernetInterfaceConfigImpl ethernetInterfaceConfig) {
NetInterfaceStatus status = getStatus(ethernetInterfaceConfig);
return status.equals(NetInterfaceStatus.netIPv4StatusEnabledLAN) || status.equals(NetInterfaceStatus.netIPv4StatusEnabledWAN);
}
private NetInterfaceStatus getStatus(EthernetInterfaceConfigImpl ethernetInterfaceConfig) {
NetInterfaceStatus status = NetInterfaceStatus.netIPv4StatusUnknown;
if (ethernetInterfaceConfig != null) {
for (NetInterfaceAddressConfig addresses : ethernetInterfaceConfig.getNetInterfaceAddresses()) {
for (NetConfig netConfig : addresses.getConfigs()) {
if (netConfig instanceof NetConfigIP4) {
status = ((NetConfigIP4)netConfig).getStatus();
}
}
}
}
return status;
}
// Initialize a monitor thread for each ethernet interface
private void initializeMonitors() {
List<String> currentInterfaceNames;
try {
currentInterfaceNames = m_networkService.getAllNetworkInterfaceNames();
if(currentInterfaceNames != null && currentInterfaceNames.size() > 0) {
for (String interfaceName : currentInterfaceNames) {
// skip non-ethernet interfaces
if(LinuxNetworkUtil.getType(interfaceName) != NetInterfaceType.ETHERNET) {
continue;
}
startMonitor(interfaceName);
}
}
} catch (KuraException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Start a interface specific monitor thread
private void startMonitor(final String interfaceName) {
if (tasks == null) {
tasks = new HashMap<String, Future<?>>();
}
if (stopThreads == null) {
stopThreads = new HashMap<String, Boolean>();
}
stopThreads.put(interfaceName, false);
// Ensure monitor doesn't already exist for this interface
if (tasks.get(interfaceName) == null) {
s_logger.debug("Starting monitor for " + interfaceName);
Future<?> task = m_executor.submit(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("EthernetMonitor_" + interfaceName);
while (!stopThreads.get(interfaceName)) {
try {
monitor(interfaceName);
Thread.sleep(THREAD_INTERVAL);
} catch (InterruptedException interruptedException) {
Thread.currentThread().interrupt();
s_logger.debug(interruptedException.getMessage());
} catch (Throwable t) {
s_logger.error("Exception while monitoring ethernet connection {}", t.toString());
t.printStackTrace();
}
}
}});
tasks.put(interfaceName, task);
}
}
// Stop a interface specific monitor thread
private void stopMonitor(String interfaceName) {
m_interfaceState.remove(interfaceName);
Future<?> task = tasks.get(interfaceName);
if ((task != null) && (!task.isDone())) {
stopThreads.put(interfaceName, true);
s_logger.debug("Stopping monitor for {} ...", interfaceName);
task.cancel(true);
s_logger.info("Monitor for {} cancelled? = {}", interfaceName, task.isDone());
tasks.put(interfaceName, null);
}
}
private void disableInterface(String interfaceName) throws Exception {
LinuxNetworkUtil.disableInterface(interfaceName);
LinuxNetworkUtil.powerOnEthernetController(interfaceName);
m_netAdminService.manageDhcpServer(interfaceName, false);
}
} |
package org.mozilla.mozstumbler.service.stumblerthread.datahandling;
import android.annotation.TargetApi;
import android.location.Location;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.mozilla.mozstumbler.service.AppGlobals;
import org.mozilla.mozstumbler.service.stumblerthread.scanners.cellscanner.CellInfo;
import org.mozilla.mozstumbler.svclocator.ServiceLocator;
import org.mozilla.mozstumbler.svclocator.services.ISystemClock;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
/**
* A StumblerBundle contains stumbling data related to a single GPS lat/long fix.
*/
public final class StumblerBundle implements Parcelable {
/* The maximum number of Wi-Fi access points in a single observation. */
public static final int MAX_WIFIS_PER_LOCATION = 200;
/* The maximum number of cells in a single observation */
public static final int MAX_CELLS_PER_LOCATION = 50;
private final Location mGpsPosition;
private int mTrackSegment = -1;
private final TreeMap<String, ScanResult> mWifiData;
private final TreeMap<String, CellInfo> mCellData;
public StumblerBundle(Location position) {
mGpsPosition = position;
mWifiData = new TreeMap<String, ScanResult>();
mCellData = new TreeMap<String, CellInfo>();
}
public StumblerBundle(Location position, int trackSegment) {
this(position);
mTrackSegment = trackSegment;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
Bundle wifiBundle = new Bundle(ScanResult.class.getClassLoader());
Collection<String> scans = mWifiData.keySet();
for (String s : scans) {
wifiBundle.putParcelable(s, mWifiData.get(s));
}
Bundle cellBundle = new Bundle(CellInfo.class.getClassLoader());
Collection<String> cells = mCellData.keySet();
for (String c : cells) {
cellBundle.putParcelable(c, mCellData.get(c));
}
out.writeBundle(wifiBundle);
out.writeBundle(cellBundle);
out.writeParcelable(mGpsPosition, 0);
out.writeInt(mTrackSegment);
}
public Location getGpsPosition() {
return mGpsPosition;
}
public int getTrackSegment() {
return mTrackSegment;
}
public boolean hasRadioData() {
boolean hasCellData = mCellData != null && !mCellData.isEmpty();
boolean hasWifiData = mWifiData != null && !mWifiData.isEmpty();
return hasCellData || hasWifiData;
}
public Map<String, ScanResult> getUnmodifiableWifiData() {
if (mWifiData == null) {
return null;
}
return Collections.unmodifiableMap(mWifiData);
}
public Map<String, CellInfo> getUnmodifiableCellData() {
if (mCellData == null) {
return null;
}
return Collections.unmodifiableMap(mCellData);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public MLSJSONObject toMLSGeosubmit() throws JSONException {
MLSJSONObject headerFields = new MLSJSONObject();
headerFields.put(DataStorageConstants.ReportsColumns.LAT, Math.floor(mGpsPosition.getLatitude() * 1.0E6) / 1.0E6);
headerFields.put(DataStorageConstants.ReportsColumns.LON, Math.floor(mGpsPosition.getLongitude() * 1.0E6) / 1.0E6);
headerFields.put(DataStorageConstants.ReportsColumns.TIME, mGpsPosition.getTime());
if (mCellData.size() > 0) {
JSONArray cellJSON = new JSONArray();
for (CellInfo c : mCellData.values()) {
JSONObject obj = c.toJSONObject();
cellJSON.put(obj);
}
headerFields.put(DataStorageConstants.ReportsColumns.CELL, cellJSON);
}
if (mWifiData.size() > 0) {
JSONArray wifis = new JSONArray();
long gpsTimeSinceBootInMS = (mGpsPosition.getElapsedRealtimeNanos()/1000000);
for (ScanResult scanResult : mWifiData.values()) {
JSONObject wifiEntry = new JSONObject();
wifiEntry.put("macAddress", scanResult.BSSID);
if (scanResult.frequency != 0) {
wifiEntry.put("frequency", scanResult.frequency);
}
if (scanResult.level != 0) {
wifiEntry.put("signalStrength", scanResult.level);
}
long wifiTimeSinceBootInMS = (scanResult.timestamp / 1000);
long ageMS = wifiTimeSinceBootInMS - gpsTimeSinceBootInMS;
wifiEntry.put("age", ageMS);
wifis.put(wifiEntry);
}
headerFields.put(DataStorageConstants.ReportsColumns.WIFI, wifis);
}
if (mGpsPosition.hasAltitude()) {
headerFields.put(DataStorageConstants.ReportsColumns.ALTITUDE, (float) mGpsPosition.getAltitude());
}
if (mGpsPosition.hasAccuracy()) {
// Note that Android does not support an accuracy measurement specific to altitude
headerFields.put(DataStorageConstants.ReportsColumns.ACCURACY, mGpsPosition.getAccuracy());
}
return headerFields;
}
public JSONObject toMLSGeolocate() throws JSONException {
JSONObject headerFields = new JSONObject();
headerFields.put(DataStorageConstants.ReportsColumns.LAT, Math.floor(mGpsPosition.getLatitude() * 1.0E6) / 1.0E6);
headerFields.put(DataStorageConstants.ReportsColumns.LON, Math.floor(mGpsPosition.getLongitude() * 1.0E6) / 1.0E6);
headerFields.put(DataStorageConstants.ReportsColumns.TIME, mGpsPosition.getTime());
if (mCellData.size() > 0) {
headerFields.put(DataStorageConstants.ReportsColumns.RADIO, firstRadioType());
JSONArray cellJSON = new JSONArray();
for (CellInfo c : mCellData.values()) {
JSONObject obj = c.toJSONObject();
cellJSON.put(obj);
}
headerFields.put(DataStorageConstants.ReportsColumns.CELL, cellJSON);
}
if (mWifiData.size() > 0) {
JSONArray wifis = new JSONArray();
for (ScanResult s : mWifiData.values()) {
JSONObject wifiEntry = new JSONObject();
wifiEntry.put("macAddress", s.BSSID);
if (s.frequency != 0) {
wifiEntry.put("frequency", s.frequency);
}
if (s.level != 0) {
wifiEntry.put("signalStrength", s.level);
}
wifis.put(wifiEntry);
}
headerFields.put(DataStorageConstants.ReportsColumns.WIFI, wifis);
}
return headerFields;
}
private String firstRadioType() {
return mCellData.firstEntry().getValue().getCellRadio();
}
public boolean hasMaxWifisPerLocation() {
return mWifiData.size() == MAX_WIFIS_PER_LOCATION;
}
public boolean hasMaxCellsPerLocation() {
return mCellData.size() == MAX_CELLS_PER_LOCATION;
}
public void addWifiData(String key, ScanResult result) {
if (mWifiData.size() == MAX_WIFIS_PER_LOCATION) {
AppGlobals.guiLogInfo("Max wifi limit reached for this location, ignoring data.");
return;
}
if (!mWifiData.containsKey(key)) {
mWifiData.put(key, result);
}
}
public void addCellData(String key, CellInfo result) {
if (mCellData.size() > MAX_CELLS_PER_LOCATION) {
AppGlobals.guiLogInfo("Max cell limit reached for this location, ignoring data.");
return;
}
if (!mCellData.containsKey(key)) {
mCellData.put(key, result);
}
}
} |
package org.eclipse.dawnsci.remotedataset.test.server;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.eclipse.dawnsci.analysis.api.dataset.IRemoteDataset;
import org.eclipse.dawnsci.analysis.api.io.IRemoteDatasetService;
import org.eclipse.dawnsci.remotedataset.client.RemoteDatasetServiceImpl;
import org.eclipse.dawnsci.remotedataset.server.DataServerMode;
import org.eclipse.dawnsci.remotedataset.server.DiagnosticInfo;
import org.junit.Test;
/**
*
* This class attempts to find out how many threads and file events
* are generated when listening to a file and check that there are not
* too many.
*
* @author Matthew Gerring
*
*
*/
public class FileMonitoringTest extends DataServerTest {
@Test
public void testHDF5FileConnections() throws Exception {
// We force the DataServer into diagnostic mode.
server.setMode(DataServerMode.DIAGNOSTIC);
// Connect to five different chaning files and ensure that only one thread is there.
for (int i = 0; i < 5; i++) {
doConnectionAndDisconnect(i, true);
}
Thread.sleep(1000); // Give it a chance to close out.
DiagnosticInfo info = server.getDiagnosticInfo();
assertTrue("The started thread count was "+info.getCount("Start Thread")+" and should have been 5", info.getCount("Start Thread")==5);
assertTrue("The closed thread count was "+info.getCount("Close Thread")+" and should have been 5", info.getCount("Close Thread")==5);
System.out.println("> testHDF5FileConnections ok");
}
@Test
public void testHDF5FileConnectionsNoListener() throws Exception {
// We force the DataServer into diagnostic mode.
server.setMode(DataServerMode.DIAGNOSTIC);
// Connect to five different chaining files and ensure that only one thread is there.
doConnectionAndDisconnect(0, false);
Thread.sleep(1000); // Give it a chance to close out.
DiagnosticInfo info = server.getDiagnosticInfo();
assertTrue("There should be no file monitor threads started", info.getCount("Start Thread")==0);
assertTrue("There should be no file monitor threads closed", info.getCount("Close Thread")==0);
System.out.println("> testHDF5FileConnectionsNoListener ok");
}
private void doConnectionAndDisconnect(int index, boolean checkListen) throws Exception {
IRemoteDataset data = null;
try {
testIsRunning = true;
final File h5File = startHDF5WritingThread(100);
Thread.sleep(400);
IRemoteDatasetService service = new RemoteDatasetServiceImpl();
data = service.createRemoteDataset("localhost", 8080);
data.setPath(h5File.getAbsolutePath());
data.setDataset("/entry/data/image"); // We just get the first image in the PNG file.
data.connect();
if (checkListen) {
checkAndWait(data, 2000, 100, 1); // This one is unreliable so we reduced the required events.
} else {
Thread.sleep(2000);
}
DiagnosticInfo info = server.getDiagnosticInfo();
if (checkListen) {
assertTrue("The started thread count is "+info.getCount("Start Thread")+" and the closed is "+info.getCount("Close Thread"), (info.getCount("Start Thread")-info.getCount("Close Thread"))==1); // One file changing, there should be one thread.
assertTrue(info.getCount("Close Thread")==index); // Ensure all closed picked up.
}
System.out.println(info);
} finally {
testIsRunning = false;
if (data!=null) data.disconnect();
}
}
} |
package org.eclipse.mylyn.internal.bugzilla.core;
import java.util.Locale;
import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskDataCollector;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Parser for RDF bugzilla query results.
*
* @author Rob Elves
*/
public class SaxBugzillaQueryContentHandler extends DefaultHandler {
private StringBuffer characters;
private final TaskDataCollector collector;
private final String repositoryUrl;
private int resultCount;
private final TaskAttributeMapper mapper;
private TaskData taskData;
public SaxBugzillaQueryContentHandler(String repositoryUrl, TaskDataCollector collector, TaskAttributeMapper mapper) {
this.repositoryUrl = repositoryUrl;
this.collector = collector;
this.mapper = mapper;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
characters.append(ch, start, length);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
characters = new StringBuffer();
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
String parsedText = characters.toString();
BugzillaAttribute tag = BugzillaAttribute.UNKNOWN;
try {
tag = BugzillaAttribute.valueOf(localName.trim().toUpperCase(Locale.ENGLISH));
switch (tag) {
case ID:
taskData = new TaskData(mapper, BugzillaCorePlugin.CONNECTOR_KIND, repositoryUrl, parsedText);
taskData.setPartial(true);
break;
case SHORT_SHORT_DESC:
if (taskData != null) {
BugzillaTaskDataHandler.createAttribute(taskData, BugzillaAttribute.SHORT_DESC)
.setValue(parsedText);
}
break;
case LI:
if (taskData != null) {
collector.accept(taskData);
}
resultCount++;
break;
default:
if (taskData != null) {
BugzillaTaskDataHandler.createAttribute(taskData, tag).setValue(parsedText);
}
break;
}
} catch (RuntimeException e) {
if (e instanceof IllegalArgumentException) {
// ignore unrecognized tags
return;
}
throw e;
}
}
public int getResultCount() {
return resultCount;
}
} |
package ua.com.fielden.platform.entity.query.metadata;
import static java.util.Arrays.asList;
import static ua.com.fielden.platform.entity.AbstractEntity.ID;
import static ua.com.fielden.platform.entity.AbstractEntity.KEY;
import static ua.com.fielden.platform.entity.AbstractUnionEntity.unionProperties;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.expr;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAggregates;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchKeyAndDescOnly;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.orderBy;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select;
import static ua.com.fielden.platform.utils.EntityUtils.getRealProperties;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import ua.com.fielden.platform.dao.QueryExecutionModel;
import ua.com.fielden.platform.data.generator.WithCreatedByUser;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.AbstractPersistentEntity;
import ua.com.fielden.platform.entity.AbstractUnionEntity;
import ua.com.fielden.platform.entity.annotation.MapEntityTo;
import ua.com.fielden.platform.entity.annotation.MapTo;
import ua.com.fielden.platform.entity.query.EntityAggregates;
import ua.com.fielden.platform.entity.query.model.AggregatedResultQueryModel;
import ua.com.fielden.platform.entity.query.model.ExpressionModel;
import ua.com.fielden.platform.entity.query.model.PrimitiveResultQueryModel;
public class DataDependencyQueriesGenerator {
public static QueryExecutionModel<EntityAggregates, AggregatedResultQueryModel> queryForDependentTypesSummary(final Map<Class<? extends AbstractEntity<?>>, Map<Class<? extends AbstractEntity<?>>, Set<String>>> dependenciesMetadata, final Long entityId, final Class<? extends AbstractEntity<?>> entityType) {
final AggregatedResultQueryModel[] queries = produceQueries(dependenciesMetadata, entityType, entityId).toArray(new AggregatedResultQueryModel[] {});
final AggregatedResultQueryModel qry = select(queries).groupBy().prop("type").yield().prop("type").as("type").yield().countAll().as("qty").modelAsAggregate();
return from(qry).with(orderBy().yield("qty").desc().model()).model();
}
public static QueryExecutionModel<EntityAggregates, AggregatedResultQueryModel> queryForDependentTypeDetails(final Map<Class<? extends AbstractEntity<?>>, Map<Class<? extends AbstractEntity<?>>, Set<String>>> dependenciesMetadata, final Long entityId, final Class<? extends AbstractEntity<?>> entityType, final Class<? extends AbstractEntity<?>> detailsType) {
final PrimitiveResultQueryModel[] detailsQueries = produceDetailsQueries(dependenciesMetadata, detailsType).toArray(new PrimitiveResultQueryModel[] {});
final ExpressionModel hasDependencies = detailsQueries.length > 0 ? expr().caseWhen().existsAnyOf(detailsQueries).then().val("Y").otherwise().val("N").end().model()
: expr().val("N").model();
final AggregatedResultQueryModel qry = select(detailsType).
where().
anyOfProps(dependenciesMetadata.get(detailsType).get(entityType).toArray(new String[] {})).eq().val(entityId).
yield().model(select(detailsType).where().prop(ID).eq().extProp(ID).model()).as("entity").
yield().expr(hasDependencies).as("hasDependencies").
modelAsAggregate();
return from(qry).with(fetchAggregates().with("hasDependencies").with("entity", fetchKeyAndDescOnly(detailsType))).with(orderBy().prop("key").asc().model()).model();
}
/**
* Generates map between persistent entity types and persistent entity types referenced by its properties (represented as map between types and set of prop names (as type can contain several props of the same type)).
*
* @param entityTypes
* @return
*/
@SuppressWarnings("unchecked")
public static Map<Class<? extends AbstractEntity<?>>, Map<Class<? extends AbstractEntity<?>>, Set<String>>> produceDependenciesMetadata(final List<Class<? extends AbstractEntity<?>>> entityTypes) {
final Map<Class<? extends AbstractEntity<?>>, Map<Class<? extends AbstractEntity<?>>, Set<String>>> result = new HashMap<>();
for (final Class<? extends AbstractEntity<?>> entityType : entityTypes) {
if (entityType.isAnnotationPresent(MapEntityTo.class) && AbstractPersistentEntity.class.isAssignableFrom(entityType) && !WithCreatedByUser.class.isAssignableFrom(entityType)) {
final Map<Class<? extends AbstractEntity<?>>, Set<String>> pmd = new HashMap<>();
for (Field ep : getRealProperties(entityType)) {
if (ep.isAnnotationPresent(MapTo.class) && !KEY.equals(ep.getName()) && (AbstractPersistentEntity.class.isAssignableFrom(ep.getType()) || AbstractUnionEntity.class.isAssignableFrom(ep.getType()))) {
final boolean isUnionEntityProp = AbstractUnionEntity.class.isAssignableFrom(ep.getType());
final List<Field> props = isUnionEntityProp ? unionProperties((Class<? extends AbstractUnionEntity>) ep.getType()) : asList(ep);
for (Field subProp : props) {
Set<String> existing = pmd.get(subProp.getType());
if (existing == null) {
existing = new HashSet<String>();
pmd.put((Class<? extends AbstractEntity<?>>) subProp.getType(), existing);
}
existing.add(isUnionEntityProp ? ep.getName() + "." + subProp.getName() : subProp.getName());
}
}
}
if (!pmd.isEmpty()) {
result.put(entityType, pmd);
}
}
}
return result;
}
private static List<AggregatedResultQueryModel> produceQueries(final Map<Class<? extends AbstractEntity<?>>, Map<Class<? extends AbstractEntity<?>>, Set<String>>> dependenciesMetadata, final Class<? extends AbstractEntity<?>> entityType, final Long entityId) {
final List<AggregatedResultQueryModel> queries = new ArrayList<>();
for (final Entry<Class<? extends AbstractEntity<?>>, Map<Class<? extends AbstractEntity<?>>, Set<String>>> el : dependenciesMetadata.entrySet()) {
if (el.getValue().containsKey(entityType)) {
final AggregatedResultQueryModel qry = select(el.getKey()).where().anyOfProps(el.getValue().get(entityType).toArray(new String[] {})).eq().val(entityId).yield().val(el.getKey().getName()).as("type").yield().prop(ID).as("entity").modelAsAggregate();
queries.add(qry);
}
}
return queries;
}
private static List<PrimitiveResultQueryModel> produceDetailsQueries(final Map<Class<? extends AbstractEntity<?>>, Map<Class<? extends AbstractEntity<?>>, Set<String>>> dependenciesMetadata, final Class<? extends AbstractEntity<?>> entityType) {
final List<PrimitiveResultQueryModel> queries = new ArrayList<>();
for (final Entry<Class<? extends AbstractEntity<?>>, Map<Class<? extends AbstractEntity<?>>, Set<String>>> el : dependenciesMetadata.entrySet()) {
if (el.getValue().containsKey(entityType)) {
final PrimitiveResultQueryModel qry = select(el.getKey()).where().anyOfProps(el.getValue().get(entityType).toArray(new String[] {})).eq().extProp(ID).yield().prop(ID).modelAsPrimitive();
queries.add(qry);
}
}
return queries;
}
} |
package org.pocketcampus.plugin.freeroom.android.views;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.pocketcampus.android.platform.sdk.core.PluginController;
import org.pocketcampus.android.platform.sdk.tracker.Tracker;
import org.pocketcampus.android.platform.sdk.ui.element.InputBarElement;
import org.pocketcampus.android.platform.sdk.ui.element.OnKeyPressedListener;
import org.pocketcampus.android.platform.sdk.ui.layout.StandardTitledLayout;
import org.pocketcampus.android.platform.sdk.ui.list.LabeledListViewElement;
import org.pocketcampus.plugin.freeroom.R;
import org.pocketcampus.plugin.freeroom.android.FreeRoomAbstractView;
import org.pocketcampus.plugin.freeroom.android.FreeRoomController;
import org.pocketcampus.plugin.freeroom.android.FreeRoomModel;
import org.pocketcampus.plugin.freeroom.android.adapter.ActualOccupationArrayAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.ExpandableListViewAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.ExpandableListViewFavoriteAdapter;
import org.pocketcampus.plugin.freeroom.android.adapter.FRRoomSuggestionArrayAdapter;
import org.pocketcampus.plugin.freeroom.android.iface.IFreeRoomView;
import org.pocketcampus.plugin.freeroom.android.utils.FRRequestDetails;
import org.pocketcampus.plugin.freeroom.android.utils.SetArrayList;
import org.pocketcampus.plugin.freeroom.shared.ActualOccupation;
import org.pocketcampus.plugin.freeroom.shared.AutoCompleteRequest;
import org.pocketcampus.plugin.freeroom.shared.FRPeriod;
import org.pocketcampus.plugin.freeroom.shared.FRRequest;
import org.pocketcampus.plugin.freeroom.shared.FRRoom;
import org.pocketcampus.plugin.freeroom.shared.ImWorkingRequest;
import org.pocketcampus.plugin.freeroom.shared.Occupancy;
import org.pocketcampus.plugin.freeroom.shared.WorkingOccupancy;
import org.pocketcampus.plugin.freeroom.shared.utils.FRTimes;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.TimePicker;
import android.widget.Toast;
import com.markupartist.android.widget.ActionBar.Action;
/**
* <code>FreeRoomHomeView</code> is the main <code>View</code>, it's the entry
* of the plugin. It displays the availabilities for the search given, and for
* your favorites NOW at the start.
* <p>
* All others views are supposed to be popup windows, therefore it's always
* visible.
*
* @author FreeRoom Project Team (2014/05)
* @author Julien WEBER <julien.weber@epfl.ch>
* @author Valentin MINDER <valentin.minder@epfl.ch>
*/
public class FreeRoomHomeView extends FreeRoomAbstractView implements
IFreeRoomView {
/**
* FreeRoom controller in MVC scheme.
*/
private FreeRoomController mController;
/**
* FreeRoom model in MVC scheme.
*/
private FreeRoomModel mModel;
/**
* Titled layout that holds the title and the main layout.
*/
private StandardTitledLayout titleLayout;
/**
* Main layout that hold all UI components.
*/
private LinearLayout mainLayout;
/**
* TextView to display a short message about what is currently displayed.
* It's also the anchor to all the popup windows.
*/
private TextView mTextView;
/**
* ExpandableListView to display the results of occupancies building by
* building.
*/
private ExpandableListView mExpListView;
/**
* Adapter for the results (to display the occupancies).
*/
private ExpandableListViewAdapter<Occupancy> mExpListAdapter;
/**
* View that holds the INFO popup content, defined in xml in layout folder.
*/
private View popupInfoView;
/**
* Window that holds the INFO popup. Note: popup window can be closed by:
* the closing button (red cross), back button, or clicking outside the
* popup.
*/
private PopupWindow popupInfoWindow;
/**
* View that holds the SEARCH dialog content, defined in xml in layout
* folder.
*/
private View mSearchView;
/**
* ListView that holds previous searches.
*/
private ListView searchPreviousListView;
/**
* Dialog that holds the SEARCH Dialog.
*/
private AlertDialog searchDialog;
/**
* View that holds the FAVORITES popup content, defined in xml in layout
* folder.
*/
private View popupFavoritesView;
/**
* Window that holds the FAVORITES popup. Note: popup window can be closed
* by: the closing button (red cross), back button, or clicking outside the
* popup.
*/
private PopupWindow popupFavoritesWindow;
/**
* View that holds the ADDROOM popup content, defined in xml in layout
* folder.
*/
private View mAddRoomView;
/**
* Dialog that holds the ADDROOM Dialog.
*/
private AlertDialog mAddRoomDialog;
/**
* View that holds the SHARE popup content, defined in xml in layout folder.
*/
private View mShareView;
/**
* Dialog that holds the SHARE Dialog.
*/
private AlertDialog mShareDialog;
private int activityWidth;
private int activityHeight;
private LayoutInflater mLayoutInflater;
/**
* Action to perform a customized search.
*/
private Action search = new Action() {
public void performAction(View view) {
refreshPopupSearch();
searchDialog.show();
}
public int getDrawable() {
return R.drawable.magnify2x06;
}
};
/**
* Action to edit the user's favorites.
*/
private Action editFavorites = new Action() {
public void performAction(View view) {
mAdapterFav.notifyDataSetChanged();
popupFavoritesWindow.showAsDropDown(mTextView, 0, 0);
}
public int getDrawable() {
return R.drawable.star2x28;
}
};
/**
* Action to refresh the view (it sends the same stored request again).
* <p>
* TODO: useful? useless ? delete !
*/
private Action refresh = new Action() {
public void performAction(View view) {
refresh();
}
public int getDrawable() {
return R.drawable.refresh2x01;
}
};
@Override
protected Class<? extends PluginController> getMainControllerClass() {
return FreeRoomController.class;
}
@Override
protected void onDisplay(Bundle savedInstanceState,
PluginController controller) {
// Tracker
Tracker.getInstance().trackPageView("freeroom");
// Get and cast the controller and model
mController = (FreeRoomController) controller;
mModel = (FreeRoomModel) controller.getModel();
// Setup the layout
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
titleLayout = (StandardTitledLayout) layoutInflater.inflate(
R.layout.freeroom_layout_home, null);
mainLayout = (LinearLayout) titleLayout
.findViewById(R.id.freeroom_layout_home_main_layout);
// The ActionBar is added automatically when you call setContentView
setContentView(titleLayout);
titleLayout.setTitle(getString(R.string.freeroom_title_main_title));
mExpListView = (ExpandableListView) titleLayout
.findViewById(R.id.freeroom_layout_home_list);
mTextView = (TextView) titleLayout
.findViewById(R.id.freeroom_layout_home_text_summary);
setTextSummary(getString(R.string.freeroom_home_init_please_wait));
initializeView();
titleLayout.removeView(mainLayout);
titleLayout.addFillerView(mainLayout);
initDefaultRequest();
refresh();
// TODO: NOT the right call to handle the intent
handleIntent(getIntent());
}
/**
* This is called when the Activity is resumed.
*
* If the user presses back on the Authentication window, This Activity is
* resumed but we do not have the freeroomCookie. In this case we close the
* Activity.
*/
@Override
protected void onResume() {
super.onResume();
/*
* if(mModel != null && mModel.getFreeRoomCookie() == null) { // Resumed
* and lot logged in? go back finish(); }
*/
if (mController != null) {
mController.sendFRRequest(this);
}
}
/**
* Handles an intent for a search coming from outside.
* <p>
* // TODO: handles occupancy.epfl.ch + pockecampus://
*
* @param intent
* the intent to handle
*/
private void handleSearchIntent(Intent intent) {
// TODO: if search launched by other plugin.
}
@Override
public void initializeView() {
mLayoutInflater = this.getLayoutInflater();
// retrieve display dimensions
Rect displayRectangle = new Rect();
Window window = this.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
activityWidth = displayRectangle.width();
activityHeight = displayRectangle.height();
mExpListAdapter = new ExpandableListViewAdapter<Occupancy>(
getApplicationContext(), mModel.getOccupancyResults(),
mController, this);
mExpListView.setAdapter(mExpListAdapter);
addActionToActionBar(refresh);
addActionToActionBar(editFavorites);
addActionToActionBar(search);
initPopupInfoRoom();
initSearchDialog();
initPopupFavorites();
initAddRoomDialog();
initPopupShare();
}
/**
* Inits the popup to diplay the information about a room.
*/
private void initPopupInfoRoom() {
// construct the popup
// it MUST fill the parent in height, such that weight works in xml for
// heights. Otherwise, some elements may not be displayed anymore
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
popupInfoView = layoutInflater.inflate(
R.layout.freeroom_layout_popup_info, null);
popupInfoWindow = new PopupWindow(popupInfoView,
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
// allows outside clicks to close the popup
popupInfoWindow.setOutsideTouchable(true);
popupInfoWindow.setBackgroundDrawable(new BitmapDrawable());
TextView tv = (TextView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_name);
tv.setText("room"); // TODO
}
/**
* Inits the popup to diplay the favorites.
*/
private ArrayList<String> buildings;
private Map<String, List<FRRoom>> rooms;
private ExpandableListViewFavoriteAdapter mAdapterFav;
private void initPopupFavorites() {
// construct the popup
// it MUST fill the parent in height, such that weight works in xml for
// heights. Otherwise, some elements may not be displayed anymore
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
popupFavoritesView = layoutInflater.inflate(
R.layout.freeroom_layout_popup_fav, null);
popupFavoritesWindow = new PopupWindow(popupFavoritesView,
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
// allows outside clicks to close the popup
popupFavoritesWindow.setOutsideTouchable(true);
popupFavoritesWindow.setBackgroundDrawable(new BitmapDrawable());
Button tv = (Button) popupFavoritesView
.findViewById(R.id.freeroom_layout_popup_fav_add);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!mAddRoomDialog.isShowing()) {
showAddRoomDialog(true);
}
}
});
ExpandableListView lv = (ExpandableListView) popupFavoritesView
.findViewById(R.id.freeroom_layout_popup_fav_list);
// TODO: THIS IS AWWWWWWWFUUUUULLL
// PLEASE STORE FRROOM OBJECTS, NOT THESE UIDS
Map<String, String> allFavorites = mModel.getAllRoomMapFavorites();
HashSet<FRRoom> favoritesAsFRRoom = new HashSet<FRRoom>();
for (Entry<String, String> e : allFavorites.entrySet()) {
// Favorites beeing stored as uid -> doorCode
favoritesAsFRRoom.add(new FRRoom(e.getValue(), e.getKey()));
}
rooms = mModel.sortFRRoomsByBuildingsAndFavorites(favoritesAsFRRoom,
false);
buildings = new ArrayList<String>(rooms.keySet());
mAdapterFav = new ExpandableListViewFavoriteAdapter(this, buildings,
rooms, mModel);
lv.setAdapter(mAdapterFav);
mAdapterFav.notifyDataSetChanged();
}
// true: fav // false: user-def search
private boolean calling = true;
private void showAddRoomDialog(boolean calling) {
mAddRoomDialog.show();
// TODO: reset the data ? the text input, the selected room ?
this.calling = calling;
}
private void treatEndAddPopup() {
if (calling) {
Iterator<FRRoom> iter = selectedRooms.iterator();
while (iter.hasNext()) {
FRRoom mRoom = iter.next();
mModel.addRoomFavorites(mRoom.getUid(), mRoom.getDoorCode());
}
resetUserDefined();
} else {
// we do nothing: reset will be done at search time
mSummarySelectedRoomsTextViewSearchMenu
.setText(getSummaryTextFromCollection(selectedRooms));
}
}
private void initAddRoomDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the AlertDialog from create()
mAddRoomDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mAddRoomDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.WRAP_CONTENT;
mAddRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mAddRoomDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mAddRoomDialog.getWindow().setAttributes(lp);
mAddRoomView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_add_room, null);
// these work perfectly
mAddRoomView.setMinimumWidth((int) (activityWidth * 0.9f));
// mAddRoomView.setMinimumHeight((int) (activityHeight * 0.8f));
mAddRoomDialog.setView(mAddRoomView);
mAddRoomDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
// searchButton.setEnabled(auditSubmit() == 0);
}
});
Button bt_done = (Button) mAddRoomView
.findViewById(R.id.freeroom_layout_dialog_add_room_done);
bt_done.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mAddRoomDialog.dismiss();
treatEndAddPopup();
}
});
mSummarySelectedRoomsTextView = (TextView) mAddRoomView
.findViewById(R.id.freeroom_layout_dialog_add_room_summary);
UIConstructInputBar();
LinearLayout ll = (LinearLayout) mAddRoomView
.findViewById(R.id.freeroom_layout_dialog_add_layout_main);
ll.addView(mAutoCompleteSuggestionInputBarElement);
createSuggestionsList();
}
private void initPopupShare() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.freeroom_dialog_share_title));
builder.setPositiveButton(
getString(R.string.freeroom_dialog_share_button_friends), null);
builder.setNegativeButton(getString(R.string.freeroom_search_cancel),
null);
builder.setNeutralButton(
getString(R.string.freeroom_dialog_share_button_server), null);
builder.setIcon(R.drawable.share_white_50);
// Get the AlertDialog from create()
mShareDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = mShareDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.FILL_PARENT;
mShareDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
mShareDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mShareDialog.getWindow().setAttributes(lp);
mShareView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_share, null);
// these work perfectly
mShareView.setMinimumWidth((int) (activityWidth * 0.95f));
// mShareView.setMinimumHeight((int) (activityHeight * 0.8f));
mShareDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
disableSoftKeyBoard(mShareView);
}
});
mShareDialog.setView(mShareView);
}
public void showPopupShare(final FRPeriod mPeriod, final FRRoom mRoom) {
mShareDialog.hide();
mShareDialog.show();
final TextView tv = (TextView) mShareView
.findViewById(R.id.freeroom_layout_dialog_share_textBasic);
tv.setText(wantToShare(mPeriod, mRoom, ""));
final EditText ed = (EditText) mShareView
.findViewById(R.id.freeroom_layout_dialog_share_text_edit);
ed.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
tv.setText(wantToShare(mPeriod, mRoom, ed.getText().toString()));
return true;
}
});
Button shareWithServer = mShareDialog
.getButton(DialogInterface.BUTTON_NEUTRAL);
shareWithServer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(mPeriod, mRoom, false, ed.getText().toString());
mShareDialog.dismiss();
}
});
Button shareWithFriends = mShareDialog
.getButton(DialogInterface.BUTTON_POSITIVE);
shareWithFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
share(mPeriod, mRoom, true, ed.getText().toString());
mShareDialog.dismiss();
}
});
Spinner spinner = (Spinner) mShareView
.findViewById(R.id.freeroom_layout_dialog_share_spinner_course);
// Create an ArrayAdapter using the string array and a default spinner
// layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO do something with that
System.out.println("selected" + arg0.getItemAtPosition(arg2));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO find out how is this relevant
System.out.println("nothing selected!");
}
});
// it's automatically in center of screen!
mShareDialog.show();
}
/**
* Dismiss the keyboard associated with the view.
*
* @param v
*/
private void disableSoftKeyBoard(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
/**
* Inits the popup to diplay the information about a room.
*/
private void initSearchDialog() {
// Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Various setter methods to set the searchDialog characteristics
builder.setTitle(getString(R.string.freeroom_search_title));
builder.setPositiveButton(getString(R.string.freeroom_search_search),
null);
builder.setNegativeButton(getString(R.string.freeroom_search_cancel),
null);
builder.setNeutralButton(getString(R.string.freeroom_search_reset),
null);
builder.setIcon(R.drawable.magnify2x06);
// Get the AlertDialog from create()
searchDialog = builder.create();
// redefine paramaters to dim screen when displayed
WindowManager.LayoutParams lp = searchDialog.getWindow()
.getAttributes();
lp.dimAmount = 0.60f;
// these doesn't work
lp.width = LayoutParams.FILL_PARENT;
lp.height = LayoutParams.FILL_PARENT;
searchDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
searchDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
searchDialog.getWindow().setAttributes(lp);
mSearchView = mLayoutInflater.inflate(
R.layout.freeroom_layout_dialog_search, null);
// these work perfectly
mSearchView.setMinimumWidth((int) (activityWidth * 0.9f));
mSearchView.setMinimumHeight((int) (activityHeight * 0.8f));
searchDialog.setView(mSearchView);
searchDialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
searchButton.setEnabled(auditSubmit() == 0);
}
});
// this is necessary o/w buttons don't exists!
searchDialog.hide();
searchDialog.show();
searchDialog.dismiss();
resetButton = searchDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
searchButton = searchDialog.getButton(DialogInterface.BUTTON_POSITIVE);
mSummarySelectedRoomsTextViewSearchMenu = (TextView) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_text_summary);
// the view will be removed or the text changed, no worry
mSummarySelectedRoomsTextViewSearchMenu.setText("empty");
searchPreviousListView = (ListView) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_prev_search);
// TODO: previous search
// searchPreviousListView.setAdapter();
initSearch();
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
System.out
.println("TOuch outside the dialog ******************** ");
searchDialog.dismiss();
}
return false;
}
/**
* Overrides the legacy <code>onKeyDown</code> method in order to close the
* popupWindow if one was opened.
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Override back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
boolean flag = false;
if (popupInfoWindow.isShowing()) {
popupInfoWindow.dismiss();
flag = true;
}
if (searchDialog.isShowing()) {
searchDialog.dismiss();
flag = true;
}
if (popupFavoritesWindow.isShowing()) {
popupFavoritesWindow.dismiss();
flag = true;
}
selectedRooms.clear();
if (flag) {
resetUserDefined();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void anyError() {
setTextSummary(getString(R.string.freeroom_home_error_sorry));
}
/**
* Sets the summary text box to the specified text.
*
* @param text
* the new summary to be displayed.
*/
private void setTextSummary(String text) {
mTextView.setText(text);
}
/**
* Constructs the default request (check all the favorites for the next
* valid period) and sets it in the model for future use. You may call
* <code>refresh</code> in order to send it to the server.
*/
private void initDefaultRequest() {
mModel.setFRRequestDetails(validRequest());
}
private FRRequestDetails validRequest() {
Set<String> set = mModel.getAllRoomMapFavorites().keySet();
FRRequestDetails details = null;
if (set.isEmpty()) {
// NO FAV = check all free rooms
details = new FRRequestDetails(FRTimes.getNextValidPeriod(), true,
new ArrayList<String>(1), true, false, false,
new SetArrayList<FRRoom>());
} else {
// FAV: check occupancy of ALL favs
ArrayList<String> array = new ArrayList<String>(set.size());
array.addAll(set);
details = new FRRequestDetails(FRTimes.getNextValidPeriod(), false,
array, false, true, false, new SetArrayList<FRRoom>());
}
return details;
}
/**
* Asks the controller to send again the request which was already set in
* the model.
*/
private void refresh() {
setTextSummary(getString(R.string.freeroom_home_please_wait));
mController.sendFRRequest(this);
}
@Override
public void freeRoomResultsUpdated() {
// we do nothing here
}
@Override
public void occupancyResultUpdated() {
// we do nothing here
}
@Override
public void occupancyResultsUpdated() {
StringBuilder build = new StringBuilder(50);
if (mModel.getOccupancyResults().isEmpty()) {
build.append(getString(R.string.freeroom_home_error_no_results));
} else {
FRRequest request = mModel.getFRRequestDetails();
if (request.isOnlyFreeRooms()) {
build.append(getString(R.string.freeroom_home_info_free_rooms));
} else {
build.append(getString(R.string.freeroom_home_info_rooms));
}
FRPeriod period = request.getPeriod();
build.append(generateFullTimeSummary(period));
}
setTextSummary(build.toString());
mExpListAdapter.notifyDataSetChanged();
updateCollapse(mExpListView, mExpListAdapter);
}
/**
* Expands all the groups if there are no more than 4 groups or not more
* than 10 results.
* <p>
* TODO defines these consts somewhere else
*
* @param ev
*/
public void updateCollapse(ExpandableListView ev,
ExpandableListViewAdapter<Occupancy> ad) {
System.out.println("check: " + ad.getGroupCount() + "/"
+ ad.getChildrenTotalCount()); // TODO delete
if (ad.getGroupCount() <= 4 || ad.getChildrenTotalCount() <= 10) {
System.out.println("i wanted to expand");
// TODO: this cause troubles in performance when first launch
for (int i = 0; i < ad.getGroupCount(); i++) {
ev.expandGroup(i);
}
}
}
/**
* Generates a string summary of a given period of time.
* <p>
* eg: "Wednesday Apr 24 from 9am to 12pm"
*
* @param period
* the period of time
* @return a string summary of a given period of time.
*/
private String generateFullTimeSummary(FRPeriod period) {
StringBuilder build = new StringBuilder(100);
Date endDate = new Date(period.getTimeStampEnd());
Date startDate = new Date(period.getTimeStampStart());
SimpleDateFormat day_month = new SimpleDateFormat(
getString(R.string.freeroom_pattern_day_format));
SimpleDateFormat hour_min = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format));
build.append(" ");
// TODO: if date is today, use "today" instead of specifying date
build.append(getString(R.string.freeroom_check_occupancy_result_onthe));
build.append(" ");
build.append(day_month.format(startDate));
build.append(" ");
build.append(getString(R.string.freeroom_check_occupancy_result_from));
build.append(" ");
build.append(hour_min.format(startDate));
build.append(" ");
build.append(getString(R.string.freeroom_check_occupancy_result_to));
build.append(" ");
build.append(hour_min.format(endDate));
return build.toString();
}
/**
* Generates a short string summary of a given period of time.
* <p>
* eg: "9:00\n12:00pm"
*
* @param period
* the period of time
* @return a string summary of a given period of time.
*/
private String generateShortTimeSummary(FRPeriod period) {
StringBuilder build = new StringBuilder(100);
Date endDate = new Date(period.getTimeStampEnd());
Date startDate = new Date(period.getTimeStampStart());
SimpleDateFormat hour_min = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format));
build.append(hour_min.format(startDate));
build.append("\n");
build.append(hour_min.format(endDate));
return build.toString();
}
/**
* Put a onClickListener on an imageView in order to share the location and
* time when clicking share, if available.
*
* @param shareImageView
* the view on which to put the listener
* @param homeView
* reference to the home view
* @param mOccupancy
* the holder of data for location and time
*/
public void setShareClickListener(ImageView shareImageView,
final FreeRoomHomeView homeView, final Occupancy mOccupancy) {
if (!mOccupancy.isIsAtLeastOccupiedOnce()
&& mOccupancy.isIsAtLeastFreeOnce()) {
shareImageView.setClickable(true);
shareImageView.setImageResource(R.drawable.share);
shareImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
homeView.showPopupShare(
getMaxPeriodFromList(mOccupancy.getOccupancy()),
mOccupancy.getRoom());
}
});
} else {
shareImageView.setClickable(false);
shareImageView.setImageResource(R.drawable.share_disabled);
}
}
/**
* Finds the whole period covered by a list of contiguous and ordered of
* occupancies.
*
* @param listOccupations
* the list of occupancies.
* @return the period covered by the list
*/
private FRPeriod getMaxPeriodFromList(List<ActualOccupation> listOccupations) {
long tss = listOccupations.get(0).getPeriod().getTimeStampStart();
long tse = listOccupations.get(listOccupations.size() - 1).getPeriod()
.getTimeStampEnd();
return new FRPeriod(tss, tse, false);
}
/**
* Display the popup that provides more info about the occupation of the
* selected room.
*/
public void displayPopupInfo() {
final Occupancy mOccupancy = mModel.getDisplayedOccupancy();
if (mOccupancy != null) {
TextView tv = (TextView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_name);
final FRRoom mRoom = mOccupancy.getRoom();
String text = mRoom.getDoorCode();
if (mRoom.isSetDoorCodeAlias()) {
// alias is displayed IN PLACE of the official name
// the official name can be found in bottom of popup
text = mRoom.getDoorCodeAlias();
}
tv.setText(text);
TextView periodTextView = (TextView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_period);
periodTextView
.setText(generateShortTimeSummary(getMaxPeriodFromList(mOccupancy
.getOccupancy())));
ImageView iv = (ImageView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_share);
setShareClickListener(iv, this, mOccupancy);
ListView roomOccupancyListView = (ListView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_roomOccupancy);
roomOccupancyListView
.setAdapter(new ActualOccupationArrayAdapter<ActualOccupation>(
getApplicationContext(), mOccupancy.getOccupancy(),
mController, this));
TextView detailsTextView = (TextView) popupInfoView
.findViewById(R.id.freeroom_layout_popup_info_details);
detailsTextView.setText(getInfoFRRoom(mOccupancy.getRoom()));
popupInfoWindow.showAsDropDown(mTextView, 0, 0);
}
}
private void refreshPopupSearch() {
final FRRequestDetails request = mModel.getFRRequestDetails();
if (request != null) {
refreshPopupSearch(request);
}
}
private void refreshPopupSearch(final FRRequestDetails request) {
resetTimes(request.getPeriod());
anyButton.setChecked(request.isAny());
specButton.setChecked(!request.isAny());
favButton.setChecked(request.isFav());
userDefButton.setChecked(request.isUser());
freeButton.setChecked(request.isOnlyFreeRooms());
searchButton.setEnabled(auditSubmit() == 0);
boolean enabled = !request.isAny();
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
if (enabled) {
mOptionalLineLinearLayoutContainer
.addView(mOptionalLineLinearLayoutWrapper);
}
mOptionalLineLinearLayoutWrapper
.removeView(mOptionalLineLinearLayoutWrapperIn);
if (request.isUser()) {
mOptionalLineLinearLayoutWrapper
.addView(mOptionalLineLinearLayoutWrapperIn);
selectedRooms.addAll(request.getUidNonFav());
mSummarySelectedRoomsTextViewSearchMenu
.setText(getSummaryTextFromCollection(selectedRooms));
}
}
public String wantToShare(FRPeriod mPeriod, FRRoom mRoom, String toShare) {
// TODO: in case of "now" request (nextPeriodValid is now), just put
// "i am, now, " instead of
// time
StringBuilder textBuilder = new StringBuilder(100);
textBuilder.append(getString(R.string.freeroom_share_iwillbe) + " ");
textBuilder.append(getString(R.string.freeroom_share_in_room) + " ");
if (mRoom.isSetDoorCodeAlias()) {
textBuilder.append(mRoom.getDoorCodeAlias() + " ("
+ mRoom.getDoorCode() + ") ");
} else {
textBuilder.append(mRoom.getDoorCode() + " ");
}
// TODO: which period to use ?
// in case of specified in request, we should use the personalized
// period
textBuilder.append(generateFullTimeSummary(mPeriod) + ". ");
if (toShare.length() == 0) {
textBuilder.append(getString(R.string.freeroom_share_please_come));
} else {
textBuilder.append(toShare);
}
return textBuilder.toString();
}
private void share(FRPeriod mPeriod, FRRoom mRoom, boolean withFriends,
String toShare) {
WorkingOccupancy work = new WorkingOccupancy(mPeriod, mRoom);
ImWorkingRequest request = new ImWorkingRequest(work,
mModel.getAnonymID());
mController.prepareImWorking(request);
mController.ImWorking(this);
if (withFriends) {
shareWithFriends(mPeriod, mRoom, toShare);
}
}
/**
* Construct the Intent to share the location and time with friends. The
* same information is shared with the server at the same time
*
* @param mPeriod
* time period
* @param mRoom
* location
*/
private void shareWithFriends(FRPeriod mPeriod, FRRoom mRoom, String toShare) {
String sharing = wantToShare(mPeriod, mRoom, toShare);
sharing += " \n" + getString(R.string.freeroom_share_ref_pocket);
Log.v(this.getClass().getName() + "-share", "sharing:" + sharing);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, sharing);
// this ensure that our handler, that is handling home-made text types,
// will also work. But our won't work outside the app, which is needed,
// because it waits for this special type.
/**
* Converts a FRRoom to a String of only major properties, in order to
* display them. It includes name (with alias), type, capacity, surface and
* UID.
* <p>
* TODO: this method may be changed
*
* @param mFrRoom
* @return
*/
private String getInfoFRRoom(FRRoom mFrRoom) {
StringBuilder builder = new StringBuilder(50);
if (mFrRoom.isSetDoorCode()) {
if (mFrRoom.isSetDoorCodeAlias()) {
builder.append(mFrRoom.getDoorCode() + " (alias: "
+ mFrRoom.getDoorCodeAlias() + ")");
} else {
builder.append(mFrRoom.getDoorCode());
}
}
if (mFrRoom.isSetTypeFR() || mFrRoom.isSetTypeEN()) {
builder.append(" / " + getString(R.string.freeroom_popup_info_type)
+ ": ");
if (mFrRoom.isSetTypeFR()) {
builder.append(mFrRoom.getTypeFR());
}
if (mFrRoom.isSetTypeFR() && mFrRoom.isSetTypeEN()) {
builder.append(" / ");
}
if (mFrRoom.isSetTypeFR()) {
builder.append(mFrRoom.getTypeEN());
}
}
if (mFrRoom.isSetCapacity()) {
builder.append(" / "
+ getString(R.string.freeroom_popup_info_capacity) + ": "
+ mFrRoom.getCapacity() + " "
+ getString(R.string.freeroom_popup_info_places));
}
if (mFrRoom.isSetSurface()) {
builder.append(" / "
+ getString(R.string.freeroom_popup_info_surface) + ": "
+ mFrRoom.getSurface() + " "
+ getString(R.string.freeroom_popup_info_sqm));
}
// TODO: for production, remove UID (it's useful for debugging for the
// moment)
if (mFrRoom.isSetUid()) {
// uniq UID must be 1201XXUID, with XX filled with 0 such that
// it has 10 digit
// the prefix "1201" indiquates that it's a EPFL room (not a phone,
// a computer)
String communUID = "1201";
String roomUID = mFrRoom.getUid();
for (int i = roomUID.length() + 1; i <= 6; i++) {
communUID += "0";
}
communUID += roomUID;
builder.append(" / "
+ getString(R.string.freeroom_popup_info_uniqID) + ": "
+ communUID);
}
return builder.toString();
}
// ** REUSED FROM SCRATCH FROM FreeRoomSearchView ** //
private SetArrayList<FRRoom> selectedRooms;
private ListView mAutoCompleteSuggestionListView;
private List<FRRoom> mAutoCompleteSuggestionArrayListFRRoom;
/** The input bar to make the search */
private InputBarElement mAutoCompleteSuggestionInputBarElement;
/** Adapter for the <code>mListView</code> */
private FRRoomSuggestionArrayAdapter<FRRoom> mAdapter;
private DatePickerDialog mDatePickerDialog;
private TimePickerDialog mTimePickerStartDialog;
private TimePickerDialog mTimePickerEndDialog;
private Button showDatePicker;
private Button showStartTimePicker;
private Button showEndTimePicker;
private RadioButton specButton;
private RadioButton anyButton;
private CheckBox favButton;
private CheckBox userDefButton;
/**
* TRUE: "only free rooms" FALSE: "allow non-free rooms"
*/
private CheckBox freeButton;
private Button searchButton;
private Button resetButton;
private Button userDefEditButton;
private Button userDefResetButton;
private ImageButton addHourButton;
private ImageButton upToEndHourButton;
/**
* Stores if the "up to end" button has been trigged.
* <p>
* If yes, the endHour don't follow anymore the startHour when you change
* it. It will be disabled when you change manually the endHour to a value
* under the maximal hour.
*/
private boolean upToEndSelected = false;
private TextView mSummarySelectedRoomsTextView;
private TextView mSummarySelectedRoomsTextViewSearchMenu;
private int yearSelected = -1;
private int monthSelected = -1;
private int dayOfMonthSelected = -1;
private int startHourSelected = -1;
private int startMinSelected = -1;
private int endHourSelected = -1;
private int endMinSelected = -1;
private SimpleDateFormat dateFormat;
private SimpleDateFormat timeFormat;
private LinearLayout mOptionalLineLinearLayoutWrapper;
private LinearLayout mOptionalLineLinearLayoutWrapperIn;
private LinearLayout mOptionalLineLinearLayoutContainer;
private void initSearch() {
mOptionalLineLinearLayoutWrapper = (LinearLayout) searchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_wrapper);
mOptionalLineLinearLayoutContainer = (LinearLayout) searchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_container);
mOptionalLineLinearLayoutWrapperIn = (LinearLayout) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_wrapper_in);
selectedRooms = new SetArrayList<FRRoom>();
formatters();
// createSuggestionsList();
// addAllFavsToAutoComplete();
mAutoCompleteSuggestionArrayListFRRoom = new ArrayList<FRRoom>(10);
resetTimes();
UIConstructPickers();
UIConstructButton();
// UIConstructInputBar();
reset();
}
private void formatters() {
dateFormat = new SimpleDateFormat(
getString(R.string.freeroom_pattern_day_format));
timeFormat = new SimpleDateFormat(
getString(R.string.freeroom_pattern_hour_format));
}
private void UIConstructPickers() {
// First allow the user to select a date
showDatePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_date);
mDatePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int nYear,
int nMonthOfYear, int nDayOfMonth) {
yearSelected = nYear;
monthSelected = nMonthOfYear;
dayOfMonthSelected = nDayOfMonth;
updateDatePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, yearSelected, monthSelected, dayOfMonthSelected);
showDatePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDatePickerDialog.show();
}
});
// Then the starting time of the period
showStartTimePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_start);
mTimePickerStartDialog = new TimePickerDialog(this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int nHourOfDay,
int nMinute) {
int previous = startHourSelected;
startHourSelected = nHourOfDay;
startMinSelected = nMinute;
if (startHourSelected < FRTimes.FIRST_HOUR_CHECK) {
startHourSelected = FRTimes.FIRST_HOUR_CHECK;
startMinSelected = 0;
}
if (startHourSelected >= FRTimes.LAST_HOUR_CHECK) {
startHourSelected = FRTimes.LAST_HOUR_CHECK - 1;
startMinSelected = 0;
}
if (startHourSelected != -1 && !upToEndSelected) {
int shift = startHourSelected - previous;
int newEndHour = endHourSelected + shift;
if (newEndHour > FRTimes.LAST_HOUR_CHECK) {
newEndHour = FRTimes.LAST_HOUR_CHECK;
}
if (newEndHour < FRTimes.FIRST_HOUR_CHECK) {
newEndHour = FRTimes.FIRST_HOUR_CHECK + 1;
}
endHourSelected = newEndHour;
if (endHourSelected == FRTimes.LAST_HOUR_CHECK) {
endMinSelected = 0;
}
updateEndTimePickerAndButton();
}
updateStartTimePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, startHourSelected, startMinSelected, true);
showStartTimePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimePickerStartDialog.show();
}
});
// Then the ending time of the period
showEndTimePicker = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end);
mTimePickerEndDialog = new TimePickerDialog(this,
new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int nHourOfDay,
int nMinute) {
endHourSelected = nHourOfDay;
endMinSelected = nMinute;
if (endHourSelected < startHourSelected) {
endHourSelected = startHourSelected + 1;
}
if (endHourSelected < FRTimes.FIRST_HOUR_CHECK) {
endHourSelected = FRTimes.FIRST_HOUR_CHECK + 1;
endMinSelected = 0;
}
if (endHourSelected == FRTimes.FIRST_HOUR_CHECK
&& endMinSelected <= FRTimes.MIN_MINUTE_INTERVAL) {
endMinSelected = FRTimes.MIN_MINUTE_INTERVAL;
// TODO: if start is not 8h00 (eg 8h10 dont work)
}
if (endHourSelected >= FRTimes.LAST_HOUR_CHECK) {
endHourSelected = FRTimes.LAST_HOUR_CHECK;
endMinSelected = 0;
}
if (endHourSelected != FRTimes.LAST_HOUR_CHECK) {
upToEndSelected = false;
upToEndHourButton.setEnabled(!upToEndSelected);
}
updateEndTimePickerAndButton();
searchButton.setEnabled(auditSubmit() == 0);
}
}, endHourSelected, endMinSelected, true);
showEndTimePicker.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTimePickerEndDialog.show();
}
});
}
private void resetUserDefined() {
// TODO: add/remove
// mGlobalSubLayout.removeView(mAutoCompleteSuggestionInputBarElement);
// mGlobalSubLayout.removeView(mSummarySelectedRoomsTextView);
mOptionalLineLinearLayoutWrapper
.removeView(mOptionalLineLinearLayoutWrapperIn);
selectedRooms.clear();
userDefButton.setChecked(false);
mSummarySelectedRoomsTextView
.setText(getSummaryTextFromCollection(selectedRooms));
mSummarySelectedRoomsTextViewSearchMenu
.setText(getSummaryTextFromCollection(selectedRooms));
mAutoCompleteSuggestionInputBarElement.setInputText("");
}
private void UIConstructButton() {
specButton = (RadioButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_spec);
specButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (specButton.isChecked()) {
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
mOptionalLineLinearLayoutContainer
.addView(mOptionalLineLinearLayoutWrapper);
}
specButton.setChecked(true);
anyButton.setChecked(false);
anyButton.setEnabled(true);
specButton.setChecked(true);
freeButton.setChecked(false);
boolean enabled = true;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
// TODO: is this great ? this guarantees that search is always
// available, but requires two steps to remove the fav (ass
// user-def, remove fav)
favButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
anyButton = (RadioButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_any);
anyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (anyButton.isChecked()) {
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
}
specButton.setChecked(false);
resetUserDefined();
boolean enabled = false;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
favButton.setChecked(false);
userDefButton.setChecked(false);
freeButton.setChecked(true);
anyButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
favButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_fav);
favButton.setEnabled(true);
favButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!userDefButton.isChecked()) {
favButton.setChecked(true);
}
anyButton.setChecked(false);
specButton.setChecked(true);
searchButton.setEnabled(auditSubmit() == 0);
}
});
userDefButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user);
userDefButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (userDefButton.isChecked()) {
anyButton.setChecked(false);
specButton.setChecked(true);
freeButton.setChecked(false);
// TODO: init and use the data.
mOptionalLineLinearLayoutWrapper
.removeView(mOptionalLineLinearLayoutWrapperIn);
mOptionalLineLinearLayoutWrapper
.addView(mOptionalLineLinearLayoutWrapperIn);
mSummarySelectedRoomsTextViewSearchMenu
.setText(getSummaryTextFromCollection(selectedRooms));
showAddRoomDialog(false);
} else if (!favButton.isChecked()) {
userDefButton.setChecked(true);
anyButton.setChecked(false);
specButton.setChecked(true);
freeButton.setChecked(false);
} else {
resetUserDefined();
}
searchButton.setEnabled(auditSubmit() == 0);
}
});
freeButton = (CheckBox) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_non_free);
freeButton.setEnabled(true);
freeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!freeButton.isChecked()) {
anyButton.setChecked(false);
specButton.setChecked(true);
}
searchButton.setEnabled(auditSubmit() == 0);
}
});
searchButton.setEnabled(auditSubmit() == 0);
searchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
prepareSearchQuery();
}
});
resetButton.setEnabled(true);
resetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
reset();
// addAllFavsToAutoComplete();
// we reset the input bar...
// TODO
// mAutoCompleteSuggestionInputBarElement.setInputText("");
}
});
addHourButton = (ImageButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end_plus);
addHourButton.setEnabled(true);
addHourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (endHourSelected <= 18) {
endHourSelected += 1;
updateEndTimePickerAndButton();
mTimePickerEndDialog.updateTime(endHourSelected,
endMinSelected);
}
if (endHourSelected >= 19) {
addHourButton.setEnabled(false);
}
}
});
upToEndHourButton = (ImageButton) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_hour_end_toend);
upToEndHourButton.setEnabled(true);
upToEndHourButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
endHourSelected = FRTimes.LAST_HOUR_CHECK;
endMinSelected = 0;
updateEndTimePickerAndButton();
mTimePickerEndDialog
.updateTime(endHourSelected, endMinSelected);
upToEndSelected = true;
upToEndHourButton.setEnabled(!upToEndSelected);
searchButton.setEnabled(auditSubmit() == 0);
}
});
// on vertical screens, choose fav and choose user-def are vertically
// aligned
// on horizontal screens, there are horizontally aligned.
if (activityHeight > activityWidth) {
LinearLayout mLinearLayout = (LinearLayout) searchDialog
.findViewById(R.id.freeroom_layout_dialog_search_opt_line_semi);
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
}
userDefEditButton = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user_edit);
userDefEditButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showAddRoomDialog(false);
}
});
userDefResetButton = (Button) mSearchView
.findViewById(R.id.freeroom_layout_dialog_search_user_reset);
userDefResetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
resetUserDefined();
}
});
}
// TODO: the InputBar is not used so far
private void UIConstructInputBar() {
final IFreeRoomView view = this;
mAutoCompleteSuggestionInputBarElement = new InputBarElement(
this,
null,
getString(R.string.freeroom_check_occupancy_search_inputbarhint));
mAutoCompleteSuggestionInputBarElement
.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
mAutoCompleteSuggestionInputBarElement
.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
String query = mAutoCompleteSuggestionInputBarElement
.getInputText();
Log.v(this.getClass().toString(),
"we do nothing here... with query: "
+ query);
}
return true;
}
});
mAutoCompleteSuggestionInputBarElement
.setOnButtonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String query = mAutoCompleteSuggestionInputBarElement
.getInputText();
if (query.length() >= 2) {
AutoCompleteRequest request = new AutoCompleteRequest(
query);
mController.autoCompleteBuilding(view, request);
}
}
});
mAdapter = new FRRoomSuggestionArrayAdapter<FRRoom>(
getApplicationContext(),
mAutoCompleteSuggestionArrayListFRRoom, mModel);
mAutoCompleteSuggestionInputBarElement
.setOnKeyPressedListener(new OnKeyPressedListener() {
@Override
public void onKeyPressed(String text) {
mAutoCompleteSuggestionListView.setAdapter(mAdapter);
if (mAutoCompleteSuggestionInputBarElement
.getInputText().length() == 0) {
mAutoCompleteSuggestionInputBarElement
.setButtonText(null);
mAutoCompleteSuggestionListView.invalidate();
addAllFavsToAutoComplete();
} else {
mAutoCompleteSuggestionInputBarElement
.setButtonText("");
if (text.length() >= 2) {
AutoCompleteRequest request = new AutoCompleteRequest(
text);
mController.autoCompleteBuilding(view, request);
}
}
}
});
}
private void addAllFavsToAutoComplete() {
Map<String, String> map = mModel.getAllRoomMapFavorites();
mAutoCompleteSuggestionArrayListFRRoom.clear();
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String uid = iter.next();
String doorCode = map.get(uid);
FRRoom room = new FRRoom(doorCode, uid);
if (!selectedRooms.contains(room)) {
mAutoCompleteSuggestionArrayListFRRoom.add(room);
}
}
mAdapter.notifyDataSetChanged();
}
/**
* Initialize the autocomplete suggestion list
*/
private void createSuggestionsList() {
mAutoCompleteSuggestionListView = new LabeledListViewElement(this);
mAutoCompleteSuggestionInputBarElement
.addView(mAutoCompleteSuggestionListView);
mAutoCompleteSuggestionListView
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int pos, long id) {
FRRoom room = mAutoCompleteSuggestionArrayListFRRoom
.get(pos);
addRoomToCheck(room);
searchButton.setEnabled(auditSubmit() == 0);
// refresh the autocomplete, such that selected rooms
// are not displayed
if (mAutoCompleteSuggestionInputBarElement
.getInputText().length() == 0) {
addAllFavsToAutoComplete();
} else {
autoCompletedUpdated();
}
// WE DONT REMOVE the text in the input bar
// INTENTIONNALLY: user may want to select multiple
// rooms in the same building
}
});
mAutoCompleteSuggestionListView.setAdapter(mAdapter);
}
private void addRoomToCheck(FRRoom room) {
// we only add if it already contains the room
if (!selectedRooms.contains(room)) {
selectedRooms.add(room);
mSummarySelectedRoomsTextView
.setText(getSummaryTextFromCollection(selectedRooms));
} else {
Log.e(this.getClass().toString(),
"room cannot be added: already added");
}
}
private String getSummaryTextFromCollection(Collection<FRRoom> collec) {
Iterator<FRRoom> iter = collec.iterator();
StringBuffer buffer = new StringBuffer(collec.size() * 5);
FRRoom room = null;
buffer.append(getString(R.string.freeroom_check_occupancy_search_text_selected_rooms)
+ " ");
boolean empty = true;
while (iter.hasNext()) {
empty = false;
room = iter.next();
buffer.append(room.getDoorCode() + ", ");
}
buffer.setLength(buffer.length() - 2);
int MAX = 100;
if (buffer.length() > MAX) {
buffer.setLength(MAX);
buffer.append("...");
}
String result = "";
if (empty) {
result = getString(R.string.freeroom_check_occupancy_search_text_no_selected_rooms);
} else {
result = buffer.toString();
}
return result;
}
/**
* Reset the year, month, day, hour_start, minute_start, hour_end,
* minute_end to their initial values. DONT forget to update the date/time
* pickers afterwards.
*/
private void resetTimes() {
FRPeriod mFrPeriod = FRTimes.getNextValidPeriod();
resetTimes(mFrPeriod);
}
private void resetTimes(FRPeriod mFrPeriod) {
Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(mFrPeriod.getTimeStampStart());
yearSelected = mCalendar.get(Calendar.YEAR);
monthSelected = mCalendar.get(Calendar.MONTH);
dayOfMonthSelected = mCalendar.get(Calendar.DAY_OF_MONTH);
startHourSelected = mCalendar.get(Calendar.HOUR_OF_DAY);
startMinSelected = mCalendar.get(Calendar.MINUTE);
mCalendar.setTimeInMillis(mFrPeriod.getTimeStampEnd());
endHourSelected = mCalendar.get(Calendar.HOUR_OF_DAY);
endMinSelected = mCalendar.get(Calendar.MINUTE);
}
private void reset() {
searchButton.setEnabled(false);
// // reset the list of selected rooms
selectedRooms.clear();
// mSummarySelectedRoomsTextView
// .setText(getString(R.string.freeroom_check_occupancy_search_text_no_selected_rooms));
mAutoCompleteSuggestionArrayListFRRoom.clear();
resetTimes();
anyButton.setChecked(true);
mOptionalLineLinearLayoutContainer
.removeView(mOptionalLineLinearLayoutWrapper);
specButton.setChecked(false);
favButton.setChecked(false);
userDefButton.setChecked(false);
// resetUserDefined(); TODO
freeButton.setChecked(true);
// verify the submit
searchButton.setEnabled(auditSubmit() == 0);
boolean enabled = false;
favButton.setEnabled(enabled);
userDefButton.setEnabled(enabled);
freeButton.setEnabled(enabled);
// show the buttons
updateDateTimePickersAndButtons();
}
/**
* Updates ALL the date and time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the date/time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the date/time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateDateTimePickersAndButtons() {
updateDatePickerAndButton();
updateStartTimePickerAndButton();
updateEndTimePickerAndButton();
}
/**
* Updates the date <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the date selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the date has changed from somewhere else,
* the <code>PickerDialog</code> will reopen with the new value.
*
* <p>
* Instead of the usual format "Wed 24 May", the date is summarize to
* "today", "yesterday", "tomorrow" when relevant.
*/
private void updateDatePickerAndButton() {
// creating selected time
Calendar selected = Calendar.getInstance();
selected.setTimeInMillis(prepareFRFrPeriod().getTimeStampStart());
// creating now time reference
Calendar now = Calendar.getInstance();
// creating tomorrow time reference
Calendar tomorrow = Calendar.getInstance();
tomorrow.roll(Calendar.DAY_OF_MONTH, true);
// creating yesterday time reference
Calendar yesterday = Calendar.getInstance();
yesterday.roll(Calendar.DAY_OF_MONTH, false);
if (FRTimes.compareCalendars(now, selected)) {
showDatePicker.setText(getString(R.string.freeroom_search_today));
} else if (FRTimes.compareCalendars(tomorrow, selected)) {
showDatePicker
.setText(getString(R.string.freeroom_search_tomorrow));
} else if (FRTimes.compareCalendars(yesterday, selected)) {
showDatePicker
.setText(getString(R.string.freeroom_search_yesterday));
} else {
showDatePicker.setText(dateFormat.format(selected.getTime()));
}
mDatePickerDialog.updateDate(yearSelected, monthSelected,
dayOfMonthSelected);
}
/**
* Updates the START time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the START time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the START time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateStartTimePickerAndButton() {
showStartTimePicker
.setText(getString(R.string.freeroom_check_occupancy_search_start)
+ " "
+ timeFormat.format(new Date(prepareFRFrPeriod()
.getTimeStampStart())));
mTimePickerStartDialog.updateTime(startHourSelected, startMinSelected);
}
/**
* Updates the END time <code>PickerDialog</code> and related
* <code>Button</code>.
*
* <p>
* It updates the <code>Button</code> to summarize the END time selected
* according to your language preferences. The <code>PickerDialog</code> is
* also updated: it's useful if the END time has changed from somewhere
* else, the <code>PickerDialog</code> will reopen with the new value.
*/
private void updateEndTimePickerAndButton() {
showEndTimePicker
.setText(getString(R.string.freeroom_check_occupancy_search_end)
+ " "
+ timeFormat.format(new Date(prepareFRFrPeriod()
.getTimeStampEnd())));
if (endHourSelected >= FRTimes.LAST_HOUR_CHECK
|| (endHourSelected == FRTimes.LAST_HOUR_CHECK - 1 && endMinSelected != 0)) {
addHourButton.setEnabled(false);
} else {
addHourButton.setEnabled(true);
}
mTimePickerEndDialog.updateTime(endHourSelected, endMinSelected);
}
/**
* Construct the <code>FRPeriod</code> object asscociated with the current
* selected times.
*
* @return
*/
private FRPeriod prepareFRFrPeriod() {
Calendar start = Calendar.getInstance();
start.set(yearSelected, monthSelected, dayOfMonthSelected,
startHourSelected, startMinSelected, 0);
start.set(Calendar.MILLISECOND, 0);
Calendar end = Calendar.getInstance();
end.set(yearSelected, monthSelected, dayOfMonthSelected,
endHourSelected, endMinSelected, 0);
end.set(Calendar.MILLISECOND, 0);
// constructs the request
return new FRPeriod(start.getTimeInMillis(), end.getTimeInMillis(),
false);
}
/**
* Prepare the actual query to send and set it in the controller
*/
private void prepareSearchQuery() {
FRPeriod period = prepareFRFrPeriod();
List<String> mUIDList = new ArrayList<String>(selectedRooms.size());
if (favButton.isChecked()) {
mUIDList.addAll(mModel.getAllRoomMapFavorites().keySet());
}
if (userDefButton.isChecked()) {
Iterator<FRRoom> iter = selectedRooms.iterator();
while (iter.hasNext()) {
FRRoom room = iter.next();
mUIDList.add(room.getUid());
}
}
boolean any = anyButton.isChecked();
boolean fav = favButton.isChecked();
boolean user = userDefButton.isChecked();
FRRequestDetails details = new FRRequestDetails(period,
freeButton.isChecked(), mUIDList, any, fav, user, selectedRooms);
mModel.setFRRequestDetails(details);
mController.sendFRRequest(this);
searchDialog.dismiss();
resetUserDefined(); // cleans the selectedRooms of userDefined
}
/**
* Check that the times set are valid, according to the shared definition.
*
* @return 0 if times are valids, positive integer otherwise
*/
private int auditTimes() {
// NOT EVEN SET, we don't bother checking
if (yearSelected == -1 || monthSelected == -1
|| dayOfMonthSelected == -1) {
return 1;
}
if (startHourSelected == -1 || endHourSelected == -1
|| startMinSelected == -1 || endMinSelected == -1) {
return 1;
}
// IF SET, we use the shared method checking the prepared period
String errors = FRTimes.validCalendarsString(prepareFRFrPeriod());
if (errors.equals("")) {
return 0;
}
Toast.makeText(
getApplicationContext(),
"Please review the time, should be between Mo-Fr 8am-7pm.\n"
+ "The end should also be after the start, and at least 5 minutes.",
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Errors remaining: \n" + errors, Toast.LENGTH_LONG).show();
return 1;
}
/**
* This method check if the client is allowed to submit a request to the
* server.
*
* @return 0 if there is no error and the client can send the request,
* something else otherwise.
*/
private int auditSubmit() {
if (selectedRooms == null
|| (!anyButton.isChecked() && !favButton.isChecked()
&& userDefButton.isChecked() && selectedRooms.isEmpty())) {
return 1;
}
if (anyButton.isChecked()
&& (favButton.isChecked() || userDefButton.isChecked())) {
return 1;
}
if (!anyButton.isChecked() && !favButton.isChecked()
&& !userDefButton.isChecked()) {
return 1;
}
Set<String> set = mModel.getAllRoomMapFavorites().keySet();
if (favButton.isChecked()
&& set.isEmpty()
&& (!userDefButton.isChecked() || (userDefButton.isChecked() && selectedRooms
.isEmpty()))) {
return 1;
}
// we dont allow query all the room, including non-free
if (anyButton.isChecked() && !freeButton.isChecked()) {
return 1;
}
return auditTimes();
}
@Override
public void autoCompletedUpdated() {
mAdapter.notifyDataSetInvalidated();
mAutoCompleteSuggestionArrayListFRRoom.clear();
// TODO: adapt to use the new version of autocomplete mapped by building
Iterator<List<FRRoom>> iter = mModel.getAutoComplete().values()
.iterator();
System.out.println(mModel.getAutoComplete().values().size());
while (iter.hasNext()) {
List<FRRoom> list = iter.next();
System.out.println(list.size());
Iterator<FRRoom> iterroom = list.iterator();
while (iterroom.hasNext()) {
FRRoom room = iterroom.next();
// rooms that are already selected are not displayed...
if (!selectedRooms.contains(room)) {
mAutoCompleteSuggestionArrayListFRRoom.add(room);
}
}
}
mAdapter.notifyDataSetChanged();
}
} |
package radlab.rain.workload.rubbos;
import java.net.URI;
import java.util.LinkedHashSet;
import java.util.logging.Logger;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Set;
import radlab.rain.Generator;
import radlab.rain.IScoreboard;
import radlab.rain.LoadProfile;
import radlab.rain.Operation;
import radlab.rain.util.HttpTransport;
import radlab.rain.workload.rubbos.model.RubbosUser;
/**
* Base class for RUBBoS operations.
*
* @author <a href="mailto:marco.guazzone@gmail.com">Marco Guazzone</a>
*/
public abstract class RubbosOperation extends Operation
{
public RubbosOperation(boolean interactive, IScoreboard scoreboard)
{
super(interactive, scoreboard);
}
@Override
public void prepare(Generator generator)
{
this._generator = generator;
LoadProfile currentLoadProfile = generator.getLatestLoadProfile();
if (currentLoadProfile != null)
{
this.setGeneratedDuringProfile(currentLoadProfile);
}
// Reset last-search state if we aren't in a search operation
if (this._operationIndex != RubbosGenerator.SEARCH_IN_STORIES_OP
&& this._operationIndex != RubbosGenerator.SEARCH_IN_COMMENTS_OP
&& this._operationIndex != RubbosGenerator.SEARCH_IN_USERS_OP)
{
this.getSessionState().setLastSearchOperation(RubbosUtility.INVALID_STORY_ID);
}
// // Select a random user for current session (if needed)
// RubbosUser loggedUser = this.getGenerator().getUser(this.getSessionState().getLoggedUserId());
// if (this.getUtility().isAnonymousUser(loggedUser))
// loggedUser = this.getGenerator().generateUser();
// this.getSessionState().setLoggedUserId(loggedUser.id);
}
@Override
public void postExecute()
{
this.getSessionState().setLastOperation(this._operationIndex);
final String lastResponse = this.getSessionState().getLastResponse();
if (this.isFailed())
{
this.getLogger().severe("Operation failed to execute. Last response is: " + lastResponse);
this.getSessionState().setLastResponse(null);
}
else if (lastResponse != null)
{
// Look for any image to download
try
{
this.loadImages(this.parseImagesInHtml(lastResponse));
}
catch (Throwable t)
{
this.getLogger().warning("Unable to load images");
this.setFailed(true);
}
// Check for possible errors
if (lastResponse.indexOf("ERROR") != -1)
{
// A logic error happened on the server-side
this.getLogger().severe("Operation completed with server-side errors. Last response is: " + lastResponse);
this.getSessionState().setLastResponse(null);
this.setFailed(true);
}
else if (lastResponse.indexOf("Sorry") != -1)
{
// Nothing matched the request, we have to go back
this.getLogger().warning("Operation completed with warnings. Last response is: " + lastResponse);
this.setFailed(true);
}
}
}
@Override
public void cleanup()
{
// Empty
}
public RubbosGenerator getGenerator()
{
return (RubbosGenerator) this._generator;
}
public HttpTransport getHttpTransport()
{
return this.getGenerator().getHttpTransport();
}
public Random getRandomGenerator()
{
return this.getGenerator().getRandomGenerator();
}
public Logger getLogger()
{
return this.getGenerator().getLogger();
}
public RubbosSessionState getSessionState()
{
return this.getGenerator().getSessionState();
}
public RubbosUtility getUtility()
{
return this.getGenerator().getUtility();
}
public RubbosConfiguration getConfiguration()
{
return this.getGenerator().getConfiguration();
}
/**
* Parses an HTML document for image URLs specified by IMG tags.
*
* @param buffer The HTTP response; expected to be an HTML document.
* @return An unordered set of image URLs.
*/
protected Set<String> parseImagesInHtml(String html)
{
String regex = null;
regex = ".*?<img\\s+.*?src=\"([^\"]+?)\".*";
this.getLogger().finest("Parsing images from buffer: " + html);
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Set<String> urlSet = new LinkedHashSet<String>();
Matcher match = pattern.matcher(html);
while (match.find())
{
String url = match.group(1);
this.getLogger().finest("Adding " + url);
urlSet.add(url);
}
return urlSet;
}
/**
* Load the image files specified by the image URLs.
*
* @param imageURLs The set of image URLs.
* @return The number of images loaded.
*
* @throws Throwable
*/
protected long loadImages(Set<String> imageUrls) throws Throwable
{
long imagesLoaded = 0;
if (imageUrls != null)
{
for (String imageUrl : imageUrls)
{
URI uri = new URI(this.getGenerator().getBaseURL());
String url = uri.resolve(imageUrl).toString();
this.getLogger().finer("Loading image: " + url);
this.getHttpTransport().fetchUrl(url);
++imagesLoaded;
}
}
return imagesLoaded;
}
} |
package com.ForgeEssentials.backup;
import java.io.File;
import java.io.PrintWriter;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.world.WorldEvent;
import com.ForgeEssentials.api.modules.FEModule;
import com.ForgeEssentials.api.modules.FEModule.Config;
import com.ForgeEssentials.api.modules.FEModule.Init;
import com.ForgeEssentials.api.modules.FEModule.ModuleDir;
import com.ForgeEssentials.api.modules.FEModule.PreInit;
import com.ForgeEssentials.api.modules.FEModule.ServerInit;
import com.ForgeEssentials.api.modules.FEModule.ServerStop;
import com.ForgeEssentials.api.modules.event.FEModuleInitEvent;
import com.ForgeEssentials.api.modules.event.FEModulePreInitEvent;
import com.ForgeEssentials.api.modules.event.FEModuleServerInitEvent;
import com.ForgeEssentials.api.modules.event.FEModuleServerStopEvent;
import com.ForgeEssentials.api.permissions.IPermRegisterEvent;
import com.ForgeEssentials.api.permissions.PermRegister;
import com.ForgeEssentials.api.permissions.RegGroup;
import com.ForgeEssentials.core.ForgeEssentials;
import com.ForgeEssentials.util.FEChatFormatCodes;
import com.ForgeEssentials.util.OutputHandler;
import cpw.mods.fml.common.FMLCommonHandler;
@FEModule(name = "Backups", parentMod = ForgeEssentials.class, configClass = BackupConfig.class)
public class ModuleBackup
{
@Config
public static BackupConfig config;
@ModuleDir
public static File moduleDir;
public static File baseFolder;
public static AutoBackup autoBackup;
public static AutoWorldSave autoWorldSave;
@PreInit
public void preLoad(FEModulePreInitEvent e)
{
}
@Init
public void load(FEModuleInitEvent e)
{
MinecraftForge.EVENT_BUS.register(this);
}
@ServerInit
public void serverStarting(FEModuleServerInitEvent e)
{
e.registerServerCommand(new CommandBackup());
autoBackup = new AutoBackup();
autoWorldSave = new AutoWorldSave();
makeReadme();
}
@ServerStop
public void serverStopping(FEModuleServerStopEvent e)
{
autoBackup.interrupt();
autoWorldSave.interrupt();
}
@PermRegister(ident = "ModuleBackups")
public void registerPermissions(IPermRegisterEvent event)
{
event.registerPermissionLevel("ForgeEssentials.backup", RegGroup.OWNERS);
}
@ForgeSubscribe
public void worldUnload(WorldEvent.Unload e)
{
if (FMLCommonHandler.instance().getEffectiveSide().isServer())
{
if (config.backupIfUnloaded)
{
new Backup((WorldServer) e.world, false);
}
}
}
@ForgeSubscribe
public void worldUnload(WorldEvent.Load e)
{
if (FMLCommonHandler.instance().getEffectiveSide().isServer())
{
if(config.worldSaveing)
{
((WorldServer) e.world).canNotSave = !config.worldSaveing;
}
}
}
public static void msg(String msg)
{
OutputHandler.info(msg);
try
{
for (int var2 = 0; var2 < FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().playerEntityList.size(); ++var2)
{
((EntityPlayerMP) FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().playerEntityList.get(var2)).sendChatToPlayer(FEChatFormatCodes.AQUA + msg);
}
}
catch (Exception e)
{}
}
private void makeReadme()
{
try
{
if(!baseFolder.exists()) baseFolder.mkdirs();
File file = new File(baseFolder, "README.txt");
if (file.exists()) return;
PrintWriter pw = new PrintWriter(file);
pw.println("
pw.println("## WARNING ##");
pw.println("
pw.println("");
pw.println("DON'T CHANGE ANYTHING IN THIS FOLDER.");
pw.println("IF YOU DO, AUTOREMOVE WILL SCREW UP.");
pw.println("");
pw.println("If you have problems with this, report an issue and don't put:");
pw.println("\"Yes, I read the readme\" in the issue or your message on github,");
pw.println("YOU WILL BE IGNORED.");
pw.println("- The FE Team");
pw.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
} |
package org.oasis_eu.portal.core.mongo.dao.geo;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.oasis_eu.portal.core.controller.Languages;
import org.oasis_eu.portal.core.mongo.model.geo.GeographicalArea;
import org.oasis_eu.portal.core.mongo.model.geo.GeographicalAreaReplicationStatus;
import org.oasis_eu.portal.core.services.search.Tokenizer;
import org.oasis_eu.portal.services.PortalSystemUserService;
import org.oasis_eu.portal.services.dc.geoarea.GeographicalDAO;
import org.oasis_eu.spring.datacore.DatacoreClient;
import org.oasis_eu.spring.datacore.model.DCOperator;
import org.oasis_eu.spring.datacore.model.DCOrdering;
import org.oasis_eu.spring.datacore.model.DCQueryParameters;
import org.oasis_eu.spring.datacore.model.DCResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestClientException;
import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteOperation;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
@Repository
public class GeographicalAreaCache {
private static final Logger logger = LoggerFactory.getLogger(GeographicalArea.class);
@Autowired
private DatacoreClient datacore;
@Autowired
private MongoTemplate template;
@Autowired
private Mongo mongo;
@Autowired
private MappingMongoConverter mappingMongoConverter;
@Autowired
GeographicalDAO geographicalDAO;
@Value("${persistence.mongodatabase:portal}")
private String mongoDatabaseName;
@Value("${application.geoarea.replication_batch_size:100}")
private int batchSize = 100;
/** geo_0/1... can also be used to use a version not yet published (i.e. made visible in geo) */
@Value("${application.geoarea.project:geo}")
private String project;
@Value("${application.geoarea.areaModel:geo:Area_0}")
private String areaModel; //"geo:Area_0"; // "geoci:City_0"
@Value("${application.geoarea.nameField:geo:name}")
private String nameField; // or city specific "geoci:name", country-specific "geoco:name"
@Value("${application.geoarea.displayNameField:odisp:name}")
private String displayNameField;// or geo specific "geo:displayName"
@Value("${application.geoarea.searchCronField:@id}")
private String searchCronField;
@Value("${application.geoarea.findOneTokenLimit:100}")
private int findOneTokenLimit;
@Autowired
private Tokenizer tokenizer;
@Autowired
PortalSystemUserService portalSystemUserService;
public Stream<GeographicalArea> search(String country_uri, String modelType, String lang, String name, int start, int limit) {
// This method isn't the nicest to read ever, so here's what it does:
// 1. tokenize the input and search the cache for each token in the input
// 2. flatten the results into one big stream
// 3. reduce the stream into a list of pairs <Area, Frequency>
// 4. sort the stream in reverse frequency order so that results that match multiple query terms come first
// 5. turn this back into a stream of areas and return
class Pair {
GeographicalArea area;
int queryTerms;
int queryMatches = 1;
public Pair(GeographicalArea area, int queryTerms) {
this.area = area;
this.queryTerms = queryTerms;
}
public void inc() {
queryMatches = queryMatches + 1;
}
public void inc(int i) {
queryMatches = queryMatches + i;
}
public float score() {
float l = (float) area.getNameTokens().stream().count();
float v = queryMatches / Math.max((float) queryTerms, l);
return v;
}
}
boolean atLeastOneLongToken=false;
List<String> queryTerms = tokenizer.tokenize(name).stream().collect(Collectors.toList());
for (String token : queryTerms) {
if (token.length() >= 3) { atLeastOneLongToken=true; }
}
if(!atLeastOneLongToken || queryTerms.isEmpty()){
return (new ArrayList<GeographicalArea>()).stream();
}
LinkedHashMap<String, Pair> collected = findOneToken(country_uri, modelType, lang, queryTerms.toArray(new String[queryTerms.size()])) // note that findOneToken doesn't allow duplicate URIs in results
.collect(LinkedHashMap<String, Pair>::new,
(set, area) -> {
if (set.containsKey(area.getUri())) {
set.get(area.getUri()).inc();
} else {
set.put(area.getUri(), new Pair(area, queryTerms.size()));
}
},
(set1, set2) -> {
for (Pair val : set2.values()) {
if (set1.containsKey(val.area.getUri())) {
set1.get(val.area.getUri()).inc(val.queryMatches);
} else {
set1.put(val.area.getUri(), val);
}
}
}
);
return collected.values()
.stream()
.sorted((pair1, pair2) -> new Float(pair2.score()).compareTo(new Float(pair1.score())))
.map(pair -> pair.area)
.skip(start)
.limit(limit);
}
/**
* Search in local DB, filtering the results using the parameters
* @param countryUri URI of DC country Resource, therefore already encoded
* @param modelType
* @param lang
* @param nameTokens null to list all ex. geoco:Country_0
* @return Stream GeographicalArea
*/
public Stream<GeographicalArea> findOneToken(String countryUri, String modelType, String lang, String[] nameTokens) {
// we search irrespective of the replication status, but we deduplicate based on DC Resource URI.
// sort spec means we want older results first - so that incoming replicates are discarded as long as
// there is an online entry
Criteria criteria = where("lang").is(lang);
if (countryUri != null && !countryUri.trim().isEmpty()){
criteria.and("country").is(countryUri); //filter by country
}
if (modelType != null && !modelType.trim().isEmpty()){
criteria.and("modelType").in(modelType);
}
if (nameTokens != null ){
List<Criteria> c = new ArrayList<Criteria>();
for(String nToken : nameTokens){
if (!nToken.trim().isEmpty()){
c.add(where("nameTokens").regex("^"+nToken) );
}
}
if(!c.isEmpty()){
criteria.andOperator(c.toArray(new Criteria[c.size()]));
}
}
List<GeographicalArea> foundAreas = template.find(
query(criteria) // limit to prevent too much performance-hampering object scanning
.with(new Sort(Sort.Direction.ASC, "name"))
.with(new Sort(Sort.Direction.ASC, "replicationTime"))
.limit(findOneTokenLimit),
GeographicalArea.class);
if (foundAreas.size() == findOneTokenLimit) {
// should not happen
logger.warn("Hit findOneTokenLimit (so probably missing some results) on query " + query(criteria));
}
return foundAreas
.stream()
.map(DCUrlWrapper::new)
.distinct()
.map(DCUrlWrapper::unwrap);
}
public void save(GeographicalArea area) {
template.save(area);
}
public int deleteByStatus(GeographicalAreaReplicationStatus status) {
return template.remove(query(where("status").is(status)), GeographicalArea.class).getN();
}
/**
* Switch all "Incoming" entries to "Online"
*/
public void switchToOnline() {
template.updateMulti(
query(where("status").is(GeographicalAreaReplicationStatus.INCOMING)),
Update.update("status", GeographicalAreaReplicationStatus.ONLINE),
GeographicalArea.class
);
}
@Scheduled(cron = "${application.geoarea.replication}")
public void replicate() {
logger.info("Starting replication of geographical data from data core");
DB db = mongo.getDB(mongoDatabaseName);
DBCollection collection = db.getCollection("geographical_area");
Set<String> loadedUris = new HashSet<>();
// 1. fetch all the resources from the data core and insert them with status "incoming" in the cache
try {
//Since there is not admin user connected, is necessary to get its admin authorization object in order to send the request
portalSystemUserService.runAs(new Runnable() {
@Override
public void run() {
String lastDCIdFetched = null;
do {
logger.debug("Fetching batches of areas");
lastDCIdFetched = fetchBatches(collection, loadedUris, lastDCIdFetched);
System.gc();
} while (lastDCIdFetched != null);
}
});
// 2. delete all the "online" entries (they are replaced with the "incoming" ones)
long deleteStart = System.currentTimeMillis();
deleteByStatus(GeographicalAreaReplicationStatus.ONLINE);
logger.debug("Deleted online data in {} ms", System.currentTimeMillis() - deleteStart);
// 3. switch all "incoming" entries to "online"
long switchStart = System.currentTimeMillis();
this.switchToOnline();
logger.debug("Switched to online in {} ms", System.currentTimeMillis() - switchStart);
logger.info("Finish replication of {} geographical records from data core", collection.getCount());
} catch (RestClientException e) {
logger.error("Error while updating the geo area cache", e);
// "rollback"
this.deleteByStatus(GeographicalAreaReplicationStatus.INCOMING);
}
}
private String fetchBatches(DBCollection collection, Set<String> loadedUris, String lastDCIdFetched) {
BulkWriteOperation builder = collection.initializeUnorderedBulkOperation();
String prevDcId = lastDCIdFetched;
DCQueryParameters params;
params = lastDCIdFetched == null
? new DCQueryParameters(searchCronField, DCOrdering.DESCENDING)
: new DCQueryParameters(searchCronField, DCOrdering.DESCENDING, DCOperator.LT, "\""+lastDCIdFetched+"\"");
// (LT & descending order to leave possible null geo:name values at the end rather than having to skip them)
logger.debug("Querying the Data Core");
long queryStart = System.currentTimeMillis();
List<DCResource> resources = datacore.findResources(project, areaModel, params, 0, batchSize);
long queryEnd = System.currentTimeMillis();
logger.debug("Fetched {} resources in {} ms", resources.size(), queryEnd - queryStart);
boolean hasOne = false;
for (DCResource res : resources) {
String name = null;
for (Languages language : Languages.values()) {
GeographicalArea area = geographicalDAO.toGeographicalArea(res, language.getLanguage());
if (area == null) {
continue;
}
if (!loadedUris.contains(language.getLanguage() + area.getUri())) {
hasOne = true;
if (name == null) {
name = area.getName();
//logger.debug("{} - {}", name, area.getUri());
}
DBObject dbObject = new BasicDBObject();
mappingMongoConverter.write(area, dbObject);
builder.insert(dbObject);
loadedUris.add(language.getLanguage() + area.getUri());
} else {
if (name == null) {
name = area.getName();
logger.debug("Area {} already inserted for language {}, skipping", area.getName(), language.getLanguage());
}
}
}
String id = res.getUri(); // ID resource in DC is always encoded, so to match values we need to encoded as well
if (id != null) { lastDCIdFetched = id; }
}
if (hasOne) {
long st = System.currentTimeMillis();
builder.execute();
long durationSave = System.currentTimeMillis() - st;
logger.debug("Saved resources; total save time={} ms (avg = {} ms)", durationSave, durationSave / resources.size());
}
if ( (prevDcId != null && prevDcId.equals(lastDCIdFetched)) || resources.size() < batchSize){ return null;}
else return lastDCIdFetched;
}
}
class DCUrlWrapper {
private final GeographicalArea area;
public DCUrlWrapper(GeographicalArea area) {
this.area = area;
}
public GeographicalArea unwrap() {
return area;
}
@Override
public boolean equals(Object other) {
if (other instanceof DCUrlWrapper) {
return this.area.getUri().equals(((DCUrlWrapper)other).area.getUri());
} else return false;
}
@Override
public int hashCode() {
return area.getUri().hashCode();
}
} |
package com.azure.ai.textanalytics;
import com.azure.ai.textanalytics.implementation.AnalyzeActionsOperationDetailPropertiesHelper;
import com.azure.ai.textanalytics.implementation.AnalyzeActionsResultPropertiesHelper;
import com.azure.ai.textanalytics.implementation.AnalyzeSentimentActionResultPropertiesHelper;
import com.azure.ai.textanalytics.implementation.ExtractKeyPhrasesActionResultPropertiesHelper;
import com.azure.ai.textanalytics.implementation.ExtractSummaryActionResultPropertiesHelper;
import com.azure.ai.textanalytics.implementation.RecognizeEntitiesActionResultPropertiesHelper;
import com.azure.ai.textanalytics.implementation.RecognizeLinkedEntitiesActionResultPropertiesHelper;
import com.azure.ai.textanalytics.implementation.RecognizePiiEntitiesActionResultPropertiesHelper;
import com.azure.ai.textanalytics.implementation.TextAnalyticsActionResultPropertiesHelper;
import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl;
import com.azure.ai.textanalytics.implementation.Utility;
import com.azure.ai.textanalytics.implementation.models.AnalyzeBatchInput;
import com.azure.ai.textanalytics.implementation.models.AnalyzeJobState;
import com.azure.ai.textanalytics.implementation.models.EntitiesResult;
import com.azure.ai.textanalytics.implementation.models.EntitiesTask;
import com.azure.ai.textanalytics.implementation.models.EntitiesTaskParameters;
import com.azure.ai.textanalytics.implementation.models.EntityLinkingResult;
import com.azure.ai.textanalytics.implementation.models.EntityLinkingTask;
import com.azure.ai.textanalytics.implementation.models.EntityLinkingTaskParameters;
import com.azure.ai.textanalytics.implementation.models.ExtractiveSummarizationResult;
import com.azure.ai.textanalytics.implementation.models.ExtractiveSummarizationTask;
import com.azure.ai.textanalytics.implementation.models.ExtractiveSummarizationTaskParameters;
import com.azure.ai.textanalytics.implementation.models.ExtractiveSummarizationTaskParametersSortBy;
import com.azure.ai.textanalytics.implementation.models.JobManifestTasks;
import com.azure.ai.textanalytics.implementation.models.KeyPhraseResult;
import com.azure.ai.textanalytics.implementation.models.KeyPhrasesTask;
import com.azure.ai.textanalytics.implementation.models.KeyPhrasesTaskParameters;
import com.azure.ai.textanalytics.implementation.models.MultiLanguageBatchInput;
import com.azure.ai.textanalytics.implementation.models.PiiResult;
import com.azure.ai.textanalytics.implementation.models.PiiTask;
import com.azure.ai.textanalytics.implementation.models.PiiTaskParameters;
import com.azure.ai.textanalytics.implementation.models.PiiTaskParametersDomain;
import com.azure.ai.textanalytics.implementation.models.SentimentAnalysisTask;
import com.azure.ai.textanalytics.implementation.models.SentimentAnalysisTaskParameters;
import com.azure.ai.textanalytics.implementation.models.SentimentResponse;
import com.azure.ai.textanalytics.implementation.models.StringIndexType;
import com.azure.ai.textanalytics.implementation.models.TasksStateTasks;
import com.azure.ai.textanalytics.implementation.models.TasksStateTasksEntityLinkingTasksItem;
import com.azure.ai.textanalytics.implementation.models.TasksStateTasksEntityRecognitionPiiTasksItem;
import com.azure.ai.textanalytics.implementation.models.TasksStateTasksEntityRecognitionTasksItem;
import com.azure.ai.textanalytics.implementation.models.TasksStateTasksExtractiveSummarizationTasksItem;
import com.azure.ai.textanalytics.implementation.models.TasksStateTasksKeyPhraseExtractionTasksItem;
import com.azure.ai.textanalytics.implementation.models.TasksStateTasksSentimentAnalysisTasksItem;
import com.azure.ai.textanalytics.implementation.models.TextAnalyticsError;
import com.azure.ai.textanalytics.models.AnalyzeActionsOperationDetail;
import com.azure.ai.textanalytics.models.AnalyzeActionsOptions;
import com.azure.ai.textanalytics.models.AnalyzeActionsResult;
import com.azure.ai.textanalytics.models.AnalyzeSentimentAction;
import com.azure.ai.textanalytics.models.AnalyzeSentimentActionResult;
import com.azure.ai.textanalytics.models.ExtractKeyPhrasesAction;
import com.azure.ai.textanalytics.models.ExtractKeyPhrasesActionResult;
import com.azure.ai.textanalytics.models.ExtractSummaryAction;
import com.azure.ai.textanalytics.models.ExtractSummaryActionResult;
import com.azure.ai.textanalytics.models.RecognizeEntitiesAction;
import com.azure.ai.textanalytics.models.RecognizeEntitiesActionResult;
import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesAction;
import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesActionResult;
import com.azure.ai.textanalytics.models.RecognizePiiEntitiesAction;
import com.azure.ai.textanalytics.models.RecognizePiiEntitiesActionResult;
import com.azure.ai.textanalytics.models.TextAnalyticsActionResult;
import com.azure.ai.textanalytics.models.TextAnalyticsActions;
import com.azure.ai.textanalytics.models.TextAnalyticsErrorCode;
import com.azure.ai.textanalytics.models.TextDocumentInput;
import com.azure.ai.textanalytics.util.AnalyzeActionsResultPagedFlux;
import com.azure.ai.textanalytics.util.AnalyzeActionsResultPagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.IterableStream;
import com.azure.core.util.logging.ClientLogger;
import com.azure.core.util.polling.LongRunningOperationStatus;
import com.azure.core.util.polling.PollResponse;
import com.azure.core.util.polling.PollerFlux;
import com.azure.core.util.polling.PollingContext;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.azure.ai.textanalytics.TextAnalyticsAsyncClient.COGNITIVE_TRACING_NAMESPACE_VALUE;
import static com.azure.ai.textanalytics.implementation.Utility.DEFAULT_POLL_INTERVAL;
import static com.azure.ai.textanalytics.implementation.Utility.inputDocumentsValidation;
import static com.azure.ai.textanalytics.implementation.Utility.parseNextLink;
import static com.azure.ai.textanalytics.implementation.Utility.parseOperationId;
import static com.azure.ai.textanalytics.implementation.Utility.toAnalyzeSentimentResultCollection;
import static com.azure.ai.textanalytics.implementation.Utility.toCategoriesFilter;
import static com.azure.ai.textanalytics.implementation.Utility.toExtractKeyPhrasesResultCollection;
import static com.azure.ai.textanalytics.implementation.Utility.toExtractSummaryResultCollection;
import static com.azure.ai.textanalytics.implementation.Utility.toMultiLanguageInput;
import static com.azure.ai.textanalytics.implementation.Utility.toRecognizeEntitiesResultCollectionResponse;
import static com.azure.ai.textanalytics.implementation.Utility.toRecognizeLinkedEntitiesResultCollection;
import static com.azure.ai.textanalytics.implementation.Utility.toRecognizePiiEntitiesResultCollection;
import static com.azure.core.util.FluxUtil.monoError;
import static com.azure.core.util.tracing.Tracer.AZ_TRACING_NAMESPACE_KEY;
class AnalyzeActionsAsyncClient {
private static final String ENTITY_RECOGNITION_TASKS = "entityRecognitionTasks";
private static final String ENTITY_RECOGNITION_PII_TASKS = "entityRecognitionPiiTasks";
private static final String KEY_PHRASE_EXTRACTION_TASKS = "keyPhraseExtractionTasks";
private static final String ENTITY_LINKING_TASKS = "entityLinkingTasks";
private static final String SENTIMENT_ANALYSIS_TASKS = "sentimentAnalysisTasks";
private static final String EXTRACTIVE_SUMMARIZATION_TASKS = "extractiveSummarizationTasks";
private static final String REGEX_ACTION_ERROR_TARGET =
String.format("#/tasks/(%s|%s|%s|%s|%s|%s)/(\\d+)", KEY_PHRASE_EXTRACTION_TASKS, ENTITY_RECOGNITION_PII_TASKS,
ENTITY_RECOGNITION_TASKS, ENTITY_LINKING_TASKS, SENTIMENT_ANALYSIS_TASKS, EXTRACTIVE_SUMMARIZATION_TASKS);
private final ClientLogger logger = new ClientLogger(AnalyzeActionsAsyncClient.class);
private final TextAnalyticsClientImpl service;
private static final Pattern PATTERN;
static {
PATTERN = Pattern.compile(REGEX_ACTION_ERROR_TARGET, Pattern.MULTILINE);
}
AnalyzeActionsAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> beginAnalyzeActions(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail textAnalyticsOperationResult =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper
.setOperationId(textAnalyticsOperationResult,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return textAnalyticsOperationResult;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperation(operationId -> Mono.just(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext)))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
PollerFlux<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> beginAnalyzeActionsIterable(
Iterable<TextDocumentInput> documents, TextAnalyticsActions actions, AnalyzeActionsOptions options,
Context context) {
try {
inputDocumentsValidation(documents);
options = getNotNullAnalyzeActionsOptions(options);
final Context finalContext = getNotNullContext(context)
.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE);
final AnalyzeBatchInput analyzeBatchInput =
new AnalyzeBatchInput()
.setAnalysisInput(new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)))
.setTasks(getJobManifestTasks(actions));
analyzeBatchInput.setDisplayName(actions.getDisplayName());
final boolean finalIncludeStatistics = options.isIncludeStatistics();
return new PollerFlux<>(
DEFAULT_POLL_INTERVAL,
activationOperation(
service.analyzeWithResponseAsync(analyzeBatchInput, finalContext)
.map(analyzeResponse -> {
final AnalyzeActionsOperationDetail operationDetail =
new AnalyzeActionsOperationDetail();
AnalyzeActionsOperationDetailPropertiesHelper.setOperationId(operationDetail,
parseOperationId(analyzeResponse.getDeserializedHeaders().getOperationLocation()));
return operationDetail;
})),
pollingOperation(operationId -> service.analyzeStatusWithResponseAsync(operationId,
finalIncludeStatistics, null, null, finalContext)),
(activationResponse, pollingContext) ->
Mono.error(new RuntimeException("Cancellation is not supported.")),
fetchingOperationIterable(
operationId -> Mono.just(new AnalyzeActionsResultPagedIterable(getAnalyzeOperationFluxPage(
operationId, null, null, finalIncludeStatistics, finalContext))))
);
} catch (RuntimeException ex) {
return PollerFlux.error(ex);
}
}
private JobManifestTasks getJobManifestTasks(TextAnalyticsActions actions) {
if (actions == null) {
return null;
}
final JobManifestTasks jobManifestTasks = new JobManifestTasks();
if (actions.getRecognizeEntitiesActions() != null) {
jobManifestTasks.setEntityRecognitionTasks(toEntitiesTask(actions));
}
if (actions.getRecognizePiiEntitiesActions() != null) {
jobManifestTasks.setEntityRecognitionPiiTasks(toPiiTask(actions));
}
if (actions.getExtractKeyPhrasesActions() != null) {
jobManifestTasks.setKeyPhraseExtractionTasks(toKeyPhrasesTask(actions));
}
if (actions.getRecognizeLinkedEntitiesActions() != null) {
jobManifestTasks.setEntityLinkingTasks(toEntityLinkingTask(actions));
}
if (actions.getAnalyzeSentimentActions() != null) {
jobManifestTasks.setSentimentAnalysisTasks(toSentimentAnalysisTask(actions));
}
if (actions.getExtractSummaryActions() != null) {
jobManifestTasks.setExtractiveSummarizationTasks(toExtractiveSummarizationTask(actions));
}
return jobManifestTasks;
}
private List<EntitiesTask> toEntitiesTask(TextAnalyticsActions actions) {
final List<EntitiesTask> entitiesTasks = new ArrayList<>();
for (RecognizeEntitiesAction action : actions.getRecognizeEntitiesActions()) {
if (action == null) {
entitiesTasks.add(null);
} else {
entitiesTasks.add(
new EntitiesTask()
.setTaskName(action.getActionName())
.setParameters(
new EntitiesTaskParameters()
.setModelVersion(action.getModelVersion())
.setLoggingOptOut(action.isServiceLogsDisabled())
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)));
}
}
return entitiesTasks;
}
private List<PiiTask> toPiiTask(TextAnalyticsActions actions) {
final List<PiiTask> piiTasks = new ArrayList<>();
for (RecognizePiiEntitiesAction action : actions.getRecognizePiiEntitiesActions()) {
if (action == null) {
piiTasks.add(null);
} else {
piiTasks.add(
new PiiTask()
.setTaskName(action.getActionName())
.setParameters(
new PiiTaskParameters()
.setModelVersion(action.getModelVersion())
.setLoggingOptOut(action.isServiceLogsDisabled())
.setDomain(PiiTaskParametersDomain.fromString(
action.getDomainFilter() == null ? null
: action.getDomainFilter().toString()))
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)
.setPiiCategories(toCategoriesFilter(action.getCategoriesFilter()))));
}
}
return piiTasks;
}
private List<KeyPhrasesTask> toKeyPhrasesTask(TextAnalyticsActions actions) {
final List<KeyPhrasesTask> keyPhrasesTasks = new ArrayList<>();
for (ExtractKeyPhrasesAction action : actions.getExtractKeyPhrasesActions()) {
if (action == null) {
keyPhrasesTasks.add(null);
} else {
keyPhrasesTasks.add(
new KeyPhrasesTask()
.setTaskName(action.getActionName())
.setParameters(
new KeyPhrasesTaskParameters()
.setModelVersion(action.getModelVersion())
.setLoggingOptOut(action.isServiceLogsDisabled())));
}
}
return keyPhrasesTasks;
}
private List<EntityLinkingTask> toEntityLinkingTask(TextAnalyticsActions actions) {
final List<EntityLinkingTask> entityLinkingTasks = new ArrayList<>();
for (RecognizeLinkedEntitiesAction action : actions.getRecognizeLinkedEntitiesActions()) {
if (action == null) {
entityLinkingTasks.add(null);
} else {
entityLinkingTasks.add(
new EntityLinkingTask()
.setTaskName(action.getActionName())
.setParameters(
new EntityLinkingTaskParameters()
.setModelVersion(action.getModelVersion())
.setLoggingOptOut(action.isServiceLogsDisabled())
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)));
}
}
return entityLinkingTasks;
}
private List<SentimentAnalysisTask> toSentimentAnalysisTask(TextAnalyticsActions actions) {
final List<SentimentAnalysisTask> sentimentAnalysisTasks = new ArrayList<>();
for (AnalyzeSentimentAction action : actions.getAnalyzeSentimentActions()) {
if (action == null) {
sentimentAnalysisTasks.add(null);
} else {
sentimentAnalysisTasks.add(
new SentimentAnalysisTask()
.setTaskName(action.getActionName())
.setParameters(
new SentimentAnalysisTaskParameters()
.setModelVersion(action.getModelVersion())
.setLoggingOptOut(action.isServiceLogsDisabled())
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)));
}
}
return sentimentAnalysisTasks;
}
private List<ExtractiveSummarizationTask> toExtractiveSummarizationTask(TextAnalyticsActions actions) {
final List<ExtractiveSummarizationTask> extractiveSummarizationTasks = new ArrayList<>();
for (ExtractSummaryAction action : actions.getExtractSummaryActions()) {
if (action == null) {
extractiveSummarizationTasks.add(null);
} else {
extractiveSummarizationTasks.add(
new ExtractiveSummarizationTask()
.setTaskName(action.getActionName())
.setParameters(
new ExtractiveSummarizationTaskParameters()
.setModelVersion(action.getModelVersion())
.setStringIndexType(StringIndexType.UTF16CODE_UNIT)
.setLoggingOptOut(action.isServiceLogsDisabled())
.setSentenceCount(action.getMaxSentenceCount())
.setSortBy(action.getOrderBy() == null ? null
: ExtractiveSummarizationTaskParametersSortBy.fromString(
action.getOrderBy().toString()))));
}
}
return extractiveSummarizationTasks;
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsOperationDetail>>
activationOperation(Mono<AnalyzeActionsOperationDetail> operationResult) {
return pollingContext -> {
try {
return operationResult.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<PollResponse<AnalyzeActionsOperationDetail>>>
pollingOperation(Function<String, Mono<Response<AnalyzeJobState>>> pollingFunction) {
return pollingContext -> {
try {
final PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse =
pollingContext.getLatestResponse();
// TODO: [Service-Bug] change back to UUID after service support it.
// final UUID resultUUID = UUID.fromString(operationResultPollResponse.getValue().getResultId());
final String operationId = operationResultPollResponse.getValue().getOperationId();
return pollingFunction.apply(operationId)
.flatMap(modelResponse -> processAnalyzedModelResponse(modelResponse, operationResultPollResponse))
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedFlux>>
fetchingOperation(Function<String, Mono<AnalyzeActionsResultPagedFlux>> fetchingFunction) {
return pollingContext -> {
try {
// TODO: [Service-Bug] change back to UUID after service support it.
// final UUID resultUUID = UUID.fromString(pollingContext.getLatestResponse().getValue().getResultId());
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
private Function<PollingContext<AnalyzeActionsOperationDetail>, Mono<AnalyzeActionsResultPagedIterable>>
fetchingOperationIterable(Function<String, Mono<AnalyzeActionsResultPagedIterable>> fetchingFunction) {
return pollingContext -> {
try {
// TODO: [Service-Bug] change back to UUID after service support it.
// final UUID resultUUID = UUID.fromString(pollingContext.getLatestResponse().getValue().getResultId());
final String operationId = pollingContext.getLatestResponse().getValue().getOperationId();
return fetchingFunction.apply(operationId);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
};
}
AnalyzeActionsResultPagedFlux getAnalyzeOperationFluxPage(String operationId, Integer top, Integer skip,
boolean showStats, Context context) {
return new AnalyzeActionsResultPagedFlux(
() -> (continuationToken, pageSize) ->
getPage(continuationToken, operationId, top, skip, showStats, context).flux());
}
Mono<PagedResponse<AnalyzeActionsResult>> getPage(String continuationToken, String operationId, Integer top,
Integer skip, boolean showStats, Context context) {
if (continuationToken != null) {
final Map<String, Object> continuationTokenMap = parseNextLink(continuationToken);
final Integer topValue = (Integer) continuationTokenMap.getOrDefault("$top", null);
final Integer skipValue = (Integer) continuationTokenMap.getOrDefault("$skip", null);
final Boolean showStatsValue = (Boolean) continuationTokenMap.getOrDefault(showStats, false);
return service.analyzeStatusWithResponseAsync(operationId, showStatsValue, topValue, skipValue, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
} else {
return service.analyzeStatusWithResponseAsync(operationId, showStats, top, skip, context)
.map(this::toAnalyzeActionsResultPagedResponse)
.onErrorMap(Utility::mapToHttpResponseExceptionIfExists);
}
}
private PagedResponse<AnalyzeActionsResult> toAnalyzeActionsResultPagedResponse(Response<AnalyzeJobState> response) {
final AnalyzeJobState analyzeJobState = response.getValue();
return new PagedResponseBase<Void, AnalyzeActionsResult>(
response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
Arrays.asList(toAnalyzeActionsResult(analyzeJobState)),
analyzeJobState.getNextLink(),
null);
}
private AnalyzeActionsResult toAnalyzeActionsResult(AnalyzeJobState analyzeJobState) {
TasksStateTasks tasksStateTasks = analyzeJobState.getTasks();
final List<TasksStateTasksEntityRecognitionPiiTasksItem> piiTasksItems =
tasksStateTasks.getEntityRecognitionPiiTasks();
final List<TasksStateTasksEntityRecognitionTasksItem> entityRecognitionTasksItems =
tasksStateTasks.getEntityRecognitionTasks();
final List<TasksStateTasksKeyPhraseExtractionTasksItem> keyPhraseExtractionTasks =
tasksStateTasks.getKeyPhraseExtractionTasks();
final List<TasksStateTasksEntityLinkingTasksItem> linkedEntityRecognitionTasksItems =
tasksStateTasks.getEntityLinkingTasks();
final List<TasksStateTasksSentimentAnalysisTasksItem> sentimentAnalysisTasksItems =
tasksStateTasks.getSentimentAnalysisTasks();
final List<TasksStateTasksExtractiveSummarizationTasksItem> extractiveSummarizationTasksItems =
tasksStateTasks.getExtractiveSummarizationTasks();
List<RecognizeEntitiesActionResult> recognizeEntitiesActionResults = new ArrayList<>();
List<RecognizePiiEntitiesActionResult> recognizePiiEntitiesActionResults = new ArrayList<>();
List<ExtractKeyPhrasesActionResult> extractKeyPhrasesActionResults = new ArrayList<>();
List<RecognizeLinkedEntitiesActionResult> recognizeLinkedEntitiesActionResults = new ArrayList<>();
List<AnalyzeSentimentActionResult> analyzeSentimentActionResults = new ArrayList<>();
List<ExtractSummaryActionResult> extractSummaryActionResults = new ArrayList<>();
if (!CoreUtils.isNullOrEmpty(entityRecognitionTasksItems)) {
for (int i = 0; i < entityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionTasksItem taskItem = entityRecognitionTasksItems.get(i);
final RecognizeEntitiesActionResult actionResult = new RecognizeEntitiesActionResult();
final EntitiesResult results = taskItem.getResults();
if (results != null) {
RecognizeEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult,
toRecognizeEntitiesResultCollectionResponse(results));
}
TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName());
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(piiTasksItems)) {
for (int i = 0; i < piiTasksItems.size(); i++) {
final TasksStateTasksEntityRecognitionPiiTasksItem taskItem = piiTasksItems.get(i);
final RecognizePiiEntitiesActionResult actionResult = new RecognizePiiEntitiesActionResult();
final PiiResult results = taskItem.getResults();
if (results != null) {
RecognizePiiEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult,
toRecognizePiiEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName());
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizePiiEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(keyPhraseExtractionTasks)) {
for (int i = 0; i < keyPhraseExtractionTasks.size(); i++) {
final TasksStateTasksKeyPhraseExtractionTasksItem taskItem = keyPhraseExtractionTasks.get(i);
final ExtractKeyPhrasesActionResult actionResult = new ExtractKeyPhrasesActionResult();
final KeyPhraseResult results = taskItem.getResults();
if (results != null) {
ExtractKeyPhrasesActionResultPropertiesHelper.setDocumentsResults(actionResult,
toExtractKeyPhrasesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName());
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
extractKeyPhrasesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(linkedEntityRecognitionTasksItems)) {
for (int i = 0; i < linkedEntityRecognitionTasksItems.size(); i++) {
final TasksStateTasksEntityLinkingTasksItem taskItem = linkedEntityRecognitionTasksItems.get(i);
final RecognizeLinkedEntitiesActionResult actionResult = new RecognizeLinkedEntitiesActionResult();
final EntityLinkingResult results = taskItem.getResults();
if (results != null) {
RecognizeLinkedEntitiesActionResultPropertiesHelper.setDocumentsResults(actionResult,
toRecognizeLinkedEntitiesResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName());
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
recognizeLinkedEntitiesActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(sentimentAnalysisTasksItems)) {
for (int i = 0; i < sentimentAnalysisTasksItems.size(); i++) {
final TasksStateTasksSentimentAnalysisTasksItem taskItem = sentimentAnalysisTasksItems.get(i);
final AnalyzeSentimentActionResult actionResult = new AnalyzeSentimentActionResult();
final SentimentResponse results = taskItem.getResults();
if (results != null) {
AnalyzeSentimentActionResultPropertiesHelper.setDocumentsResults(actionResult,
toAnalyzeSentimentResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName());
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
analyzeSentimentActionResults.add(actionResult);
}
}
if (!CoreUtils.isNullOrEmpty(extractiveSummarizationTasksItems)) {
for (int i = 0; i < extractiveSummarizationTasksItems.size(); i++) {
final TasksStateTasksExtractiveSummarizationTasksItem taskItem =
extractiveSummarizationTasksItems.get(i);
final ExtractSummaryActionResult actionResult = new ExtractSummaryActionResult();
final ExtractiveSummarizationResult results = taskItem.getResults();
if (results != null) {
ExtractSummaryActionResultPropertiesHelper.setDocumentsResults(actionResult,
toExtractSummaryResultCollection(results));
}
TextAnalyticsActionResultPropertiesHelper.setActionName(actionResult, taskItem.getTaskName());
TextAnalyticsActionResultPropertiesHelper.setCompletedAt(actionResult,
taskItem.getLastUpdateDateTime());
extractSummaryActionResults.add(actionResult);
}
}
final List<TextAnalyticsError> errors = analyzeJobState.getErrors();
if (!CoreUtils.isNullOrEmpty(errors)) {
for (TextAnalyticsError error : errors) {
final String[] targetPair = parseActionErrorTarget(error.getTarget());
final String taskName = targetPair[0];
final Integer taskIndex = Integer.valueOf(targetPair[1]);
final TextAnalyticsActionResult actionResult;
if (ENTITY_RECOGNITION_TASKS.equals(taskName)) {
actionResult = recognizeEntitiesActionResults.get(taskIndex);
} else if (ENTITY_RECOGNITION_PII_TASKS.equals(taskName)) {
actionResult = recognizePiiEntitiesActionResults.get(taskIndex);
} else if (KEY_PHRASE_EXTRACTION_TASKS.equals(taskName)) {
actionResult = extractKeyPhrasesActionResults.get(taskIndex);
} else if (ENTITY_LINKING_TASKS.equals(taskName)) {
actionResult = recognizeLinkedEntitiesActionResults.get(taskIndex);
} else if (SENTIMENT_ANALYSIS_TASKS.equals(taskName)) {
actionResult = analyzeSentimentActionResults.get(taskIndex);
} else if (EXTRACTIVE_SUMMARIZATION_TASKS.equals(taskName)) {
actionResult = extractSummaryActionResults.get(taskIndex);
} else {
throw logger.logExceptionAsError(new RuntimeException(
"Invalid task name in target reference, " + taskName));
}
TextAnalyticsActionResultPropertiesHelper.setIsError(actionResult, true);
TextAnalyticsActionResultPropertiesHelper.setError(actionResult,
new com.azure.ai.textanalytics.models.TextAnalyticsError(
TextAnalyticsErrorCode.fromString(
error.getCode() == null ? null : error.getCode().toString()),
error.getMessage(), null));
}
}
final AnalyzeActionsResult analyzeActionsResult = new AnalyzeActionsResult();
AnalyzeActionsResultPropertiesHelper.setRecognizeEntitiesResults(analyzeActionsResult,
IterableStream.of(recognizeEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizePiiEntitiesResults(analyzeActionsResult,
IterableStream.of(recognizePiiEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setExtractKeyPhrasesResults(analyzeActionsResult,
IterableStream.of(extractKeyPhrasesActionResults));
AnalyzeActionsResultPropertiesHelper.setRecognizeLinkedEntitiesResults(analyzeActionsResult,
IterableStream.of(recognizeLinkedEntitiesActionResults));
AnalyzeActionsResultPropertiesHelper.setAnalyzeSentimentResults(analyzeActionsResult,
IterableStream.of(analyzeSentimentActionResults));
AnalyzeActionsResultPropertiesHelper.setExtractSummaryResults(analyzeActionsResult,
IterableStream.of(extractSummaryActionResults));
return analyzeActionsResult;
}
private Mono<PollResponse<AnalyzeActionsOperationDetail>> processAnalyzedModelResponse(
Response<AnalyzeJobState> analyzeJobStateResponse,
PollResponse<AnalyzeActionsOperationDetail> operationResultPollResponse) {
LongRunningOperationStatus status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
if (analyzeJobStateResponse.getValue() != null && analyzeJobStateResponse.getValue().getStatus() != null) {
switch (analyzeJobStateResponse.getValue().getStatus()) {
case NOT_STARTED:
case RUNNING:
status = LongRunningOperationStatus.IN_PROGRESS;
break;
case SUCCEEDED:
status = LongRunningOperationStatus.SUCCESSFULLY_COMPLETED;
break;
case CANCELLED:
status = LongRunningOperationStatus.USER_CANCELLED;
break;
default:
status = LongRunningOperationStatus.fromString(
analyzeJobStateResponse.getValue().getStatus().toString(), true);
break;
}
}
AnalyzeActionsOperationDetailPropertiesHelper.setDisplayName(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getDisplayName());
AnalyzeActionsOperationDetailPropertiesHelper.setCreatedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getCreatedDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setExpiresAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getExpirationDateTime());
AnalyzeActionsOperationDetailPropertiesHelper.setLastModifiedAt(operationResultPollResponse.getValue(),
analyzeJobStateResponse.getValue().getLastUpdateDateTime());
final TasksStateTasks tasksResult = analyzeJobStateResponse.getValue().getTasks();
AnalyzeActionsOperationDetailPropertiesHelper.setActionsFailed(operationResultPollResponse.getValue(),
tasksResult.getFailed());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInProgress(operationResultPollResponse.getValue(),
tasksResult.getInProgress());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsSucceeded(
operationResultPollResponse.getValue(), tasksResult.getCompleted());
AnalyzeActionsOperationDetailPropertiesHelper.setActionsInTotal(operationResultPollResponse.getValue(),
tasksResult.getTotal());
return Mono.just(new PollResponse<>(status, operationResultPollResponse.getValue()));
}
private Context getNotNullContext(Context context) {
return context == null ? Context.NONE : context;
}
private AnalyzeActionsOptions getNotNullAnalyzeActionsOptions(AnalyzeActionsOptions options) {
return options == null ? new AnalyzeActionsOptions() : options;
}
private String[] parseActionErrorTarget(String targetReference) {
if (CoreUtils.isNullOrEmpty(targetReference)) {
throw logger.logExceptionAsError(new RuntimeException(
"Expected an error with a target field referencing an action but did not get one"));
}
// action could be failed and the target reference is "#/tasks/keyPhraseExtractionTasks/0";
final Matcher matcher = PATTERN.matcher(targetReference);
String[] taskNameIdPair = new String[2];
while (matcher.find()) {
taskNameIdPair[0] = matcher.group(1);
taskNameIdPair[1] = matcher.group(2);
}
return taskNameIdPair;
}
} |
package st.alr.mqttitude.services;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import st.alr.mqttitude.App;
import st.alr.mqttitude.db.Waypoint;
import st.alr.mqttitude.db.WaypointDao;
import st.alr.mqttitude.db.WaypointDao.Properties;
import st.alr.mqttitude.model.GeocodableLocation;
import st.alr.mqttitude.model.Report;
import st.alr.mqttitude.preferences.ActivityPreferences;
import st.alr.mqttitude.support.Defaults;
import st.alr.mqttitude.support.Events;
import st.alr.mqttitude.support.MqttPublish;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.location.Location;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationStatusCodes;
import de.greenrobot.event.EventBus;
public class ServiceLocator implements ProxyableService, MqttPublish,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener, LocationClient.OnRemoveGeofencesResultListener, LocationClient.OnAddGeofencesResultListener {
private SharedPreferences sharedPreferences;
private OnSharedPreferenceChangeListener preferencesChangedListener;
private static Defaults.State.ServiceLocator state = Defaults.State.ServiceLocator.INITIAL;
private ServiceProxy context;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private boolean ready = false;
private boolean foreground = false;
private GeocodableLocation lastKnownLocation;
private Date lastPublish;
private List<Waypoint> waypoints;
private WaypointDao waypointDao;
public void onCreate(ServiceProxy p) {
context = p;
waypointDao = ServiceProxy.getServiceApplication().getWaypointDao();
loadWaypoints();
this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
preferencesChangedListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreference, String key) {
if(key.equals(Defaults.SETTINGS_KEY_BACKGROUND_UPDATES) || key.equals(Defaults.SETTINGS_KEY_BACKGROUND_UPDATES_INTERVAL))
handlePreferences();
}
};
sharedPreferences.registerOnSharedPreferenceChangeListener(preferencesChangedListener);
mLocationClient = new LocationClient(context, this, this);
if (!mLocationClient.isConnected() && !mLocationClient.isConnecting() && ServiceApplication.checkPlayServices())
mLocationClient.connect();
}
public GeocodableLocation getLastKnownLocation() {
return lastKnownLocation;
}
public void onFenceTransition(Intent intent) {
int transitionType = LocationClient.getGeofenceTransition(intent);
// Test that a valid transition was reported
if ( (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER) || (transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) ) {
List <Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
for (int i = 0; i < triggerList.size(); i++) {
Waypoint w = waypointDao.queryBuilder().where(Properties.GeofenceId.eq(triggerList.get(i).getRequestId())).limit(1).unique();
Log.v(this.toString(), "Waypoint triggered " + w.getDescription() + " transition: " + transitionType);
if(w != null)
publishGeofenceTransitionEvent(w, transitionType);
}
}
}
@Override
public void onLocationChanged(Location arg0) {
Log.v(this.toString(), "onLocationChanged");
this.lastKnownLocation = new GeocodableLocation(arg0);
EventBus.getDefault().postSticky(new Events.LocationUpdated(this.lastKnownLocation));
if (shouldPublishLocation())
publishLastKnownLocation();
}
private boolean shouldPublishLocation() {
Date now = new Date();
if (lastPublish == null)
return true;
if (now.getTime() - lastPublish.getTime() > getUpdateIntervallInMiliseconds())
return true;
return false;
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(this.toString(), "Failed to connect");
}
@Override
public void onConnected(Bundle arg0) {
ready = true;
Log.v(this.toString(), "Connected");
setupLocationRequest();
requestLocationUpdates();
setupGeofences();
}
@Override
public void onDisconnected() {
ready = false;
ServiceApplication.checkPlayServices(); // show error notification if play services were disabled
}
private void setupBackgroundLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setInterval(getUpdateIntervallInMiliseconds());
mLocationRequest.setFastestInterval(0);
mLocationRequest.setSmallestDisplacement(500);
}
private void setupForegroundLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(10 * 1000);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setSmallestDisplacement(50);
}
protected void handlePreferences() {
setupLocationRequest();
requestLocationUpdates();
}
private void disableLocationUpdates() {
Log.v(this.toString(), "Disabling updates");
if (mLocationClient != null && mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(ServiceProxy.getPendingIntentForService(context,
ServiceProxy.SERVICE_LOCATOR, Defaults.INTENT_ACTION_LOCATION_CHANGED, null, 0));
}
}
private void requestLocationUpdates() {
if (!ready) {
Log.e(this.toString(), "requestLocationUpdates but not connected to play services. Updates will be requested again once connected");
return;
}
if (foreground || areBackgroundUpdatesEnabled()) {
// locationIntent = ServiceProxy.getPendingIntentForService(context,
// ServiceProxy.SERVICE_LOCATOR, Defaults.INTENT_ACTION_LOCATION_CHANGED, null);
mLocationClient.requestLocationUpdates(mLocationRequest, ServiceProxy.getPendingIntentForService(context,
ServiceProxy.SERVICE_LOCATOR, Defaults.INTENT_ACTION_LOCATION_CHANGED, null));
} else {
Log.d(this.toString(), "Location updates are disabled (not in foreground or background updates disabled)");
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getAction() != null) {
if (intent.getAction().equals(Defaults.INTENT_ACTION_PUBLISH_LASTKNOWN)) {
publishLastKnownLocation();
} else if (intent.getAction().equals(Defaults.INTENT_ACTION_LOCATION_CHANGED)) {
Location location = intent.getParcelableExtra(LocationClient.KEY_LOCATION_CHANGED);
if (location != null)
onLocationChanged(location);
} else if (intent.getAction().equals(Defaults.INTENT_ACTION_FENCE_TRANSITION)) {
Log.v(this.toString(), "Geofence transition occured");
onFenceTransition(intent);
} else {
Log.v(this.toString(), "Received unknown intent");
}
}
return 0;
}
private void setupLocationRequest() {
if(!ready)
return;
disableLocationUpdates();
if (foreground)
setupForegroundLocationRequest();
else
setupBackgroundLocationRequest();
}
public void enableForegroundMode() {
Log.d(this.toString(), "enableForegroundMode");
foreground = true;
setupLocationRequest();
requestLocationUpdates();
}
public void enableBackgroundMode() {
Log.d(this.toString(), "enableBackgroundMode");
foreground = false;
setupLocationRequest();
requestLocationUpdates();
}
@Override
public void onDestroy() {
Log.v(this.toString(), "onDestroy. Disabling location updates");
disableLocationUpdates();
}
public void publishGeofenceTransitionEvent(Waypoint w, int transition) {
Report r = new Report(getLastKnownLocation());
r.setTransition(transition);
r.setWaypoint(w);
if(App.isDebugBuild()) {
if(transition == Geofence.GEOFENCE_TRANSITION_ENTER)
Toast.makeText(context, "Entering Geofence " + w.getDescription(), Toast.LENGTH_SHORT).show();
else if(transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
Toast.makeText(context, "Leaving Geofence " + w.getDescription(), Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "B0rked Geofence transition ("+transition +")", Toast.LENGTH_SHORT).show();
}
}
publish(r);
}
public void publishLastKnownLocation() {
publish(null);
}
public void publish(Report r) {
lastPublish = new Date();
// Safety checks
if(ServiceProxy.getServiceBroker() == null) {
Log.e(this.toString(), "publishLastKnownLocation but ServiceMqtt not ready");
return;
}
if (r == null && getLastKnownLocation() == null) {
changeState(Defaults.State.ServiceLocator.NOLOCATION);
return;
}
String topic = ActivityPreferences.getPubTopic(true);
if (topic == null) {
changeState(Defaults.State.ServiceLocator.NOTOPIC);
return;
}
Report report;
if(r == null)
report = new Report(getLastKnownLocation());
else
report = r;
if(ActivityPreferences.includeBattery())
report.setBattery(App.getBatteryLevel());
ServiceProxy.getServiceBroker().publish(
topic,
report.toString(),
sharedPreferences.getBoolean(Defaults.SETTINGS_KEY_RETAIN, Defaults.VALUE_RETAIN),
Integer.parseInt(sharedPreferences.getString(Defaults.SETTINGS_KEY_QOS, Defaults.VALUE_QOS))
, 20, this, report.getLocation());
}
@Override
public void publishSuccessfull(Object extra) {
changeState(Defaults.State.ServiceLocator.INITIAL);
EventBus.getDefault().postSticky(new Events.PublishSuccessfull(extra));
}
public static Defaults.State.ServiceLocator getState() {
return state;
}
public static String getStateAsString(Context c){
return stateAsString(getState(), c);
}
public static String stateAsString(Defaults.State.ServiceLocator state, Context c) {
return Defaults.State.toString(state, c);
}
private void changeState(Defaults.State.ServiceLocator newState) {
Log.d(this.toString(), "ServiceLocator state changed to: " + newState);
EventBus.getDefault().postSticky(new Events.StateChanged.ServiceLocator(newState));
state = newState;
}
@Override
public void publishFailed(Object extra) {
changeState(Defaults.State.ServiceLocator.PUBLISHING_TIMEOUT);
}
@Override
public void publishing(Object extra) {
changeState(Defaults.State.ServiceLocator.PUBLISHING);
}
@Override
public void publishWaiting(Object extra) {
changeState(Defaults.State.ServiceLocator.PUBLISHING_WAITING);
}
public Date getLastPublishDate() {
return lastPublish;
}
public boolean areBackgroundUpdatesEnabled() {
return sharedPreferences.getBoolean(Defaults.SETTINGS_KEY_BACKGROUND_UPDATES,
Defaults.VALUE_BACKGROUND_UPDATES);
}
public int getUpdateIntervall() {
int ui;
try{
ui = Integer.parseInt(sharedPreferences.getString(Defaults.SETTINGS_KEY_BACKGROUND_UPDATES_INTERVAL,
Defaults.VALUE_BACKGROUND_UPDATES_INTERVAL));
} catch (Exception e) {
ui = Integer.parseInt(Defaults.VALUE_BACKGROUND_UPDATES_INTERVAL);
}
return ui;
}
public int getUpdateIntervallInMiliseconds() {
return getUpdateIntervall() * 60 * 1000;
}
public void loadWaypoints() {
this.waypoints = waypointDao.loadAll();
}
public void onEvent(Events.WaypointAdded e) {
if(!isWaypointWithGeofence(e.getWaypoint()))
return;
Log.v(this.toString(), "adding geofence");
loadWaypoints();
setupGeofences();
}
public void onEvent(Events.WaypointUpdated e) {
if(!isWaypointWithGeofence(e.getWaypoint()))
return;
Log.v(this.toString(), "updating geofence");
removeGeofence(e.getWaypoint());
loadWaypoints();
setupGeofences();
}
private boolean isWaypointWithGeofence(Waypoint w) {
return w.getRadius() != null && w.getRadius() > 0;
}
public void onEvent(Events.WaypointRemoved e) {
if(!isWaypointWithGeofence(e.getWaypoint()))
return;
Log.v(this.toString(), "removing geofence");
removeGeofence(e.getWaypoint());
loadWaypoints();
setupGeofences();
}
private void setupGeofences() {
if(!ready)
return;
List<Geofence> fences = new ArrayList<Geofence>();
for (Waypoint w : waypoints) {
if(!isWaypointWithGeofence(w))
continue;
if(w.getGeofenceId() == null) {
w.setGeofenceId(UUID.randomUUID().toString());
waypointDao.update(w);
}
int transitionType;
switch (w.getTransitionType()) {
case 0:
transitionType = Geofence.GEOFENCE_TRANSITION_ENTER;
break;
case 1:
transitionType = Geofence.GEOFENCE_TRANSITION_EXIT;
break;
case 2:
transitionType = Geofence.GEOFENCE_TRANSITION_EXIT | Geofence.GEOFENCE_TRANSITION_ENTER;
break;
default:
transitionType = Geofence.GEOFENCE_TRANSITION_ENTER;
}
Log.v(this.toString() , "id " + w.getGeofenceId());
Geofence geofence = new Geofence.Builder()
.setRequestId(w.getGeofenceId())
.setTransitionTypes(transitionType)
.setCircularRegion(w.getLatitude(), w.getLongitude(), w.getRadius()).setExpirationDuration(Geofence.NEVER_EXPIRE).build();
fences.add(geofence);
}
if(fences.size() == 0) {
Log.v(this.toString(), "no geofences to add");
return;
}
Log.v(this.toString(), "adding geofences");
mLocationClient.addGeofences(fences, ServiceProxy.getPendingIntentForService(context,
ServiceProxy.SERVICE_LOCATOR, Defaults.INTENT_ACTION_FENCE_TRANSITION, null), this);
}
private void removeGeofence(Waypoint w) {
ArrayList<String> l = new ArrayList<String>();
l.add(w.getGeofenceId());
removeGeofences(l);
w.setGeofenceId(null);
waypointDao.update(w);
}
private void removeGeofences(List<String> ids) {
mLocationClient.removeGeofences(ids, this);
}
public void onEvent(Object event){}
@Override
public void onAddGeofencesResult(int arg0, String[] arg1) {
if (LocationStatusCodes.SUCCESS == arg0) {
for (int i = 0; i < arg1.length; i++) {
Log.v(this.toString(), "geofence "+ arg1[i] +" added");
}
Toast.makeText(context, "Geofences added",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Unable to add Geofence",Toast.LENGTH_SHORT).show();
Log.v(this.toString(), "geofence adding failed"); }
}
@Override
public void onRemoveGeofencesByPendingIntentResult(int arg0, PendingIntent arg1) {
if (LocationStatusCodes.SUCCESS == arg0) {
Log.v(this.toString(), "geofence removed");
} else {
Log.v(this.toString(), "geofence removing failed"); }
}
@Override
public void onRemoveGeofencesByRequestIdsResult(int arg0, String[] arg1) {
if (LocationStatusCodes.SUCCESS == arg0) {
for (int i = 0; i < arg1.length; i++) {
Log.v(this.toString(), "geofence "+ arg1[i] +" removed");
}
} else {
Log.v(this.toString(), "geofence removing failed"); }
}
} |
package uk.ac.ox.zoo.seeg.abraid.mp.modeloutputhandler.web;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.junit.Before;
import org.junit.Test;
import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.*;
import uk.ac.ox.zoo.seeg.abraid.mp.common.service.core.DiseaseService;
import uk.ac.ox.zoo.seeg.abraid.mp.common.service.core.ModelRunService;
import uk.ac.ox.zoo.seeg.abraid.mp.common.service.workflow.DiseaseOccurrenceValidationService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
public class DiseaseOccurrenceHandlerTest {
private DiseaseOccurrenceHandler diseaseOccurrenceHandler;
private DiseaseService diseaseService;
private ModelRunService modelRunService;
private DiseaseOccurrenceValidationService diseaseOccurrenceValidationService;
@Before
public void setUp() {
diseaseService = mock(DiseaseService.class);
modelRunService = mock(ModelRunService.class);
diseaseOccurrenceValidationService = mock(DiseaseOccurrenceValidationService.class);
diseaseOccurrenceHandler = new DiseaseOccurrenceHandler(diseaseService, modelRunService,
diseaseOccurrenceValidationService);
DateTimeUtils.setCurrentMillisFixed(DateTime.now().getMillis());
}
@Test
public void handleValidationParametersHasNoEffectIfModelIncomplete() {
// Arrange
int diseaseGroupId = 87;
ModelRun modelRun = createModelRun(diseaseGroupId, ModelRunStatus.FAILED);
DiseaseGroup diseaseGroup = new DiseaseGroup(diseaseGroupId);
when(modelRunService.getModelRunByName(modelRun.getName())).thenReturn(modelRun);
when(diseaseService.getDiseaseGroupById(diseaseGroupId)).thenReturn(diseaseGroup);
// Act
diseaseOccurrenceHandler.handle(modelRun);
// Assert
verify(modelRunService, never()).hasBatchingEverCompleted(anyInt());
verify(diseaseService, never()).getDiseaseOccurrencesByDiseaseGroupId(anyInt());
verify(diseaseService, never()).getDiseaseOccurrencesForBatching(anyInt(), any(DateTime.class));
verify(diseaseOccurrenceValidationService, never()).addValidationParameters(anyListOf(DiseaseOccurrence.class));
verify(diseaseService, never()).saveDiseaseOccurrence(any(DiseaseOccurrence.class));
verify(modelRunService, never()).saveModelRun(any(ModelRun.class));
}
@Test
public void handleValidationParametersHasNoEffectIfDiseaseGroupIsNotBeingSetUp() {
// Arrange
int diseaseGroupId = 87;
ModelRun modelRun = createModelRun(diseaseGroupId, ModelRunStatus.COMPLETED);
DiseaseGroup diseaseGroup = new DiseaseGroup(diseaseGroupId);
diseaseGroup.setAutomaticModelRunsStartDate(DateTime.now());
when(modelRunService.getModelRunByName(modelRun.getName())).thenReturn(modelRun);
when(diseaseService.getDiseaseGroupById(diseaseGroupId)).thenReturn(diseaseGroup);
// Act
diseaseOccurrenceHandler.handle(modelRun);
// Assert
verify(modelRunService, never()).hasBatchingEverCompleted(anyInt());
verify(diseaseService, never()).getDiseaseOccurrencesByDiseaseGroupId(anyInt());
verify(diseaseService, never()).getDiseaseOccurrencesForBatching(anyInt(), any(DateTime.class));
verify(diseaseOccurrenceValidationService, never()).addValidationParameters(anyListOf(DiseaseOccurrence.class));
verify(diseaseService, never()).saveDiseaseOccurrence(any(DiseaseOccurrence.class));
verify(modelRunService, never()).saveModelRun(any(ModelRun.class));
}
@Test
public void handleValidationParametersInitialisesBatchingIfBatchingHasNeverCompleted() {
// Arrange
int diseaseGroupId = 87;
ModelRun modelRun = createModelRun(diseaseGroupId, ModelRunStatus.COMPLETED);
modelRun.setBatchEndDate(DateTime.now());
DiseaseGroup diseaseGroup = new DiseaseGroup(diseaseGroupId);
DiseaseOccurrence occurrence1 = new DiseaseOccurrence();
occurrence1.setStatus(DiseaseOccurrenceStatus.READY);
occurrence1.setFinalWeighting(0.5);
DiseaseOccurrence occurrence2 = new DiseaseOccurrence();
occurrence2.setStatus(DiseaseOccurrenceStatus.READY);
occurrence2.setFinalWeightingExcludingSpatial(0.7);
List<DiseaseOccurrence> occurrences = Arrays.asList(occurrence1, occurrence2);
when(modelRunService.getModelRunByName(modelRun.getName())).thenReturn(modelRun);
when(diseaseService.getDiseaseGroupById(diseaseGroupId)).thenReturn(diseaseGroup);
when(modelRunService.hasBatchingEverCompleted(diseaseGroupId)).thenReturn(false);
when(diseaseService.getDiseaseOccurrencesByDiseaseGroupIdAndStatus(diseaseGroupId,
DiseaseOccurrenceStatus.READY)).thenReturn(occurrences);
// Act
diseaseOccurrenceHandler.handle(modelRun);
// Assert
verify(diseaseService).saveDiseaseOccurrence(same(occurrence1));
verify(diseaseService).saveDiseaseOccurrence(same(occurrence2));
assertThat(occurrence1.getFinalWeighting()).isNull();
assertThat(occurrence2.getFinalWeightingExcludingSpatial()).isNull();
}
@Test
public void handleValidationParametersDoesNotInitialiseBatchingIfBatchingHasCompleted() {
// Arrange
int diseaseGroupId = 87;
ModelRun modelRun = createModelRun(diseaseGroupId, ModelRunStatus.COMPLETED);
modelRun.setBatchEndDate(DateTime.now());
DiseaseGroup diseaseGroup = new DiseaseGroup(diseaseGroupId);
when(modelRunService.getModelRunByName(modelRun.getName())).thenReturn(modelRun);
when(diseaseService.getDiseaseGroupById(diseaseGroupId)).thenReturn(diseaseGroup);
when(modelRunService.hasBatchingEverCompleted(diseaseGroupId)).thenReturn(true);
// Act
diseaseOccurrenceHandler.handle(modelRun);
// Assert
verify(modelRunService).hasBatchingEverCompleted(eq(diseaseGroupId));
verify(diseaseService, never()).getDiseaseOccurrencesByDiseaseGroupId(anyInt());
verify(diseaseService, never()).saveDiseaseOccurrence(any(DiseaseOccurrence.class));
}
@Test
public void handleValidationParametersDoesNotBatchIfThereIsNoBatchEndDate() {
// Arrange
int diseaseGroupId = 87;
ModelRun modelRun = createModelRun(diseaseGroupId, ModelRunStatus.COMPLETED);
DiseaseGroup diseaseGroup = new DiseaseGroup(diseaseGroupId);
when(modelRunService.getModelRunByName(modelRun.getName())).thenReturn(modelRun);
when(diseaseService.getDiseaseGroupById(diseaseGroupId)).thenReturn(diseaseGroup);
// Act
diseaseOccurrenceHandler.handle(modelRun);
// Assert
verify(modelRunService, never()).hasBatchingEverCompleted(anyInt());
verify(diseaseService, never()).getDiseaseOccurrencesForBatching(anyInt(), any(DateTime.class));
verify(diseaseOccurrenceValidationService, never()).addValidationParameters(anyListOf(DiseaseOccurrence.class));
verify(diseaseService, never()).saveDiseaseOccurrence(any(DiseaseOccurrence.class));
verify(modelRunService, never()).saveModelRun(any(ModelRun.class));
}
@Test
public void handlingSucceedsIfThereAreNoOccurrencesToBatch() {
// Arrange
int diseaseGroupId = 87;
DateTime batchEndDate = new DateTime("2012-11-14T15:16:17");
DateTime batchEndDateWithMaximumTime = new DateTime("2012-11-14T23:59:59.999");
ModelRun modelRun = createModelRun(diseaseGroupId, ModelRunStatus.COMPLETED);
modelRun.setBatchEndDate(batchEndDate);
DiseaseGroup diseaseGroup = new DiseaseGroup(diseaseGroupId);
diseaseGroup.setName("Dengue");
when(modelRunService.getModelRunByName(modelRun.getName())).thenReturn(modelRun);
when(diseaseService.getDiseaseGroupById(diseaseGroupId)).thenReturn(diseaseGroup);
when(diseaseService.getDiseaseOccurrencesForBatching(diseaseGroupId, batchEndDateWithMaximumTime))
.thenReturn(new ArrayList<DiseaseOccurrence>());
// Act
diseaseOccurrenceHandler.handle(modelRun);
// Assert
verify(diseaseService).getDiseaseOccurrencesForBatching(
eq(diseaseGroupId), eq(batchEndDateWithMaximumTime));
verify(diseaseOccurrenceValidationService, never()).addValidationParameters(anyListOf(DiseaseOccurrence.class));
verify(diseaseService, never()).saveDiseaseOccurrence(any(DiseaseOccurrence.class));
verify(modelRunService).saveModelRun(modelRun);
}
@Test
public void handlingSucceedsIfThereAreOccurrencesToBatch() {
// Arrange
int diseaseGroupId = 87;
DateTime batchEndDate = new DateTime("2013-07-30T14:15:16");
DateTime batchEndDateWithMaximumTime = new DateTime("2013-07-30T23:59:59.999");
ModelRun modelRun = createModelRun(diseaseGroupId, ModelRunStatus.COMPLETED);
modelRun.setBatchEndDate(batchEndDate);
DiseaseGroup diseaseGroup = new DiseaseGroup(diseaseGroupId);
diseaseGroup.setName("Dengue");
DiseaseOccurrence occurrence1 = new DiseaseOccurrence();
DiseaseOccurrence occurrence2 = new DiseaseOccurrence();
List<DiseaseOccurrence> occurrences = Arrays.asList(occurrence1, occurrence2);
when(modelRunService.getModelRunByName(modelRun.getName())).thenReturn(modelRun);
when(diseaseService.getDiseaseGroupById(diseaseGroupId)).thenReturn(diseaseGroup);
when(diseaseService.getDiseaseOccurrencesForBatching(diseaseGroupId, batchEndDateWithMaximumTime))
.thenReturn(occurrences);
// Act
diseaseOccurrenceHandler.handle(modelRun);
// Assert
verify(diseaseService).getDiseaseOccurrencesForBatching(
eq(diseaseGroupId), eq(batchEndDateWithMaximumTime));
verify(diseaseOccurrenceValidationService).addValidationParameters(same(occurrences));
verify(diseaseService).saveDiseaseOccurrence(same(occurrence1));
verify(diseaseService).saveDiseaseOccurrence(same(occurrence2));
verify(modelRunService).saveModelRun(modelRun);
}
private ModelRun createModelRun(int diseaseGroupId, ModelRunStatus status) {
ModelRun modelRun = new ModelRun(1);
modelRun.setName("test");
modelRun.setDiseaseGroupId(diseaseGroupId);
modelRun.setRequestDate(DateTime.now());
modelRun.setStatus(status);
return modelRun;
}
} |
//This code is developed as part of the Java CoG Kit project
//This message may not be removed or altered.
package org.globus.cog.abstraction.impl.execution.local;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import org.globus.cog.abstraction.impl.common.AbstractDelegatedTaskHandler;
import org.globus.cog.abstraction.impl.common.StatusImpl;
import org.globus.cog.abstraction.impl.common.execution.JobException;
import org.globus.cog.abstraction.impl.common.task.IllegalSpecException;
import org.globus.cog.abstraction.impl.common.task.InvalidSecurityContextException;
import org.globus.cog.abstraction.impl.common.task.InvalidServiceContactException;
import org.globus.cog.abstraction.impl.common.task.TaskSubmissionException;
import org.globus.cog.abstraction.impl.common.util.NullOutputStream;
import org.globus.cog.abstraction.impl.common.util.OutputStreamMultiplexer;
import org.globus.cog.abstraction.interfaces.FileLocation;
import org.globus.cog.abstraction.interfaces.JobSpecification;
import org.globus.cog.abstraction.interfaces.Status;
import org.globus.cog.abstraction.interfaces.Task;
/**
* @author Kaizar Amin (amin@mcs.anl.gov)
*
*/
public class JobSubmissionTaskHandler extends AbstractDelegatedTaskHandler implements
Runnable {
private static Logger logger = Logger
.getLogger(JobSubmissionTaskHandler.class);
private static final int STDOUT = 0;
private static final int STDERR = 1;
public static final int BUFFER_SIZE = 1024;
private Thread thread = null;
private Process process;
private volatile boolean killed;
public void submit(Task task) throws IllegalSpecException,
InvalidSecurityContextException, InvalidServiceContactException,
TaskSubmissionException {
checkAndSetTask(task);
task.setStatus(Status.SUBMITTING);
JobSpecification spec;
try {
spec = (JobSpecification) task.getSpecification();
}
catch (Exception e) {
throw new IllegalSpecException(
"Exception while retrieving Job Specification", e);
}
if (logger.isDebugEnabled()) {
logger.debug(spec.toString());
}
try {
if (logger.isInfoEnabled()) {
logger.info("Submitting task " + task);
}
synchronized (this) {
thread = new Thread(this);
thread.setName("Local task " + task.getIdentity());
thread.setDaemon(true);
if (task.getStatus().getStatusCode() != Status.CANCELED) {
task.setStatus(Status.SUBMITTED);
this.thread.start();
if (spec.isBatchJob()) {
task.setStatus(Status.COMPLETED);
}
}
}
}
catch (Exception e) {
throw new TaskSubmissionException("Cannot submit job", e);
}
}
public void suspend() throws InvalidSecurityContextException,
TaskSubmissionException {
}
public void resume() throws InvalidSecurityContextException,
TaskSubmissionException {
}
public void cancel(String message) throws InvalidSecurityContextException,
TaskSubmissionException {
synchronized (this) {
killed = true;
process.destroy();
getTask().setStatus(new StatusImpl(Status.CANCELED, message, null));
}
}
private static final FileLocation REDIRECT_LOCATION = FileLocation.MEMORY
.and(FileLocation.LOCAL);
public void run() {
try {
// TODO move away from the multi-threaded approach
JobSpecification spec = (JobSpecification) getTask()
.getSpecification();
File dir = null;
if (spec.getDirectory() != null) {
dir = new File(spec.getDirectory());
}
process = Runtime.getRuntime().exec(buildCmdArray(spec),
buildEnvp(spec), dir);
getTask().setStatus(Status.ACTIVE);
processIN(spec.getStdInput(), dir);
List pairs = new LinkedList();
if (!FileLocation.NONE.equals(spec.getStdOutputLocation())) {
OutputStream os = prepareOutStream(spec.getStdOutput(), spec
.getStdOutputLocation(), dir, getTask(), STDOUT);
if (os != null) {
pairs.add(new StreamPair(process.getInputStream(), os));
}
}
if (!FileLocation.NONE.equals(spec.getStdErrorLocation())) {
OutputStream os = prepareOutStream(spec.getStdError(), spec
.getStdErrorLocation(), dir, getTask(), STDERR);
if (os != null) {
pairs.add(new StreamPair(process.getErrorStream(), os));
}
}
Processor p = new Processor(process, pairs);
if (spec.isBatchJob()) {
Thread t = new Thread(p);
t.setName("Local task");
t.start();
return;
}
p.run();
int exitCode = p.getExitCode();
if (logger.isDebugEnabled()) {
logger.debug("Exit code was " + exitCode);
}
if (killed) {
return;
}
if (exitCode == 0) {
getTask().setStatus(Status.COMPLETED);
}
else {
throw new JobException(exitCode);
}
}
catch (Exception e) {
if (killed) {
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Exception while running local executable", e);
}
failTask(null, e);
}
}
protected void processIN(String in, File dir) throws IOException {
byte[] buf = new byte[BUFFER_SIZE];
if (in != null) {
OutputStream out = process.getOutputStream();
File stdin;
if (dir != null) {
stdin = new File(dir, in);
}
else {
stdin = new File(in);
}
FileInputStream file = new FileInputStream(stdin);
int read = file.read(buf);
while (read != -1) {
out.write(buf, 0, read);
read = file.read(buf);
}
file.close();
out.close();
}
}
protected OutputStream prepareOutStream(String out, FileLocation loc,
File dir, Task task, int stream) throws IOException {
OutputStream os = null;
TaskOutputStream baos = null;
if (FileLocation.MEMORY.overlaps(loc)) {
baos = new TaskOutputStream(task, stream);
os = baos;
}
if ((FileLocation.LOCAL.overlaps(loc) || FileLocation.REMOTE
.equals(loc))
&& out != null) {
if (os != null) {
os = new OutputStreamMultiplexer(os,
new FileOutputStream(out));
}
else {
os = new FileOutputStream(out);
}
}
if (os == null) {
os = new NullOutputStream();
}
return os;
}
private String[] buildCmdArray(JobSpecification spec) {
List arguments = spec.getArgumentsAsList();
String[] cmdarray = new String[arguments.size() + 1];
cmdarray[0] = spec.getExecutable();
Iterator i = arguments.iterator();
int index = 1;
while (i.hasNext()) {
cmdarray[index++] = (String) i.next();
}
return cmdarray;
}
private String[] buildEnvp(JobSpecification spec) {
Collection names = spec.getEnvironmentVariableNames();
if (names.size() == 0) {
/*
* Questionable. An envp of null will cause the parent environment
* to be inherited, while an empty one will cause no environment
* variables to be set for the process. Or so it seems from the
* Runtime.exec docs.
*/
return null;
}
String[] envp = new String[names.size()];
Iterator i = names.iterator();
int index = 0;
while (i.hasNext()) {
String name = (String) i.next();
envp[index++] = name + "=" + spec.getEnvironmentVariable(name);
}
return envp;
}
private static class StreamPair {
public InputStream is;
public OutputStream os;
public StreamPair(InputStream is, OutputStream os) {
this.is = is;
this.os = os;
}
}
private static class TaskOutputStream extends ByteArrayOutputStream {
private Task task;
private int stream;
public TaskOutputStream(Task task, int stream) {
this.task = task;
this.stream = stream;
}
public void close() throws IOException {
super.close();
String value = toString();
if (logger.isDebugEnabled()) {
logger.debug((stream == STDOUT ? "STDOUT" : "STDERR")
+ " from job: " + value);
}
if (stream == STDOUT) {
task.setStdOutput(value);
}
else {
task.setStdError(value);
}
}
}
private static class Processor implements Runnable {
private Process p;
private List streamPairs;
byte[] buf;
public Processor(Process p, List streamPairs) {
this.p = p;
this.streamPairs = streamPairs;
}
public void run() {
try {
run2();
}
catch (Exception e) {
logger.warn("Exception caught while running process", e);
}
}
public void run2() throws IOException, InterruptedException {
while (true) {
boolean any = processPairs();
if (processDone()) {
closePairs();
return;
}
else {
if (!any) {
Thread.sleep(20);
}
}
}
}
private boolean processPairs() throws IOException {
boolean any = false;
Iterator i = streamPairs.iterator();
while (i.hasNext()) {
if (buf == null) {
buf = new byte[BUFFER_SIZE];
}
StreamPair sp = (StreamPair) i.next();
int avail = sp.is.available();
if (avail > 0) {
any = true;
int len = sp.is.read(buf);
sp.os.write(buf, 0, len);
}
}
return any;
}
private boolean processDone() {
try {
p.exitValue();
return true;
}
catch (IllegalThreadStateException e) {
return false;
}
}
private void closePairs() throws IOException {
Iterator i = streamPairs.iterator();
while (i.hasNext()) {
StreamPair sp = (StreamPair) i.next();
sp.os.close();
sp.is.close();
}
}
public int getExitCode() {
return p.exitValue();
}
}
} |
package org.carlspring.strongbox.controllers.environment;
import org.carlspring.strongbox.controllers.BaseController;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.*;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Pablo Tirado
*/
@RestController
@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping("/api/configuration/environment/info")
@Api("/api/configuration/environment/info")
public class EnvironmentInfoController
extends BaseController
{
private static final String SYSTEM_PROPERTIES_PREFIX = "-D";
private ObjectMapper objectMapper;
public EnvironmentInfoController(ObjectMapper objectMapper)
{
this.objectMapper = objectMapper;
}
@ApiOperation(value = "List all the environment variables, system properties and JVM arguments.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "The list was returned."),
@ApiResponse(code = 500, message = "An error occurred.") })
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getEnvironmentInfo()
{
logger.debug("Listing of all environment variables, system properties and JVM arguments");
Map<String, List<?>> propertiesMap = new LinkedHashMap<>();
propertiesMap.put("environment", getEnvironmentVariables());
propertiesMap.put("system", getSystemProperties());
propertiesMap.put("jvm", getJvmArguments());
try
{
return ResponseEntity.ok(objectMapper.writeValueAsString(propertiesMap));
}
catch (JsonProcessingException e)
{
logger.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(String.format("{ 'error': '%s' }", e.getMessage()));
}
}
private List<EnvironmentInfo> getEnvironmentVariables()
{
Map<String, String> environmentMap = System.getenv();
return environmentMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey(String::compareToIgnoreCase))
.map(e -> new EnvironmentInfo(e.getKey(), e.getValue()))
.collect(Collectors.toList());
}
private List<EnvironmentInfo> getSystemProperties()
{
Properties systemProperties = System.getProperties();
return systemProperties.entrySet().stream()
.sorted(Comparator.comparing(e -> ((String) e.getKey()).toLowerCase()))
.map(e -> new EnvironmentInfo((String) e.getKey(), (String) e.getValue()))
.collect(Collectors.toList());
}
private List<String> getSystemPropertiesAsString()
{
List<EnvironmentInfo> systemProperties = getSystemProperties();
return systemProperties.stream()
.map(e -> SYSTEM_PROPERTIES_PREFIX + e.getName() + "=" + e.getValue())
.collect(Collectors.toList());
}
private List<String> getJvmArguments()
{
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();
List<String> systemProperties = getSystemPropertiesAsString();
return arguments.stream()
.filter(argument -> !systemProperties.contains(argument))
.sorted(String::compareToIgnoreCase)
.collect(Collectors.toList());
}
} |
package org.jfree.experimental.swt;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
/**
* Utility class gathering some useful and general method.
* Mainly convert forth and back graphical stuff between
* awt and swt.
*/
public class SWTUtils {
private final static String Az = "ABCpqr";
/** A dummy JPanel used to provide font metrics. */
protected static final JPanel DUMMY_PANEL = new JPanel();
/**
* Create a <code>FontData</code> object which encapsulate
* the essential data to create a swt font. The data is taken
* from the provided awt Font.
* <p>Generally speaking, given a font size, the returned swt font
* will display differently on the screen than the awt one.
* Because the SWT toolkit use native graphical resources whenever
* it is possible, this fact is platform dependent. To address
* this issue, it is possible to enforce the method to return
* a font with the same size (or at least as close as possible)
* as the awt one.
* <p>When the object is no more used, the user must explicitly
* call the dispose method on the returned font to free the
* operating system resources (the garbage collector won't do it).
*
* @param device The swt device to draw on (display or gc device).
* @param font The awt font from which to get the data.
* @param ensureSameSize A boolean used to enforce the same size
* (in pixels) between the awt font and the newly created swt font.
* @return a <code>FontData</code> object.
*/
public static FontData toSwtFontData(Device device, java.awt.Font font,
boolean ensureSameSize) {
FontData fontData = new FontData();
fontData.setName(font.getFamily());
int style = SWT.NORMAL;
switch (font.getStyle()) {
case java.awt.Font.PLAIN:
style |= SWT.NORMAL;
break;
case java.awt.Font.BOLD:
style |= SWT.BOLD;
break;
case java.awt.Font.ITALIC:
style |= SWT.ITALIC;
break;
case (java.awt.Font.ITALIC + java.awt.Font.BOLD):
style |= SWT.ITALIC | SWT.BOLD;
break;
}
fontData.setStyle(style);
// convert the font size (in pt for awt) to height in pixels for swt
int height = (int) Math.round(font.getSize() * 72.0
/ device.getDPI().y);
fontData.setHeight(height);
// hack to ensure the newly created swt fonts will be rendered with the
// same height as the awt one
if (ensureSameSize) {
GC tmpGC = new GC(device);
Font tmpFont = new Font(device, fontData);
tmpGC.setFont(tmpFont);
if (tmpGC.textExtent(Az).x
> DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {
while (tmpGC.textExtent(Az).x
> DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {
tmpFont.dispose();
height
fontData.setHeight(height);
tmpFont = new Font(device, fontData);
tmpGC.setFont(tmpFont);
}
}
else if (tmpGC.textExtent(Az).x
< DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {
while (tmpGC.textExtent(Az).x
< DUMMY_PANEL.getFontMetrics(font).stringWidth(Az)) {
tmpFont.dispose();
height++;
fontData.setHeight(height);
tmpFont = new Font(device, fontData);
tmpGC.setFont(tmpFont);
}
}
tmpFont.dispose();
tmpGC.dispose();
}
return fontData;
}
/**
* Create an awt font by converting as much information
* as possible from the provided swt <code>FontData</code>.
* <p>Generally speaking, given a font size, an swt font will
* display differently on the screen than the corresponding awt
* one. Because the SWT toolkit use native graphical ressources whenever
* it is possible, this fact is platform dependent. To address
* this issue, it is possible to enforce the method to return
* an awt font with the same height as the swt one.
*
* @param device The swt device being drawn on (display or gc device).
* @param fontData The swt font to convert.
* @param ensureSameSize A boolean used to enforce the same size
* (in pixels) between the swt font and the newly created awt font.
* @return An awt font converted from the provided swt font.
*/
public static java.awt.Font toAwtFont(Device device, FontData fontData,
boolean ensureSameSize) {
int style;
switch (fontData.getStyle()) {
case SWT.NORMAL:
style = java.awt.Font.PLAIN;
break;
case SWT.ITALIC:
style = java.awt.Font.ITALIC;
break;
case SWT.BOLD:
style = java.awt.Font.BOLD;
break;
default:
style = java.awt.Font.PLAIN;
break;
}
int height = (int) Math.round(fontData.getHeight() * device.getDPI().y
/ 72.0);
// hack to ensure the newly created awt fonts will be rendered with the
// same height as the swt one
if (ensureSameSize) {
GC tmpGC = new GC(device);
Font tmpFont = new Font(device, fontData);
tmpGC.setFont(tmpFont);
JPanel DUMMY_PANEL = new JPanel();
java.awt.Font tmpAwtFont = new java.awt.Font(fontData.getName(),
style, height);
if (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)
> tmpGC.textExtent(Az).x) {
while (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)
> tmpGC.textExtent(Az).x) {
height
tmpAwtFont = new java.awt.Font(fontData.getName(), style,
height);
}
}
else if (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)
< tmpGC.textExtent(Az).x) {
while (DUMMY_PANEL.getFontMetrics(tmpAwtFont).stringWidth(Az)
< tmpGC.textExtent(Az).x) {
height++;
tmpAwtFont = new java.awt.Font(fontData.getName(), style,
height);
}
}
tmpFont.dispose();
tmpGC.dispose();
}
return new java.awt.Font(fontData.getName(), style, height);
}
/**
* Create an awt font by converting as much information
* as possible from the provided swt <code>Font</code>.
*
* @param device The swt device to draw on (display or gc device).
* @param font The swt font to convert.
* @return An awt font converted from the provided swt font.
*/
public static java.awt.Font toAwtFont(Device device, Font font) {
FontData fontData = font.getFontData()[0];
return toAwtFont(device, fontData, true);
}
/**
* Creates an awt color instance to match the rgb values
* of the specified swt color.
*
* @param color The swt color to match.
* @return an awt color abject.
*/
public static java.awt.Color toAwtColor(Color color) {
return new java.awt.Color(color.getRed(), color.getGreen(),
color.getBlue());
}
/**
* Creates a swt color instance to match the rgb values
* of the specified awt paint. For now, this method test
* if the paint is a color and then return the adequate
* swt color. Otherwise plain black is assumed.
*
* @param device The swt device to draw on (display or gc device).
* @param paint The awt color to match.
* @return a swt color object.
*/
public static Color toSwtColor(Device device, java.awt.Paint paint) {
java.awt.Color color;
if (paint instanceof java.awt.Color) {
color = (java.awt.Color) paint;
}
else {
try {
throw new Exception("only color is supported at present... "
+ "setting paint to uniform black color" );
}
catch (Exception e) {
e.printStackTrace();
color = new java.awt.Color(0, 0, 0);
}
}
return new org.eclipse.swt.graphics.Color(device,
color.getRed(), color.getGreen(), color.getBlue());
}
/**
* Creates a swt color instance to match the rgb values
* of the specified awt color. alpha channel is not supported.
* Note that the dispose method will need to be called on the
* returned object.
*
* @param device The swt device to draw on (display or gc device).
* @param color The awt color to match.
* @return a swt color object.
*/
public static Color toSwtColor(Device device, java.awt.Color color) {
return new org.eclipse.swt.graphics.Color(device,
color.getRed(), color.getGreen(), color.getBlue());
}
/**
* Transform an awt Rectangle2d instance into a swt one.
* The coordinates are rounded to integer for the swt object.
* @param rect2d The awt rectangle to map.
* @return an swt <code>Rectangle</code> object.
*/
public static Rectangle toSwtRectangle(Rectangle2D rect2d) {
return new Rectangle(
(int) Math.round(rect2d.getMinX()),
(int) Math.round(rect2d.getMinY()),
(int) Math.round(rect2d.getWidth()),
(int) Math.round(rect2d.getHeight())
);
}
/**
* Transform a swt Rectangle instance into an awt one.
* @param rect the swt <code>Rectangle</code>
* @return a Rectangle2D.Double instance with
* the eappropriate location and size.
*/
public static Rectangle2D toAwtRectangle(Rectangle rect) {
Rectangle2D rect2d = new Rectangle2D.Double();
rect2d.setRect(rect.x, rect.y, rect.width, rect.height);
return rect2d;
}
/**
* Returns an AWT point with the same coordinates as the specified
* SWT point.
*
* @param p the SWT point (<code>null</code> not permitted).
*
* @return An AWT point with the same coordinates as <code>p</code>.
*
* @see #toSwtPoint(java.awt.Point)
*/
public static Point2D toAwtPoint(Point p) {
return new java.awt.Point(p.x, p.y);
}
/**
* Returns an SWT point with the same coordinates as the specified
* AWT point.
*
* @param p the AWT point (<code>null</code> not permitted).
*
* @return An SWT point with the same coordinates as <code>p</code>.
*
* @see #toAwtPoint(Point)
*/
public static Point toSwtPoint(java.awt.Point p) {
return new Point(p.x, p.y);
}
/**
* Returns an SWT point with the same coordinates as the specified AWT
* point (rounded to integer values).
*
* @param p the AWT point (<code>null</code> not permitted).
*
* @return An SWT point with the same coordinates as <code>p</code>.
*
* @see #toAwtPoint(Point)
*/
public static Point toSwtPoint(java.awt.geom.Point2D p) {
return new Point((int) Math.round(p.getX()),
(int) Math.round(p.getY()));
}
/**
* Creates an AWT <code>MouseEvent</code> from a swt event.
* This method helps passing SWT mouse event to awt components.
* @param event The swt event.
* @return A AWT mouse event based on the given SWT event.
*/
public static MouseEvent toAwtMouseEvent(org.eclipse.swt.events.MouseEvent event) {
int button = MouseEvent.NOBUTTON;
switch (event.button) {
case 1: button = MouseEvent.BUTTON1; break;
case 2: button = MouseEvent.BUTTON2; break;
case 3: button = MouseEvent.BUTTON3; break;
}
int modifiers = 0;
if ((event.stateMask & SWT.CTRL) != 0) {
modifiers |= InputEvent.CTRL_DOWN_MASK;
}
if ((event.stateMask & SWT.SHIFT) != 0) {
modifiers |= InputEvent.SHIFT_DOWN_MASK;
}
if ((event.stateMask & SWT.ALT) != 0) {
modifiers |= InputEvent.ALT_DOWN_MASK;
}
MouseEvent awtMouseEvent = new MouseEvent(DUMMY_PANEL, event.hashCode(),
event.time, modifiers, event.x, event.y, 1, false, button);
return awtMouseEvent;
}
} |
package org.strangeforest.tcb.stats.model.records.categories;
import org.strangeforest.tcb.stats.model.*;
import org.strangeforest.tcb.stats.model.records.*;
import org.strangeforest.tcb.stats.model.records.details.*;
import static java.lang.String.*;
import static java.util.Arrays.*;
import static org.strangeforest.tcb.stats.model.records.RecordDomain.*;
import static org.strangeforest.tcb.stats.model.records.categories.HighestOpponentRankCategory.RecordType.*;
public class HighestOpponentRankCategory extends RecordCategory {
private static final String RANK_WIDTH = "180";
private static final String SEASON_WIDTH = "80";
private static final String TOURNAMENT_WIDTH = "120";
public enum RecordType {
HIGHEST("Highest", false),
LOWEST("Lowest", true);
private final String name;
private final boolean orderDesc;
RecordType(String name, boolean orderDesc) {
this.name = name;
this.orderDesc = orderDesc;
}
}
public enum RankingType {
RANK("Rank", "Rank", "exp(sum(ln(coalesce(opponent_rank, 1500)))/count(*))", " WHERE unrounded_value < 1500", false, "Using geometric mean"),
ELO_RATING("EloRating", "Elo Rating", "sum(coalesce(opponent_elo_rating, 1500))::REAL/count(*)", "", true, "Using arithmetic mean");
private final String id;
private final String name;
private final String function;
private final String where;
private final boolean orderDesc;
private final String notes;
RankingType(String id, String name, String function, String where, boolean orderDesc, String notes) {
this.id = id;
this.name = name;
this.function = function;
this.where = where;
this.orderDesc = orderDesc;
this.notes = notes;
}
}
public HighestOpponentRankCategory(RecordType type, RankingType rankingType) {
super(type.name + " Mean Opponent " + rankingType.name);
if (type == HIGHEST) {
register(highestOpponentRank(type, rankingType, ALL));
register(highestOpponentRank(type, rankingType, GRAND_SLAM));
register(highestOpponentRank(type, rankingType, TOUR_FINALS));
register(highestOpponentRank(type, rankingType, MASTERS));
register(highestOpponentRank(type, rankingType, OLYMPICS));
register(highestOpponentRank(type, rankingType, ATP_500));
register(highestOpponentRank(type, rankingType, ATP_250));
register(highestOpponentRank(type, rankingType, DAVIS_CUP));
register(highestOpponentRank(type, rankingType, HARD));
register(highestOpponentRank(type, rankingType, CLAY));
register(highestOpponentRank(type, rankingType, GRASS));
register(highestOpponentRank(type, rankingType, CARPET));
register(highestSeasonOpponentRank(type, rankingType, ALL));
register(highestSeasonOpponentRank(type, rankingType, HARD));
register(highestSeasonOpponentRank(type, rankingType, CLAY));
register(highestSeasonOpponentRank(type, rankingType, GRASS));
register(highestSeasonOpponentRank(type, rankingType, CARPET));
}
register(highestTitleOpponentRank(type, rankingType, ALL_WO_TEAM));
register(highestTitleOpponentRank(type, rankingType, GRAND_SLAM));
register(highestTitleOpponentRank(type, rankingType, TOUR_FINALS));
register(highestTitleOpponentRank(type, rankingType, MASTERS));
register(highestTitleOpponentRank(type, rankingType, OLYMPICS));
register(highestTitlesOpponentRank(type, rankingType, ALL_WO_TEAM));
register(highestTitlesOpponentRank(type, rankingType, GRAND_SLAM));
register(highestTitlesOpponentRank(type, rankingType, TOUR_FINALS));
register(highestTitlesOpponentRank(type, rankingType, MASTERS));
}
private static Record highestOpponentRank(RecordType type, RankingType rankingType, RecordDomain domain) {
PerformanceCategory perfCategory = PerformanceCategory.get(domain.perfCategory);
int minEntries = perfCategory.getMinEntries();
String desc = desc(type.orderDesc ^ rankingType.orderDesc);
return new Record<>(
type.name + domain.id + "Opponent" + rankingType.id, suffix(type.name, " ") + suffix(domain.name, " ") + " Mean Opponent " + rankingType.name,
/* language=SQL */
"WITH opponent_rank AS (\n" +
" SELECT player_id, " + rankingType.function + " AS unrounded_value\n" +
" FROM player_match_for_stats_v" + where(domain.condition) + "\n" +
" GROUP BY player_id\n" +
" HAVING count(*) >= " + minEntries + "\n" +
")\n" +
"SELECT player_id, round(unrounded_value::NUMERIC, 1) AS value, unrounded_value\n" +
"FROM opponent_rank" + rankingType.where,
"r.value", "r.unrounded_value" + desc, "r.unrounded_value" + desc,
DoubleRecordDetail.class, null,
asList(new RecordColumn("value", null, "factor", RANK_WIDTH, "right", "Mean Opponent " + rankingType.name)),
format("Minimum %1$d %2$s; %3$s", minEntries, perfCategory.getEntriesName(), rankingType.notes)
);
}
private static Record highestSeasonOpponentRank(RecordType type, RankingType rankingType, RecordDomain domain) {
PerformanceCategory perfCategory = PerformanceCategory.get(domain.perfCategory);
int minEntries = perfCategory.getMinEntries() / 10;
String desc = desc(type.orderDesc ^ rankingType.orderDesc);
return new Record<>(
type.name + "Season" + domain.id + "Opponent" + rankingType.id, suffix(type.name, " ") + suffix(domain.name, " ") + " Mean Opponent " + rankingType.name + " in Single Season",
/* language=SQL */
"WITH season_opponent_rank AS (\n" +
" SELECT player_id, season, " + rankingType.function + " AS unrounded_value\n" +
" FROM player_match_for_stats_v" + where(domain.condition) + "\n" +
" GROUP BY player_id, season\n" +
" HAVING count(*) >= " + minEntries + "\n" +
")\n" +
"SELECT player_id, season, round(unrounded_value::NUMERIC, 1) AS value, unrounded_value\n" +
"FROM season_opponent_rank" + rankingType.where,
"r.value, r.season", "r.unrounded_value" + desc, "r.unrounded_value" + desc + ", r.season",
SeasonDoubleRecordDetail.class, null,
asList(
new RecordColumn("value", null, "factor", RANK_WIDTH, "right", "Mean Opponent " + rankingType.name),
new RecordColumn("season", "numeric", null, SEASON_WIDTH, "center", "Season")
),
format("Minimum %1$d %2$s; %3$s", minEntries, perfCategory.getEntriesName(), rankingType.notes)
);
}
private static Record highestTitleOpponentRank(RecordType type, RankingType rankingType, RecordDomain domain) {
int minEntries = 3;
String desc = desc(type.orderDesc ^ rankingType.orderDesc);
return new Record<>(
type.name + "Title" + domain.id + "Opponent" + rankingType.id, type.name + " Mean Opponent " + rankingType.name + " Winning " + suffix(domain.name, " ") + "Title",
/* language=SQL */
"WITH tournament_opponent_rank AS (\n" +
" SELECT player_id, tournament_event_id, e.name AS tournament, e.level, e.season, e.date, " + rankingType.function + " AS unrounded_value\n" +
" FROM player_match_for_stats_v INNER JOIN player_tournament_event_result r USING (player_id, tournament_event_id)\n" +
" INNER JOIN tournament_event e USING (tournament_event_id)\n" +
" WHERE r.result = 'W' AND e." + domain.condition + "\n" +
" GROUP BY player_id, tournament_event_id, e.name, e.level, e.season, e.date\n" +
" HAVING count(*) >= " + minEntries + "\n" +
")\n" +
"SELECT player_id, tournament_event_id, tournament, level, season, date, round(unrounded_value::NUMERIC, 1) AS value, unrounded_value\n" +
"FROM tournament_opponent_rank" + rankingType.where,
"r.value, r.tournament_event_id, r.tournament, r.level, r.season", "r.unrounded_value" + desc, "r.unrounded_value" + desc + ", r.date",
TournamentEventDoubleRecordDetail.class, (playerId, recordDetail) -> format("/playerProfile?playerId=%1$d&tab=matches&tournamentEventId=%2$d", playerId, recordDetail.getTournamentEventId()),
asList(
new RecordColumn("value", null, "factor", RANK_WIDTH, "right", "Mean Opponent " + rankingType.name),
new RecordColumn("season", "numeric", null, SEASON_WIDTH, "center", "Season"),
new RecordColumn("tournament", null, "tournamentEvent", TOURNAMENT_WIDTH, "left", "Tournament")
),
format("Minimum %1$d matches; %2$s", minEntries, rankingType.notes)
);
}
private static Record highestTitlesOpponentRank(RecordType type, RankingType rankingType, RecordDomain domain) {
int minEntries = 10;
String desc = desc(type.orderDesc ^ rankingType.orderDesc);
return new Record<>(
type.name + "Titles" + domain.id + "Opponent" + rankingType.id, type.name + " Mean Opponent " + rankingType.name + " Winning " + suffix(domain.name, " ") + "Titles",
/* language=SQL */
"WITH titles_opponent_rank AS (\n" +
" SELECT player_id, " + rankingType.function + " AS unrounded_value\n" +
" FROM player_match_for_stats_v INNER JOIN player_tournament_event_result r USING (player_id, tournament_event_id)\n" +
" INNER JOIN tournament_event e USING (tournament_event_id)\n" +
" WHERE r.result = 'W' AND e." + domain.condition + "\n" +
" GROUP BY player_id\n" +
" HAVING count(*) >= " + minEntries + "\n" +
")\n" +
"SELECT player_id, round(unrounded_value::NUMERIC, 1) AS value, unrounded_value\n" +
"FROM titles_opponent_rank" + rankingType.where,
"r.value", "r.unrounded_value" + desc, "r.unrounded_value" + desc,
DoubleRecordDetail.class, null,
asList(new RecordColumn("value", null, "factor", RANK_WIDTH, "right", "Mean Opponent " + rankingType.name)),
format("Minimum %1$d matches; %2$s", minEntries, rankingType.notes)
);
}
private static String desc(boolean desc) {
return desc ? " DESC" : "";
}
} |
package org.jboss.as.test.integration.web.response;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
/**
* Tests the "default servlet" of the web container
*
* @author Jaikiran Pai
*/
@RunWith(Arquillian.class)
@RunAsClient
public class DefaultServletTestCase {
private static final String WEB_APP_CONTEXT = "default-servlet-test";
private static final String APP_XHTML_FILE_NAME = "app.xhtml";
private static final String INFDIRS_DEPLOYMENT = "infdirectories";
private static final Logger logger = Logger.getLogger(DefaultServletTestCase.class);
@ArquillianResource
URL url;
private HttpClient httpclient;
@Deployment(name = WEB_APP_CONTEXT)
public static WebArchive deployment() {
final WebArchive war = ShrinkWrap.create(WebArchive.class, WEB_APP_CONTEXT + ".war");
war.addAsWebResource(DefaultServletTestCase.class.getPackage(), APP_XHTML_FILE_NAME, APP_XHTML_FILE_NAME);
return war;
}
@Deployment(name = INFDIRS_DEPLOYMENT)
public static Archive<?> createDeployment() {
WebArchive war = ShrinkWrap.create(WebArchive.class, INFDIRS_DEPLOYMENT + ".war");
war.add(new StringAsset("Welcome in WEB-INFOOBAR"), "WEB-INFOOBAR/test.html");
war.add(new StringAsset("Welcome in META-INFOOBAR"), "META-INFOOBAR/test.html");
return war;
}
@Before
public void setup() {
this.httpclient = HttpClientBuilder.create().build();
}
@OperateOnDeployment(WEB_APP_CONTEXT)
@Test
public void testForbidSourceFileAccess() throws Exception {
// first try accessing the valid URL and expect it to serve the right content
final String correctURL = url.toString() + APP_XHTML_FILE_NAME;
final HttpGet httpGetCorrectURL = new HttpGet(correctURL);
final HttpResponse response = this.httpclient.execute(httpGetCorrectURL);
Assert.assertEquals("Unexpected response code for URL " + correctURL, HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
final String content = EntityUtils.toString(response.getEntity());
Assert.assertTrue("Unexpected content served at " + correctURL, content.contains("Hello World"));
// now try accessing the same URL with a "." at the end of the resource name.
// This should throw a 404 error and NOT show up the "source" content of the resource
final String nonExistentURL = url.toString() + APP_XHTML_FILE_NAME + ".";
final HttpGet httpGetNonExistentURL = new HttpGet(nonExistentURL);
final HttpResponse responseForNonExistentURL = this.httpclient.execute(httpGetNonExistentURL);
Assert.assertEquals("Unexpected response code for URL " + nonExistentURL, HttpServletResponse.SC_NOT_FOUND, responseForNonExistentURL.getStatusLine().getStatusCode());
}
/**
* Tests if the default servlet serves content from any directories starting with WEB-INF or META-INF
*
* [WFLY-15045]
*
* @param webAppURL
* @throws Exception
*/
@OperateOnDeployment(INFDIRS_DEPLOYMENT)
@Test
public void testInfDirectories(@ArquillianResource URL webAppURL) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(new HttpGet(webAppURL.toURI() + "WEB-INFOOBAR/test.html"));
Assert.assertEquals(200, httpResponse.getStatusLine().getStatusCode());
EntityUtils.consumeQuietly(httpResponse.getEntity());
httpResponse = httpClient.execute(new HttpGet(webAppURL.toURI() + "META-INFOOBAR/test.html"));
Assert.assertEquals(200, httpResponse.getStatusLine().getStatusCode());
}
} |
package thredds.tdm;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScheme;
import org.apache.commons.httpclient.auth.CredentialsNotAvailableException;
import org.apache.commons.httpclient.auth.CredentialsProvider;
import org.apache.log4j.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import thredds.catalog.DataFormatType;
import thredds.catalog.InvDatasetFeatureCollection;
import thredds.inventory.*;
import ucar.nc2.grib.GribCollection;
import ucar.nc2.grib.TimePartitionBuilder;
import ucar.nc2.grib.grib2.Grib2CollectionBuilder;
import ucar.nc2.time.CalendarDate;
import ucar.nc2.time.CalendarPeriod;
import ucar.nc2.units.TimeDuration;
import ucar.nc2.util.net.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Thredds Data Manager.
*
* run: java -Xmx4g -server -jar tdm-4.3.jar
* if you need to muck with that, use:
* java -Xmx4g -server -jar tdm-4.3.jar -catalog <muck.xml>
* where you can start with tdm-4.3.jar/resources/indexNomads.xml
* or modify resources/applicatin-config.xml to set the catalog
*
* @author caron
* @since 4/26/11
*/
public class TdmRunner {
//static private final Logger logger = org.slf4j.LoggerFactory.getLogger(TdmRunner.class);
static private boolean seperateFiles = true;
static private String serverName = "http://localhost:8080/"; // hack for now
static private HTTPSession session;
private java.util.concurrent.ExecutorService executor;
private Resource catalog;
private boolean indexOnly = false; // if true, just use existing .ncx
private boolean showOnly = false; // if true, just show dirs and exit
public void setShowOnly(boolean showOnly) {
this.showOnly = showOnly;
}
// spring beaned
public void setExecutor(ExecutorService executor) {
this.executor = executor;
}
public void setCatalog(Resource catalog) {
this.catalog = catalog;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
// Task causes a new index to be written - we know collection has changed, dont test again
// run these through the executor so we can control how many we can do at once.
// thread pool set in spring config file
private class IndexTask implements Runnable {
String name;
InvDatasetFeatureCollection fc;
CollectionManager dcm;
Listener liz;
org.slf4j.Logger logger;
private IndexTask(InvDatasetFeatureCollection fc, CollectionManager dcm, Listener liz, org.slf4j.Logger logger) {
this.name = fc.getName();
this.fc = fc;
this.dcm = dcm;
this.liz = liz;
this.logger = logger;
}
@Override
public void run() {
try {
FeatureCollectionConfig config = fc.getConfig();
thredds.catalog.DataFormatType format = fc.getDataFormatType();
// delete any files first
if (config.tdmConfig.deleteAfter != null) {
doManage(config.tdmConfig.deleteAfter);
}
if (dcm instanceof TimePartitionCollection) {
TimePartitionCollection tpc = (TimePartitionCollection) dcm;
logger.debug("**** running TimePartitionBuilder.factory {} thread {}", name, Thread.currentThread().hashCode());
Formatter f = new Formatter();
try {
if (TimePartitionBuilder.writeIndexFile(tpc, CollectionManager.Force.always, f)) {
// send a trigger if enabled
if (config.tdmConfig.triggerOk) {
String url = serverName + "thredds/admin/collection?trigger=true&collection="+fc.getName();
int status = sendTrigger(url, f);
f.format(" trigger %s status = %d%n", url, status);
}
}
f.format("**** TimePartitionBuilder.factory complete %s%n", name);
} catch (Throwable e) {
logger.error("TimePartitionBuilder.factory " + name, e);
}
logger.debug("\n{}", f.toString());
} else {
logger.debug("**** running GribCollectionBuilder.factory {} Thread {}", name, Thread.currentThread().hashCode());
Formatter f = new Formatter();
try {
GribCollection gc = GribCollection.factory(format == DataFormatType.GRIB1, dcm, CollectionManager.Force.always, f);
gc.close();
f.format("**** GribCollectionBuilder.factory complete %s%n", name);
if (config.tdmConfig.triggerOk) {
String url = serverName + "thredds/admin/collection?trigger=true&collection="+fc.getName();
int status = sendTrigger(url, f);
f.format(" trigger %s status = %d%n", url, status);
}
} catch (Throwable e) {
logger.error("GribCollectionBuilder.factory " + name, e);
}
logger.debug("\n{}", f.toString());
}
} finally {
// tell liz that task is done
if (!liz.inUse.getAndSet(false))
logger.warn("Listener InUse should have been set");
}
/* System.out.printf("OpenFiles:%n");
for (String s : RandomAccessFile.getOpenFiles())
System.out.printf("%s%n", s);*/
}
private int sendTrigger(String url, Formatter f) {
logger.debug("send trigger to {}", url);
HTTPMethod m = null;
try {
m = HTTPMethod.Get(session, url);
int status = m.execute();
String s = m.getResponseAsString();
f.format("%s == %s", url, s);
System.out.printf("Trigger response = %s%n", s);
return status;
} catch (HTTPException e) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
e.printStackTrace(new PrintStream(bos));
f.format("%s == %s", url, bos.toString());
e.printStackTrace();
return -1;
} finally {
if (m != null) m.close();
}
}
private void doManage(String deleteAfterS) {
TimeDuration deleteAfter = null;
if (deleteAfterS != null) {
try {
deleteAfter = new TimeDuration(deleteAfterS);
} catch (Exception e) {
logger.error(dcm.getCollectionName()+": Invalid time unit for deleteAfter = {}", deleteAfter);
return;
}
}
// awkward
double val = deleteAfter.getValue();
CalendarPeriod.Field unit = CalendarPeriod.fromUnitString( deleteAfter.getTimeUnit().getUnitString());
CalendarDate now = CalendarDate.of(new Date());
CalendarDate last = now.add(val, unit);
for (MFile mfile : dcm.getFiles()) {
CalendarDate cd = dcm.extractRunDate(mfile);
if (cd.isBefore(last)) {
logger.info("delete={}", mfile.getPath());
}
}
}
}
// these objects listen for schedule events from quartz and dcm.
// one listener for each dcm.
private class Listener implements CollectionManager.TriggerListener {
InvDatasetFeatureCollection fc;
CollectionManager dcm;
AtomicBoolean inUse = new AtomicBoolean(false);
org.slf4j.Logger logger;
private Listener(InvDatasetFeatureCollection fc, CollectionManager dcm) {
this.fc = fc;
this.dcm = dcm;
if (seperateFiles) {
try {
//create logger in log4j
Layout layout = new PatternLayout("%d{yyyy-MM-dd'T'HH:mm:ss.SSS Z} %-5p - %c - %m%n");
String loggerName = fc.getName()+".log";
FileAppender app = new FileAppender(layout, loggerName);
org.apache.log4j.Logger log4j = LogManager.getLogger(fc.getName());
log4j.addAppender(app);
log4j.setLevel(Level.DEBUG);
// get wrapper in slf4j
logger = org.slf4j.LoggerFactory.getLogger(fc.getName());
} catch (IOException ioe) {
}
} else {
logger = org.slf4j.LoggerFactory.getLogger(getClass());
}
}
@Override
public void handleCollectionEvent(CollectionManager.TriggerEvent event) {
if (event.getType() != CollectionManager.TriggerType.update) return;
// make sure that each collection is only being indexed by one thread at a time
if (inUse.get()) {
logger.debug("** Update already in progress for {} {}", fc.getName(), event.getType());
return;
}
if (!inUse.compareAndSet(false, true)) return;
executor.execute(new IndexTask(fc, dcm, this, logger));
}
/* private boolean needsUpdate(long indexLastModified) {
if (dcm instanceof TimePartitionCollection)
return needsPartitionUpdate((TimePartitionCollection) dcm, indexLastModified);
else
return needsUpdate(dcm, indexLastModified);
}
private boolean needsPartitionUpdate(TimePartitionCollection tpc, long indexLastModified) {
try {
for (CollectionManager cm : tpc.makePartitions()) {
if (needsUpdate(cm, indexLastModified)) return true;
}
} catch (IOException ioe) {
logger.warn("** needsPartitionUpdate ", ioe);
}
return false;
}
private boolean needsUpdate(CollectionManager cm, long since) {
int count = 0;
for (MFile f : cm.getFiles()) {
if (wasUpdated(f, since)) return true;
count++;
}
if (count == 0) return true; // not scanned yet
// LOOK return !dcm.directoryWasModifiedAfter(lastDate)// LOOK - what if files were deleted ?
return false;
}
// could make this into a strategy thats passed into CollectionManager
private boolean wasUpdated(MFile mfile, long since) {
File gribFile = new File(mfile.getPath());
File idxFile = DiskCache.getFile(mfile.getPath() + GribIndex.IDX_EXT, false);
if (!idxFile.exists()) return true;
if (idxFile.lastModified() < gribFile.lastModified()) return true;
if (since < idxFile.lastModified()) return true;
return false;
} */
}
void start() throws IOException {
System.out.printf("Tdm startup at %s%n", new Date());
CatalogReader reader = new CatalogReader(catalog);
List<InvDatasetFeatureCollection> fcList = reader.getFcList();
if (showOnly) {
List<String> result = new ArrayList<String>();
for (InvDatasetFeatureCollection fc : fcList) {
CollectionManager dcm = fc.getDatasetCollectionManager();
result.add(dcm.getRoot());
}
Collections.sort(result);
System.out.printf("Directories:%n");
for (String dir : result)
System.out.printf(" %s%n", dir);
return;
}
for (InvDatasetFeatureCollection fc : fcList) {
CollectionManager dcm = fc.getDatasetCollectionManager();
FeatureCollectionConfig fcConfig = fc.getConfig();
if (fcConfig != null && fcConfig.gribConfig != null && fcConfig.gribConfig.gdsHash != null)
dcm.putAuxInfo("gdsHash", fcConfig.gribConfig.gdsHash); // sneak in extra config info
dcm.addEventListener( new Listener(fc, dcm)); // now wired for events
dcm.removeEventListener( fc); // not needed
// CollectionUpdater.INSTANCE.scheduleTasks( CollectionUpdater.FROM.tdm, fc.getConfig(), dcm); // already done in finish() method
}
// show whats up
Formatter f = new Formatter();
f.format("Feature Collections found:%n");
for (InvDatasetFeatureCollection fc : fcList) {
CollectionManager dcm = fc.getDatasetCollectionManager();
f.format(" %s == %s%n%s%n%n", fc, fc.getClass().getName(), dcm);
}
System.out.printf("%s%n", f.toString());
}
public static void main(String args[]) throws IOException, InterruptedException {
ApplicationContext springContext = new FileSystemXmlApplicationContext("classpath:resources/application-config.xml");
TdmRunner driver = (TdmRunner) springContext.getBean("testDriver");
//RandomAccessFile.setDebugLeaks(true);
for (int i=0; i<args.length; i++) {
if (args[i].equalsIgnoreCase("-help")) {
System.out.printf("usage: TdmRunner [-force] [-catalog <cat>] [-showDirs] %n");
System.exit(0);
}
//if (args[i].equalsIgnoreCase("-force"))
// driver.setForce(true);
//if (args[i].equalsIgnoreCase("-ncxOnly"))
// driver.setIndexOnly(true);
if (args[i].equalsIgnoreCase("-showDirs"))
driver.setShowOnly(true);
if (args[i].equalsIgnoreCase("-catalog")) {
Resource cat = new FileSystemResource(args[i+1]);
driver.setCatalog(cat); // allow default catalog overide
}
}
session = new HTTPSession(serverName);
session.setCredentialsProvider(new CredentialsProvider() {
public Credentials getCredentials(AuthScheme authScheme, String s, int i, boolean b) throws CredentialsNotAvailableException {
System.out.printf("getCredentials called%n");
return new UsernamePasswordCredentials("", "");
}
});
session.setUserAgent("TdsMonitor");
HTTPSession.setGlobalUserAgent("TDM v4.3");
driver.start();
}
} |
package org.eclipse.birt.report.utility;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.eclipse.birt.report.IBirtConstants;
import org.eclipse.birt.report.context.ScalarParameterBean;
import org.eclipse.birt.report.engine.api.IScalarParameterDefn;
import org.eclipse.birt.report.service.api.ParameterDefinition;
import org.eclipse.birt.report.service.api.ParameterSelectionChoice;
import org.eclipse.birt.report.soapengine.api.SelectItemChoice;
/**
* Utility class for parameter handling
*/
public class ParameterUtility
{
/**
* Processes the given selection list, and adds the element
* to the given parameter bean's selection list.
* @param selectionList original selection list to be processed
* @param parameterBean scalar parameter bean
* @param locale locale (for data conversion)
* @param timeZone time zone (for data conversion)
* @param processDefault update "selected" fields in parameterBean
* @return processed selection list
*/
public static List<ParameterSelectionChoice> makeSelectionList(
Collection<ParameterSelectionChoice> selectionList,
ScalarParameterBean parameterBean,
Locale locale, TimeZone timeZone, boolean processDefault )
{
// TODO: refactor according to the code path which depends on processDefault
boolean nullValueFound = false;
List<ParameterSelectionChoice> processedList = parameterBean.getSelectionList();
ParameterDefinition paramDef = parameterBean.getParameter( );
List<String> defaultValues = null;
if ( parameterBean.getDefaultValues( ) != null )
{
// make a copy, so the values can be removed one by one
// after processing
defaultValues = new ArrayList<String>( parameterBean.getDefaultValues( ) );
}
parameterBean.setValueInList( false );
if ( selectionList != null )
{
boolean isDisplayTextInList = false;
for ( ParameterSelectionChoice selectionItem : selectionList )
{
if ( selectionItem == null )
continue;
Object value = selectionItem.getValue( );
try
{
// try convert value to parameter definition data type
value = DataUtil.convert( value, paramDef.getDataType( ) );
}
catch ( Exception e )
{
value = null;
}
// Convert parameter value using standard format
String displayValue = DataUtil.getDisplayValue( value, timeZone );
String label = selectionItem.getLabel( );
if ( label == null || label.length( ) <= 0 )
{
// If label is null or blank, then use the format parameter
// value for display
label = DataUtil.getDisplayValue( null,
paramDef.getPattern( ), value, locale, timeZone );
}
// if parameter is required
if ( paramDef.isRequired( ) )
{
// discard null values, and if the parameter is a string,
// then also discard empty strings
if ( value == null
|| ( "".equals( value ) && //$NON-NLS-1$
paramDef.getDataType( ) == IScalarParameterDefn.TYPE_STRING ) )
{
continue;
}
}
if ( value == null )
{
nullValueFound = true;
if ( label == null )
{
label = IBirtConstants.NULL_VALUE_DISPLAY;
}
}
// TODO: warning, replacing values in the same list!
selectionItem.setLabel( label );
selectionItem.setValue( displayValue );
processedList.add( selectionItem );
// TODO: below code not required for cascading params, move out?
if ( processDefault )
{
// If parameter value is in the selection list
if ( !paramDef.isMultiValue( )
&& DataUtil.equals( displayValue, parameterBean.getValue( ) ) )
{
parameterBean.setValueInList( true );
// check whether parameter display text is in the label list
if ( !DataUtil.equals( label, parameterBean.getDisplayText( ) ) )
{
if ( parameterBean.getParameter( ).isDistinct( )
&& parameterBean.isDisplayTextInReq( ) )
{
selectionItem.setLabel( parameterBean
.getDisplayText( ) );
isDisplayTextInList = true;
}
}
else
{
isDisplayTextInList = true;
}
}
// Find out whether parameter default value is in the selection list
// if is multivalue and the default value is an array
if ( paramDef.isMultiValue( ) && defaultValues != null )
{
if ( DataUtil.contain( (List<?>)defaultValues, displayValue, true ) )
{
parameterBean.setDefaultValueInList( true );
// remove current value from the defaultvalues list
//If the default values is one, the defaultValues is null
if (defaultValues != null)
{
defaultValues.remove(displayValue);
}
}
}
// if it is a single default value
else if ( DataUtil.equals( displayValue, parameterBean.getDefaultValue( ) ) )
{
parameterBean.setDefaultValueInList( true );
// remove current value from the defaultvalues list
defaultValues.remove(displayValue);
}
}
}
if ( processDefault )
{
// add new item
if ( parameterBean.isValueInList( )
&& parameterBean.isDisplayTextInReq( )
&& !isDisplayTextInList )
{
processedList.add(
new ParameterSelectionChoice( parameterBean
.getDisplayText( ), parameterBean
.getValue( ) ) );
isDisplayTextInList = true;
}
// handle multiple default values
if ( defaultValues != null && defaultValues.size() > 0 )
{
for (int i = 0; i < defaultValues.size(); i++)
{
// add these default values which are not in the selectionList as string values,
// for those values have already been evaluated and are of string type.
processedList.add(i, new ParameterSelectionChoice( defaultValues.get(i), defaultValues.get(i) ) );
}
}
parameterBean.setDisplayTextInList( isDisplayTextInList );
}
}
if ( !nullValueFound && !parameterBean.isRequired( ) )
{
// add null value if none exists in the list
ParameterSelectionChoice selectionItem =
new ParameterSelectionChoice(
IBirtConstants.NULL_VALUE_DISPLAY,
null);
processedList.add( 0, selectionItem );
}
return processedList;
}
/**
* Convert a list of ParameterSelectionChoice to a list of SelectItemChoice
* (for SOAP)
* @param paramChoices list of ParameterSelectionChoice
* @return list of SelectItemChoice
*/
public static List<SelectItemChoice> toSelectItemChoice(
List<ParameterSelectionChoice> paramChoices )
{
List<SelectItemChoice> soapChoices = new ArrayList<SelectItemChoice>( );
soapChoices.add( SelectItemChoice.EMPTY_VALUE );
for ( ParameterSelectionChoice element : paramChoices )
{
SelectItemChoice itemChoice = new SelectItemChoice(
(String) element.getValue( ), element.getLabel( ) );
if ( itemChoice.getValue( ) == null )
{
itemChoice.setValue( IBirtConstants.NULL_VALUE );
}
soapChoices.add( itemChoice );
}
return soapChoices;
}
} |
package gov.nih.nci.cabig.caaers.domain.repository;
import static org.easymock.EasyMock.expect;
import gov.nih.nci.cabig.caaers.AbstractTestCase;
import gov.nih.nci.cabig.caaers.dao.InvestigatorConverterDao;
import gov.nih.nci.cabig.caaers.dao.InvestigatorDao;
import gov.nih.nci.cabig.caaers.dao.OrganizationDao;
import gov.nih.nci.cabig.caaers.dao.SiteInvestigatorDao;
import gov.nih.nci.cabig.caaers.dao.query.InvestigatorQuery;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.event.EventFactory;
import gov.nih.nci.cabig.caaers.security.CaaersSecurityFacade;
import gov.nih.nci.cabig.caaers.security.CaaersSecurityFacadeImpl;
import org.easymock.EasyMock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* This is the repository class for managing investigators
*
* @author Biju Joseph
*/
public class InvestigatorRepositoryImplTest extends AbstractTestCase {
InvestigatorRepositoryImpl repositoryImpl;
InvestigatorDao investigatorDao;
CaaersSecurityFacade caaersSecurityFacade;
OrganizationDao organizationDao;
SiteInvestigatorDao siteInvestigatorDao;
EventFactory eventFactory;
InvestigatorConverterDao investigatorConverterDao;
protected void setUp() throws Exception {
super.setUp();
eventFactory = registerMockFor(EventFactory.class);
repositoryImpl = new InvestigatorRepositoryImpl();
investigatorDao = registerDaoMockFor(InvestigatorDao.class);
organizationDao = registerDaoMockFor(OrganizationDao.class);
investigatorConverterDao = registerDaoMockFor(InvestigatorConverterDao.class);
siteInvestigatorDao = registerDaoMockFor(SiteInvestigatorDao.class);
repositoryImpl.setInvestigatorDao(investigatorDao);
repositoryImpl.setInvestigatorConverterDao(investigatorConverterDao);
caaersSecurityFacade = registerMockFor(CaaersSecurityFacade.class);
repositoryImpl.setCaaersSecurityFacade(caaersSecurityFacade);
repositoryImpl.setEventFactory(eventFactory);
repositoryImpl.setAuthenticationMode("local");
repositoryImpl.setOrganizationDao(organizationDao);
repositoryImpl.setSiteInvestigatorDao(siteInvestigatorDao);
assertSame(eventFactory, repositoryImpl.getEventFactory());
assertSame(investigatorDao, repositoryImpl.getInvestigatorDao());
}
public void testSave() {
Investigator inv = Fixtures.createInvestigator("Joel");
Organization org = Fixtures.createOrganization("NCI");
String changeUrl = "/pages/url";
expect(investigatorDao.merge(inv)).andReturn(inv).anyTimes();
replayMocks();
repositoryImpl.save(inv, changeUrl);
verifyMocks();
}
public void testSave_NotAllowedToLogin() {
Investigator inv = Fixtures.createInvestigator("Joel");
inv.setAllowedToLogin(false);
Organization org = Fixtures.createOrganization("NCI");
String changeUrl = "/pages/url";
expect(investigatorDao.merge(inv)).andReturn(inv).anyTimes();
replayMocks();
repositoryImpl.save(inv, changeUrl);
verifyMocks();
}
public void testSearchInvestigator_EmptyCriteria() throws Exception {
InvestigatorQuery query = new InvestigatorQuery();
HashMap searchCriteriaMap = new HashMap();
List<Investigator> investigators = new ArrayList<Investigator>();
expect(investigatorDao.getLocalInvestigator(query)).andReturn(investigators);
replayMocks();
List<Investigator> invList = repositoryImpl.searchInvestigator(query, searchCriteriaMap);
assertSame(investigators, invList);
verifyMocks();
}
public void testSearchInvestigator_OnFirstName() throws Exception {
InvestigatorQuery query = new InvestigatorQuery();
HashMap criteria = new HashMap();
criteria.put("firstName", "%");
List<Investigator> investigators = new ArrayList<Investigator>();
expect(investigatorDao.getLocalInvestigator(query)).andReturn(investigators);
replayMocks();
List<Investigator> invList = repositoryImpl.searchInvestigator(query, criteria);
assertSame(investigators, invList);
verifyMocks();
}
public void testSearchInvestigator_OnLastName() throws Exception {
InvestigatorQuery query = new InvestigatorQuery();
HashMap criteria = new HashMap();
criteria.put("lastName", "%");
List<Investigator> investigators = new ArrayList<Investigator>();
expect(investigatorDao.getLocalInvestigator(query)).andReturn(investigators);
replayMocks();
List<Investigator> invList = repositoryImpl.searchInvestigator(query, criteria);
assertSame(investigators, invList);
verifyMocks();
}
public void testSearchInvestigator_OnNciIdentifier() throws Exception {
InvestigatorQuery query = new InvestigatorQuery();
HashMap criteria = new HashMap();
criteria.put("personIdentifier", "%");
List<Investigator> investigators = new ArrayList<Investigator>();
expect(investigatorDao.getLocalInvestigator(query)).andReturn(investigators);
replayMocks();
List<Investigator> invList = repositoryImpl.searchInvestigator(query, criteria);
assertSame(investigators, invList);
verifyMocks();
}
public void testSearchInvestigator_OnLoginId() throws Exception {
InvestigatorQuery query = new InvestigatorQuery();
query.filterByLoginId("SYSTEM_ADMIN");
HashMap criteria = new HashMap();
List<Investigator> investigators = new ArrayList<Investigator>();
expect(investigatorDao.getLocalInvestigator(query)).andReturn(investigators);
replayMocks();
List<Investigator> invList = repositoryImpl.searchInvestigator(query, criteria);
assertSame(investigators, invList);
verifyMocks();
}
public void testSearchInvestigator_OnlyRemoteInvestigators() throws Exception {
InvestigatorQuery query = new InvestigatorQuery();
HashMap criteria = new HashMap();
criteria.put("organization", "1");
Organization org = Fixtures.createOrganization("test", 1);
List<Investigator> investigators = new ArrayList<Investigator>();
expect(investigatorDao.getLocalInvestigator(query)).andReturn(investigators);
expect(organizationDao.getById(1)).andReturn(org);
expect(investigatorDao.getRemoteInvestigators((RemoteInvestigator) EasyMock.anyObject())).andReturn(investigators);
replayMocks();
List<Investigator> invList = repositoryImpl.searchInvestigator(query, criteria);
assertSame(investigators, invList);
verifyMocks();
}
public void testGetBySubnames() throws Exception {
List<SiteInvestigator> siteInvestigators = new ArrayList<SiteInvestigator>();
String[] subNames = new String[]{"a", "b"};
expect(siteInvestigatorDao.getBySubnames(subNames, 1)).andReturn(siteInvestigators);
replayMocks();
List<SiteInvestigator> siteInvList = repositoryImpl.getBySubnames(subNames, 1);
assertSame(siteInvestigators, siteInvList);
verifyMocks();
}
public void testGetById() throws Exception {
Investigator inv = Fixtures.createInvestigator("x");
expect(investigatorDao.getInvestigatorById(1)).andReturn(inv);
replayMocks();
Investigator i = repositoryImpl.getById(1);
assertSame(inv, i);
verifyMocks();
}
public void testConvertToRemote() throws Exception {
Investigator local = Fixtures.createInvestigator("x");
local.setId(1);
RemoteInvestigator remote = Fixtures.createRemoteInvestigator("r1");
ConverterInvestigator conInv = new ConverterInvestigator();
expect(investigatorConverterDao.getById(1)).andReturn(conInv);
investigatorConverterDao.save(conInv);
replayMocks();
repositoryImpl.convertToRemote(local, remote);
assertEquals("REMOTE", conInv.getType());
assertEquals(remote.getFirstName(), conInv.getFirstName());
assertEquals(remote.getLastName(), conInv.getLastName());
assertEquals(remote.getExternalId(), conInv.getExternalId());
verifyMocks();
}
} |
package gov.nih.nci.cagrid.data.utilities;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.cqlresultset.CQLObjectResult;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.axis.message.MessageElement;
import org.apache.axis.utils.XMLUtils;
import org.globus.wsrf.encoding.ObjectDeserializer;
import org.xml.sax.InputSource;
/**
* CQLObjectResultIterator
* Iterator over CQL Object Results
*
* @author <A HREF="MAILTO:ervin@bmi.osu.edu">David W. Ervin</A>
*
* @created Mar 20, 2006
* @version $Id$
*/
public class CQLObjectResultIterator implements Iterator {
private CQLObjectResult[] results;
private int currentIndex;
private Class objectClass;
private boolean xmlOnly;
private InputStream wsddInputStream;
private byte[] wsddContent;
CQLObjectResultIterator(CQLObjectResult[] results, boolean xmlOnly, InputStream wsdd) {
if (results.length != 0) {
objectClass = getObjectClass(results[0]);
}
this.results = results;
this.currentIndex = -1;
this.xmlOnly = xmlOnly;
this.wsddInputStream = wsdd;
}
public void remove() {
throw new UnsupportedOperationException("remove() is not supported by " + getClass().getName());
}
public boolean hasNext() {
return currentIndex + 1 < results.length;
}
public Object next() {
currentIndex++;
if (currentIndex >= results.length) {
throw new NoSuchElementException();
}
MessageElement element = results[currentIndex].get_any()[0];
try {
String documentString = element.getAsString();
if (xmlOnly) {
return documentString;
}
InputStream configStream = getConsumableInputStream();
if (configStream != null) {
return Utils.deserializeObject(new StringReader(documentString), objectClass,
getConsumableInputStream());
} else {
org.w3c.dom.Document doc = XMLUtils.newDocument(
new InputSource(new StringReader(documentString)));
return ObjectDeserializer.toObject(doc.getDocumentElement(), objectClass);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private Class getObjectClass(CQLObjectResult result) {
Class c = null;
try {
c = Class.forName(result.getType());
} catch (Exception ex) {
ex.printStackTrace();
}
return c;
}
private InputStream getConsumableInputStream() throws IOException {
if (wsddInputStream != null) {
if (wsddContent == null) {
wsddContent = new byte[0];
byte[] readBytes = new byte[1024];
int len = -1;
BufferedInputStream buffStream = new BufferedInputStream(wsddInputStream);
while ((len = buffStream.read(readBytes)) != -1) {
byte[] tmpContent = new byte[wsddContent.length + len];
System.arraycopy(wsddContent, 0, tmpContent, 0, wsddContent.length);
System.arraycopy(readBytes, 0, tmpContent, wsddContent.length, len);
wsddContent = tmpContent;
}
buffStream.close();
}
return new ByteArrayInputStream(wsddContent);
}
return null;
}
} |
package com.griddynamics.jagger.xml.beanParsers.task;
import com.griddynamics.jagger.engine.e1.scenario.FixedDelay;
import com.griddynamics.jagger.engine.e1.scenario.VirtualUsersClockConfiguration;
import com.griddynamics.jagger.xml.beanParsers.XMLConstants;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
public class VirtualUserDefinitionParser extends AbstractSimpleBeanDefinitionParser {
@Override
protected Class getBeanClass(Element element) {
return VirtualUsersClockConfiguration.class;
}
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String tickInterval = element.getAttribute(XMLConstants.TICK_INTERVAL);
if (tickInterval.isEmpty()){
builder.addPropertyValue(XMLConstants.TICK_INTERVAL, XMLConstants.DEFAULT_TICK_INTERVAL);
} else {
builder.addPropertyValue(XMLConstants.TICK_INTERVAL, tickInterval);
}
if (!element.getAttribute(XMLConstants.DELAY).isEmpty()){
builder.addPropertyValue(XMLConstants.DELAY, new FixedDelay(Integer.parseInt(element.getAttribute(XMLConstants.DELAY))));
}
if (!element.getAttribute(XMLConstants.COUNT).isEmpty()){
builder.addPropertyValue(XMLConstants.COUNT, Integer.parseInt(element.getAttribute(XMLConstants.COUNT)));
}
}
} |
package org.wildfly.clustering.web.hotrod.session;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.infinispan.client.hotrod.MetadataValue;
import org.infinispan.client.hotrod.configuration.NearCacheMode;
import org.infinispan.client.hotrod.event.impl.ClientListenerNotifier;
import org.infinispan.client.hotrod.near.NearCacheService;
import org.wildfly.clustering.infinispan.client.NearCacheFactory;
import org.wildfly.clustering.infinispan.client.near.CaffeineNearCacheService;
import org.wildfly.clustering.infinispan.client.near.SimpleKeyWeigher;
import org.wildfly.clustering.web.hotrod.session.coarse.SessionAttributesKey;
import org.wildfly.clustering.web.hotrod.session.fine.SessionAttributeKey;
import org.wildfly.clustering.web.hotrod.session.fine.SessionAttributeNamesKey;
import org.wildfly.clustering.web.session.SessionAttributePersistenceStrategy;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.RemovalListener;
/**
* A near-cache factory based on max-active-sessions.
* @author Paul Ferraro
*/
public class SessionManagerNearCacheFactory<K, V> implements NearCacheFactory<K, V>, Supplier<Cache<K, MetadataValue<V>>>, RemovalListener<Object, Object> {
private final Integer maxActiveSessions;
private final SessionAttributePersistenceStrategy strategy;
private final AtomicReference<Cache<K, MetadataValue<V>>> cache = new AtomicReference<>();
public SessionManagerNearCacheFactory(Integer maxActiveSessions, SessionAttributePersistenceStrategy strategy) {
this.maxActiveSessions = maxActiveSessions;
this.strategy = strategy;
}
@Override
public NearCacheService<K, V> createService(ClientListenerNotifier notifier) {
return new CaffeineNearCacheService<>(this, notifier);
}
@Override
public NearCacheMode getMode() {
return (this.maxActiveSessions == null) || (this.maxActiveSessions.intValue() == 0) ? NearCacheMode.DISABLED : NearCacheMode.INVALIDATED;
}
@Override
public Cache<K, MetadataValue<V>> get() {
Caffeine<Object, Object> builder = Caffeine.newBuilder();
if (this.maxActiveSessions != null) {
builder.executor(Runnable::run)
.maximumWeight(this.maxActiveSessions.longValue())
.weigher(new SimpleKeyWeigher(SessionCreationMetaDataKey.class::isInstance))
.removalListener(this);
}
Cache<K, MetadataValue<V>> cache = builder.build();
// Set reference for use by removal listener
this.cache.set(cache);
return cache;
}
@Override
public void onRemoval(Object key, Object value, RemovalCause cause) {
// Cascade invalidation to dependent entries
if ((cause == RemovalCause.SIZE) && (key instanceof SessionCreationMetaDataKey)) {
String id = ((SessionCreationMetaDataKey) key).getId();
Cache<K, MetadataValue<V>> cache = this.cache.get();
List<Object> keys = new LinkedList<>();
keys.add(new SessionAccessMetaDataKey(id));
switch (this.strategy) {
case COARSE: {
keys.add(new SessionAttributesKey(id));
break;
}
case FINE: {
SessionAttributeNamesKey namesKey = new SessionAttributeNamesKey(id);
keys.add(namesKey);
MetadataValue<V> namesValue = cache.getIfPresent(namesKey);
if (namesValue != null) {
@SuppressWarnings("unchecked")
Map<String, UUID> names = (Map<String, UUID>) namesValue.getValue();
for (UUID attributeId : names.values()) {
keys.add(new SessionAttributeKey(id, attributeId));
}
}
break;
}
}
cache.invalidateAll(keys);
}
}
} |
package com.archimatetool.editor.diagram.figures.connections;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.RotatableDecoration;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import com.archimatetool.model.IDiagramModelArchimateConnection;
/**
* Assignment Connection Figure class
*
* @author Phillip Beauvoir
* @author Jean-Baptiste Sarrodie
*/
public class AssignmentConnectionFigure extends AbstractArchimateConnectionFigure {
/**
* @return Decoration to use on Target Node
*/
public static class OvalDecoration extends Figure implements RotatableDecoration {
private int radius = 2;
public OvalDecoration() {
setSize(radius * 2 + 1, radius * 2 + 1);
}
public void setReferencePoint(Point ref) {
}
@Override
public void setLocation(Point p) {
if(getLocation().equals(p)) {
return;
}
Dimension size = getBounds().getSize();
setBounds(new Rectangle(p.x - (size.width >> 1), p.y - (size.height >> 1), size.width, size.height));
}
@Override
public void paintFigure(Graphics graphics) {
graphics.setBackgroundColor(getParent().getForegroundColor());
graphics.fillOval(bounds);
}
}
/**
* @return Decoration to use on Target Node
*/
public static OvalDecoration createFigureTargetDecoration() {
return new OvalDecoration();
}
/**
* @return Decoration to use on Source Node
*/
public static OvalDecoration createFigureSourceDecoration() {
return createFigureTargetDecoration();
}
public AssignmentConnectionFigure(IDiagramModelArchimateConnection connection) {
super(connection);
}
@Override
protected void setFigureProperties() {
setSourceDecoration(createFigureSourceDecoration());
setTargetDecoration(createFigureTargetDecoration());
}
} |
package com.bitplan.jmediawiki;
import com.bitplan.jmediawiki.api.Api;
/**
* Base class for API tests
* @author wf
*
*/
public class TestAPI {
/**
* set to true for debugging
*/
protected boolean debug=false;
/**
* Logging may be enabled by setting debug to true
*/
protected static java.util.logging.Logger LOGGER = java.util.logging.Logger
.getLogger("com.bitplan.jmediawiki");
/**
* get a query Result
* @param query
* @return
* @throws Exception
*/
public Api getQueryResult(String query) throws Exception {
JMediawiki wiki=new JMediawiki("http:
wiki.setDebug(debug);
Api api=wiki.getQueryResult(query);
return api;
}
} |
package home.solver;
import home.finiteElements.FemBeam2d;
import home.finiteElements.interfaces.FemElement;
import home.other.Direction;
import home.other.FemPoint;
import home.other.Force;
import home.other.Support;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class StrengthSolverTest {
// @Test
// public void testBending() {
// FemPoint[] femPoints = new FemPoint[]{
// new FemPoint(0, 0, 0),
// new FemPoint(1, 5, 0),
// FemElementStrength[] lines = new FemElementStrength[]{
// new FemBeam2d(2e11, 53.8e-4, 8356e-8, new FemPoint[]{femPoints[0], femPoints[1]}),
// Force[] forces = new Force[]{
// new Force(femPoints[1], Direction.DIRECTION_Y, 10000),
// Support[] supports = new Support[]{
// new Support(femPoints[0], Direction.DIRECTION_X),
// new Support(femPoints[0], Direction.DIRECTION_Y),
// new Support(femPoints[0], Direction.ROTATE),
// boolean exception = false;
// try {
// StrengthSolver solver = new StrengthSolver(femPoints, lines, forces, supports);
// } catch (Exception e) {
// e.printStackTrace();
// exception = true;
// assertFalse(exception);
// assertEquals(lines[0].getInternalForce().get(1, 0), -10000, 1e-5);
// assertEquals(lines[0].getInternalForce().get(2, 0), -50000, 1e-5);
// assertEquals(lines[0].getDisplacementInGlobalSystem().get(4, 0), 0.0249, 1e-4);
// assertEquals(lines[0].getDisplacementInLocalSystem().get(4, 0), 0.0249, 1e-4);
// assertEquals(femPoints[0].getGlobalDisplacement()[0], 0.0000, 1e-4);
// assertEquals(femPoints[1].getGlobalDisplacement()[1], 0.0249, 1e-4);
// @Test
// public void testBendingWithIntermediantPoints() {
// // E = 2e11
// // J = 1e-5
// // A = 1
// // P = 1e4
// // l = 5
// // Vmax = P*l^3/(3*E*J) = 0.2083333
// int amount = 4;
// FemPoint[] femPoints = new FemPoint[amount];
// for (int i = 0; i < amount; i++) {
// femPoints[i] = new FemPoint(i, i * 5. / (amount - 1), 0);
// FemElement[] lines = new FemElement[amount - 1];
// for (int i = 0; i < lines.length; i++) {
// lines[i] = new FemBeam2d(2e11, 1, 1e-5, new FemPoint[]{femPoints[i], femPoints[i + 1]});
// Force[] forces = new Force[]{
// new Force(femPoints[amount - 1], Direction.DIRECTION_Y, 1e4),
// Support[] supports = new Support[]{
// new Support(femPoints[0], Direction.DIRECTION_X),
// new Support(femPoints[0], Direction.DIRECTION_Y),
// new Support(femPoints[0], Direction.ROTATE),
// boolean exception = false;
// try {
// StrengthSolver.calculate(femPoints, lines, forces, supports);
// } catch (Exception e) {
// e.printStackTrace();
// exception = true;
// assertFalse(exception);
// assertEquals(lines[0].getInternalForce().get(0, 0), 0, 1e-5);
// assertEquals(lines[0].getInternalForce().get(1, 0), -1e4, 1e-5);
// assertEquals(lines[0].getInternalForce().get(2, 0), -5e4, 1e-5);
// assertEquals(femPoints[0].getGlobalDisplacement()[0], 0.0000, 1e-4);
// assertEquals(femPoints[amount - 1].getGlobalDisplacement()[1], 0.2083333, 1e-4);
@Test
public void testBookPage535() {
double L = 1;
FemPoint[] femPoints = new FemPoint[2];
femPoints[0] = new FemPoint(0, 0.0, 0);
femPoints[1] = new FemPoint(1, L, 0);
double E = 200000e6;
double I = 78e-8;
double elacity = E;
double inertia = I;
double area = 1e-13;
double Q = 1230;
FemElement[] femElements = new FemElement[1];
femElements[0] = new FemBeam2d(elacity, area, inertia, new FemPoint[]{femPoints[0], femPoints[1]});
Support[] supports = new Support[]{
new Support(femPoints[0], Direction.DIRECTION_X),
new Support(femPoints[0], Direction.DIRECTION_Y),
new Support(femPoints[0], Direction.ROTATE),
};
Force[] forces = new Force[]{
new Force(femPoints[1], Direction.DIRECTION_Y, Q)
};
boolean exception = false;
StrengthSolver solver = null;
try {
solver = new StrengthSolver(femPoints, femElements, forces, supports);
} catch (Exception e) {
e.printStackTrace();
exception = true;
}
assertFalse(exception);
double deflection = Q * Math.pow(L, 3.) / (3 * E * I);
System.out.println("Deflection = " + deflection);
assertEquals(solver.getGlobalDeformationPoint(femPoints[1]).getX(), 0.0000, 1e-4);
assertEquals(solver.getGlobalDeformationPoint(femPoints[1]).getY(), deflection, 1e-4);
}
} |
package org.agmip.common;
import java.util.Date;
import static org.agmip.common.Functions.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.After;
import static org.junit.Assert.*;
public class FunctionsTest {
@Test
public void numericStringNonRoundedTest() {
int test = 1234;
assertEquals("Numeric conversion failed", test, numericStringToBigInteger("1234.56", false).intValue());
}
@Test
public void numericStringRoundedTest() {
int test = 1235;
assertEquals("Numeric conversion failed", test, numericStringToBigInteger("1234.56").intValue());
}
@Test
public void toDateTest() {
Date test = new Date(2012-1900, 0, 1);
Date d = convertFromAgmipDateString("20120101");
assertEquals("Dates not the same", test, d);
}
@Test
public void toStringTest() {
String test = "20120101";
String d = convertToAgmipDateString(new Date(2012-1900, 0, 1));
assertEquals("Dates not the same", test, d);
}
@Test
public void failToDateTest() {
Date d = convertFromAgmipDateString("1");
assertNull("Converted invalid date", d);
}
@Test
public void dateOffsetTest() {
String test = "20120219";
String initial = "20120212";
String offset="7";
assertEquals("Date offset incorrect", test, dateOffset(initial, offset));
}
@Test
public void dateOffsetMonthBoundary() {
String test = "20120703";
String initial = "20120628";
String offset = "5";
assertEquals("Date offset incorrect", test, dateOffset(initial, offset));
}
@Test
public void dateOffsetYearBoundary() {
String test = "20120101";
String initial = "20111225";
String offset = "7";
assertEquals("Date offset incorrect", test, dateOffset(initial, offset));
}
@Test
public void dateOffsetReverseOffset() {
String test = "20120101";
String initial = "20120105";
String offset = "-4";
assertEquals("Date offset incorrect", test, dateOffset(initial, offset));
}
@Test
public void failDateOffsetBadDate() {
assertNull("Offset invalid date", dateOffset("1232", "1"));
}
@Test
public void failDateOffsetBadOffset() {
assertNull("Offset invalid offset", dateOffset("20120101", "abc"));
}
@Test
public void failDateOffsetBadNumericOffsetTest() {
assertNull("Offset invalid offset", dateOffset("20120101", "1.0"));
}
@Test
public void failDateOffsetBadNumericOffset2Test() {
assertNull("Offset invalid offset", dateOffset("20120101", "1.2"));
}
@Test
public void numericOffsetTest() {
String test = "12.34";
String initial = "11.22";
String offset = "1.12";
assertEquals("Numeric offset incorrect", test, numericOffset(initial, offset));
}
@Test
public void integerOffsetTest() {
String test = "12";
String initial = "11";
String offset = "1";
assertEquals("Numeric offset incorrect", test, numericOffset(initial, offset));
}
@Test
public void mixedNumericOffsetTest() {
String test = "12.34";
String initial = "11";
String offset = "1.34";
assertEquals("Numeric offset incorrect", test, numericOffset(initial, offset));
}
@Test
public void failedNumericOffsetBadInitialTest() {
assertNull("Offset invalid initial", numericOffset("abc", "12.34"));
}
@Test
public void failedNumericOffsetBadOffsetTest() {
assertNull("Offset invalid offset", numericOffset("12.34", "abc"));
}
@Test
public void numericNegativeOffsetTest() {
String test = "12.34";
String initial = "23.45";
String offset = "-11.11";
assertEquals("Numeric offset incorrect", test, numericOffset(initial, offset));
}
@Test
public void multiplySimple() {
String test="12.34";
String f1 = "1234";
String f2 = ".01";
assertEquals("Multiply incorrect", test, multiply(f1, f2));
}
@Test
public void mutliplyIntentionalFailure() {
String f1 = "Hi";
String f2 = "12";
assertNull("This shouldn't work", multiply(f1, f2));
}
@Test
public void sumSingle() {
String test="1234";
String f1 = "1234";
assertEquals("Sum incorrect", test, sum(f1));
}
@Test
public void sumMultiple() {
String test="1234.01";
String f1 = "1234";
String f2 = ".01";
assertEquals("Sum incorrect", test, sum(f1, f2));
}
@Test
public void sumIntentionalFailure() {
String f1 = null;
String f2 = "Hi";
assertNull("This shouldn't work", sum(f1, f2));
}
@Test
public void substractNull() {
String test="1234";
String f1 = "1234";
assertEquals("Substract incorrect", test, substract(f1));
}
@Test
public void substractSingle() {
String test="1012";
String f1 = "1234";
String f2 = "222";
assertEquals("Substract incorrect", test, substract(f1, f2));
}
@Test
public void substractMultiple() {
String test="499.77";
String f1 = "1234";
String f2 = "234";
String f3 = "500.23";
assertEquals("Substract incorrect", test, substract(f1, f2, f3));
}
@Test
public void substractIntentionalFailure() {
String f1 = null;
String f2 = "Hi";
assertNull("This shouldn't work", substract(f1, f2));
}
@Test
public void productSingle() {
String test="1234";
String f1 = "1234";
assertEquals("Product incorrect", test, product(f1));
}
@Test
public void productMultiple() {
String test="12.34";
String f1 = "1234";
String f2 = ".01";
assertEquals("Product incorrect", test, product(f1, f2));
}
@Test
public void productIntentionalFailure() {
String f1 = null;
String f2 = "Hi";
assertNull("This shouldn't work", product(f1, f2));
}
@Test
public void divideSimpleDivisible() {
String test="2.55";
String f1 ="10.2";
String f2 = "4";
assertEquals("Divide incorrect", test, divide(f1, f2));
}
@Test
public void divideSimpleIndivisible() {
String test="10.2352";
String f1 ="23.541";
String f2 = "2.3";
assertEquals("Divide incorrect", test, divide(f1, f2));
}
@Test
public void divideWithScaleDivisible() {
String test="2.6";
String f1 ="10.2";
String f2 = "4";
int scale = 1;
assertEquals("Divide incorrect", test, divide(f1, f2, scale));
}
@Test
public void divideWithScaleIndivisible() {
String test="10.2";
String f1 ="23.541";
String f2 = "2.3";
int scale = 1;
assertEquals("Divide incorrect", test, divide(f1, f2, scale));
}
@Test
public void divideIntentionalFailure() {
String f1 = null;
String f2 = "Hi";
assertNull("This shouldn't work", divide(f1, f2));
}
@Test
public void averageSimpleDivisible() {
String test="7.1";
String f1 ="10.2";
String f2 = "4";
assertEquals("Average incorrect", test, average(f1, f2));
}
@Test
public void averageSimpleIndivisible() {
String test="9.38553";
String f1 ="23.541";
String f2 = "2.3";
String f3 = "2.3156";
assertEquals("Average incorrect", test, average(f1, f2, f3));
}
@Test
public void averageWithScaleDivisible() {
String test="7.10";
String f1 ="10.2";
String f2 = "4";
int scale = 2;
assertEquals("Average incorrect", test, average(scale, f1, f2));
}
@Test
public void averageWithScaleIndivisible() {
String test="9.39";
String f1 ="23.541";
String f2 = "2.3";
String f3 = "2.3156";
int scale = 2;
assertEquals("Average incorrect", test, average(scale, f1, f2, f3));
}
@Test
public void averageIntentionalFailure() {
String f1 = null;
String f2 = "Hi";
assertNull("This shouldn't work", average(f1, f2));
}
@Test
public void logWithScaleIndivisible() {
String test=Math.log(12) + "";
String f1 ="12";
assertEquals("Log incorrect", test, log(f1));
}
@Test
public void logIntentionalFailure() {
String f1 = "H1";
assertNull("This shouldn't work", log(f1));
}
@Test
public void expWithScaleIndivisible() {
String test=Math.exp(12) + "";
String f1 ="12";
assertEquals("Exp incorrect", test, exp(f1));
}
@Test
public void expIntentionalFailure() {
String f1 = "H1";
assertNull("This shouldn't work", exp(f1));
}
@Test
public void minSingle() {
String test="1234";
String f1 = "1234";
assertEquals("Min incorrect", test, min(f1));
}
@Test
public void minMultiple() {
String test="0.01";
String f1 = "1234";
String f2 = ".01";
String f3 = "3.01";
assertEquals("Min incorrect", test, min(f1, f2, f3));
}
@Test
public void minIntentionalFailure() {
String f1 = null;
String f2 = "Hi";
assertNull("This shouldn't work", min(f1, f2));
}
@Test
public void maxSingle() {
String test="1234";
String f1 = "1234";
assertEquals("Max incorrect", test, max(f1));
}
@Test
public void maxMultiple() {
String test="1234";
String f1 = "1234";
String f2 = ".01";
String f3 = "3.01";
assertEquals("Max incorrect", test, max(f1, f2, f3));
}
@Test
public void maxIntentionalFailure() {
String f1 = null;
String f2 = "Hi";
assertNull("This shouldn't work", max(f1, f2));
}
@Test
public void roundUp() {
String test="0.13";
String f1 = "0.1251";
int scale = 2;
assertEquals("Round incorrect", test, round(f1, scale));
}
@Test
public void roundDown() {
String test="0.12";
String f1 = "0.1249";
int scale = 2;
assertEquals("Round incorrect", test, round(f1, scale));
}
@Test
public void roundIntentionalFailure() {
String f1 = "Hi";
int scale = 2;
assertNull("This shouldn't work", round(f1, scale));
}
@Test
public void compareGreaterMode() {
String small = "1.1";
String big = "2.1";
CompareMode mode = CompareMode.GREATER;
assertFalse("Compare incorrect", compare(small, big, mode));
assertFalse("Compare incorrect", compare(big, big, mode));
assertTrue("Compare incorrect", compare(big, small, mode));
}
@Test
public void compareNotGreaterMode() {
String small = "1.1";
String big = "2.1";
CompareMode mode = CompareMode.NOTGREATER;
assertTrue("Compare incorrect", compare(small, big, mode));
assertTrue("Compare incorrect", compare(big, big, mode));
assertFalse("Compare incorrect", compare(big, small, mode));
}
@Test
public void compareLessMode() {
String small = "1.1";
String big = "2.1";
CompareMode mode = CompareMode.LESS;
assertTrue("Compare incorrect", compare(small, big, mode));
assertFalse("Compare incorrect", compare(big, big, mode));
assertFalse("Compare incorrect", compare(big, small, mode));
}
@Test
public void compareNotLessMode() {
String small = "1.1";
String big = "2.1";
CompareMode mode = CompareMode.NOTLESS;
assertFalse("Compare incorrect", compare(small, big, mode));
assertTrue("Compare incorrect", compare(big, big, mode));
assertTrue("Compare incorrect", compare(big, small, mode));
}
@Test
public void compareEqualMode() {
String small = "1.1";
String big = "2.1";
CompareMode mode = CompareMode.EQUAL;
assertFalse("Compare incorrect", compare(small, big, mode));
assertTrue("Compare incorrect", compare(big, big, mode));
assertFalse("Compare incorrect", compare(big, small, mode));
}
@Test
public void compareIntentionalFailure() {
String f1 = "H1.1";
String f2 = "2.1";
CompareMode mode = CompareMode.LESS;
assertFalse("This shouldn't work", compare(f1, f2, mode));
}
} |
package org.phenotips.data.internal.controller;
import org.phenotips.Constants;
import org.phenotips.data.IndexedPatientData;
import org.phenotips.data.Patient;
import org.phenotips.data.PatientData;
import org.phenotips.data.PatientDataController;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.EntityReference;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.inject.Named;
import javax.inject.Singleton;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseStringProperty;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Handles the patients rejected genes.
*
* @version $Id$
* @since 1.1M1
*/
@Component(roles = { PatientDataController.class })
@Named("rejectedGenes")
@Singleton
public class RejectedGeneListController extends AbstractComplexController<Map<String, String>>
{
/** The XClass used for storing gene data. */
private static final EntityReference GENE_CLASS_REFERENCE = new EntityReference("RejectedGenesClass",
EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE);
private static final String COMMENTS_KEY = "comments";
@Override
public String getName()
{
return "rejectedGenes";
}
@Override
protected String getJsonPropertyName()
{
return getName();
}
@Override
protected List<String> getProperties()
{
return Arrays.asList("gene", COMMENTS_KEY);
}
@Override
protected List<String> getBooleanFields()
{
return Collections.emptyList();
}
@Override
protected List<String> getCodeFields()
{
return Collections.emptyList();
}
@Override
public PatientData<Map<String, String>> load(Patient patient)
{
try {
XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument());
List<BaseObject> geneXWikiObjects = doc.getXObjects(GENE_CLASS_REFERENCE);
if (geneXWikiObjects == null) {
throw new NullPointerException("The patient does not have any gene information");
}
List<Map<String, String>> allGenes = new LinkedList<Map<String, String>>();
for (BaseObject geneObject : geneXWikiObjects) {
Map<String, String> singleGene = new LinkedHashMap<String, String>();
for (String property : getProperties()) {
BaseStringProperty field = (BaseStringProperty) geneObject.getField(property);
if (field != null) {
singleGene.put(property, field.getValue());
}
}
allGenes.add(singleGene);
}
return new IndexedPatientData<Map<String, String>>(getName(), allGenes);
} catch (Exception e) {
// TODO. Log an error.
}
return null;
}
@Override
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames)
{
// FIXME. selectedFieldNames have no effect.
PatientData<Map<String, String>> data = patient.getData(getName());
if (data == null) {
return;
}
Iterator<Map<String, String>> iterator = data.iterator();
if (iterator == null || !iterator.hasNext()) {
return;
}
JSONArray container = null;
while (iterator.hasNext()) {
Map<String, String> item = iterator.next();
if (container == null) {
// put() is placed here because we want to create the property iff at least one field is set/enabled
json.put(getJsonPropertyName(), new JSONArray());
container = json.getJSONArray(getJsonPropertyName());
}
if (item != null && "".equals(item.get(COMMENTS_KEY))) {
item.remove(COMMENTS_KEY);
}
container.add(item);
}
}
} |
package org.guvnor.structure.client.navigator;
import java.util.List;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
import org.guvnor.structure.client.resources.NavigatorResources;
import org.uberfire.ext.widgets.common.client.common.popups.YesNoCancelPopup;
import org.uberfire.ext.widgets.common.client.resources.i18n.CommonConstants;
import org.uberfire.ext.widgets.core.client.resources.i18n.CoreConstants;
import org.uberfire.java.nio.base.version.VersionRecord;
import org.uberfire.mvp.Command;
import org.uberfire.mvp.ParameterizedCommand;
public class CommitNavigator extends Composite {
private FlowPanel container = new FlowPanel();
private FlexTable navigator = null;
private int lastIndex;
private ParameterizedCommand<VersionRecord> onRevertCommand = null;
public CommitNavigator() {
initWidget( container );
}
public void setOnRevertCommand( final ParameterizedCommand<VersionRecord> command ) {
this.onRevertCommand = command;
}
public void loadContent( final List<VersionRecord> versionRecords ) {
lastIndex = 0;
container.clear();
if ( navigator != null ) {
navigator.clear();
}
navigator = new FlexTable();
navigator.setStyleName( NavigatorResources.INSTANCE.css().navigator() );
setupContent( versionRecords );
}
public void addContent( final List<VersionRecord> content ) {
int base = navigator.getRowCount();
for ( int i = 0; i < content.size(); i++ ) {
final VersionRecord dataContent = content.get( i );
createElement( base + i, dataContent );
}
}
private void setupContent( final List<VersionRecord> content ) {
addContent( content );
container.add( navigator );
}
private void createElement( final int row,
final VersionRecord dataContent ) {
int col = 0;
final Element messageCol = DOM.createDiv();
messageCol.addClassName( NavigatorResources.INSTANCE.css().navigatorMessage() );
{
{ //comment
final Element message = DOM.createSpan();
message.addClassName( NavigatorResources.INSTANCE.css().message() );
message.setInnerText( dataContent.comment() );
messageCol.appendChild( message );
}
final Element metadata = DOM.createDiv();
{//author
final Element author = DOM.createSpan();
author.addClassName( NavigatorResources.INSTANCE.css().author() );
author.setInnerText( dataContent.author() + " - " );
metadata.appendChild( author );
}
{//date
final Element date = DOM.createSpan();
date.addClassName( NavigatorResources.INSTANCE.css().date() );
DateTimeFormat fmt = DateTimeFormat.getFormat( "yyyy-MM-dd h:mm a" );
date.setInnerText( fmt.format( dataContent.date() ) );
metadata.appendChild( date );
}
messageCol.appendChild( metadata );
}
navigator.setWidget( row, col, new Widget() {{
setElement( messageCol );
}} );
if ( onRevertCommand != null ) {
navigator.setWidget( row, ++col, new Button( CoreConstants.INSTANCE.RevertToThis() ) {{
setType( ButtonType.DANGER );
addClickHandler( new ClickHandler() {
@Override
public void onClick( final ClickEvent event ) {
final YesNoCancelPopup yesNoCancelPopup = YesNoCancelPopup.newYesNoCancelPopup( CommonConstants.INSTANCE.Warning(),
CoreConstants.INSTANCE.ConfirmStateRevert(),
new Command() {
@Override
public void execute() {
onRevertCommand.execute( dataContent );
}
},
new Command() {
@Override
public void execute() {
}
},
null
);
yesNoCancelPopup.setCloseVisible( false );
yesNoCancelPopup.show();
}
} );
}} );
}
lastIndex++;
}
public int getLastIndex() {
return lastIndex;
}
} |
package test.net.jawr.web.resource.bundle.locale;
import static org.junit.Assert.assertEquals;
import java.io.Reader;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import net.jawr.web.JawrConstant;
import net.jawr.web.config.JawrConfig;
import net.jawr.web.resource.bundle.IOUtils;
import net.jawr.web.resource.bundle.generator.GeneratorContext;
import net.jawr.web.resource.bundle.locale.ResourceBundleMessagesGenerator;
import net.jawr.web.util.js.JavascriptEngine;
import test.net.jawr.web.FileUtils;
public class ResourceBundleMessageGeneratorTestCase {
private ResourceBundleMessagesGenerator generator;
private Locale defaultLocale;
@Before
public void setUp() {
defaultLocale = Locale.getDefault();
generator = new ResourceBundleMessagesGenerator();
}
@After
public void tearDown() {
Locale.setDefault(defaultLocale);
}
@Test
public void testGenerateMessageBundle() throws Exception {
// Force default locale
Locale.setDefault(Locale.FRENCH);
Properties prop = new Properties();
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_ADD_QUOTE_TO_MSG_KEY, "false");
JawrConfig config = new JawrConfig("js", prop);
GeneratorContext ctx = new GeneratorContext(config, "bundleLocale.messages");
ctx.setLocale(null);
Reader rd = generator.createResource(ctx);
String result = IOUtils.toString(rd);
assertEquals(readFile("bundleLocale/resultScript_fr.js"), FileUtils.removeCarriageReturn(result));
ctx.setLocale(Locale.FRENCH);
rd = generator.createResource(ctx);
result = IOUtils.toString(rd);
assertEquals(readFile("bundleLocale/resultScript_fr.js"), FileUtils.removeCarriageReturn(result));
ctx.setLocale(new Locale("es"));
rd = generator.createResource(ctx);
result = IOUtils.toString(rd);
assertEquals(readFile("bundleLocale/resultScript_es.js"), FileUtils.removeCarriageReturn(result));
}
@Test
@Ignore
public void testGenerateMessageBundleWithCharset() throws Exception {
// Force default locale
Locale.setDefault(Locale.FRENCH);
Properties prop = new Properties();
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_RESOURCE_BUNDLE_CHARSET, "UTF-8");
JawrConfig config = new JawrConfig("js", prop);
GeneratorContext ctx = new GeneratorContext(config, "bundleLocale.messagesResourceBundleUTF8");
ctx.setLocale(null);
Reader rd = generator.createResource(ctx);
String result = IOUtils.toString(rd);
assertEquals(readFile("bundleLocale/resultScriptResourceBundleUTF8_fr.js"),
FileUtils.removeCarriageReturn(result));
ctx.setLocale(Locale.FRENCH);
rd = generator.createResource(ctx);
result = IOUtils.toString(rd);
assertEquals(readFile("bundleLocale/resultScriptResourceBundleUTF8_fr.js"),
FileUtils.removeCarriageReturn(result));
ctx.setLocale(new Locale("es"));
rd = generator.createResource(ctx);
result = IOUtils.toString(rd);
assertEquals(readFile("bundleLocale/resultScriptResourceBundleUTF8_es.js"),
FileUtils.removeCarriageReturn(result));
}
private String readFile(String path) throws Exception {
return readFile(path, "UTF-8");
}
private String readFile(String path, String charset) throws Exception {
return FileUtils.readFile(FileUtils.getClassPathFile(path), charset);
}
@Test
public void testGenerateMessageBundleSystemFallback() throws Exception {
// Force default locale
Locale.setDefault(Locale.FRENCH);
Properties prop = new Properties();
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_FALLBACK_TO_SYSTEM_LOCALE, "false");
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_ADD_QUOTE_TO_MSG_KEY, "false");
JawrConfig config = new JawrConfig("js", prop);
GeneratorContext ctx = new GeneratorContext(config, "bundleLocale.messages");
ctx.setLocale(null);
Reader rd = generator.createResource(ctx);
String result = IOUtils.toString(rd);
assertEquals(readFile("bundleLocale/resultScript.js"), FileUtils.removeCarriageReturn(result));
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_FALLBACK_TO_SYSTEM_LOCALE, "true");
ctx.setLocale(null);
rd = generator.createResource(ctx);
result = IOUtils.toString(rd);
assertEquals(readFile("bundleLocale/resultScript_fr.js"), FileUtils.removeCarriageReturn(result));
}
@Test
public void testGenerateMessageBundleAddQuoteToKey() throws Exception {
// Force default locale
Locale.setDefault(Locale.FRENCH);
Properties prop = new Properties();
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_FALLBACK_TO_SYSTEM_LOCALE, "false");
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_ADD_QUOTE_TO_MSG_KEY, "true");
JawrConfig config = new JawrConfig("js", prop);
GeneratorContext ctx = new GeneratorContext(config, "bundleLocale.messages");
ctx.setLocale(null);
Reader rd = generator.createResource(ctx);
String result = IOUtils.toString(rd);
assertEquals(readFile("bundleLocale/resultScriptWithQuoteForKeys.js"), FileUtils.removeCarriageReturn(result));
}
@Test
public void testBundleWithFilter() throws Exception {
// Force default locale
Locale.setDefault(Locale.FRENCH);
Properties prop = new Properties();
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_FALLBACK_TO_SYSTEM_LOCALE, "false");
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_ADD_QUOTE_TO_MSG_KEY, "false");
JawrConfig config = new JawrConfig("js", prop);
GeneratorContext ctx = new GeneratorContext(config, "bundleLocale.messages|bundleLocale.errors[ui|error]");
ctx.setLocale(null);
Reader rd = generator.createResource(ctx);
String result = IOUtils.toString(rd);
// Checks result content instead of file to overcome the difference
// between JDK < 8 and JDK >= 8
// where the order of the message definition change
Map<String, String> expectedMsg = new HashMap<String, String>();
expectedMsg.put("messages.error.login", "Login failed");
expectedMsg.put("messages.ui.msg.hello.world", "Hello $ world!");
expectedMsg.put("messages.ui.msg.salut", "Mr.");
checkGeneratedMsgContent(result, expectedMsg);
ctx.setLocale(Locale.FRENCH);
rd = generator.createResource(ctx);
result = IOUtils.toString(rd);
expectedMsg.clear();
expectedMsg.put("messages.error.login", "Erreur lors de la connection");
expectedMsg.put("messages.ui.msg.hello.world", "¡Bonjour $ š tout le monde!");
expectedMsg.put("messages.ui.msg.salut", "Mr.");
expectedMsg.put("messages.ui.error.panel.title", "Erreur");
ctx.setLocale(new Locale("es"));
rd = generator.createResource(ctx);
result = IOUtils.toString(rd);
expectedMsg.clear();
expectedMsg.put("messages.error.login", "Login failed");
expectedMsg.put("messages.ui.msg.hello.world", "¡Hola $ Mundo!");
expectedMsg.put("messages.ui.msg.salut", "Mr.");
checkGeneratedMsgContent(result, expectedMsg);
}
@Test
public void testBundleWithNamespace() throws Exception {
// Force default locale
Locale.setDefault(Locale.FRENCH);
Properties prop = new Properties();
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_FALLBACK_TO_SYSTEM_LOCALE, "false");
prop.put(JawrConstant.JAWR_LOCALE_GENERATOR_ADD_QUOTE_TO_MSG_KEY, "false");
JawrConfig config = new JawrConfig("js", prop);
GeneratorContext ctx = new GeneratorContext(config, "bundleLocale.messages|bundleLocale.errors(myMessages)");
ctx.setLocale(null);
Reader rd = generator.createResource(ctx);
String result = IOUtils.toString(rd);
// Checks result content instead of file to overcome the difference
// between JDK < 8 and JDK >= 8
// where the order of the message definition change
Map<String, String> expectedMsg = new HashMap<String, String>();
expectedMsg.put("myMessages.error.login", "Login failed");
expectedMsg.put("myMessages.ui.msg.hello.world", "Hello $ world!");
expectedMsg.put("myMessages.ui.msg.salut", "Mr.");
expectedMsg.put("myMessages.warning.password.expired", "Password expired");
checkGeneratedMsgContent(result, expectedMsg);
ctx.setLocale(Locale.FRENCH);
rd = generator.createResource(ctx);
result = IOUtils.toString(rd);
expectedMsg.clear();
expectedMsg.put("myMessages.error.login", "Erreur lors de la connection");
expectedMsg.put("myMessages.ui.msg.hello.world", "¡Bonjour $ š tout le monde!");
expectedMsg.put("myMessages.ui.msg.salut", "Mr.");
expectedMsg.put("myMessages.warning.password.expired", "Password expiré");
expectedMsg.put("myMessages.ui.error.panel.title", "Erreur");
checkGeneratedMsgContent(result, expectedMsg);
ctx.setLocale(new Locale("es"));
rd = generator.createResource(ctx);
result = IOUtils.toString(rd);
expectedMsg.clear();
expectedMsg.put("myMessages.error.login", "Login failed");
expectedMsg.put("myMessages.ui.msg.hello.world", "¡Hola $ Mundo!");
expectedMsg.put("myMessages.ui.msg.salut", "Mr.");
expectedMsg.put("myMessages.warning.password.expired", "Password expired");
checkGeneratedMsgContent(result, expectedMsg);
// assertEquals(
// readFile("bundleLocale/resultScriptWithNamespace_es.js"),
// FileUtils.removeCarriageReturn(result));
}
/**
* Checks if the generated script contains the expected messages Here we
* check result content instead of generated file content to overcome the
* difference between JDK < 8 and JDK >= 8 where the order of the message
* definition change
*
* @param generatedScript
* the generated script
* @param expectedMsg
* the expected message
*/
private void checkGeneratedMsgContent(String generatedScript, Map<String, String> expectedMsg) {
// Checks result content instead of file to overcome the difference
// between JDK < 8 and JDK >= 8
// where the order of the message definition change
JavascriptEngine engine = new JavascriptEngine(true);
engine.evaluate("msg.js", generatedScript);
for (Map.Entry<String, String> entries : expectedMsg.entrySet()) {
String msg = (String) engine.evaluate(entries.getKey() + "()");
assertEquals(entries.getValue(), msg);
}
}
} |
package com.yahoo.jdisc.http.filter.security.misc;
import com.yahoo.jdisc.http.filter.DiscFilterResponse;
import com.yahoo.jdisc.http.filter.RequestView;
import com.yahoo.jdisc.http.filter.SecurityResponseFilter;
/**
* Adds recommended security response headers intended for hardening Rest APIs over https.
*
* @author bjorncs
*/
public class SecurityHeadersResponseFilter implements SecurityResponseFilter {
@Override
public void filter(DiscFilterResponse response, RequestView request) {
response.setHeader("Cache-control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
response.setHeader("X-Content-Type-Options", "nosniff");
response.setHeader("X-Frame-Options", "DENY");
response.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
response.setHeader("Vary", "*");
}
} |
package org.multibit.hd.ui.views.wizards.receive_bitcoin;
import com.google.bitcoin.uri.BitcoinURI;
import com.google.common.base.Optional;
import net.miginfocom.swing.MigLayout;
import org.multibit.hd.ui.events.view.ViewEvents;
import org.multibit.hd.ui.i18n.MessageKey;
import org.multibit.hd.ui.views.components.*;
import org.multibit.hd.ui.views.components.display_address.DisplayBitcoinAddressModel;
import org.multibit.hd.ui.views.components.display_address.DisplayBitcoinAddressView;
import org.multibit.hd.ui.views.components.display_qrcode.DisplayQRCodeModel;
import org.multibit.hd.ui.views.components.display_qrcode.DisplayQRCodeView;
import org.multibit.hd.ui.views.components.enter_amount.EnterAmountModel;
import org.multibit.hd.ui.views.components.enter_amount.EnterAmountView;
import org.multibit.hd.ui.views.wizards.AbstractWizard;
import org.multibit.hd.ui.views.wizards.AbstractWizardPanelView;
import org.multibit.hd.ui.views.wizards.WizardButton;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.math.BigInteger;
/**
* <p>View to provide the following to UI:</p>
* <ul>
* <li>Receive bitcoin: Enter amount</li>
* </ul>
*
* @since 0.0.1
*
*/
public class ReceiveBitcoinEnterAmountPanelView extends AbstractWizardPanelView<ReceiveBitcoinWizardModel, ReceiveBitcoinEnterAmountPanelModel> {
// Panel specific components
private ModelAndView<EnterAmountModel, EnterAmountView> enterAmountMaV;
private ModelAndView<DisplayBitcoinAddressModel, DisplayBitcoinAddressView> displayBitcoinAddressMaV;
private ModelAndView<DisplayQRCodeModel, DisplayQRCodeView> displayQRCodeMaV;
private JTextField label;
private JButton showQRCode;
/**
* @param wizard The wizard managing the states
*/
public ReceiveBitcoinEnterAmountPanelView(AbstractWizard<ReceiveBitcoinWizardModel> wizard, String panelName) {
super(wizard.getWizardModel(), panelName, MessageKey.RECEIVE_BITCOIN_TITLE);
PanelDecorator.addFinish(this, wizard);
}
@Override
public void newPanelModel() {
enterAmountMaV = Components.newEnterAmountMaV(getPanelName());
// TODO Link this to the recipient address service
displayBitcoinAddressMaV = Components.newDisplayBitcoinAddressMaV("1AhN6rPdrMuKBGFDKR1k9A8SCLYaNgXhty");
// Create the QR code display
displayQRCodeMaV = Components.newDisplayQRCodeMaV();
label = TextBoxes.newEnterLabel();
showQRCode = Buttons.newQRCodeButton(getShowQRCodePopoverAction());
// Configure the panel model
setPanelModel(new ReceiveBitcoinEnterAmountPanelModel(
getPanelName(),
enterAmountMaV.getModel(),
displayBitcoinAddressMaV.getModel()
));
getWizardModel().setEnterAmountModel(enterAmountMaV.getModel());
getWizardModel().setTransactionLabel(label.getText());
}
@Override
public JPanel newWizardViewPanel() {
JPanel panel = Panels.newPanel(new MigLayout(
"fillx,insets 0", // Layout constraints
"[][][]", // Column constraints
"[]10[]" // Row constraints
));
panel.add(enterAmountMaV.getView().newComponentPanel(), "span 3,wrap");
panel.add(Labels.newRecipient());
panel.add(displayBitcoinAddressMaV.getView().newComponentPanel(), "growx,push");
panel.add(showQRCode, "wrap");
panel.add(Labels.newTransactionLabel());
panel.add(label, "span 2,wrap");
return panel;
}
@Override
public void fireInitialStateViewEvents() {
// Finish button is always enabled
ViewEvents.fireWizardButtonEnabledEvent(getPanelName(), WizardButton.FINISH, true);
}
@Override
public void updateFromComponentModels(Optional componentModel) {
// No need to update since we expose the component models
// No view events to fire
}
/**
* @return A new action for showing the QR code popover
*/
private Action getShowQRCodePopoverAction() {
// Show or hide the QR code
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
ReceiveBitcoinEnterAmountPanelModel model = getPanelModel().get();
String bitcoinAddress = model.getDisplayBitcoinAddressModel().getValue();
BigInteger satoshis = model.getEnterAmountModel().getSatoshis();
// Form a Bitcoin URI from the contents
String bitcoinUri = BitcoinURI.convertToBitcoinURI(
bitcoinAddress,
satoshis,
label.getText(),
null
);
displayQRCodeMaV.getModel().setValue(bitcoinUri);
// Show the QR code as a popover
Panels.showLightBoxPopover(displayQRCodeMaV.getView().newComponentPanel());
}
};
}
} |
package net.sourceforge.javahexeditor.plugin.editors;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import net.sourceforge.javahexeditor.Manager;
import net.sourceforge.javahexeditor.Texts;
/**
* HexEditor contributor. Contributes status bar and menu bar items
*
* @author Jordi Bergenthal
*/
public final class HexEditorActionBarContributor extends EditorActionBarContributor {
private final class MyMenuContributionItem extends ContributionItem {
MenuItem myMenuItem;
MyMenuContributionItem(String id) {
super(id);
}
@Override
public void fill(Menu parent, int index) {
myMenuItem = new MenuItem(parent, SWT.PUSH, index);
myMenuItem.setEnabled(false);
if (MenuIds.SAVE_SELECTION_AS.equals(getId())) {
myMenuItem.setText(Texts.EDITOR_SAVE_SELECTION_AS_MENU_ITEM_LABEL);
myMenuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
activeEditor.saveToFile(true);
}
});
} else if (MenuIds.TRIM.equals(getId())) {
myMenuItem.setText(Texts.EDITOR_TRIM_MENU_ITEM_LABEL);
myMenuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Manager manager = activeEditor.getManager();
if (manager.isValid()) {
activeEditor.getManager().doTrim();
}
}
});
} else if (MenuIds.SELECT_BLOCK.equals(getId())) {
myMenuItem.setText(Texts.EDITOR_SELECT_BLOCK_MENU_ITEM_LABEL);
// TODO This only works after the "Edit" menu was shown once
myMenuItem.setAccelerator(SWT.CONTROL | 'E');
myMenuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Manager manager = activeEditor.getManager();
if (manager.isValid()) {
manager.doSelectBlock();
}
}
});
}
}
}
private final class MyMenuListener implements IMenuListener {
public MyMenuListener() {
}
@Override
public void menuAboutToShow(IMenuManager menu) {
boolean textSelected = activeEditor.getManager().isTextSelected();
boolean lengthModifiable = textSelected && !activeEditor.getManager().isOverwriteMode();
boolean filled = activeEditor.getManager().isFilled();
MenuItem menuItem = getMenuItem(IWorkbenchActionConstants.M_FILE, MenuIds.SAVE_SELECTION_AS);
if (menuItem != null) {
menuItem.setEnabled(textSelected);
}
menuItem = getMenuItem(IWorkbenchActionConstants.M_EDIT, MenuIds.TRIM);
if (menuItem != null) {
menuItem.setEnabled(lengthModifiable);
}
menuItem = getMenuItem(IWorkbenchActionConstants.M_EDIT, MenuIds.SELECT_BLOCK);
if (menuItem != null) {
menuItem.setEnabled(filled);
}
}
private MenuItem getMenuItem(String prefix, String menuId) {
IActionBars bars = getActionBars();
IContributionItem contributionItem = bars.getMenuManager().findUsingPath(prefix + '/' + menuId);
if (contributionItem != null && ((MyMenuContributionItem) contributionItem).myMenuItem != null
&& !((MyMenuContributionItem) contributionItem).myMenuItem.isDisposed()) {
return ((MyMenuContributionItem) contributionItem).myMenuItem;
}
return null;
}
}
private final class MyStatusLineContributionItem extends ContributionItem {
MyStatusLineContributionItem(String id) {
super(id);
}
@Override
public void fill(Composite parent) {
if (activeEditor != null) {
activeEditor.getManager().createStatusPart(parent, true);
}
}
}
private static final class MenuIds {
public static final String SAVE_SELECTION_AS = "saveSelectionAs";
public static final String TRIM = "trim";
public static final String SELECT_BLOCK = "selectBlock";
public static final String ADDITIONS = "additions";
}
private static final String STATUS_LINE_ITEM_ID = "AllHexEditorStatusItemsItem";
HexEditor activeEditor;
/**
* @see EditorActionBarContributor#contributeToMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
public void contributeToMenu(IMenuManager menuManager) {
IMenuManager menu;
IMenuListener myMenuListener = new MyMenuListener();
menu = menuManager.findMenuUsingPath(IWorkbenchActionConstants.M_FILE);
IContributionItem[] ici = menu.getItems();
for (IContributionItem ic : ici) {
System.out.println(ic.toString());
}
if (menu != null) {
// This is the correct place to add the menu contribution
// "Auswahl speichern unter" aber er findet die MenuID
// Das Problem ist mit der Migration auf Eclipse 2020-09
// gekommen. In Eclipse 2019-09 funktionierte es noch.
// menu.insertAfter(IWorkbenchCommandConstants.FILE_SAVE, new MyMenuContributionItem(MenuIds.SAVE_SELECTION_AS));
// menu.addMenuListener(myMenuListener);
menu.add(new MyMenuContributionItem(MenuIds.SAVE_SELECTION_AS));
menu.addMenuListener(myMenuListener);
}
menu = menuManager.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT);
if (menu != null) {
menu.add(new MyMenuContributionItem(MenuIds.TRIM));
menu.addMenuListener(myMenuListener);
}
menu = menuManager.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT);
if (menu != null) {
menu.add(new MyMenuContributionItem(MenuIds.SELECT_BLOCK));
menu.addMenuListener(myMenuListener);
}
menu = menuManager.findMenuUsingPath(IWorkbenchActionConstants.M_NAVIGATE);
if (menu != null) {
Action goToAction = new Action() {
@Override
public boolean isEnabled() {
return activeEditor.getManager().isFilled();
}
@Override
public void run() {
activeEditor.getManager().doGoTo();
}
};
// declared in org.eclipse.ui.workbench.text plugin.xml
goToAction.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_GOTO);
goToAction.setText(Texts.EDITOR_GO_TO_MENU_ITEM_LABEL);
// TODO This only works after the "Navigate" menu was shown once
// Eclipse standard even has the correct accelerator.
// goToAction.setAccelerator(SWT.CTRL + 'L');
menu.appendToGroup(MenuIds.ADDITIONS, goToAction);
}
}
/**
* @see EditorActionBarContributor#contributeToStatusLine(org.eclipse.jface.action.IStatusLineManager)
*/
@Override
public void contributeToStatusLine(IStatusLineManager statusLineManager) {
statusLineManager.add(new MyStatusLineContributionItem(STATUS_LINE_ITEM_ID));
}
/**
* @see IEditorActionBarContributor#setActiveEditor(org.eclipse.ui.IEditorPart)
*/
@Override
public void setActiveEditor(IEditorPart targetEditor) {
if (targetEditor instanceof HexEditor) {
if (activeEditor != null) {
Manager manager = ((HexEditor) targetEditor).getManager();
manager.reuseStatusLinelFrom(activeEditor.getManager());
}
activeEditor = (HexEditor) targetEditor;
activeEditor.getManager().setFocus();
activeEditor.updateActionsStatus();
}
}
} |
package org.eclipse.che.ide.editor.orion.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.DomEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.HasChangeHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.json.client.JSONBoolean;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.ide.api.text.Position;
import org.eclipse.che.ide.api.text.Region;
import org.eclipse.che.ide.api.text.RegionImpl;
import org.eclipse.che.ide.api.text.annotation.Annotation;
import org.eclipse.che.ide.api.texteditor.HandlesUndoRedo;
import org.eclipse.che.ide.editor.orion.client.jso.OrionAnnotationOverlay;
import org.eclipse.che.ide.editor.orion.client.jso.OrionEditorOverlay;
import org.eclipse.che.ide.editor.orion.client.jso.OrionKeyBindingModule;
import org.eclipse.che.ide.editor.orion.client.jso.OrionKeyModeOverlay;
import org.eclipse.che.ide.editor.orion.client.jso.OrionKeyStrokeOverlay;
import org.eclipse.che.ide.editor.orion.client.jso.OrionProblemOverlay;
import org.eclipse.che.ide.editor.orion.client.jso.OrionSelectionOverlay;
import org.eclipse.che.ide.editor.orion.client.jso.OrionStyleOverlay;
import org.eclipse.che.ide.editor.orion.client.jso.OrionTextThemeOverlay;
import org.eclipse.che.ide.editor.orion.client.jso.OrionTextViewOverlay;
import org.eclipse.che.ide.jseditor.client.annotation.AnnotationModel;
import org.eclipse.che.ide.jseditor.client.annotation.AnnotationModelEvent;
import org.eclipse.che.ide.jseditor.client.codeassist.CompletionProposal;
import org.eclipse.che.ide.jseditor.client.codeassist.CompletionReadyCallback;
import org.eclipse.che.ide.jseditor.client.codeassist.CompletionsSource;
import org.eclipse.che.ide.jseditor.client.document.EmbeddedDocument;
import org.eclipse.che.ide.jseditor.client.editortype.EditorType;
import org.eclipse.che.ide.jseditor.client.events.CursorActivityEvent;
import org.eclipse.che.ide.jseditor.client.events.CursorActivityHandler;
import org.eclipse.che.ide.jseditor.client.events.GutterClickHandler;
import org.eclipse.che.ide.jseditor.client.events.HasCursorActivityHandlers;
import org.eclipse.che.ide.jseditor.client.events.HasScrollHandlers;
import org.eclipse.che.ide.jseditor.client.events.ScrollEvent;
import org.eclipse.che.ide.jseditor.client.events.ScrollHandler;
import org.eclipse.che.ide.jseditor.client.keymap.Keybinding;
import org.eclipse.che.ide.jseditor.client.keymap.Keymap;
import org.eclipse.che.ide.jseditor.client.keymap.KeymapChangeEvent;
import org.eclipse.che.ide.jseditor.client.keymap.KeymapChangeHandler;
import org.eclipse.che.ide.jseditor.client.link.LinkedMode;
import org.eclipse.che.ide.jseditor.client.position.PositionConverter;
import org.eclipse.che.ide.jseditor.client.prefmodel.KeymapPrefReader;
import org.eclipse.che.ide.jseditor.client.requirejs.ModuleHolder;
import org.eclipse.che.ide.jseditor.client.text.TextRange;
import org.eclipse.che.ide.jseditor.client.texteditor.CompositeEditorWidget;
import org.eclipse.che.ide.jseditor.client.texteditor.EditorWidget;
import org.eclipse.che.ide.jseditor.client.texteditor.LineStyler;
import org.eclipse.che.ide.util.browser.UserAgent;
import org.eclipse.che.ide.util.loging.Log;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class OrionEditorWidget extends CompositeEditorWidget implements HasChangeHandlers, HasCursorActivityHandlers, HasScrollHandlers {
/** The UI binder instance. */
private static final OrionEditorWidgetUiBinder UIBINDER = GWT.create(OrionEditorWidgetUiBinder.class);
/** The logger. */
private static final Logger LOG = Logger.getLogger(OrionEditorWidget.class.getSimpleName());
@UiField
SimplePanel panel;
/** The instance of the orion editor native element style. */
@UiField
EditorElementStyle editorElementStyle;
private final OrionEditorOverlay editorOverlay;
private String modeName;
private final KeyModeInstances keyModeInstances;
private final JavaScriptObject orionEditorModule;
private final KeymapPrefReader keymapPrefReader;
private final ContentAssistWidgetFactory contentAssistWidgetFactory;
/** Component that handles undo/redo. */
private final HandlesUndoRedo undoRedo;
private OrionDocument embeddedDocument;
private OrionKeyModeOverlay cheContentAssistMode;
private boolean changeHandlerAdded = false;
private boolean focusHandlerAdded = false;
private boolean blurHandlerAdded = false;
private boolean scrollHandlerAdded = false;
private boolean cursorHandlerAdded = false;
private Keymap keymap;
private Provider<OrionKeyBindingModule> keyBindingModuleProvider;
private final ContentAssistWidget assistWidget;
@AssistedInject
public OrionEditorWidget(final ModuleHolder moduleHolder,
final KeyModeInstances keyModeInstances,
final EventBus eventBus,
final KeymapPrefReader keymapPrefReader,
final Provider<OrionKeyBindingModule> keyBindingModuleProvider,
final ContentAssistWidgetFactory contentAssistWidgetFactory,
@Assisted final List<String> editorModes) {
this.keyBindingModuleProvider = keyBindingModuleProvider;
this.contentAssistWidgetFactory = contentAssistWidgetFactory;
initWidget(UIBINDER.createAndBindUi(this));
this.keymapPrefReader = keymapPrefReader;
this.orionEditorModule = moduleHolder.getModule("OrionEditor");
// just first choice for the moment
if (editorModes != null && !editorModes.isEmpty()) {
setMode(editorModes.get(0));
}
panel.getElement().setId("orion-parent-" + Document.get().createUniqueId());
panel.getElement().addClassName(this.editorElementStyle.editorParent());
this.editorOverlay = OrionEditorOverlay.createEditor(panel.getElement(), getConfiguration(), orionEditorModule);
this.keyModeInstances = keyModeInstances;
final OrionTextViewOverlay textView = this.editorOverlay.getTextView();
this.keyModeInstances.add(KeyMode.VI, OrionKeyModeOverlay.getViKeyMode(moduleHolder.getModule("OrionVi"), textView));
this.keyModeInstances.add(KeyMode.EMACS, OrionKeyModeOverlay.getEmacsKeyMode(moduleHolder.getModule("OrionEmacs"), textView));
setupKeymode();
eventBus.addHandler(KeymapChangeEvent.TYPE, new KeymapChangeHandler() {
@Override
public void onKeymapChanged(final KeymapChangeEvent event) {
setupKeymode();
}
});
this.undoRedo = new OrionUndoRedo(this.editorOverlay.getUndoStack());
editorOverlay.setZoomRulerVisible(true);
editorOverlay.getAnnotationStyler().addAnnotationType("che-marker", 100);
this.cheContentAssistMode =
OrionKeyModeOverlay.getCheCodeAssistMode(moduleHolder.getModule("CheContentAssistMode"), editorOverlay.getTextView());
assistWidget = contentAssistWidgetFactory.create(this, cheContentAssistMode);
}
@Override
public String getValue() {
return editorOverlay.getText();
}
@Override
public void setValue(String newValue) {
this.editorOverlay.setText(newValue);
this.editorOverlay.getUndoStack().reset();
}
private JavaScriptObject getConfiguration() {
final JSONObject json = new JSONObject();
json.put("theme", new JSONObject(OrionTextThemeOverlay.getDefautTheme()));
json.put("contentType", new JSONString(this.modeName));
json.put("noComputeSize", JSONBoolean.getInstance(true));
json.put("showZoomRuler", JSONBoolean.getInstance(true));
json.put("expandTab", JSONBoolean.getInstance(true));
json.put("tabSize", new JSONNumber(4));
return json.getJavaScriptObject();
}
protected void autoComplete(OrionEditorOverlay editor) {
// TODO
}
public void setMode(final String modeName) {
String mode = modeName;
if (modeName.equals("text/x-java")) {
mode = "text/x-java-source";
}
LOG.fine("Requested mode: " + modeName + " kept " + mode);
this.modeName = mode;
}
@Override
public String getMode() {
return modeName;
}
@Override
public void setReadOnly(final boolean isReadOnly) {
this.editorOverlay.getTextView().getOptions().setReadOnly(isReadOnly);
this.editorOverlay.getTextView().update();
}
@Override
public boolean isReadOnly() {
return this.editorOverlay.getTextView().getOptions().isReadOnly();
}
@Override
public boolean isDirty() {
return this.editorOverlay.isDirty();
}
@Override
public void markClean() {
this.editorOverlay.setDirty(false);
}
private void selectKeyMode(Keymap keymap) {
resetKeyModes();
Keymap usedKeymap = keymap;
if (usedKeymap == null) {
usedKeymap = KeyMode.DEFAULT;
}
if (KeyMode.DEFAULT.equals(usedKeymap)) {
// nothing to do
} else if (KeyMode.EMACS.equals(usedKeymap)) {
this.editorOverlay.getTextView().addKeyMode(keyModeInstances.getInstance(KeyMode.EMACS));
} else if (KeyMode.VI.equals(usedKeymap)) {
this.editorOverlay.getTextView().addKeyMode(keyModeInstances.getInstance(KeyMode.VI));
} else {
usedKeymap = KeyMode.DEFAULT;
Log.error(OrionEditorWidget.class, "Unknown keymap type: " + keymap + " - changing to defaut one.");
}
this.keymap = usedKeymap;
}
private void resetKeyModes() {
this.editorOverlay.getTextView().removeKeyMode(keyModeInstances.getInstance(KeyMode.VI));
this.editorOverlay.getTextView().removeKeyMode(keyModeInstances.getInstance(KeyMode.EMACS));
}
@Override
public EmbeddedDocument getDocument() {
if (this.embeddedDocument == null) {
this.embeddedDocument = new OrionDocument(this.editorOverlay.getTextView(), this, editorOverlay);
}
return this.embeddedDocument;
}
@Override
public Region getSelectedRange() {
final OrionSelectionOverlay selection = this.editorOverlay.getSelection();
final int start = selection.getStart();
final int end = selection.getEnd();
if (start < 0 || end > this.editorOverlay.getModel().getCharCount() || start > end) {
throw new RuntimeException("Invalid selection");
}
return new RegionImpl(start, end - start);
}
public void setSelectedRange(final Region selection, final boolean show) {
this.editorOverlay.setSelection(selection.getOffset(), selection.getLength(), show);
}
public void setDisplayRange(final Region range) {
// show the line at the head of the range
final int headOffset = range.getOffset() + range.getLength();
if (range.getLength() < 0) {
this.editorOverlay.getTextView().setTopIndex(headOffset);
} else {
this.editorOverlay.getTextView().setBottomIndex(headOffset);
}
}
@Override
public int getTabSize() {
return this.editorOverlay.getTextView().getOptions().getTabSize();
}
@Override
public void setTabSize(int tabSize) {
this.editorOverlay.getTextView().getOptions().setTabSize(tabSize);
}
@Override
public HandlerRegistration addChangeHandler(final ChangeHandler handler) {
if (!changeHandlerAdded) {
changeHandlerAdded = true;
final OrionTextViewOverlay textView = this.editorOverlay.getTextView();
textView.addEventListener(OrionEventContants.MODEL_CHANGED_EVENT, new OrionTextViewOverlay.EventHandlerNoParameter() {
@Override
public void onEvent() {
fireChangeEvent();
}
});
}
return addHandler(handler, ChangeEvent.getType());
}
private void fireChangeEvent() {
DomEvent.fireNativeEvent(Document.get().createChangeEvent(), this);
}
@Override
public HandlerRegistration addCursorActivityHandler(CursorActivityHandler handler) {
if (!cursorHandlerAdded) {
cursorHandlerAdded = true;
final OrionTextViewOverlay textView = this.editorOverlay.getTextView();
textView.addEventListener(OrionEventContants.SELECTION_EVENT, new OrionTextViewOverlay.EventHandlerNoParameter() {
@Override
public void onEvent() {
fireCursorActivityEvent();
}
});
}
return addHandler(handler, CursorActivityEvent.TYPE);
}
private void fireCursorActivityEvent() {
fireEvent(new CursorActivityEvent());
}
@Override
public HandlerRegistration addFocusHandler(FocusHandler handler) {
if (!focusHandlerAdded) {
focusHandlerAdded = true;
final OrionTextViewOverlay textView = this.editorOverlay.getTextView();
textView.addEventListener(OrionEventContants.FOCUS_EVENT, new OrionTextViewOverlay.EventHandlerNoParameter() {
@Override
public void onEvent() {
fireFocusEvent();
}
});
}
return addHandler(handler, FocusEvent.getType());
}
private void fireFocusEvent() {
DomEvent.fireNativeEvent(Document.get().createFocusEvent(), this);
}
@Override
public HandlerRegistration addBlurHandler(BlurHandler handler) {
if (!blurHandlerAdded) {
blurHandlerAdded = true;
final OrionTextViewOverlay textView = this.editorOverlay.getTextView();
textView.addEventListener(OrionEventContants.BLUR_EVENT, new OrionTextViewOverlay.EventHandlerNoParameter() {
@Override
public void onEvent() {
fireBlurEvent();
}
});
}
return addHandler(handler, BlurEvent.getType());
}
private void fireBlurEvent() {
DomEvent.fireNativeEvent(Document.get().createBlurEvent(), this);
}
@Override
public HandlerRegistration addScrollHandler(final ScrollHandler handler) {
if (!scrollHandlerAdded) {
scrollHandlerAdded = true;
final OrionTextViewOverlay textView = this.editorOverlay.getTextView();
textView.addEventListener(OrionEventContants.SCROLL_EVENT, new OrionTextViewOverlay.EventHandlerNoParameter() {
@Override
public void onEvent() {
fireScrollEvent();
}
});
}
return addHandler(handler, ScrollEvent.TYPE);
}
private void fireScrollEvent() {
fireEvent(new ScrollEvent());
}
private void setupKeymode() {
final String propertyValue = this.keymapPrefReader.readPref(OrionEditorExtension.ORION_EDITOR_KEY);
Keymap keymap;
try {
keymap = Keymap.fromKey(propertyValue);
} catch (final IllegalArgumentException e) {
LOG.log(Level.WARNING, "Unknown value in keymap preference.", e);
return;
}
selectKeyMode(keymap);
}
@Override
public EditorType getEditorType() {
return EditorType.getInstance(OrionEditorExtension.ORION_EDITOR_KEY);
}
@Override
public Keymap getKeymap() {
return this.keymap;
}
public PositionConverter getPositionConverter() {
return embeddedDocument.getPositionConverter();
}
public void setFocus() {
this.editorOverlay.focus();
}
public void showMessage(final String message) {
this.editorOverlay.reportStatus(message);
}
@Override
protected void onLoad() {
// fix for native editor height
if (panel.getElement().getChildCount() > 0) {
final Element child = panel.getElement().getFirstChildElement();
child.setId("orion-editor-" + Document.get().createUniqueId());
child.getStyle().clearHeight();
} else {
LOG.severe("Orion insertion failed.");
}
}
public void onResize() {
// redraw text and rulers
// maybe just redrawing the text would be enough
this.editorOverlay.getTextView().redraw();
}
public HandlesUndoRedo getUndoRedo() {
return this.undoRedo;
}
public void addKeybinding(final Keybinding keybinding) {
OrionKeyStrokeOverlay strokeOverlay;
if(UserAgent.isMac()) {
strokeOverlay = OrionKeyStrokeOverlay.create(keybinding.getKeyCode(),
keybinding.isCmd(),
keybinding.isShift(),
keybinding.isAlt(),
keybinding.isControl(),
"keydown",
keyBindingModuleProvider.get());
} else {
strokeOverlay = OrionKeyStrokeOverlay.create(keybinding.getKeyCode(),
keybinding.isControl(),
keybinding.isShift(),
keybinding.isAlt(),
false,
"keydown",
keyBindingModuleProvider.get());
}
String actionId = "che-action" + keybinding.getAction().toString();
editorOverlay.getTextView().setKeyBinding(strokeOverlay, actionId);
editorOverlay.getTextView().setAction(actionId, new Action() {
@Override
public void onAction() {
keybinding.getAction().action();
}
});
}
public MarkerRegistration addMarker(final TextRange range, final String className) {
final OrionAnnotationOverlay annotation = OrionAnnotationOverlay.create();
OrionStyleOverlay styleOverlay = OrionStyleOverlay.create();
styleOverlay.setStyleClass(className);
int start = embeddedDocument.getIndexFromPosition(range.getFrom());
int end = embeddedDocument.getIndexFromPosition(range.getTo());
annotation.setStart(start);
annotation.setEnd(end);
annotation.setRangeStyle(styleOverlay);
annotation.setType("che-marker");
editorOverlay.getAnnotationModel().addAnnotation(annotation);
return new MarkerRegistration() {
@Override
public void clearMark() {
editorOverlay.getAnnotationModel().removeAnnotation(annotation);
}
};
}
public void showCompletionsProposals(final List<CompletionProposal> proposals) {
if (proposals == null || proposals.isEmpty()) {
return;
}
assistWidget.clear();
for (final CompletionProposal proposal : proposals) {
assistWidget.addItem(proposal);
}
assistWidget.positionAndShow();
}
public void showCompletionProposals(final CompletionsSource completionsSource) {
// currently not implemented
completionsSource.computeCompletions(new CompletionReadyCallback() {
@Override
public void onCompletionReady(List<CompletionProposal> proposals) {
showCompletionsProposals(proposals);
}
});
}
@Override
public LineStyler getLineStyler() {
return null;
}
@Override
public HandlerRegistration addGutterClickHandler(final GutterClickHandler handler) {
return null;
}
public void refresh() {
this.editorOverlay.getTextView().redraw();
}
public void scrollToLine(int line) {
this.editorOverlay.getTextView().setTopIndex(line);
}
public void showErrors(AnnotationModelEvent event) {
List<Annotation> addedAnnotations = event.getAddedAnnotations();
JsArray<OrionProblemOverlay> jsArray = JsArray.createArray().cast();
AnnotationModel annotationModel = event.getAnnotationModel();
for (Annotation annotation : addedAnnotations) {
Position position = annotationModel.getPosition(annotation);
OrionProblemOverlay problem = JavaScriptObject.createObject().cast();
problem.setDescription(annotation.getText());
problem.setStart(position.getOffset());
problem.setEnd(position.getOffset() + position.getLength());
problem.setId("che-annotation");
problem.setSeverity(getSeverity(annotation.getType()));
jsArray.push(problem);
}
editorOverlay.showProblems(jsArray);
}
private String getSeverity(String type) {
switch (type) {
case "org.eclipse.jdt.ui.error":
return "error";
case "org.eclipse.jdt.ui.warning":
return "warning";
default:
return "task";
}
}
public void clearErrors() {
editorOverlay.showProblems(JavaScriptObject.createArray().<JsArray<OrionProblemOverlay>>cast());
}
public OrionTextViewOverlay getTextView() {
return editorOverlay.getTextView();
}
public LinkedMode getLinkedMode() {
return editorOverlay.getLinkedMode();
}
interface OrionEditorWidgetUiBinder extends UiBinder<SimplePanel, OrionEditorWidget> {
}
public interface EditorElementStyle extends CssResource {
@ClassName("editor-parent")
String editorParent();
}
} |
package com.redhat.ceylon.eclipse.imp.contentProposer;
import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.LIDENTIFIER;
import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.MEMBER_OP;
import static com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer.UIDENTIFIER;
import static com.redhat.ceylon.eclipse.imp.core.CeylonReferenceResolver.getDeclarationNode;
import static com.redhat.ceylon.eclipse.imp.editor.CeylonDocumentationProvider.getDocumentation;
import static java.lang.Character.isJavaIdentifierPart;
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.Token;
import org.eclipse.imp.editor.SourceProposal;
import org.eclipse.imp.parser.IParseController;
import org.eclipse.imp.services.IContentProposer;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Generic;
import com.redhat.ceylon.compiler.typechecker.model.ImportList;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.eclipse.imp.parser.CeylonParseController;
import com.redhat.ceylon.eclipse.imp.tokenColorer.CeylonTokenColorer;
import com.redhat.ceylon.eclipse.imp.treeModelBuilder.CeylonLabelProvider;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
import com.redhat.ceylon.eclipse.ui.ICeylonResources;
public class CeylonContentProposer implements IContentProposer {
private static Image REFINEMENT = CeylonPlugin.getInstance()
.getImageRegistry().get(ICeylonResources.CEYLON_REFINEMENT);
/**
* Returns an array of content proposals applicable relative to the AST of the given
* parse controller at the given position.
*
* (The provided ITextViewer is not used in the default implementation provided here
* but but is stipulated by the IContentProposer interface for purposes such as accessing
* the IDocument for which content proposals are sought.)
*
* @param controller A parse controller from which the AST of the document being edited
* can be obtained
* @param int The offset for which content proposals are sought
* @param viewer The viewer in which the document represented by the AST in the given
* parse controller is being displayed (may be null for some implementations)
* @return An array of completion proposals applicable relative to the AST of the given
* parse controller at the given position
*/
public ICompletionProposal[] getContentProposals(IParseController controller,
final int offset, ITextViewer viewer) {
CeylonParseController cpc = (CeylonParseController) controller;
//BEGIN HUGE BUG WORKAROUND
//What is going on here is that when I have a list of proposals open
//and then I type a character, IMP sends us the old syntax tree and
//doesn't bother to even send us the character I just typed, except
//in the ITextViewer. So we need to do some guessing to figure out
//that there is a missing character in the token stream and take
//corrective action. This should be fixed in IMP!
String prefix="";
int start=0;
int end=0;
CommonToken previousToken = null;
for (CommonToken token: (List<CommonToken>) cpc.getTokenStream().getTokens()) {
if (/*t.getStartIndex()<=offset &&*/ token.getStopIndex()+1>=offset) {
char charAtOffset = viewer.getDocument().get().charAt(offset-1);
char charInTokenAtOffset = token.getText().charAt(offset-token.getStartIndex()-1);
if (charAtOffset==charInTokenAtOffset) {
if (isIdentifier(token)) {
start = token.getStartIndex();
end = token.getStopIndex();
prefix = token.getText().substring(0, offset-token.getStartIndex());
}
else {
prefix = "";
start = offset;
end = offset;
}
}
else {
boolean isIdentifierChar = isJavaIdentifierPart(charAtOffset);
if (previousToken!=null) {
start = previousToken.getStartIndex();
end = previousToken.getStopIndex();
if (previousToken.getType()==MEMBER_OP && isIdentifierChar) {
prefix = Character.toString(charAtOffset);
}
else if (isIdentifier(previousToken) && isIdentifierChar) {
prefix = previousToken.getText()+charAtOffset;
}
else {
prefix = isIdentifierChar ?
Character.toString(charAtOffset) : "";
}
}
else {
prefix = isIdentifierChar ?
Character.toString(charAtOffset) : "";
start = offset;
end = offset;
}
}
break;
}
previousToken = token;
}
//END BUG WORKAROUND
if (cpc.getRootNode() != null) {
Node node = cpc.getSourcePositionLocator()
.findNode(cpc.getRootNode(), start, end);
if (node==null) {
node = cpc.getRootNode();
}
else if (node instanceof Tree.Import) {
return constructPackageCompletions(cpc, offset, prefix, null, node);
}
else if (node instanceof Tree.ImportPath) {
return constructPackageCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node);
}
else {
return constructCompletions(offset, prefix,
sortProposals(prefix, getProposals(node, prefix, cpc)),
cpc, node);
}
}
/*result.add(new ErrorProposal("No proposals available due to syntax errors",
offset));*/
return null;
}
public ICompletionProposal[] constructPackageCompletions(CeylonParseController cpc,
int offset, String prefix, Tree.ImportPath path, Node node) {
StringBuilder fullPath = new StringBuilder();
if (path!=null) {
for (int i=0; i<path.getIdentifiers().size()-1; i++) {
fullPath.append(path.getIdentifiers().get(i).getText()).append('.');
}
}
int len = fullPath.length();
fullPath.append(prefix);
List<ICompletionProposal> result = new ArrayList<ICompletionProposal>();
//TODO: someday it would be nice to propose from all packages
// and auto-add the module dependency!
/*TypeChecker tc = CeylonBuilder.getProjectTypeChecker(cpc.getProject().getRawProject());
if (tc!=null) {
for (Module m: tc.getContext().getModules().getListOfModules()) {*/
for (Module m: node.getUnit().getPackage().getModule().getDependencies()) {
for (Package p: m.getAllPackages()) {
if (p.getQualifiedNameString().startsWith(fullPath.toString())) {
boolean already = false;
for (ImportList il: node.getUnit().getImportLists()) {
if (il.getImportedPackage()==p) {
already = true;
break;
}
}
if (!already) {
result.add(sourceProposal(offset, prefix, CeylonLabelProvider.PACKAGE,
"[" + p.getQualifiedNameString() + "]", p.getQualifiedNameString(),
p.getQualifiedNameString().substring(len), false));
}
}
}
}
return result.toArray(new ICompletionProposal[result.size()]);
}
private static boolean isIdentifier(Token token) {
return token.getType()==LIDENTIFIER ||
token.getType()==UIDENTIFIER;
}
private static ICompletionProposal[] constructCompletions(int offset, String prefix,
Set<DeclarationWithProximity> set, CeylonParseController cpc, Node node) {
List<ICompletionProposal> result = new ArrayList<ICompletionProposal>();
for (String keyword: CeylonTokenColorer.keywords) {
if (!prefix.isEmpty() && keyword.startsWith(prefix)) {
result.add(sourceProposal(offset, prefix, null,
keyword + " keyword", keyword, keyword,
true));
}
}
boolean inImport = node.getScope() instanceof ImportList;
for (final DeclarationWithProximity dwp: set) {
Declaration d = dwp.getDeclaration();
result.add(sourceProposal(offset, prefix,
CeylonLabelProvider.getImage(d),
getDocumentation(getDeclarationNode(cpc, d)),
getDescriptionFor(dwp, !inImport),
getTextFor(dwp, !inImport), true));
if (!inImport) {
if (d instanceof Functional) {
boolean isAbstractClass = d instanceof Class && ((Class) d).isAbstract();
if (!isAbstractClass) {
result.add(sourceProposal(offset, prefix,
CeylonLabelProvider.getImage(d),
getDocumentation(getDeclarationNode(cpc, d)),
getPositionalInvocationDescriptionFor(dwp),
getPositionalInvocationTextFor(dwp), true));
List<ParameterList> pls = ((Functional) d).getParameterLists();
if ( !pls.isEmpty() && pls.get(0).getParameters().size()>1) {
//if there is more than one parameter,
//suggest a named argument invocation
result.add(sourceProposal(offset, prefix,
CeylonLabelProvider.getImage(d),
getDocumentation(getDeclarationNode(cpc, d)),
getNamedInvocationDescriptionFor(dwp),
getNamedInvocationTextFor(dwp), true));
}
}
}
if (d instanceof MethodOrValue || d instanceof Class) {
if (node.getScope() instanceof ClassOrInterface &&
((ClassOrInterface) node.getScope()).isInheritedFromSupertype(d)) {
result.add(sourceProposal(offset, prefix,
REFINEMENT,
getDocumentation(getDeclarationNode(cpc, d)),
getRefinementDescriptionFor(d),
getRefinementTextFor(d), false));
}
}
}
}
return result.toArray(new ICompletionProposal[result.size()]);
}
private static Set<DeclarationWithProximity> sortProposals(final String prefix,
Map<String, DeclarationWithProximity> proposals) {
Set<DeclarationWithProximity> set = new TreeSet<DeclarationWithProximity>(
new Comparator<DeclarationWithProximity>() {
public int compare(DeclarationWithProximity x, DeclarationWithProximity y) {
String xName = x.getName();
String yName = y.getName();
if (prefix.length()!=0) {
int lowers = isLowerCase(prefix.charAt(0)) ? -1 : 1;
if (isLowerCase(xName.charAt(0)) &&
isUpperCase(yName.charAt(0))) {
return lowers;
}
else if (isUpperCase(xName.charAt(0)) &&
isLowerCase(yName.charAt(0))) {
return -lowers;
}
}
if (x.getProximity()!=y.getProximity()) {
return new Integer(x.getProximity()).compareTo(y.getProximity());
}
return xName.compareTo(yName);
}
});
set.addAll(proposals.values());
return set;
}
private static SourceProposal sourceProposal(final int offset, final String prefix,
final Image image, String doc, String desc, final String text,
final boolean selectParams) {
return new SourceProposal(desc, text, "",
new Region(offset - prefix.length(), prefix.length()),
offset + text.length(), doc) {
@Override
public Image getImage() {
return image;
}
@Override
public Point getSelection(IDocument document) {
if (selectParams) {
int locOfTypeArgs = text.indexOf('<');
int loc = locOfTypeArgs;
if (loc<0) loc = text.indexOf('(');
if (loc<0) loc = text.indexOf('=')+1;
int start;
int length;
if (loc<=0 || locOfTypeArgs<0 &&
(text.contains("()") || text.contains("{}"))) {
start = text.length();
length = 0;
}
else {
int endOfTypeArgs = text.indexOf('>');
int end = text.indexOf(',');
if (end<0) end = text.indexOf(';');
if (end<0) end = text.length()-1;
if (endOfTypeArgs>0) end = end < endOfTypeArgs ? end : endOfTypeArgs;
start = loc+1;
length = end-loc-1;
}
return new Point(offset-prefix.length() + start, length);
}
else {
return new Point(offset + text.length()-prefix.length(), 0);
}
}
};
}
private Map<String, DeclarationWithProximity> getProposals(Node node, String prefix,
CeylonParseController cpc) {
//TODO: substitute type arguments to receiving type
if (node instanceof Tree.QualifiedMemberExpression) {
ProducedType type = ((Tree.QualifiedMemberExpression) node).getPrimary().getTypeModel();
if (type!=null) {
return type.getDeclaration().getMatchingMemberDeclarations(prefix, 0);
}
else {
return Collections.emptyMap();
}
}
else if (node instanceof Tree.QualifiedTypeExpression) {
ProducedType type = ((Tree.QualifiedTypeExpression) node).getPrimary().getTypeModel();
if (type!=null) {
return type.getDeclaration().getMatchingMemberDeclarations(prefix, 0);
}
else {
return Collections.emptyMap();
}
}
else {
Map<String, DeclarationWithProximity> result = getLanguageModuleProposals(node, prefix, cpc);
result.putAll(node.getScope().getMatchingDeclarations(node.getUnit(), prefix, 0));
return result;
}
}
//TODO: move this method to the model (perhaps make a LanguageModulePackage subclass)
private static Map<String, DeclarationWithProximity> getLanguageModuleProposals(Node node, String prefix,
CeylonParseController cpc) {
Map<String, DeclarationWithProximity> result = new TreeMap<String, DeclarationWithProximity>();
Module languageModule = cpc.getContext().getModules().getLanguageModule();
if (languageModule!=null && !(node.getScope() instanceof ImportList)) {
for (Package languageScope: languageModule.getPackages() ) {
for (Map.Entry<String, DeclarationWithProximity> entry:
languageScope.getMatchingDeclarations(null, prefix, 1000).entrySet()) {
if (entry.getValue().getDeclaration().isShared()) {
result.put(entry.getKey(), entry.getValue());
}
}
}
}
return result;
}
private static boolean forceExplicitTypeArgs(Declaration d) {
//TODO: this is a pretty limited implementation
// for now, but eventually we could do
// something much more sophisticated to
// guess is explicit type args will be
// necessary (variance, etc)
if (d instanceof Functional) {
List<ParameterList> pls = ((Functional) d).getParameterLists();
return pls.isEmpty() || pls.get(0).getParameters().isEmpty();
}
else {
return false;
}
}
private static String getTextFor(DeclarationWithProximity d,
boolean includeTypeArgs) {
StringBuilder result = new StringBuilder(d.getName());
if (includeTypeArgs) appendTypeParameters(d.getDeclaration(), result);
return result.toString();
}
private static String getPositionalInvocationTextFor(DeclarationWithProximity d) {
StringBuilder result = new StringBuilder(d.getName());
if (forceExplicitTypeArgs(d.getDeclaration()))
appendTypeParameters(d.getDeclaration(), result);
appendPositionalArgs(d.getDeclaration(), result);
return result.toString();
}
private static String getNamedInvocationTextFor(DeclarationWithProximity d) {
StringBuilder result = new StringBuilder(d.getName());
if (forceExplicitTypeArgs(d.getDeclaration()))
appendTypeParameters(d.getDeclaration(), result);
appendNamedArgs(d.getDeclaration(), result);
return result.toString();
}
private static String getDescriptionFor(DeclarationWithProximity d,
boolean includeTypeArgs) {
StringBuilder result = new StringBuilder(d.getName());
if (includeTypeArgs) appendTypeParameters(d.getDeclaration(), result);
return result.toString();
}
private static String getPositionalInvocationDescriptionFor(DeclarationWithProximity d) {
StringBuilder result = new StringBuilder(d.getName());
if (forceExplicitTypeArgs(d.getDeclaration()))
appendTypeParameters(d.getDeclaration(), result);
appendPositionalArgs(d.getDeclaration(), result);
return result/*.append(" - invoke with positional arguments")*/.toString();
}
private static String getNamedInvocationDescriptionFor(DeclarationWithProximity d) {
StringBuilder result = new StringBuilder(d.getName());
if (forceExplicitTypeArgs(d.getDeclaration()))
appendTypeParameters(d.getDeclaration(), result);
appendNamedArgs(d.getDeclaration(), result);
return result/*.append(" - invoke with named arguments")*/.toString();
}
private static String getRefinementTextFor(Declaration d) {
StringBuilder result = new StringBuilder();
appendDeclarationText(d, result);
appendTypeParameters(d, result);
appendParameters(d, result);
return result.toString();
}
private static String getRefinementDescriptionFor(Declaration d) {
StringBuilder result = new StringBuilder();
appendDeclarationText(d, result);
appendTypeParameters(d, result);
appendParameters(d, result);
/*result.append(" - refine declaration in ")
.append(((Declaration) d.getContainer()).getName());*/
return result.toString();
}
private static void appendPositionalArgs(Declaration d, StringBuilder result) {
if (d instanceof Functional) {
List<ParameterList> plists = ((Functional) d).getParameterLists();
if (plists!=null && !plists.isEmpty()) {
ParameterList params = plists.get(0);
if (params.getParameters().isEmpty()) {
result.append("()");
}
else {
result.append("(");
for (Parameter p: params.getParameters()) {
result.append(p.getName()).append(", ");
}
result.setLength(result.length()-2);
result.append(")");
}
}
}
}
private static void appendNamedArgs(Declaration d, StringBuilder result) {
if (d instanceof Functional) {
List<ParameterList> plists = ((Functional) d).getParameterLists();
if (plists!=null && !plists.isEmpty()) {
ParameterList params = plists.get(0);
if (params.getParameters().isEmpty()) {
result.append(" {}");
}
else {
result.append(" { ");
for (Parameter p: params.getParameters()) {
if (!p.isSequenced()) {
result.append(p.getName()).append(" = ")
.append(p.getName()).append("; ");
}
}
result.append("}");
}
}
}
}
private static void appendTypeParameters(Declaration d, StringBuilder result) {
if (d instanceof Generic) {
List<TypeParameter> types = ((Generic) d).getTypeParameters();
if (!types.isEmpty()) {
result.append("<");
for (TypeParameter p: types) {
result.append(p.getName()).append(", ");
}
result.setLength(result.length()-2);
result.append(">");
}
}
}
private static void appendDeclarationText(Declaration d, StringBuilder result) {
result.append("shared actual ");
if (d instanceof Class) {
result.append("class");
}
else if (d instanceof TypedDeclaration) {
TypedDeclaration td = (TypedDeclaration) d;
String typeName = td.getType().getProducedTypeName();
if (d instanceof Method) {
if (typeName.equals("Void")) { //TODO: fix this!
result.append("void");
}
else {
result.append(typeName);
}
}
else {
result.append(typeName);
}
}
result.append(" ").append(d.getName());
}
/*private static void appendPackage(Declaration d, StringBuilder result) {
if (d.isToplevel()) {
String pkg = d.getUnit().getPackage().getQualifiedNameString();
if (pkg.isEmpty()) pkg="default package";
result.append(" [").append(pkg).append("]");
}
if (d.isClassOrInterfaceMember()) {
result.append(" - ");
ClassOrInterface td = (ClassOrInterface) d.getContainer();
result.append( td.getName() );
appendPackage(td, result);
}
}*/
private static void appendParameters(Declaration d, StringBuilder result) {
if (d instanceof Functional) {
List<ParameterList> plists = ((Functional) d).getParameterLists();
if (plists!=null && !plists.isEmpty()) {
ParameterList params = plists.get(0);
if (params.getParameters().isEmpty()) {
result.append("()");
}
else {
result.append("(");
for (Parameter p: params.getParameters()) {
result.append(p.getType().getProducedTypeName()).append(" ")
.append(p.getName()).append(", ");
}
result.setLength(result.length()-2);
result.append(")");
}
}
}
}
} |
package ccare.service;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import javax.naming.NamingException;
import org.junit.Test;
import ccare.domain.Observable;
import ccare.symboltable.SymbolReference;
public class SymbolTableBeanTest {
private SymbolTableService service = new SymbolTableBean();
@Test
public void testBeanIsSingleton() throws NamingException {
SymbolTableService serviceBean = service();
assertNotNull(serviceBean);
SymbolTableService serviceBean2 = service();
assertEquals(serviceBean.getId(), serviceBean2.getId());
}
@Test
public void testSetAndGetSymbol() throws NamingException {
SymbolTableService serviceBean = service();
Observable def = new Observable();
def.setDefinition("
SymbolReference r = new SymbolReference();
serviceBean.define(r, def);
Observable o = serviceBean.observe(r);
assertEquals(o.getDefinition(), "
}
@Test
public void testListSymbol() throws NamingException {
SymbolTableService serviceBean = service();
Observable def = new Observable();
def.setDefinition("a+b");
SymbolReference r = new SymbolReference();
serviceBean.define(r, def);
assertTrue(serviceBean.listSymbols().contains(r));
}
// private InitialContext createContext() {
// Properties props = new Properties();
// props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
// InitialContext context = null;
// try {
// context = new InitialContext(props);
// } catch (NamingException e) {
// throw new RuntimeException(e);
// return context;
private SymbolTableService service() throws NamingException {
return service;
//InitialContext context = createContext();
//return (SymbolTableService) context.lookup("SymbolTableBeanLocal");
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.aspose.words.api;
import static org.junit.Assert.assertNull;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.aspose.client.ApiException;
import com.aspose.storage.api.StorageApi;
import com.aspose.words.model.BookmarkData;
import com.aspose.words.model.BookmarkResponse;
import com.aspose.words.model.BookmarksResponse;
import com.aspose.words.model.DocumentEntryList;
import com.aspose.words.model.DocumentPropertiesResponse;
import com.aspose.words.model.DocumentProperty;
import com.aspose.words.model.DocumentPropertyResponse;
import com.aspose.words.model.DocumentResponse;
import com.aspose.words.model.DrawingObjectsResponse;
import com.aspose.words.model.FieldNamesResponse;
import com.aspose.words.model.Font;
import com.aspose.words.model.FontResponse;
import com.aspose.words.model.FormField;
import com.aspose.words.model.FormFieldResponse;
import com.aspose.words.model.HyperlinkResponse;
import com.aspose.words.model.HyperlinksResponse;
import com.aspose.words.model.LoadWebDocumentData;
import com.aspose.words.model.PageNumber;
import com.aspose.words.model.PageSetup;
import com.aspose.words.model.ParagraphLinkCollectionResponse;
import com.aspose.words.model.ParagraphResponse;
import com.aspose.words.model.ProtectionDataResponse;
import com.aspose.words.model.ProtectionRequest;
import com.aspose.words.model.ReplaceTextRequest;
import com.aspose.words.model.ReplaceTextResponse;
import com.aspose.words.model.ResponseMessage;
import com.aspose.words.model.RevisionsModificationResponse;
import com.aspose.words.model.RunResponse;
import com.aspose.words.model.SaaSposeResponse;
import com.aspose.words.model.SaveOptions;
import com.aspose.words.model.SaveResponse;
import com.aspose.words.model.SectionLinkCollectionResponse;
import com.aspose.words.model.SectionPageSetupResponse;
import com.aspose.words.model.SectionResponse;
import com.aspose.words.model.SplitDocumentResponse;
import com.aspose.words.model.StatDataResponse;
import com.aspose.words.model.TextItemsResponse;
import com.aspose.words.model.TiffSaveOptionsData;
import com.aspose.words.model.WatermarkText;
/**
*
* @author Imran Anwar
* @author Farooq Sheikh
*/
public class WordsApiTest {
static WordsApi wordsApi;
static StorageApi storageApi;
static String appSID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
static String apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
public WordsApiTest() {
}
@BeforeClass
public static void setUpClass() {
try {
wordsApi = new WordsApi("http://api.aspose.com/v1.1",apiKey,appSID);
storageApi = new StorageApi("http://api.aspose.com/v1.1",apiKey,appSID);
storageApi.PutCreate("test_multi_pages.docx", "", "", new File(WordsApiTest.class.getResource("/test_multi_pages.docx").toURI()));
storageApi.PutCreate("test_convertlocal.docx", "", "", new File(WordsApiTest.class.getResource("/test_convertlocal.docx").toURI()));
storageApi.PutCreate("test_doc.docx", "", "", new File(WordsApiTest.class.getResource("/test_doc.docx").toURI()));
storageApi.PutCreate("test_uploadfile.docx", "", "", new File(WordsApiTest.class.getResource("/test_uploadfile.docx").toURI()));
storageApi.PutCreate("test_multi_pages.docx", "", "", new File(WordsApiTest.class.getResource("/test_multi_pages.docx").toURI()));
storageApi.PutCreate("TestMailMerge.doc", "", "", new File(WordsApiTest.class.getResource("/TestMailMerge.doc").toURI()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of GetDocumentBookmarkByName method, of class WordsApi.
*/
@Test
public void testGetDocumentBookmarkByName() {
System.out.println("GetDocumentBookmarkByName");
String name = "test_multi_pages.docx";
String bookmarkName = "aspose";
String storage = "";
String folder = "";
try {
BookmarkResponse result = wordsApi.GetDocumentBookmarkByName(name, bookmarkName, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentBookmarks method, of class WordsApi.
*/
@Test
public void testGetDocumentBookmarks() {
System.out.println("GetDocumentBookmarks");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
BookmarksResponse result = wordsApi.GetDocumentBookmarks(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostUpdateDocumentBookmark method, of class WordsApi.
*/
@Test
public void testPostUpdateDocumentBookmark() {
System.out.println("PostUpdateDocumentBookmark");
String name = "test_multi_pages.docx";
String bookmarkName = "aspose";
String filename = "test.docx";
String storage = "";
String folder = "";
BookmarkData body = new BookmarkData();
body.setName("aspose");
body.setText("This is updated Bookmark");
try {
BookmarkResponse result = wordsApi.PostUpdateDocumentBookmark(name, bookmarkName, filename, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocument method, of class WordsApi.
*/
@Test
public void testGetDocument() {
System.out.println("GetDocument");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
ResponseMessage result = wordsApi.GetDocument(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentWithFormat method, of class WordsApi.
*/
@Test
public void testGetDocumentWithFormat() {
System.out.println("GetDocumentWithFormat");
String name = "test_multi_pages.docx";
String format = "text";
String storage = "";
String folder = "";
String outPath = "";
try {
ResponseMessage result = wordsApi.GetDocumentWithFormat(name, format, storage, folder, outPath);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostAppendDocument method, of class WordsApi.
*/
@Test
public void testPostAppendDocument() {
System.out.println("PostAppendDocument");
String name = "test_multi_pages.docx";
String filename = "test_multi_pages.docx";
String storage = "";
String folder = "";
DocumentEntryList body = new DocumentEntryList();
List<com.aspose.words.model.DocumentEntry> docEntries = new ArrayList();
com.aspose.words.model.DocumentEntry docEntry = new com.aspose.words.model.DocumentEntry();
docEntry.setHref("test_multi_pages.docx");
docEntry.setImportFormatMode("KeepSourceFormatting");
docEntries.add(docEntry);
body.setDocumentEntries(docEntries);
try {
DocumentResponse result = wordsApi.PostAppendDocument(name, filename, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostExecuteTemplate method, of class WordsApi.
*/
@Test
public void testPostExecuteTemplate() {
System.out.println("PostExecuteTemplate");
String name = "TestExecuteTemplate.doc";
String cleanup = null;
String filename = "TestExecuteResult.doc";
String storage = null;
String folder = null;
Boolean useWholeParagraphAsRegion = null;
Boolean withRegions = null;
File file;
try {
file = new File(getClass().getResource("/TestExecuteTemplateData.txt").toURI());
storageApi.PutCreate("TestExecuteTemplate.doc", "", "", new File(getClass().getResource("/TestExecuteTemplate.doc").toURI()));
DocumentResponse result = wordsApi.PostExecuteTemplate(name, cleanup, filename, storage, folder, useWholeParagraphAsRegion, withRegions, file);
} catch (Exception apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostInsertPageNumbers method, of class WordsApi.
*/
@Test
public void testPostInsertPageNumbers() {
System.out.println("PostInsertPageNumbers");
String name = "test_multi_pages.docx";
String filename = "test_multi_pages.docx";
String storage = "";
String folder = "";
PageNumber body = new PageNumber();
body.setFormat("{PAGE} of {NUMPAGES}");
body.setAlignment("center");
try {
DocumentResponse result = wordsApi.PostInsertPageNumbers(name, filename, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostInsertWatermarkImage method, of class WordsApi.
*/
@Test
public void testPostInsertWatermarkImage() {
System.out.println("PostInsertWatermarkImage");
String name = "test_multi_pages.docx";
String filename = "test.docx";
Double rotationAngle = null;
String image = "aspose-cloud.png";
String storage = "";
String folder = "";
File file;
try {
file = new File(getClass().getResource("/aspose-cloud.png").toURI());
storageApi.PutCreate("aspose-cloud.png", "", "", new File(getClass().getResource("/aspose-cloud.png").toURI()));
DocumentResponse result = wordsApi.PostInsertWatermarkImage(name, filename, rotationAngle, image, storage, folder, file);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
} catch(java.net.URISyntaxException uriExp){
System.out.println("uri exp:" + uriExp.getMessage());
}
}
/**
* Test of PostInsertWatermarkText method, of class WordsApi.
*/
@Test
public void testPostInsertWatermarkText() {
System.out.println("PostInsertWatermarkText");
String name = "test_multi_pages.docx";
String text = "New";
Double rotationAngle = 90.0;
String filename = "test_multi_pages.docx";
String storage = "";
String folder = "";
WatermarkText body = new WatermarkText();
body.setText("text");
try {
DocumentResponse result = wordsApi.PostInsertWatermarkText(name, text, rotationAngle, filename, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostLoadWebDocument method, of class WordsApi.
*/
@Test
public void testPostLoadWebDocument() {
System.out.println("PostLoadWebDocument");
LoadWebDocumentData loadWebDocumentData = new LoadWebDocumentData();
loadWebDocumentData.setLoadingDocumentUrl("http://google.com");
SaveOptions saveOptions = new SaveOptions();
saveOptions.setSaveFormat("doc");
saveOptions.setFileName("google.doc");
loadWebDocumentData.setSaveOptions(saveOptions);
try {
SaveResponse result = wordsApi.PostLoadWebDocument(loadWebDocumentData);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostSplitDocument method, of class WordsApi.
*/
@Test
public void testPostSplitDocument() {
System.out.println("PostSplitDocument");
String name = "test_multi_pages.docx";
String format = "text";
Integer from = 1;
Integer to = 2;
Boolean zipOutput = false;
String storage = "";
String folder = "";
try {
SplitDocumentResponse result = wordsApi.PostSplitDocument(name, format, from, to, zipOutput, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PutConvertDocument method, of class WordsApi.
*/
@Test
public void testPutConvertDocument() {
System.out.println("PutConvertDocument");
String format = "text";
String outPath = "";
File file;
try {
file = new File(getClass().getResource("/test_uploadfile.docx").toURI());
ResponseMessage result = wordsApi.PutConvertDocument(format, outPath, file);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
} catch(java.net.URISyntaxException uriExp){
System.out.println("uri exp:" + uriExp.getMessage());
}
}
/**
* Test of PutExecuteMailMergeOnline method, of class WordsApi.
*/
@Test
public void testPutExecuteMailMergeOnline() {
System.out.println("PutExecuteMailMergeOnline");
Boolean withRegions = false;
String cleanup = "yes";
File file;
try {
//file = new File(getClass().getResource("/test_uploadfile.docx").toURI());
//ResponseMessage result = wordsApi.PutExecuteMailMergeOnline(withRegions, cleanup, file);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostUpdateDocumentFields method, of class WordsApi.
*/
@Test
public void testPostUpdateDocumentFields() {
System.out.println("PostUpdateDocumentFields");
String name = "test_multi_pages.docx";
String filename = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
DocumentResponse result = wordsApi.PostUpdateDocumentFields(name, filename, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of DeleteDocumentProperty method, of class WordsApi.
*/
@Test
public void testDeleteDocumentProperty() {
System.out.println("DeleteDocumentProperty");
String name = "test_multi_pages.docx";
String propertyName = "AsposeAuthor";
String filename = "test_multi_pages.docx";
String storage = "";
String folder = "";
DocumentProperty body = new DocumentProperty();
body.setName("AsposeAuthor");
body.setValue("Farooq Sheikh");
body.setBuiltIn(false);
try {
wordsApi.PutUpdateDocumentProperty(name, propertyName, filename, storage, folder, body);
SaaSposeResponse result = wordsApi.DeleteDocumentProperty(name, propertyName, filename, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentProperties method, of class WordsApi.
*/
@Test
public void testGetDocumentProperties() {
System.out.println("GetDocumentProperties");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
DocumentPropertiesResponse result = wordsApi.GetDocumentProperties(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentProperty method, of class WordsApi.
*/
@Test
public void testGetDocumentProperty() {
System.out.println("GetDocumentProperty");
String name = "test_multi_pages.docx";
String propertyName = "Author";
String storage = "";
String folder = "";
try {
DocumentPropertyResponse result = wordsApi.GetDocumentProperty(name, propertyName, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PutUpdateDocumentProperty method, of class WordsApi.
*/
@Test
public void testPutUpdateDocumentProperty() {
System.out.println("PutUpdateDocumentProperty");
String name = "test_multi_pages.docx";
String propertyName = "Author";
String filename = "test_multi_pages.docx";
String storage = "";
String folder = "";
DocumentProperty body = new DocumentProperty();
body.setName("Author");
body.setValue("Imran Anwar");
try {
DocumentPropertyResponse result = wordsApi.PutUpdateDocumentProperty(name, propertyName, filename, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of DeleteUnprotectDocument method, of class WordsApi.
*/
@Test
public void testDeleteUnprotectDocument() {
System.out.println("DeleteUnprotectDocument");
String name = "test_multi_pages.docx";
String filename = "test_multi_pages.docx";
String storage = "";
String folder = "";
ProtectionRequest body = new ProtectionRequest();
body.setNewPassword("aspose");
body.setPassword("aspose");
body.setProtectionType("ReadOnly");
try {
// wordsApi.PutProtectDocument(name, filename, storage, folder, body);
// ProtectionDataResponse result = wordsApi.DeleteUnprotectDocument(name, filename, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentProtection method, of class WordsApi.
*/
@Test
public void testGetDocumentProtection() {
System.out.println("GetDocumentProtection");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
ProtectionDataResponse result = wordsApi.GetDocumentProtection(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostChangeDocumentProtection method, of class WordsApi.
*/
@Test
public void testPostChangeDocumentProtection() {
System.out.println("PostChangeDocumentProtection");
String name = "test_multi_pages.docx";
String filename = "test_multi_pages.docx";
String storage = "";
String folder = "";
ProtectionRequest body = new ProtectionRequest();
body.setNewPassword("");
try {
ProtectionDataResponse result = wordsApi.PostChangeDocumentProtection(name, filename, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PutProtectDocument method, of class WordsApi.
*/
@Test
public void testPutProtectDocument() {
System.out.println("PutProtectDocument");
String name = "test_multi_pages.docx";
String filename = "test_multi_pages.docx";
String storage = "";
String folder = "";
ProtectionRequest body = new ProtectionRequest();
try {
ProtectionDataResponse result = wordsApi.PutProtectDocument(name, filename, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostDocumentSaveAs method, of class WordsApi.
*/
@Test
public void testPostDocumentSaveAs() {
System.out.println("PostDocumentSaveAs");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
String xml = "<PdfSaveOptions>" +
"<SaveFormat>pdf</SaveFormat>" +
"<FileName>Output.pdf</FileName>" +
"<ImageCompression>Jpeg</ImageCompression>" +
"<JpegQuality>70</JpegQuality>" +
"<TextCompression>Flate</TextCompression>" +
"</PdfSaveOptions>";
try {
SaveResponse result = wordsApi.PostDocumentSaveAs(name, storage, folder, xml.getBytes("UTF-8"));
} catch (Exception apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PutDocumentSaveAsTiff method, of class WordsApi.
*/
@Test
public void testPutDocumentSaveAsTiff() {
System.out.println("PutDocumentSaveAsTiff");
String name = "test_multi_pages.docx";
String resultFile = "test.docx";
Boolean useAntiAliasing = false;
Boolean useHighQualityRendering = false;
Float imageBrightness = null;
String imageColorMode = null;
Float imageContrast =null;
String numeralFormat = null;
Integer pageCount = null;
Integer pageIndex = null;
String paperColor = null;
String pixelFormat = null;
Float resolution = null;
Float scale = null;
String tiffCompression = null;
String dmlRenderingMode = null;
String dmlEffectsRenderingMode = null;
String tiffBinarizationMethod = null;
String storage = null;
String folder = null;
Boolean zipOutput = false;
TiffSaveOptionsData body = new TiffSaveOptionsData();
body.setSaveFormat("tiff");
body.setFileName("abc.tiff");
try {
SaveResponse result = wordsApi.PutDocumentSaveAsTiff(name, resultFile, useAntiAliasing, useHighQualityRendering, imageBrightness, imageColorMode, imageContrast, numeralFormat, pageCount, pageIndex, paperColor, pixelFormat, resolution, scale, tiffCompression, dmlRenderingMode, dmlEffectsRenderingMode, tiffBinarizationMethod, storage, folder, zipOutput, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentStatistics method, of class WordsApi.
*/
@Test
public void testGetDocumentStatistics() {
System.out.println("GetDocumentStatistics");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
StatDataResponse result = wordsApi.GetDocumentStatistics(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of DeleteDocumentWatermark method, of class WordsApi.
*/
@Test
public void testDeleteDocumentWatermark() {
System.out.println("DeleteDocumentWatermark");
String name = "test_multi_pages.docx";
String filename = "test.docx";
String storage = "";
String folder = "";
try {
DocumentResponse result = wordsApi.DeleteDocumentWatermark(name, filename, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostInsertDocumentWatermarkImage method, of class WordsApi.
*/
@Test
public void testPostInsertDocumentWatermarkImage() {
System.out.println("PostInsertDocumentWatermarkImage");
String name = "test_multi_pages.docx";
String filename = "test.docx";
Double rotationAngle = null;
String image = "aspose-cloud.png";
String storage = null;
String folder = null;
File file;
try {
storageApi.PutCreate("aspose-cloud.png", "", "", new File(getClass().getResource("/aspose-cloud.png").toURI()));
file = new File(getClass().getResource("/aspose-cloud.png").toURI());
DocumentResponse result = wordsApi.PostInsertDocumentWatermarkImage(name, filename, rotationAngle, image, storage, folder, file);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
} catch(java.net.URISyntaxException uriExp){
System.out.println("uri exp:" + uriExp.getMessage());
}
}
/**
* Test of PostInsertDocumentWatermarkText method, of class WordsApi.
*/
@Test
public void testPostInsertDocumentWatermarkText() {
System.out.println("PostInsertDocumentWatermarkText");
String name = "test_multi_pages.docx";
String filename = "test.docx";
String text = "test";
Double rotationAngle = 60.0;
String storage = "";
String folder = "";
WatermarkText body = new WatermarkText();
body.setText("Aspose.com");
try {
DocumentResponse result = wordsApi.PostInsertDocumentWatermarkText(name, filename, text, rotationAngle, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentDrawingObjectByIndex method, of class WordsApi.
*/
@Test
public void testGetDocumentDrawingObjectByIndex() {
System.out.println("GetDocumentDrawingObjectByIndex");
String name = "test_multi_pages.docx";
Integer objectIndex = 0;
String storage = "";
String folder = "";
try {
ResponseMessage result = wordsApi.GetDocumentDrawingObjectByIndex(name, objectIndex, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentDrawingObjectByIndexWithFormat method, of class
* WordsApi.
*/
@Test
public void testGetDocumentDrawingObjectByIndexWithFormat() {
System.out.println("GetDocumentDrawingObjectByIndexWithFormat");
String name = "test_multi_pages.docx";
Integer objectIndex = 0;
String format = "png";
String storage = "";
String folder = "";
try {
ResponseMessage result = wordsApi.GetDocumentDrawingObjectByIndexWithFormat(name, objectIndex, format, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentDrawingObjectImageData method, of class WordsApi.
*/
@Test
public void testGetDocumentDrawingObjectImageData() {
System.out.println("GetDocumentDrawingObjectImageData");
String name = "test_multi_pages.docx";
Integer objectIndex = 0;
String storage = "";
String folder = "";
try {
ResponseMessage result = wordsApi.GetDocumentDrawingObjectImageData(name, objectIndex, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentDrawingObjectOleData method, of class WordsApi.
*/
@Test
public void testGetDocumentDrawingObjectOleData() {
System.out.println("GetDocumentDrawingObjectOleData");
String name = "sample_EmbeddedOLE.docx";
Integer objectIndex = 0;
String storage = "";
String folder = "";
try {
storageApi.PutCreate("sample_EmbeddedOLE.docx", "", "", new File(getClass().getResource("/sample_EmbeddedOLE.docx").toURI()));
ResponseMessage result = wordsApi.GetDocumentDrawingObjectOleData(name, objectIndex, storage, folder);
} catch (Exception apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentDrawingObjects method, of class WordsApi.
*/
@Test
public void testGetDocumentDrawingObjects() {
System.out.println("GetDocumentDrawingObjects");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
DrawingObjectsResponse result = wordsApi.GetDocumentDrawingObjects(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of DeleteFormField method, of class WordsApi.
*/
@Test
public void testDeleteFormField() {
System.out.println("DeleteFormField");
String name = "FormFilled.docx";
Integer sectionIndex = 0;
Integer paragraphIndex = 0;
Integer formfieldIndex = 0;
String destFileName = "FormFilledTest.docx";
String storage = "";
String folder = "";
try {
storageApi.PutCreate("FormFilled.docx", "", "", new File(getClass().getResource("/FormFilled.docx").toURI()));
SaaSposeResponse result = wordsApi.DeleteFormField(name, sectionIndex, paragraphIndex, formfieldIndex, destFileName, storage, folder);
} catch (Exception apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetFormField method, of class WordsApi.
*/
@Test
public void testGetFormField() {
System.out.println("GetFormField");
String name = "FormFilled.docx";
Integer sectionIndex = 0;
Integer paragraphIndex = 0;
Integer formfieldIndex = 0;
String storage = "";
String folder = "";
try {
storageApi.PutCreate("FormFilled.docx", "", "", new File(getClass().getResource("/FormFilled.docx").toURI()));
FormFieldResponse result = wordsApi.GetFormField(name, sectionIndex, paragraphIndex, formfieldIndex, storage, folder);
} catch (Exception apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostFormField method, of class WordsApi.
*/
@Test
public void testPostFormField() {
System.out.println("PostFormField");
String name = "FormFilled.docx";
Integer sectionIndex = 0;
Integer paragraphIndex = 0;
Integer formfieldIndex = 0;
String destFileName = "FormFilledTest.docx";
String storage = "";
String folder = "";
FormField body = null;
try {
/* storageApi.PutCreate("FormFilled.docx", "", "", new File(getClass().getResource("/FormFilled.docx").toURI()));
FormFieldResponse result = wordsApi.GetFormField(name, sectionIndex, paragraphIndex, formfieldIndex, storage, folder);
if(result!=null && result.getFormField() !=null){
body = result.getFormField();
body.setHelpText(body.getHelpText() + "updated");
FormFieldResponse result2 = wordsApi.PostFormField(name, sectionIndex, paragraphIndex, formfieldIndex, destFileName, storage, folder, body);
}
*/
} catch (Exception apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PutFormField method, of class WordsApi.
*/
@Test
public void testPutFormField() {
System.out.println("PutFormField");
String name = "FormFilled.docx";
Integer sectionIndex = 0;
Integer paragraphIndex = 0;
String insertBeforeNode = "";
String destFileName = "test.docx";
String storage = "";
String folder = "";
FormField body = new FormField();
body.setName("myfield");
body.setEnabled(true);
body.setCalculateOnExit(false);
try {
//FormFieldResponse result = wordsApi.PutFormField(name, sectionIndex, paragraphIndex, insertBeforeNode, destFileName, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of DeleteHeadersFooters method, of class WordsApi.
*/
@Test
public void testDeleteHeadersFooters() {
System.out.println("DeleteHeadersFooters");
String name = "test_multi_pages.docx";
String headersFootersTypes = null;
String filename = "test.docx";
String storage = "";
String folder = "";
try {
SaaSposeResponse result = wordsApi.DeleteHeadersFooters(name, headersFootersTypes, filename, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentHyperlinkByIndex method, of class WordsApi.
*/
@Test
public void testGetDocumentHyperlinkByIndex() {
System.out.println("GetDocumentHyperlinkByIndex");
String name = "test_doc.docx";
Integer hyperlinkIndex = 0;
String storage = "";
String folder = "";
try {
storageApi.PutCreate(name, "", "", new File(getClass().getResource("/test_doc.docx").toURI()));
HyperlinkResponse result = wordsApi.GetDocumentHyperlinkByIndex(name, hyperlinkIndex, storage, folder);
} catch (Exception apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentHyperlinks method, of class WordsApi.
*/
@Test
public void testGetDocumentHyperlinks() {
System.out.println("GetDocumentHyperlinks");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
HyperlinksResponse result = wordsApi.GetDocumentHyperlinks(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentFieldNames method, of class WordsApi.
*/
@Test
public void testGetDocumentFieldNames() {
System.out.println("GetDocumentFieldNames");
String name = "test_multi_pages.docx";
Boolean useNonMergeFields = false;
String storage = "";
String folder = "";
try {
FieldNamesResponse result = wordsApi.GetDocumentFieldNames(name, useNonMergeFields, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostDocumentExecuteMailMerge method, of class WordsApi.
*/
@Test
public void testPostDocumentExecuteMailMerge() {
System.out.println("PostDocumentExecuteMailMerge");
String name = "TestMailMerge.doc";
Boolean withRegions = false;
String mailMergeDataFile = null;
String cleanup = null;
String filename = "TestMailMergeResult.docx";
String storage = null;
String folder = null;
Boolean useWholeParagraphAsRegion = false;
File file;
try {
file = new File(getClass().getResource("/TestMailMergeData.txt").toURI());
//storageApi.PutCreate("TestMailMerge.doc", "", "", new File(getClass().getResource("/TestMailMerge.doc").toURI()));
DocumentResponse result = wordsApi.PostDocumentExecuteMailMerge(name, withRegions, mailMergeDataFile, cleanup, filename, storage, folder, useWholeParagraphAsRegion, file);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
} catch(java.net.URISyntaxException uriExp){
System.out.println("uri exp:" + uriExp.getMessage());
}
}
/**
* Test of GetDocumentParagraph method, of class WordsApi.
*/
@Test
public void testGetDocumentParagraph() {
System.out.println("GetDocumentParagraph");
String name = "test_multi_pages.docx";
Integer index = 1;
String storage = "";
String folder = "";
try {
ParagraphResponse result = wordsApi.GetDocumentParagraph(name, index, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentParagraphRun method, of class WordsApi.
*/
@Test
public void testGetDocumentParagraphRun() {
System.out.println("GetDocumentParagraphRun");
String name = "test_multi_pages.docx";
Integer index = 0;
Integer runIndex = 0;
String storage = "";
String folder = "";
try {
RunResponse result = wordsApi.GetDocumentParagraphRun(name, index, runIndex, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentParagraphRunFont method, of class WordsApi.
*/
@Test
public void testGetDocumentParagraphRunFont() {
System.out.println("GetDocumentParagraphRunFont");
String name = "test_multi_pages.docx";
Integer index = 0;
Integer runIndex = 0;
String storage = "";
String folder = "";
try {
FontResponse result = wordsApi.GetDocumentParagraphRunFont(name, index, runIndex, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentParagraphs method, of class WordsApi.
*/
@Test
public void testGetDocumentParagraphs() {
System.out.println("GetDocumentParagraphs");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
ParagraphLinkCollectionResponse result = wordsApi.GetDocumentParagraphs(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostDocumentParagraphRunFont method, of class WordsApi.
*/
@Test
public void testPostDocumentParagraphRunFont() {
System.out.println("PostDocumentParagraphRunFont");
String name = "test_multi_pages.docx";
Integer index = 0;
Integer runIndex = 0;
String storage = "";
String folder = "";
String filename = "test.docx";
Font body = new Font();
body.setBold(true);
try {
FontResponse result = wordsApi.PostDocumentParagraphRunFont(name, index, runIndex, storage, folder, filename, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of AcceptAllRevisions method, of class WordsApi.
*/
@Test
public void testAcceptAllRevisions() {
System.out.println("AcceptAllRevisions");
String name = "test_multi_pages.docx";
String filename = "test.docx";
String storage = "";
String folder = "";
try {
RevisionsModificationResponse result = wordsApi.AcceptAllRevisions(name, filename, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of RejectAllRevisions method, of class WordsApi.
*/
@Test
public void testRejectAllRevisions() {
System.out.println("RejectAllRevisions");
String name = "test_multi_pages.docx";
String filename = "test.docx";
String storage = "";
String folder = "";
try {
RevisionsModificationResponse result = wordsApi.RejectAllRevisions(name, filename, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetSection method, of class WordsApi.
*/
@Test
public void testGetSection() {
System.out.println("GetSection");
String name = "test_multi_pages.docx";
Integer sectionIndex = 0;
String storage = "";
String folder = "";
try {
SectionResponse result = wordsApi.GetSection(name, sectionIndex, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetSectionPageSetup method, of class WordsApi.
*/
@Test
public void testGetSectionPageSetup() {
System.out.println("GetSectionPageSetup");
String name = "test_multi_pages.docx";
Integer sectionIndex = 0;
String storage = "";
String folder = "";
try {
SectionPageSetupResponse result = wordsApi.GetSectionPageSetup(name, sectionIndex, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetSections method, of class WordsApi.
*/
@Test
public void testGetSections() {
System.out.println("GetSections");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
SectionLinkCollectionResponse result = wordsApi.GetSections(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of UpdateSectionPageSetup method, of class WordsApi.
*/
@Test
public void testUpdateSectionPageSetup() {
System.out.println("UpdateSectionPageSetup");
String name = "test_multi_pages.docx";
Integer sectionIndex = 0;
String storage = "";
String folder = "";
String filename = "";
PageSetup body = new PageSetup();
body.setRtlGutter(true);
try {
SectionPageSetupResponse result = wordsApi.UpdateSectionPageSetup(name, sectionIndex, storage, folder, filename, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of GetDocumentTextItems method, of class WordsApi.
*/
@Test
public void testGetDocumentTextItems() {
System.out.println("GetDocumentTextItems");
String name = "test_multi_pages.docx";
String storage = "";
String folder = "";
try {
TextItemsResponse result = wordsApi.GetDocumentTextItems(name, storage, folder);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
/**
* Test of PostReplaceText method, of class WordsApi.
*/
@Test
public void testPostReplaceText() {
System.out.println("PostReplaceText");
String name = "test_multi_pages.docx";
String filename = "test_multi_pages_result.docx";
String storage = "";
String folder = "";
ReplaceTextRequest body = new ReplaceTextRequest();
body.setOldValue("aspose");
body.setNewValue("aspose.com");
try {
ReplaceTextResponse result = wordsApi.PostReplaceText(name, filename, storage, folder, body);
} catch (ApiException apiException) {
System.out.println("exp:" + apiException.getMessage());
assertNull(apiException);
}
}
} |
package com.bandwidth.iris.sdk;
import com.bandwidth.iris.sdk.model.*;
import com.bandwidth.iris.sdk.utils.XmlUtils;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
public class OrderTests extends BaseModelTests {
@Test
public void testCreate() throws Exception {
String ordersUrl = "/v1.0/accounts/accountId/orders";
stubFor(post(urlMatching(ordersUrl))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/xml")
.withBody(IrisClientTestUtils.validOrderResponseXml)));
Order o = new Order();
o.setName("A New Order");
ExistingTelephoneNumberOrderType existingTelephoneNumberOrderType = new ExistingTelephoneNumberOrderType();
existingTelephoneNumberOrderType.getTelephoneNumberList().add("2052865046");
o.setExistingTelephoneNumberOrderType(existingTelephoneNumberOrderType);
OrderResponse createdOrder = Order.create(getDefaultClient(), o);
assertEquals(createdOrder.getOrder().getid(), "someid");
assertEquals(createdOrder.getOrder().getExistingTelephoneNumberOrderType().getTelephoneNumberList().get(0),
"2052865046");
assertEquals(createdOrder.getOrder().getName(), "A New Order");
}
@Test
public void testGet() throws Exception {
String url = "/v1.0/accounts/accountId/orders/someid";
stubFor(get(urlMatching(url))
.willReturn(aResponse()
.withStatus(200)
.withBody(IrisClientTestUtils.validOrderResponseXml)));
OrderResponse orderResponse = Order.get(getDefaultClient(), "someid");
assertEquals(orderResponse.getOrder().getid(), "someid");
assertEquals(orderResponse.getOrder().getExistingTelephoneNumberOrderType().getTelephoneNumberList().get(0),
"2052865046");
assertEquals(orderResponse.getOrder().getName(), "A New Order");
}
@Test
public void testPartialOrderStatusCheck() throws Exception {
String url = "/v1.0/accounts/accountId/orders/someid";
stubFor(get(urlMatching(url))
.willReturn(aResponse()
.withStatus(200)
.withBody(IrisClientTestUtils.validPartialOrderStatusXml)));
OrderResponse orderResponse = Order.get(getDefaultClient(), "someid");
assertEquals("2055551212", orderResponse.getOrder().getExistingTelephoneNumberOrderType().getTelephoneNumberList().get(0));
assertNotNull(orderResponse.getOrderCompletedDate());
assertEquals(0, orderResponse.getPendingQuantity());
assertEquals(1, orderResponse.getFailedNumbers().size());
assertEquals("2055551212", orderResponse.getFailedNumbers().get(0).getFullNumber());
}
@Test
public void testAddNote() throws Exception {
String url = "/v1.0/accounts/accountId/orders/someid";
String notesUrl = url + "/notes";
stubFor(get(urlMatching(url))
.willReturn(aResponse()
.withStatus(200)
.withBody(IrisClientTestUtils.validOrderResponseXml)));
stubFor(put(urlMatching(notesUrl))
.willReturn(aResponse()
.withStatus(200)));
OrderResponse orderResponse = Order.get(getDefaultClient(), "someid");
Order order = orderResponse.getOrder();
Note note = new Note();
note.setDescription("This is a new note");
order.addNote(note);
}
@Test
public void testGetNotes() throws Exception {
String url = "/v1.0/accounts/accountId/orders/someid";
String notesUrl = url + "/notes";
stubFor(get(urlMatching(url))
.willReturn(aResponse()
.withStatus(200)
.withBody(IrisClientTestUtils.validOrderResponseXml)));
stubFor(get(urlMatching(notesUrl))
.willReturn(aResponse()
.withStatus(200)
.withBody(IrisClientTestUtils.validOrderNotesResponseXml)));
OrderResponse orderResponse = Order.get(getDefaultClient(), "someid");
Order order = orderResponse.getOrder();
Notes notes = order.getNotes();
assertNotNull(notes);
assertEquals(1, notes.getNotes().size());
assertEquals("Adding a note", notes.getNotes().get(0).getDescription());
}
@Test
public void testParseErrorXml() throws Exception {
OrderResponse response = XmlUtils.fromXml("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><OrderResponse><Order><Name>A New Order</Name><OrderCreateDate>2015-06-19T13:21:56.677Z</OrderCreateDate><BackOrderRequested>false</BackOrderRequested><id>cc5a89ab-19bd-4e62-b8c7-eabe914191e9</id><ExistingTelephoneNumberOrderType><ReservationIdList/><TelephoneNumberList><TelephoneNumber>2052865046</TelephoneNumber></TelephoneNumberList></ExistingTelephoneNumberOrderType><PartialAllowed>false</PartialAllowed><SiteId>2297</SiteId></Order><OrderStatus>RECEIVED</OrderStatus></OrderResponse>", OrderResponse.class);
assertEquals("RECEIVED", response.getOrderStatus());
}
@Test
public void rateCenterSearchAndOrderTypeTestCreate() throws Exception {
Order order = new Order();
order.setName("Test RateCenterSearchAndOrderType Order");
RateCenterSearchAndOrderType rateCenterSearchAndOrderType = new RateCenterSearchAndOrderType();
rateCenterSearchAndOrderType.setEnableLCA(false);
rateCenterSearchAndOrderType.setQuantity(1);
rateCenterSearchAndOrderType.setRateCenter("DOVER"); // No inventory available here
rateCenterSearchAndOrderType.setState("NH");
order.setRateCenterSearchAndOrderType(rateCenterSearchAndOrderType);
OrderResponse createdOrder = Order.create(getDefaultClient(), order);
assertEquals(createdOrder.getOrder().getName(), "Test RateCenterSearchAndOrderType Order");
}
} |
package org.codingmatters.poom.services.domain.property.query;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.codingmatters.poom.services.domain.property.query.events.*;
import org.codingmatters.poom.services.domain.property.query.parsers.PropertyFilterLexer;
import org.codingmatters.poom.services.domain.property.query.parsers.PropertyFilterParser;
import org.codingmatters.poom.services.domain.property.query.parsers.PropertySortLexer;
import org.codingmatters.poom.services.domain.property.query.parsers.PropertySortParser;
import org.codingmatters.poom.services.domain.property.query.validation.FilterPropertyValidation;
import org.codingmatters.poom.services.domain.property.query.validation.InvalidPropertyException;
import org.codingmatters.poom.services.domain.property.query.validation.SortPropertyValidation;
import java.util.function.Predicate;
public class PropertyQueryParser {
static public Builder builder() {
return new Builder();
}
static public class Builder {
private Predicate<String> leftHandSidePropertyValidator;
private Predicate<String> rightHandSidePropertyValidator;
public Builder leftHandSidePropertyValidator(Predicate<String> propertyValidator) {
this.leftHandSidePropertyValidator = propertyValidator;
return this;
}
public Builder rightHandSidePropertyValidator(Predicate<String> propertyValidator) {
this.rightHandSidePropertyValidator = propertyValidator;
return this;
}
public PropertyQueryParser build(FilterEvents events) {
return this.build(events, SortEvents.noop());
}
public PropertyQueryParser build(SortEvents events) {
return this.build(FilterEvents.noop(), events);
}
public PropertyQueryParser build(FilterEvents filterEvents, SortEvents sortEvents) {
return new PropertyQueryParser(
filterEvents,
sortEvents,
this.leftHandSidePropertyValidator,
this.rightHandSidePropertyValidator);
}
public PropertyQueryParser build() {
return this.build(FilterEvents.noop(), SortEvents.noop());
}
}
private final FilterEvents filterEvents;
private final SortEvents sortEvents;
private final Predicate<String> leftHandSidePropertyValidator;
private final Predicate<String> rightHandSidePropertyValidator;
private PropertyQueryParser(FilterEvents filterEvents, SortEvents sortEvents, Predicate<String> leftHandSidePropertyValidator, Predicate<String> rightHandSidePropertyValidator) {
this.filterEvents = filterEvents;
this.sortEvents = sortEvents;
this.leftHandSidePropertyValidator = leftHandSidePropertyValidator != null ? leftHandSidePropertyValidator : s -> true;
this.rightHandSidePropertyValidator = rightHandSidePropertyValidator != null ? rightHandSidePropertyValidator : s -> true;
}
public void parse(PropertyQuery query) throws InvalidPropertyException, FilterEventException, SortEventException {
if(query != null && query.filter() != null) {
this.parseFilter(query.filter());
}
if(query != null && query.sort() != null) {
this.parseSort(query.sort());
}
}
public void parseFilter(String filter) throws InvalidPropertyException, FilterEventException {
ReportErrorListener errors = new ReportErrorListener();
CodePointCharStream input = CharStreams.fromString(filter);
PropertyFilterLexer lexer = new PropertyFilterLexer(input);
lexer.addErrorListener(errors);
CommonTokenStream tokens = new CommonTokenStream(lexer);
PropertyFilterParser parser = new PropertyFilterParser(tokens);
parser.addErrorListener(errors);
FilterPropertyValidation propertyValidation = new FilterPropertyValidation(this.leftHandSidePropertyValidator, this.rightHandSidePropertyValidator);
PropertyFilterParser.CriterionContext criterion = parser.criterion();
if(! errors.report().isEmpty()) {
throw new FilterEventException(String.format("%d syntax error%s found while parsing filter \"%s\" : %s",
errors.report().size(),
errors.report().size() > 1 ? "s" : "",
filter, errors.report()));
}
propertyValidation.visit(criterion);
propertyValidation.isValid();
try {
tokens.seek(0);
new FilterEventsGenerator(this.filterEvents).visit(parser.criterion());
} catch (FilterEventError e) {
throw new FilterEventException(e);
}
}
private void parseSort(String sort) throws SortEventException, InvalidPropertyException {
ReportErrorListener errors = new ReportErrorListener();
CodePointCharStream input = CharStreams.fromString(sort);
PropertySortLexer lexer = new PropertySortLexer(input);
lexer.addErrorListener(errors);
CommonTokenStream tokens = new CommonTokenStream(lexer);
PropertySortParser parser = new PropertySortParser(tokens);
parser.addErrorListener(errors);
SortPropertyValidation propertyValidation = new SortPropertyValidation(this.leftHandSidePropertyValidator);
PropertySortParser.SortExpressionContext expression = parser.sortExpression();
if(! errors.report().isEmpty()) {
throw new SortEventException(String.format("%d syntax error%s found while parsing sort \"%s\" : %s",
errors.report().size(), errors.report().size() > 1 ? "s" : "",
sort, errors.report()
));
}
propertyValidation.visit(expression);
propertyValidation.isValid();
try {
tokens.seek(0);
new SortEventsGenerator(this.sortEvents).visit(parser.sortExpression());
} catch (SortEventError e) {
throw new SortEventException(e);
}
}
} |
package jolie.net.http;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.zip.InflaterInputStream;
import java.util.zip.GZIPInputStream;
import jolie.Interpreter;
import jolie.lang.parse.Scanner;
import jolie.net.ChannelClosingException;
public class HttpParser
{
private static final String HTTP = "HTTP";
private static final String GET = "GET";
private static final String POST = "POST";
private static final String PUT = "PUT";
private static final String HEAD = "HEAD";
private static final String DELETE = "DELETE";
private static final String TRACE = "TRACE";
private static final String CONNECT = "CONNECT";
private static final String OPTIONS = "OPTIONS";
private static final String PATCH = "PATCH";
private static final Pattern cookiesSplitPattern = Pattern.compile( ";" );
private static final Pattern cookieNameValueSplitPattern = Pattern.compile( "=" );
private final HttpScanner scanner;
private Scanner.Token token;
private void getToken()
throws IOException
{
token = scanner.getToken();
}
public HttpParser( InputStream istream )
throws IOException
{
scanner = new HttpScanner( istream, URI.create( "urn:network" ) );
}
private void tokenAssert( Scanner.TokenType type )
throws IOException
{
if ( token.isNot( type ) )
throwException();
}
private void throwException()
throws IOException
{
throw new IOException( "Malformed HTTP header" );
}
private void parseHeaderProperties( HttpMessage message )
throws IOException
{
String name, value;
getToken();
HttpMessage.Cookie cookie;
while( token.is( Scanner.TokenType.ID ) ) {
name = token.content().toLowerCase();
getToken();
tokenAssert( Scanner.TokenType.COLON );
value = scanner.readLine();
if ( "set-cookie".equals( name ) ) {
//cookie = parseSetCookie( value );
if ( (cookie=parseSetCookie( value )) != null ) {
message.addSetCookie( cookie );
}
} else if ( "cookie".equals( name ) ) {
String ss[] = value.split( ";" );
for( String s : ss ) {
String nv[] = s.trim().split( "=" );
if ( nv.length > 1 ) {
message.addCookie( nv[0], nv[1] );
}
}
} else if ( "user-agent".equals( name ) ) {
message.setUserAgent( value );
message.setProperty( name, value );
} else {
message.setProperty( name, value );
}
getToken();
}
}
private HttpMessage.Cookie parseSetCookie( String cookieString )
{
String ss[] = cookiesSplitPattern.split( cookieString );
if ( cookieString.isEmpty() == false && ss.length > 0 ) {
boolean secure = false;
String domain = "";
String path = "";
String expires = "";
String nameValue[] = cookieNameValueSplitPattern.split( ss[ 0 ], 2 );
if ( ss.length > 1 ) {
String kv[];
for( int i = 1; i < ss.length; i++ ) {
if ( "secure".equals( ss[ i ] ) ) {
secure = true;
} else {
kv = cookieNameValueSplitPattern.split( ss[ i ], 2 );
if ( kv.length > 1 ) {
kv[ 0 ] = kv[ 0 ].trim();
if ( "expires".equalsIgnoreCase( kv[ 0 ] ) ) {
expires = kv[ 1 ];
} else if ( "path".equalsIgnoreCase( kv[ 0 ] ) ) {
path = kv[ 1 ];
} else if ( "domain".equalsIgnoreCase( kv[ 0 ] ) ) {
domain = kv[ 1 ];
}
}
}
}
}
return new HttpMessage.Cookie(
nameValue[0],
nameValue[1],
domain,
path,
expires,
secure
);
}
return null;
}
private HttpMessage parseRequest()
throws IOException
{
HttpMessage message = null;
if ( token.isKeyword( GET ) ) {
message = new HttpMessage( HttpMessage.Type.GET );
} else if ( token.isKeyword( POST ) ) {
message = new HttpMessage( HttpMessage.Type.POST );
} else if ( token.isKeyword( HEAD ) ) {
message = new HttpMessage( HttpMessage.Type.HEAD );
} else if ( token.isKeyword( DELETE ) ) {
message = new HttpMessage( HttpMessage.Type.DELETE );
} else if ( token.isKeyword( PUT ) ) {
message = new HttpMessage( HttpMessage.Type.PUT );
} else if ( token.is( Scanner.TokenType.EOF ) ) {
throw new ChannelClosingException( "[http] Remote host closed connection." ); // It's not a real message, the client is just closing a connection.
} else {
throw new UnsupportedMethodException( "Unknown/Unsupported HTTP request type: "
+ token.content() + "(" + token.type() + ")" );
}
message.setRequestPath( URLDecoder.decode( scanner.readWord().substring( 1 ), HttpUtils.URL_DECODER_ENC ) );
getToken();
if ( !token.isKeyword( HTTP ) )
throw new UnsupportedHttpVersionException( "Invalid HTTP header: expected HTTP version" );
if ( scanner.currentCharacter() != '/' )
throw new UnsupportedHttpVersionException( "Expected HTTP version" );
String version = scanner.readWord();
if ( "1.0".equals( version ) )
message.setVersion( HttpMessage.Version.HTTP_1_0 );
else if ( "1.1".equals( version ) )
message.setVersion( HttpMessage.Version.HTTP_1_1 );
else
throw new UnsupportedHttpVersionException( "Unsupported HTTP version specified: " + version );
return message;
}
private HttpMessage parseMessageType()
throws IOException
{
if ( token.isKeyword( HTTP ) ) {
return parseResponse();
} else {
return parseRequest();
}
}
private HttpMessage parseResponse()
throws IOException
{
HttpMessage message = new HttpMessage( HttpMessage.Type.RESPONSE );
if ( scanner.currentCharacter() != '/' )
throw new IOException( "Expected HTTP version" );
String version = scanner.readWord();
if ( !( "1.1".equals( version ) || "1.0".equals( version ) ) )
throw new IOException( "Unsupported HTTP version specified: " + version );
getToken();
tokenAssert( Scanner.TokenType.INT );
message.setStatusCode( Integer.parseInt( token.content() ) );
message.setReason( scanner.readLine() );
return message;
}
@SuppressWarnings( "empty-statement" )
public static void blockingRead( InputStream stream, byte[] buffer, int offset, int length )
throws IOException
{
int r = 0;
while( (r+=stream.read( buffer, offset+r, length-r )) < length );
}
private static final int BLOCK_SIZE = 1024;
public static byte[] readAll( InputStream stream )
throws IOException
{
int r = -1;
ByteArrayOutputStream c = new ByteArrayOutputStream();
byte[] tmp = new byte[ BLOCK_SIZE ];
while( (r=stream.read( tmp, 0, BLOCK_SIZE )) != -1 ) {
c.write( tmp, 0, r );
tmp = new byte[ BLOCK_SIZE ];
}
return c.toByteArray();
}
private void readContent( HttpMessage message )
throws IOException
{
boolean chunked = false;
int contentLength = -1;
String p = message.getProperty( "transfer-encoding" );
if ( p != null && p.startsWith( "chunked" ) ) {
// Transfer-encoding has the precedence over Content-Length
chunked = true;
} else {
p = message.getProperty( "content-length" );
if ( p != null && !p.isEmpty() ) {
try {
contentLength = Integer.parseInt( p );
if ( contentLength == 0 ) {
message.setContent( new byte[0] );
return;
}
} catch( NumberFormatException e ) {
throw new IOException( "Illegal Content-Length value " + p );
}
}
}
byte buffer[] = null;
InputStream stream = scanner.inputStream();
if ( chunked ) {
// Link: http://tools.ietf.org/html/rfc2616#section-3.6.1
List< byte[] > chunks = new ArrayList< byte[] > ();
int l = -1, totalLen = 0;
scanner.readChar();
do {
// the chunk header contains the size in hex format
// and could contain additional parameters which we ignore atm
String chunkHeader = scanner.readLine( false );
String chunkSize = chunkHeader.split( ";" )[0];
try {
l = Integer.parseInt( chunkSize, 16 );
} catch ( NumberFormatException e ) {
throw new IOException( "Illegal chunk size " + chunkSize );
}
// parses the real chunk with the specified size, follwed by CR-LF
if ( l > 0 ) {
totalLen += l;
byte[] chunk = new byte[ l ];
blockingRead( stream, chunk, 0, l );
chunks.add( chunk );
scanner.readChar();
scanner.eatSeparators();
}
} while ( l > 0 );
// parse optional trailer (additional HTTP headers)
parseHeaderProperties( message );
ByteBuffer b = ByteBuffer.allocate( totalLen );
for( byte[] c : chunks )
b.put( c );
buffer = b.array();
} else if ( contentLength > 0 ) {
buffer = new byte[ contentLength ];
blockingRead( stream, buffer, 0, contentLength );
} else {
HttpMessage.Version version = message.version();
if ( // Will the connection be closed?
// HTTP 1.1
((version == null || version.equals( HttpMessage.Version.HTTP_1_1 ))
&&
message.getPropertyOrEmptyString( "connection" ).equalsIgnoreCase( "close" ))
||
// HTTP 1.0
(version.equals( HttpMessage.Version.HTTP_1_0 )
&&
!message.getPropertyOrEmptyString( "connection" ).equalsIgnoreCase( "keep-alive" )
)
) {
buffer = readAll( scanner.inputStream() );
}
}
if ( buffer != null ) {
p = message.getProperty( "content-encoding" );
if ( p != null ) {
if ( p.contains( "deflate" ) ) {
buffer = readAll( new InflaterInputStream( new ByteArrayInputStream( buffer ) ) );
} else if ( p.contains( "gzip" ) ) {
buffer = readAll( new GZIPInputStream( new ByteArrayInputStream( buffer ) ) );
} else if ( !p.equals( "identity" ) ) {
throw new UnsupportedEncodingException( "Unrecognized Content-Encoding: " + p );
}
}
message.setContent( buffer );
}
}
public HttpMessage parse()
throws IOException
{
getToken();
HttpMessage message = parseMessageType();
parseHeaderProperties( message );
readContent( message );
scanner.eatSeparatorsUntilEOF();
return message;
}
} |
package com.jcabi.github.mock;
import com.jcabi.github.Coordinates;
import com.jcabi.github.Github;
import com.jcabi.github.Issue;
import com.jcabi.github.Label;
import com.jcabi.github.Repo;
import java.util.Collections;
import javax.json.Json;
import org.hamcrest.CustomMatcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Test case for {@link MkIssue}.
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @checkstyle MultipleStringLiterals (500 lines)
*/
@SuppressWarnings("PMD.TooManyMethods")
public final class MkIssueTest {
/**
* MkIssue can open and close.
* @throws Exception If some problem inside
*/
@Test
public void opensAndCloses() throws Exception {
final Issue issue = this.issue();
MatcherAssert.assertThat(
new Issue.Smart(issue).isOpen(),
Matchers.is(true)
);
new Issue.Smart(issue).close();
MatcherAssert.assertThat(
new Issue.Smart(issue).isOpen(),
Matchers.is(false)
);
}
/**
* MkIssue can point to an absent pull request.
* @throws Exception If some problem inside
*/
@Test
public void pointsToAnEmptyPullRequest() throws Exception {
final Issue issue = this.issue();
MatcherAssert.assertThat(
new Issue.Smart(issue).isPull(),
Matchers.is(false)
);
}
/**
* MkIssue can show an issue author.
* @throws Exception If some problem inside
*/
@Test
public void showsIssueAuthor() throws Exception {
final Issue issue = this.issue();
MatcherAssert.assertThat(
new Issue.Smart(issue).author().login(),
Matchers.notNullValue()
);
}
/**
* MkIssue can change title.
* @throws Exception If some problem inside
*/
@Test
public void changesTitle() throws Exception {
final Issue issue = this.issue();
new Issue.Smart(issue).title("hey, works?");
MatcherAssert.assertThat(
new Issue.Smart(issue).title(),
Matchers.startsWith("hey, ")
);
}
/**
* MkIssue can change body.
* @throws Exception If some problem inside
*/
@Test
public void changesBody() throws Exception {
final Issue issue = this.issue();
new Issue.Smart(issue).body("hey, body works?");
MatcherAssert.assertThat(
new Issue.Smart(issue).body(),
Matchers.startsWith("hey, b")
);
}
/**
* MkIssue can expose all properties.
* @throws Exception If some problem inside
*/
@Test
public void exponsesProperties() throws Exception {
final Issue.Smart issue = new Issue.Smart(this.issue());
MatcherAssert.assertThat(issue.createdAt(), Matchers.notNullValue());
MatcherAssert.assertThat(issue.updatedAt(), Matchers.notNullValue());
MatcherAssert.assertThat(issue.htmlUrl(), Matchers.notNullValue());
}
/**
* MkIssue can list its labels.
* @throws Exception If some problem inside
*/
@Test
public void listsReadOnlyLabels() throws Exception {
final Issue issue = this.issue();
final String tag = "test-tag";
issue.repo().labels().create(tag, "c0c0c0");
issue.labels().add(Collections.singletonList(tag));
MatcherAssert.assertThat(
new Issue.Smart(issue).roLabels().iterate(),
Matchers.<Label>hasItem(
new CustomMatcher<Label>("label just created") {
@Override
public boolean matches(final Object item) {
return Label.class.cast(item).name().equals(tag);
}
}
)
);
}
/**
* MkIssue should be able to compare different instances.
* @throws Exception when a problem occurs.
*/
@Test
public void canCompareInstances() throws Exception {
final MkIssue less = new MkIssue(
new MkStorage.InFile(),
"login-less",
Mockito.mock(Coordinates.class),
1
);
final MkIssue greater = new MkIssue(
new MkStorage.InFile(),
"login-greater",
Mockito.mock(Coordinates.class),
2
);
MatcherAssert.assertThat(
less.compareTo(greater),
Matchers.lessThan(0)
);
MatcherAssert.assertThat(
greater.compareTo(less),
Matchers.greaterThan(0)
);
}
/**
* MkIssue can remember it's author.
* @throws Exception when a problem occurs.
*/
@Test
public void canRememberItsAuthor() throws Exception {
final MkGithub first = new MkGithub("first");
final Github second = first.relogin("second");
final Repo repo = first.repos().create(
Json.createObjectBuilder().add("name", "test").build()
);
final int number = second.repos()
.get(repo.coordinates())
.issues()
.create("", "")
.number();
final Issue issue = first.repos()
.get(repo.coordinates())
.issues()
.get(number);
MatcherAssert.assertThat(
new Issue.Smart(issue).author().login(),
Matchers.is("second")
);
}
/**
* Can check if issue exists.
* @throws Exception if any error occurs.
*/
@Test
public void canCheckIfIssueExists() throws Exception {
MatcherAssert.assertThat(this.issue().exists(), Matchers.is(true));
}
/**
* MkIssue.exists() return false on nonexistent issues.
* @throws Exception if any error occurs.
*/
@Test
public void canCheckNonExistentIssue() throws Exception {
MatcherAssert.assertThat(
new MkIssue(
new MkStorage.InFile(),
"login",
new Coordinates.Simple("user", "repo"),
1
).exists(),
Matchers.is(false)
);
}
/**
* MkIssue can assign a user.
* @throws Exception If some problem inside
*/
@Test
public void assignsUser() throws Exception {
final Issue.Smart issue = new Issue.Smart(this.issue());
issue.assign("walter");
MatcherAssert.assertThat(
issue.assignee().login(),
Matchers.startsWith("wal")
);
}
/**
* Create an issue to work with.
* @return Issue just created
* @throws Exception If some problem inside
*/
private Issue issue() throws Exception {
return new MkGithub().repos().create(
Json.createObjectBuilder().add("name", "test").build()
).issues().create("hey", "how are you?");
}
} |
package org.sagebionetworks.repo.manager;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sagebionetworks.repo.model.AuthorizationConstants.ACCESS_AND_COMPLIANCE_TEAM_NAME;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.sagebionetworks.evaluation.dao.EvaluationDAO;
import org.sagebionetworks.evaluation.manager.EvaluationManager;
import org.sagebionetworks.evaluation.model.Evaluation;
import org.sagebionetworks.repo.model.ACCESS_TYPE;
import org.sagebionetworks.repo.model.AccessApproval;
import org.sagebionetworks.repo.model.AccessApprovalDAO;
import org.sagebionetworks.repo.model.AccessControlListDAO;
import org.sagebionetworks.repo.model.AccessRequirement;
import org.sagebionetworks.repo.model.AccessRequirementDAO;
import org.sagebionetworks.repo.model.ActivityDAO;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.Node;
import org.sagebionetworks.repo.model.NodeDAO;
import org.sagebionetworks.repo.model.NodeInheritanceDAO;
import org.sagebionetworks.repo.model.NodeQueryDao;
import org.sagebionetworks.repo.model.PaginatedResults;
import org.sagebionetworks.repo.model.Reference;
import org.sagebionetworks.repo.model.RestrictableObjectDescriptor;
import org.sagebionetworks.repo.model.RestrictableObjectType;
import org.sagebionetworks.repo.model.TermsOfUseAccessApproval;
import org.sagebionetworks.repo.model.TermsOfUseAccessRequirement;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.User;
import org.sagebionetworks.repo.model.UserGroup;
import org.sagebionetworks.repo.model.UserGroupDAO;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.dao.FileHandleDao;
import org.sagebionetworks.repo.model.message.ObjectType;
import org.sagebionetworks.repo.model.provenance.Activity;
import org.sagebionetworks.repo.web.NotFoundException;
public class AuthorizationManagerImplUnitTest {
NodeInheritanceDAO mockNodeInheritanceDAO;
AccessControlListDAO mockAccessControlListDAO;
AccessRequirementDAO mockAccessRequirementDAO;
AccessApprovalDAO mockAccessApprovalDAO;
EvaluationManager mockEvaluationManager;
ActivityDAO mockActivityDAO;
NodeQueryDao mockNodeQueryDao;
NodeDAO mockNodeDAO;
UserManager mockUserManager;
FileHandleDao mockFileHandleDao;
EvaluationDAO mockEvaluationDAO;
private static String USER_PRINCIPAL_ID = "123";
private static String EVAL_OWNER_PRINCIPAL_ID = "987";
private static String EVAL_ID = "1234567";
private AuthorizationManagerImpl authorizationManager = null;
private UserInfo userInfo = null;
private UserInfo adminUser = null;
private Evaluation evaluation = null;
private UserGroup actTeam = null;
private UserGroupDAO mockUserGroupDAO = null;
@Before
public void setUp() throws Exception {
mockNodeInheritanceDAO = mock(NodeInheritanceDAO.class);
mockAccessControlListDAO = mock(AccessControlListDAO.class);
mockAccessRequirementDAO = mock(AccessRequirementDAO.class);
mockAccessApprovalDAO = mock(AccessApprovalDAO.class);
mockActivityDAO = mock(ActivityDAO.class);
mockNodeQueryDao = mock(NodeQueryDao.class);
mockNodeDAO = mock(NodeDAO.class);
mockUserManager = mock(UserManager.class);
mockEvaluationManager = mock(EvaluationManager.class);
mockFileHandleDao = mock(FileHandleDao.class);
mockEvaluationDAO = mock(EvaluationDAO.class);
mockUserGroupDAO = Mockito.mock(UserGroupDAO.class);
authorizationManager = new AuthorizationManagerImpl(
mockNodeInheritanceDAO, mockAccessControlListDAO,
mockAccessRequirementDAO, mockAccessApprovalDAO,
mockActivityDAO, mockNodeQueryDao,
mockNodeDAO, mockUserManager, mockFileHandleDao,
mockEvaluationDAO, mockUserGroupDAO);
actTeam = new UserGroup();
actTeam.setId("101");
actTeam.setIsIndividual(false);
actTeam.setName(ACCESS_AND_COMPLIANCE_TEAM_NAME);
when(mockUserGroupDAO.findGroup(ACCESS_AND_COMPLIANCE_TEAM_NAME, false)).thenReturn(actTeam);
userInfo = new UserInfo(false);
UserGroup userInfoGroup = new UserGroup();
userInfoGroup.setId(USER_PRINCIPAL_ID);
userInfo.setIndividualGroup(userInfoGroup);
User user = new User();
user.setId("not_anonymous");
userInfo.setUser(user);
userInfo.setGroups(new ArrayList<UserGroup>());
adminUser = new UserInfo(true);
UserGroup adminInfoGroup = new UserGroup();
adminInfoGroup.setId("456");
adminUser.setIndividualGroup(adminInfoGroup);
Node mockNode = mock(Node.class);
when(mockNode.getCreatedByPrincipalId()).thenReturn(-1l);
when(mockNodeDAO.getNode(any(String.class))).thenReturn(mockNode);
evaluation = new Evaluation();
evaluation.setId(EVAL_ID);
evaluation.setOwnerId(EVAL_OWNER_PRINCIPAL_ID);
when(mockEvaluationDAO.get(EVAL_ID)).thenReturn(evaluation);
when(mockAccessRequirementDAO.unmetAccessRequirements(
any(RestrictableObjectDescriptor.class), any(Collection.class), eq(ACCESS_TYPE.PARTICIPATE))).
thenReturn(new ArrayList<Long>());
}
private PaginatedResults<Reference> generateQueryResults(int numResults, int total) {
PaginatedResults<Reference> results = new PaginatedResults<Reference>();
List<Reference> resultList = new ArrayList<Reference>();
for(int i=0; i<numResults; i++) {
Reference ref = new Reference();
ref.setTargetId("nodeId");
resultList.add(ref);
}
results.setResults(resultList);
results.setTotalNumberOfResults(total);
return results;
}
@Test
public void testCanAccessActivityPagination() throws Exception {
Activity act = new Activity();
String actId = "1";
int limit = 1000;
int total = 2001;
int offset = 0;
// create as admin, try to access as user so fails access and tests pagination
act.setId(actId);
act.setCreatedBy(adminUser.getIndividualGroup().getId());
when(mockActivityDAO.get(actId)).thenReturn(act);
PaginatedResults<Reference> results1 = generateQueryResults(limit, total);
PaginatedResults<Reference> results2 = generateQueryResults(total-limit, total);
PaginatedResults<Reference> results3 = generateQueryResults(total-(2*limit), total);
when(mockActivityDAO.getEntitiesGeneratedBy(actId, limit, offset)).thenReturn(results1);
when(mockActivityDAO.getEntitiesGeneratedBy(actId, limit, offset+limit)).thenReturn(results2);
when(mockActivityDAO.getEntitiesGeneratedBy(actId, limit, offset+(2*limit))).thenReturn(results3);
boolean canAccess = authorizationManager.canAccessActivity(userInfo, actId);
verify(mockActivityDAO).getEntitiesGeneratedBy(actId, limit, offset);
verify(mockActivityDAO).getEntitiesGeneratedBy(actId, limit, offset+limit);
verify(mockActivityDAO).getEntitiesGeneratedBy(actId, limit, offset+(2*limit));
assertFalse(canAccess);
}
@Test
public void testCanAccessActivityPaginationSmallResultSet() throws Exception {
Activity act = new Activity();
String actId = "1";
int limit = 1000;
int offset = 0;
// create as admin, try to access as user so fails access and tests pagination
act.setId(actId);
act.setCreatedBy(adminUser.getIndividualGroup().getId());
when(mockActivityDAO.get(actId)).thenReturn(act);
PaginatedResults<Reference> results1 = generateQueryResults(1, 1);
when(mockActivityDAO.getEntitiesGeneratedBy(actId, limit, offset)).thenReturn(results1);
boolean canAccess = authorizationManager.canAccessActivity(userInfo, actId);
verify(mockActivityDAO).getEntitiesGeneratedBy(actId, limit, offset);
assertFalse(canAccess);
}
@Test
public void testCanAccessRawFileHandleByCreator(){
// The admin can access anything
String creator = userInfo.getIndividualGroup().getId();
assertTrue("Admin should have access to all FileHandles",authorizationManager.canAccessRawFileHandleByCreator(adminUser, creator));
assertTrue("Creator should have access to their own FileHandles", authorizationManager.canAccessRawFileHandleByCreator(userInfo, creator));
// Set the creator to be the admin this time.
creator = adminUser.getIndividualGroup().getId();
assertFalse("Only the creator (or admin) should have access a FileHandle", authorizationManager.canAccessRawFileHandleByCreator(userInfo, creator));
}
@Test
public void testCanAccessRawFileHandleById() throws NotFoundException{
// The admin can access anything
String creator = userInfo.getIndividualGroup().getId();
String fileHandlId = "3333";
when(mockFileHandleDao.getHandleCreator(fileHandlId)).thenReturn(creator);
assertTrue("Admin should have access to all FileHandles",authorizationManager.canAccessRawFileHandleById(adminUser, fileHandlId));
assertTrue("Creator should have access to their own FileHandles", authorizationManager.canAccessRawFileHandleById(userInfo, fileHandlId));
// change the users id
UserInfo notTheCreatoro = new UserInfo(false);
UserGroup userInfoGroup = new UserGroup();
userInfoGroup.setId("999999");
notTheCreatoro.setIndividualGroup(userInfoGroup);
assertFalse("Only the creator (or admin) should have access a FileHandle", authorizationManager.canAccessRawFileHandleById(notTheCreatoro, fileHandlId));
}
@Test
public void testCanAccessWithObjectTypeAdmin() throws DatastoreException, NotFoundException{
// Admin can always access
assertTrue("An admin can access any entity",authorizationManager.canAccess(adminUser, "syn123", ObjectType.ENTITY, ACCESS_TYPE.DELETE));
assertTrue("An admin can access any competition",authorizationManager.canAccess(adminUser, "334", ObjectType.EVALUATION, ACCESS_TYPE.DELETE));
}
@Test
public void testCanAccessWithObjectTypeEntityAllow() throws DatastoreException, NotFoundException{
String entityId = "syn123";
// Setup to allow.
when(mockAccessControlListDAO.canAccess(any(Collection.class), any(String.class), any(ACCESS_TYPE.class))).thenReturn(true);
assertTrue("User should have acces to do anything with this entity", authorizationManager.canAccess(userInfo, entityId, ObjectType.ENTITY, ACCESS_TYPE.DELETE));
}
@Test
public void testCanAccessWithObjectTypeEntityDeny() throws DatastoreException, NotFoundException{
String entityId = "syn123";
// Setup to deny.
when(mockAccessControlListDAO.canAccess(any(Collection.class), any(String.class), any(ACCESS_TYPE.class))).thenReturn(false);
assertFalse("User should not have acces to do anything with this entity", authorizationManager.canAccess(userInfo, entityId, ObjectType.ENTITY, ACCESS_TYPE.DELETE));
}
@Test
public void testCanAccessWithObjectTypeCompetitionNonCompAdmin() throws DatastoreException, UnauthorizedException, NotFoundException{
// This user is not an admin but the should be able to read.
assertTrue("User should have read access to any competition.", authorizationManager.canAccess(userInfo, EVAL_ID, ObjectType.EVALUATION, ACCESS_TYPE.READ));
assertFalse("User should not have delete access to this competition.", authorizationManager.canAccess(userInfo, EVAL_ID, ObjectType.EVALUATION, ACCESS_TYPE.DELETE));
assertTrue("A user should have PARTICIPATE access to an evaluation", authorizationManager.canAccess(userInfo, EVAL_ID, ObjectType.EVALUATION, ACCESS_TYPE.PARTICIPATE));
}
@Test
public void testCanAccessWithObjectTypeCompetitionCompAdmin() throws DatastoreException, UnauthorizedException, NotFoundException{
// make the user the creator of the evaluation
userInfo.getIndividualGroup().setId(EVAL_OWNER_PRINCIPAL_ID);
assertTrue("An evaluation admin should have read access", authorizationManager.canAccess(userInfo, EVAL_ID, ObjectType.EVALUATION, ACCESS_TYPE.READ));
assertTrue("An evaluation admin should have delete access", authorizationManager.canAccess(userInfo, EVAL_ID, ObjectType.EVALUATION, ACCESS_TYPE.DELETE));
assertTrue("An evaluation admin should have PARTICIPATE access to an evaluation", authorizationManager.canAccess(userInfo, EVAL_ID, ObjectType.EVALUATION, ACCESS_TYPE.PARTICIPATE));
}
@Test
public void testCanAccessWithObjectTypeCompetitionUnmetAccessRequirement() throws Exception {
when(mockAccessRequirementDAO.unmetAccessRequirements(
any(RestrictableObjectDescriptor.class), any(Collection.class), eq(ACCESS_TYPE.PARTICIPATE))).
thenReturn(Arrays.asList(new Long[]{101L}));
// takes a little more to mock admin access to evaluation
String origEvaluationOwner = evaluation.getOwnerId();
evaluation.setOwnerId(userInfo.getIndividualGroup().getId());
assertFalse("admin shouldn't have PARTICIPATE access if there are unmet requirements", authorizationManager.canAccess(userInfo, EVAL_ID, ObjectType.EVALUATION, ACCESS_TYPE.PARTICIPATE));
evaluation.setOwnerId(origEvaluationOwner);
assertFalse("non-admin shouldn't have PARTICIPATE access if there are unmet requirements", authorizationManager.canAccess(userInfo, EVAL_ID, ObjectType.EVALUATION, ACCESS_TYPE.PARTICIPATE));
}
@Test
public void testVerifyACTTeamMembershipOrIsAdmin_Admin() {
UserInfo adminInfo = new UserInfo(true);
assertTrue(authorizationManager.isACTTeamMemberOrAdmin(adminInfo));
}
@Test
public void testVerifyACTTeamMembershipOrIsAdmin_ACT() {
userInfo.getGroups().add(actTeam);
assertTrue(authorizationManager.isACTTeamMemberOrAdmin(userInfo));
}
@Test
public void testVerifyACTTeamMembershipOrIsAdmin_NONE() {
assertFalse(authorizationManager.isACTTeamMemberOrAdmin(userInfo));
}
@Test
public void testVerifyACTTeamMembershipOrCanCreateOrEdit_isAdmin() throws Exception {
List<String> ids = new ArrayList<String>(Arrays.asList(new String[]{"101"}));
assertTrue(authorizationManager.isACTTeamMemberOrCanCreateOrEdit(adminUser, ids));
}
@Test
public void testVerifyACTTeamMembershipOrCanCreateOrEdit_ACT() throws Exception {
userInfo.getGroups().add(actTeam);
List<String> ids = new ArrayList<String>(Arrays.asList(new String[]{"101"}));
assertTrue(authorizationManager.isACTTeamMemberOrCanCreateOrEdit(userInfo, ids));
}
@Test
public void testVerifyACTTeamMembershipOrCanCreateOrEdit_multiple() throws Exception {
List<String> ids = new ArrayList<String>(Arrays.asList(new String[]{"101", "102"}));
assertFalse(authorizationManager.isACTTeamMemberOrCanCreateOrEdit(userInfo, ids));
}
@Test
public void testVerifyACTTeamMembershipOrCanCreateOrEdit_editAccess() throws Exception {
List<String> ids = new ArrayList<String>(Arrays.asList(new String[]{"101"}));
when(mockNodeInheritanceDAO.getBenefactor("101")).thenReturn("101");
when(mockAccessControlListDAO.canAccess(eq(userInfo.getGroups()), eq("101"), any(ACCESS_TYPE.class))).thenReturn(true);
assertTrue(authorizationManager.isACTTeamMemberOrCanCreateOrEdit(userInfo, ids));
}
@Test
public void testVerifyACTTeamMembershipOrCanCreateOrEdit_none() throws Exception {
List<String> ids = new ArrayList<String>(Arrays.asList(new String[]{"101"}));
when(mockNodeInheritanceDAO.getBenefactor("101")).thenReturn("101");
when(mockAccessControlListDAO.canAccess(eq(userInfo.getGroups()), eq("101"), any(ACCESS_TYPE.class))).thenReturn(false);
assertFalse(authorizationManager.isACTTeamMemberOrCanCreateOrEdit(userInfo, ids));
}
private static RestrictableObjectDescriptor createEntitySubjectId() {
RestrictableObjectDescriptor subjectId = new RestrictableObjectDescriptor();
subjectId.setType(RestrictableObjectType.ENTITY);
subjectId.setId("101");
return subjectId;
}
private AccessRequirement createEntityAccessRequirement() throws Exception {
TermsOfUseAccessRequirement ar = new TermsOfUseAccessRequirement();
ar.setSubjectIds(Arrays.asList(new RestrictableObjectDescriptor[]{createEntitySubjectId()}));
ar.setId(1234L);
when(mockAccessRequirementDAO.get(ar.getId().toString())).thenReturn(ar);
return ar;
}
private AccessApproval createEntityAccessApproval() throws Exception {
AccessRequirement ar = createEntityAccessRequirement();
TermsOfUseAccessApproval aa = new TermsOfUseAccessApproval();
aa.setAccessorId(userInfo.getIndividualGroup().getId());
aa.setId(656L);
aa.setRequirementId(ar.getId());
when(mockAccessApprovalDAO.get(aa.getId().toString())).thenReturn(aa);
return aa;
}
private static RestrictableObjectDescriptor createEvaluationSubjectId() {
RestrictableObjectDescriptor subjectId = new RestrictableObjectDescriptor();
subjectId.setType(RestrictableObjectType.EVALUATION);
subjectId.setId(EVAL_ID);
return subjectId;
}
private AccessRequirement createEvaluationAccessRequirement() throws Exception {
TermsOfUseAccessRequirement ar = new TermsOfUseAccessRequirement();
ar.setSubjectIds(Arrays.asList(new RestrictableObjectDescriptor[]{createEvaluationSubjectId()}));
ar.setId(1234L);
when(mockAccessRequirementDAO.get(ar.getId().toString())).thenReturn(ar);
return ar;
}
private AccessApproval createEvaluationAccessApproval() throws Exception {
AccessRequirement ar = createEvaluationAccessRequirement();
TermsOfUseAccessApproval aa = new TermsOfUseAccessApproval();
aa.setAccessorId(userInfo.getIndividualGroup().getId());
aa.setId(656L);
aa.setRequirementId(ar.getId());
when(mockAccessApprovalDAO.get(aa.getId().toString())).thenReturn(aa);
return aa;
}
@Test
public void testCanAccessEntityAccessRequirement() throws Exception {
AccessRequirement ar = createEntityAccessRequirement();
assertFalse(authorizationManager.canAccess(userInfo, ar.getId().toString(), ObjectType.ACCESS_REQUIREMENT, ACCESS_TYPE.UPDATE));
userInfo.getGroups().add(actTeam);
assertTrue(authorizationManager.canAccess(userInfo, "1234", ObjectType.ACCESS_REQUIREMENT, ACCESS_TYPE.UPDATE));
}
@Test
public void testCanAccessEvaluationAccessRequirement() throws Exception {
AccessRequirement ar = createEvaluationAccessRequirement();
assertFalse(authorizationManager.canAccess(userInfo, ar.getId().toString(), ObjectType.ACCESS_REQUIREMENT, ACCESS_TYPE.UPDATE));
userInfo.getIndividualGroup().setId(EVAL_OWNER_PRINCIPAL_ID);
assertTrue(authorizationManager.canAccess(userInfo, ar.getId().toString(), ObjectType.ACCESS_REQUIREMENT, ACCESS_TYPE.UPDATE));
}
@Test
public void testCanAccessEntityAccessApproval() throws Exception {
AccessApproval aa = createEntityAccessApproval();
assertFalse(authorizationManager.canAccess(userInfo, aa.getId().toString(), ObjectType.ACCESS_APPROVAL, ACCESS_TYPE.READ));
userInfo.getGroups().add(actTeam);
assertTrue(authorizationManager.canAccess(userInfo, aa.getId().toString(), ObjectType.ACCESS_APPROVAL, ACCESS_TYPE.READ));
}
@Test
public void testCanAccessEvaluationAccessApproval() throws Exception {
AccessApproval aa = createEvaluationAccessApproval();
assertFalse(authorizationManager.canAccess(userInfo, aa.getId().toString(), ObjectType.ACCESS_APPROVAL, ACCESS_TYPE.READ));
userInfo.getIndividualGroup().setId(EVAL_OWNER_PRINCIPAL_ID);
assertTrue(authorizationManager.canAccess(userInfo, aa.getId().toString(), ObjectType.ACCESS_APPROVAL, ACCESS_TYPE.READ));
}
@Test
public void testCanCreateEntityAccessRequirement() throws Exception {
AccessRequirement ar = createEntityAccessRequirement();
assertFalse(authorizationManager.canCreateAccessRequirement(userInfo, ar));
userInfo.getGroups().add(actTeam);
assertTrue(authorizationManager.canCreateAccessRequirement(userInfo, ar));
userInfo.getGroups().remove(actTeam);
assertFalse(authorizationManager.canCreateAccessRequirement(userInfo, ar));
// give user edit ability on entity 101
when(mockNodeInheritanceDAO.getBenefactor("101")).thenReturn("101");
when(mockAccessControlListDAO.canAccess(eq(userInfo.getGroups()), eq("101"), any(ACCESS_TYPE.class))).thenReturn(true);
assertTrue(authorizationManager.canCreateAccessRequirement(userInfo, ar));
}
@Test
public void testCanAccessEntityAccessApprovalsForSubject() throws Exception {
AccessApproval aa = createEntityAccessApproval();
assertFalse(authorizationManager.canAccessAccessApprovalsForSubject(userInfo, createEntitySubjectId(), ACCESS_TYPE.READ));
userInfo.getGroups().add(actTeam);
assertTrue(authorizationManager.canAccessAccessApprovalsForSubject(userInfo, createEntitySubjectId(), ACCESS_TYPE.READ));
}
@Test
public void testCanAccessEvaluationAccessApprovalsForSubject() throws Exception {
AccessApproval aa = createEvaluationAccessApproval();
assertFalse(authorizationManager.canAccessAccessApprovalsForSubject(userInfo, createEvaluationSubjectId(), ACCESS_TYPE.READ));
userInfo.getIndividualGroup().setId(EVAL_OWNER_PRINCIPAL_ID);
assertTrue(authorizationManager.canAccessAccessApprovalsForSubject(userInfo, createEvaluationSubjectId(), ACCESS_TYPE.READ));
}
} |
package ca.etsmtl.applets.etsmobile.ui.fragment;
import java.util.Vector;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import ca.etsmtl.applets.etsmobile.ApplicationManager;
import ca.etsmtl.applets.etsmobile.http.DataManager;
import ca.etsmtl.applets.etsmobile.http.DataManager.SignetMethods;
import ca.etsmtl.applets.etsmobile.model.ListeDeCours;
import ca.etsmtl.applets.etsmobile.model.ListeDeSessions;
import ca.etsmtl.applets.etsmobile.ui.adapter.NoteAdapter;
import ca.etsmtl.applets.etsmobile.ui.adapter.NotesSessionItem;
import ca.etsmtl.applets.etsmobile.ui.adapter.SessionCoteAdapter;
import ca.etsmtl.applets.etsmobile.ui.adapter.SessionCoteItem;
import ca.etsmtl.applets.etsmobile.ui.fragment.HttpFragment;
import ca.etsmtl.applets.etsmobile2.R;
import com.octo.android.robospice.persistence.exception.SpiceException;
public class NotesFragment extends HttpFragment {
private ListView mListView;
private NoteAdapter adapter;
private SessionCoteItem[] sessionCoteItemArray;
private NotesSessionItem[] notesSession;
private ListeDeCours listeDeCours;
private ListeDeSessions listeDeSessions;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_note, container, false);
mListView = (ListView) v.findViewById(R.id.activity_note_listview);
return v;
}
@Override
public void onStart() {
super.onStart();
DataManager datamanager = DataManager.getInstance(getActivity());
datamanager.getDataFromSignet(SignetMethods.LIST_COURS, ApplicationManager.userCredentials, this, "");
datamanager.getDataFromSignet(SignetMethods.LIST_SESSION, ApplicationManager.userCredentials, this, "");
}
@Override
public void onRequestFailure(SpiceException e) {
}
@Override
public void onRequestSuccess(Object o) {
if (o != null)
if (o instanceof ListeDeCours) {
listeDeCours = (ListeDeCours)o;
refreshList();
}else if( o instanceof ListeDeSessions){
listeDeSessions = (ListeDeSessions)o;
refreshList();
}
}
@Override
void updateUI() {
// TODO Auto-generated method stub
}
private void refreshList(){
if(listeDeCours!=null && listeDeSessions !=null){
if(listeDeCours.liste.size()!=0){
sessionCoteItemArray= new SessionCoteItem[listeDeCours.liste.size()];
Vector<SessionCoteItem> vector = new Vector<SessionCoteItem>();
Vector<NotesSessionItem> vectoNoteSession = new Vector<NotesSessionItem>();
String sessionString ="";
int index =0;
for (int i=0;i<listeDeCours.liste.size();i++) {
if(sessionString.equals("")){
sessionString = listeDeCours.liste.get(i).session;
}
//Permet le regroupement par session, on ajoute le vecteur des cours dans la session
if(!sessionString.equals(listeDeCours.liste.get(i).session) ||i==listeDeCours.liste.size()-1){
if(i==listeDeCours.liste.size()-1 && sessionString.equals(listeDeCours.liste.get(i).session)){
vector.add(new SessionCoteItem(listeDeCours.liste.get(i).sigle, listeDeCours.liste.get(i).cote, listeDeCours.liste.get(i).groupe));
}
sessionCoteItemArray= new SessionCoteItem[vector.size()];
int j=0;
for (SessionCoteItem sessionCoteItem : vector) {
sessionCoteItemArray[j] = sessionCoteItem;
j++;
}
vectoNoteSession.add(new NotesSessionItem(listeDeSessions.liste.get(index).auLong , new SessionCoteAdapter(getActivity(), sessionCoteItemArray)));
index+=1;
vector.clear();
if(i==listeDeCours.liste.size()-1 && !sessionString.equals(listeDeCours.liste.get(i).session)){
SessionCoteItem sessionCoteItem=new SessionCoteItem(listeDeCours.liste.get(i).sigle, listeDeCours.liste.get(i).cote, listeDeCours.liste.get(i).groupe);
vectoNoteSession.add(new NotesSessionItem(listeDeSessions.liste.get(index).auLong , new SessionCoteAdapter(getActivity(), new SessionCoteItem[]{sessionCoteItem})));
sessionString = listeDeCours.liste.get(i).session;
}
sessionString = listeDeCours.liste.get(i).session;
}
vector.add(new SessionCoteItem(listeDeCours.liste.get(i).sigle, listeDeCours.liste.get(i).cote, listeDeCours.liste.get(i).groupe));
}
int i = vectoNoteSession.size()-1;
notesSession = new NotesSessionItem[vectoNoteSession.size()];
for (NotesSessionItem notesSessionItem : vectoNoteSession) {
notesSession[i] = notesSessionItem;
i
}
getActivity().runOnUiThread(new Runnable(){
@Override
public void run() {
adapter = new NoteAdapter(getActivity(), R.layout.row_note_menu, notesSession);
mListView.setAdapter(adapter);
}
});
}
}
}
} |
package com.stanfy.gsonxml.test;
import static org.junit.Assert.assertEquals;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.Test;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.stanfy.gsonxml.GsonXmlBuilder;
public class ListsTest extends AbstractXmlTest {
/** Test XML. */
public static final String TEST_XML =
"<places>"
+ " <place id=\"1\" lat=\"0.25\" long=\"0.26\">"
+ " <name><Place></name>"
+ " </place>"
+ " <place id=\"2\" lat=\"0.27\" long=\"0.28\">"
+ " <name>Place 2</name>"
+ " </place>"
+ "</places>";
public static final String TEST_XML_WITH_HEADER =
"<places>"
+ " <error>0</error>"
+ " <place id=\"1\" lat=\"0.25\" long=\"0.26\">"
+ " <name><Place></name>"
+ " </place>"
+ " <place id=\"2\" lat=\"0.27\" long=\"0.28\">"
+ " <name>Place 2</name>"
+ " </place>"
+ "</places>";
public static final String TEST_XML_WITH_HEADER_AND_PRIMITIVES_LIST =
"<responce>"
+ " <error>0</error>"
+ " <list>item0</list>"
+ " <list>item1</list>"
+ "</responce>";
/** Place object. */
public static class Place {
@SerializedName("@id")
long id;
@SerializedName("@lat")
double lat;
@SerializedName("@long")
double lon;
String name;
}
/** Container. */
public static class PlacesContainer {
String error;
List<Place> places;
}
public static class ListWithHeader {
String error;
List<Object> list;
}
@Test
public void listsTest() {
final List<Place> places = gsonXml.fromXml(TEST_XML, new TypeToken<List<Place>>() {}.getType());
assertPlaces(places);
}
@Test
public void mixedListTest() throws JsonSyntaxException, JsonIOException, FileNotFoundException {
final ListWithHeader listWithHeader =
new GsonXmlBuilder()
.setXmlParserCreator(SimpleXmlReaderTest.PARSER_CREATOR)
.setSameNameLists(true)
.setSkipRoot(false)
.create()
.fromXml(TEST_XML_WITH_HEADER_AND_PRIMITIVES_LIST, ListWithHeader.class);
assertEquals("0", listWithHeader.error);
assertEquals("item0", listWithHeader.list.get(0));
assertEquals("item1", listWithHeader.list.get(1));
}
private void assertPlaces(final List<Place> places) {
assertEquals(2, places.size());
assertEquals(1, places.get(0).id);
assertEquals(2, places.get(1).id);
assertEquals(0.26, places.get(0).lon, 0.00001);
}
@Test
public void skipTest() {
final PlacesContainer placesC = new GsonXmlBuilder()
.setXmlParserCreator(SimpleXmlReaderTest.PARSER_CREATOR)
.setSkipRoot(false)
.create()
.fromXml(TEST_XML_WITH_HEADER, PlacesContainer.class);
assertPlaces(placesC.places);
}
} |
package ca.mcgill.mcb.pcingola.bigDataScript.exec;
import java.util.ArrayList;
import java.util.HashMap;
import ca.mcgill.mcb.pcingola.bigDataScript.util.Timer;
/**
* A system that can execute an Exec
*
* @author pcingola
*/
public abstract class Executioner extends Thread {
protected boolean debug = true;
protected boolean verbose = true;
protected boolean running;
protected int hostIdx = 0;
ArrayList<Task> tasksToRun;
HashMap<String, Task> tasksDone, tasksRunning;
public Executioner() {
super();
tasksToRun = new ArrayList<Task>();
tasksDone = new HashMap<String, Task>();
tasksRunning = new HashMap<String, Task>();
}
/**
* Queue an Exec and return a the id
* @return
*/
public void add(Task task) {
if (verbose) Timer.showStdErr("Queuing task '" + task.getId() + "'");
tasksToRun.add(task);
}
/**
* Task finished executing
* @param id
* @return
*/
public synchronized boolean finished(String id) {
if (verbose) Timer.showStdErr("Finished task '" + id + "'");
Task task = tasksRunning.get(id);
if (task == null) {
if (debug) Timer.showStdErr("Finished task: ERROR, cannot find task '" + id + "'");
return false;
}
// Move from 'running' to 'done'
tasksRunning.remove(task);
tasksDone.put(id, task);
return true;
}
public synchronized boolean hasTaskToRun() {
return !tasksToRun.isEmpty() || !tasksRunning.isEmpty();
}
/**
* Is this executioner running?
* @return
*/
public boolean isRunning() {
return running;
}
/**
* Is this executioner valid?
* An Executioner may expire or become otherwise invalid
*
* @return
*/
public boolean isValid() {
return isRunning();
}
/**
* Stop executioner and kill all tasks
*/
public void kill() {
running = false;
// Kill all tasks
ArrayList<Task> tokill = new ArrayList<Task>();
tokill.addAll(tasksRunning.values());
for (Task t : tokill)
kill(t.getId());
}
/**
* Kill a task
*
* @param id : Task id
* @return true if it was killed
*/
public boolean kill(String id) {
if (verbose) Timer.showStdErr("Killing task '" + id + "'");
Task task = tasksRunning.get(id);
if (task == null) {
// Try tasks to run
if (remove(id)) return true;
// No such task
if (verbose) Timer.showStdErr("Killing task: ERROR, cannot find task '" + id + "'");
return false;
}
// Running task? Kill and move to 'done'
boolean ok = killTask(task);
finished(id);
return ok;
}
/**
* Kill a task
*/
protected abstract boolean killTask(Task task);
/**
* Remove a task from the list of tasks to run
* @param id
* @return
*/
public synchronized boolean remove(String id) {
// Find task number
int delete = -1;
for (int i = 0; (i < tasksToRun.size()) && (delete < 0); i++)
if (tasksToRun.get(i).getId().equals(id)) delete = i;
// Remove task number
if (delete > 0) {
tasksToRun.remove(delete);
return true;
}
return false;
}
/**
* Run a task
* @param task
* @return
*/
public synchronized boolean run(Task task) {
if (verbose) Timer.showStdErr("Running task '" + task.getId() + "'");
boolean ok = runTask(task);
if (ok) {
tasksRunning.put(task.getId(), task);
} else if (verbose) Timer.showStdErr("Running task: ERROR, could not run task '" + task.getId() + "'");
return ok;
}
/**
* Run a task
* @param task
* @return
*/
protected abstract boolean runTask(Task task);
public void setDebug(boolean debug) {
this.debug = debug;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
} |
package de.ids_mannheim.korap;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.ids_mannheim.korap.index.Indexer;
/**
* @author margaretha
*
*/
public class TestIndexer {
private Logger logger = LoggerFactory.getLogger(TestIndexer.class);
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private String info = "usage: Krill indexer";
private File outputDirectory = new File("test-index");
@Test
public void testArguments () throws IOException {
Indexer.main(new String[] { "-c", "src/test/resources/krill.properties",
"-i", "src/test/resources/bzk" });
assertEquals("Indexed 1 file.", outputStream.toString());
}
@Test
public void testOutputArgument () throws IOException {
Indexer.main(new String[] { "-c", "src/test/resources/krill.properties",
"-i", "src/test/resources/bzk", "-o", "test-output"});
assertEquals("Indexed 1 file.", outputStream.toString());
}
@Test
public void testMultipleInputFiles () throws IOException {
Indexer.main(new String[] { "-c", "src/test/resources/krill.properties",
"-i", "src/test/resources/wiki" });
assertEquals("Indexed 14 files.", outputStream.toString());
}
@Test
public void testMultipleInputDirectories () throws IOException {
Indexer.main(new String[] { "-c", "src/test/resources/krill.properties",
"-i",
"src/test/resources/bzk;src/test/resources/goe;src/test/resources/sgbr",
"-o", "test-index" });
assertEquals("Indexed 5 files.", outputStream.toString());
}
@Test
public void testEmptyArgument () throws IOException {
Indexer.main(new String[] {});
logger.info(outputStream.toString());
assertEquals(true, outputStream.toString().startsWith(info));
}
@Test
public void testMissingConfig () throws IOException {
Indexer.main(new String[] { "-i", "src/test/resources/bzk",
"-o test-index" });
logger.info(outputStream.toString());
assertEquals(true, outputStream.toString().startsWith(info));
}
@Test
public void testMissingInput () throws IOException {
Indexer.main(new String[] { "-c", "src/test/resources/krill.properties",
"-o", "test-index" });
logger.info(outputStream.toString());
assertEquals(true, outputStream.toString().startsWith(info));
}
@Before
public void setOutputStream () {
System.setOut(new PrintStream(outputStream));
}
@After
public void cleanOutputStream () {
System.setOut(null);
}
@Before
public void cleanOutputDirectory () {
if (outputDirectory.exists()) {
logger.debug("Output directory exists");
deleteFile(outputDirectory);
}
}
private void deleteFile (File path) {
if (path.isDirectory()) {
File file;
for (String filename : path.list()) {
file = new File(path + "/" + filename);
deleteFile(file);
logger.debug(file.getAbsolutePath());
}
}
path.delete();
}
} |
package mho.wheels.misc;
import mho.wheels.iterables.ExhaustiveProvider;
import mho.wheels.iterables.IterableProvider;
import mho.wheels.iterables.RandomProvider;
import mho.wheels.ordering.Ordering;
import mho.wheels.structures.Pair;
import org.junit.Test;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Optional;
import java.util.Random;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.misc.Readers.*;
import static org.junit.Assert.*;
public class ReadersProperties {
private static boolean USE_RANDOM;
private static int LIMIT;
private static IterableProvider P;
private static void initialize() {
if (USE_RANDOM) {
P = new RandomProvider(new Random(0x6af477d9a7e54fcaL));
LIMIT = 1000;
} else {
P = ExhaustiveProvider.INSTANCE;
LIMIT = 10000;
}
}
@Test
public void testAllProperties() {
System.out.println("Readers properties");
for (boolean useRandom : Arrays.asList(false, true)) {
System.out.println("\ttesting " + (useRandom ? "randomly" : "exhaustively"));
USE_RANDOM = useRandom;
propertiesReadBoolean();
propertiesFindBooleanIn();
propertiesReadOrdering();
propertiesFindOrderingIn();
propertiesReadRoundingMode();
propertiesFindRoundingModeIn();
}
System.out.println("Done");
}
private static void propertiesReadBoolean() {
initialize();
System.out.println("testing readBoolean(String) properties...");
for (String s : take(LIMIT, P.strings())) {
readBoolean(s);
}
for (boolean b : take(LIMIT, P.booleans())) {
Optional<Boolean> ob = readBoolean(Boolean.toString(b));
assertEquals(Boolean.toString(b), ob.get(), b);
}
}
private static void propertiesFindBooleanIn() {
initialize();
System.out.println("testing findBooleanIn(String) properties...");
for (String s : take(LIMIT, P.strings())) {
findBooleanIn(s);
}
Iterable<Pair<String, Integer>> ps = P.dependentPairsLogarithmic(P.strings(), s -> range(0, s.length()));
Iterable<String> ss;
if (P instanceof ExhaustiveProvider) {
ss = map(
p -> {
assert p.a != null;
assert p.a.a != null;
assert p.a.b != null;
return take(p.a.b, p.a.a) + p.b + drop(p.a.b, p.a.a);
},
((ExhaustiveProvider) P).pairsLogarithmicOrder(ps, P.booleans())
);
} else {
ss = map(
p -> {
assert p.a != null;
assert p.a.a != null;
assert p.a.b != null;
return take(p.a.b, p.a.a) + p.b + drop(p.a.b, p.a.a);
},
P.pairs(ps, P.booleans())
);
}
for (String s : take(LIMIT, ss)) {
Optional<Pair<Boolean, Integer>> op = findBooleanIn(s);
Pair<Boolean, Integer> p = op.get();
assertNotNull(s, p.a);
assertNotNull(s, p.b);
assertTrue(s, p.b >= 0 && p.b < s.length());
assertTrue(s, s.substring(p.b).startsWith(p.a.toString()));
}
}
private static void propertiesReadOrdering() {
initialize();
System.out.println("testing readOrdering(String) properties...");
for (String s : take(LIMIT, P.strings())) {
readOrdering(s);
}
for (Ordering o : take(LIMIT, P.orderings())) {
Optional<Ordering> oo = readOrdering(o.toString());
assertEquals(o.toString(), oo.get(), o);
}
}
private static void propertiesFindOrderingIn() {
initialize();
System.out.println("testing findOrderingIn(String) properties...");
for (String s : take(LIMIT, P.strings())) {
findOrderingIn(s);
}
Iterable<Pair<String, Integer>> ps = P.dependentPairsLogarithmic(P.strings(), s -> range(0, s.length()));
Iterable<String> ss;
if (P instanceof ExhaustiveProvider) {
ss = map(
p -> {
assert p.a != null;
assert p.a.a != null;
assert p.a.b != null;
return take(p.a.b, p.a.a) + p.b + drop(p.a.b, p.a.a);
},
((ExhaustiveProvider) P).pairsLogarithmicOrder(ps, P.orderings())
);
} else {
ss = map(
p -> {
assert p.a != null;
assert p.a.a != null;
assert p.a.b != null;
return take(p.a.b, p.a.a) + p.b + drop(p.a.b, p.a.a);
},
P.pairs(ps, P.orderings())
);
}
for (String s : take(LIMIT, ss)) {
Optional<Pair<Ordering, Integer>> op = findOrderingIn(s);
Pair<Ordering, Integer> p = op.get();
assertNotNull(s, p.a);
assertNotNull(s, p.b);
assertTrue(s, p.b >= 0 && p.b < s.length());
assertTrue(s, s.substring(p.b).startsWith(p.a.toString()));
}
}
private static void propertiesReadRoundingMode() {
initialize();
System.out.println("testing readRoundingMode(String) properties...");
for (String s : take(LIMIT, P.strings())) {
readRoundingMode(s);
}
for (RoundingMode rm : take(LIMIT, P.roundingModes())) {
Optional<RoundingMode> orm = readRoundingMode(rm.toString());
assertEquals(rm.toString(), orm.get(), rm);
}
}
private static void propertiesFindRoundingModeIn() {
initialize();
System.out.println("testing findRoundingModeIn(String) properties...");
for (String s : take(LIMIT, P.strings())) {
findRoundingModeIn(s);
}
Iterable<Pair<String, Integer>> ps = P.dependentPairsLogarithmic(P.strings(), s -> range(0, s.length()));
Iterable<String> ss;
if (P instanceof ExhaustiveProvider) {
ss = map(
p -> {
assert p.a != null;
assert p.a.a != null;
assert p.a.b != null;
return take(p.a.b, p.a.a) + p.b + drop(p.a.b, p.a.a);
},
((ExhaustiveProvider) P).pairsLogarithmicOrder(ps, P.roundingModes())
);
} else {
ss = map(
p -> {
assert p.a != null;
assert p.a.a != null;
assert p.a.b != null;
return take(p.a.b, p.a.a) + p.b + drop(p.a.b, p.a.a);
},
P.pairs(ps, P.roundingModes())
);
}
for (String s : take(LIMIT, ss)) {
System.out.println(s);
Optional<Pair<RoundingMode, Integer>> op = findRoundingModeIn(s);
Pair<RoundingMode, Integer> p = op.get();
assertNotNull(s, p.a);
assertNotNull(s, p.b);
assertTrue(s, p.b >= 0 && p.b < s.length());
assertTrue(s, s.substring(p.b).startsWith(p.a.toString()));
}
}
} |
package kawa.lang;
import codegen.*;
/**
* The static information associated with a local variable binding.
* @author Per Bothner
*
* These are the kinds of Declaration we use:
*
* A local variable that is not captured by an inner lambda is stored
* in a Java local variables slot (register). The predicate isSimple ()
* is true, and offset is the number of the local variable slot.
*
* If a local variable is captured by an inner lambda, the
* variable is stored in the heapFrame array variable.
* The offset field indicates the element in the heapFrame array.
* The baseVariable field points to the declaration of the headFrame array.
*
* If a function needs a heapFrame array, then LambdaExp.heapFrame
* points to the declaration variable that points to the heapFrame array.
* This declaration has isSimple and isArtificial true.
*
* The heapFrame array is passed to the constructors of inferior
* procedures that need a static link. It is pointed to by the
* staticLink field of the generated procedure object. When
* the procedure is applied, the procedure prologue copies the
* staticLink field into the local staticLink variable.
* That staticLink variable has isArtificial set.
* In the case of multi-level capture, then the staticLink variable
* may in turn also be captured.
*
* If a function takes a fixed number of parameters, at most four,
* then the arguments are passed in Java registers 1..4.
* If a parameter is not captured by an inner lambda, the parameter
* has the flags isSimple and isParameter true.
*
* A parameter named "foo" that is captured by an inner lambda is represented
* using two Declarations, named "foo" and "fooIncoming".
* The "fooIncoming" declaration is the actual parameter as passed
* by the caller using a Java local variable slot. It has isParameter(),
* isSimple(), and isArtificial set. Its baseVariable field points to
* the "foo" Declaration. The "foo" Declaration has isParameter() set.
* Its baseVariable points to the heapFrame Declaration.
* The procedure prologue copies "fooIncoming" to "foo", which acts
* just like a normal captured local variable.
*
* If a function takes more than 4 or a variable number of parameters,
* the arguments are passed in an array (using the applyN virtual method).
* This array is referenced by the argsArray declaration, which has
* isSimple(), isParameter(), and isArtificial() true, and its offset is 1.
* The parameters are copied into the program-named variables by the
* procedure prologue, so the parameters henceforth act like local variables.
*/
public class Declaration extends Variable
{
/** The name of the new variable. */
Symbol sym;
public final Symbol symbol () { return sym; }
ScopeExp context;
/* SEMI-OBOSLETE (misleading):
* A frame is a set of local variables. In interpreted code, the frame
* is mapped into a single Object array, indexed by Variable.offset.
* In compiled code, the frame is mapped into the local variable slots
* of the current method, where Variable.offset is the variable number.
*
* The value of a simple variable is stored directly in the frame
* (array element or local variable slot). This only works for variables
* that are not captured by inner functions. The index field specified
* the array index or local variable slot; the baseVariable is null.
*
* A 'frame-indirect' variable is stored in a heap array pointed to
* by another variable. The baseVariable is that other variable,
* the index field specifies the array element.
*/
public Declaration baseVariable;
/** If non-null, the Declaration that we "shadow" (hide). */
Declaration shadowed;
/** If non-null, the single expression used to set this variable.
* If the variable can be set more than once, then value is null. */
Expression value = QuoteExp.undefined_exp;
public void noteValue (Expression value)
{
// We allow assigning a real value after undefined ...
if (this.value == QuoteExp.undefined_exp)
this.value = value;
else
this.value = null;
}
public Declaration (Symbol s)
{
sym = s;
name = ClassType.to_utf8 (s.toString ());
type = Type.pointer_type;
}
public String string_name () { return sym.toString (); }
public Object getValue (Object[] frame)
{
//System.err.println ("getvalue: " + sym + " offset:"+offset + " context:"+context + " this:"+this);
if (context.heapFrame == this)
return frame;
if (baseVariable != null)
frame = (Object[]) baseVariable.getValue (frame);
return frame[offset];
}
public Object[] getFrame (Environment env)
{
//System.err.println ("getframe: " + sym + " offset:"+offset);
Object frame[] = env.values;
ScopeExp curScope = env.scope;
ScopeExp declScope = context;
while (declScope.shared) declScope = declScope.outer;
for (; curScope != declScope; curScope = curScope.outer)
{
if (curScope instanceof LambdaExp)
{
LambdaExp lambda = (LambdaExp) curScope;
if (lambda.staticLink == null)
throw new Error ("interal error - canot find static link");
frame = (Object[]) lambda.staticLink.getValue (frame);
}
}
return frame;
}
Object getValue (Environment env)
{
if (context.heapFrame == this)
return env.values;
//System.err.println ("getvalue: " + sym);
return getValue (getFrame (env));
}
void setValue (Environment env, Object value)
{
Object[] frame = getFrame (env);
if (baseVariable != null)
frame = (Object[]) baseVariable.getValue (frame);
frame[offset] = value;
}
/**
* Insert this into Interpreter.current_decls.
* (Used at rewrite time, not eval time.)
*/
void push (Interpreter interp)
{
Declaration old_decl = (Declaration) interp.current_decls.get (sym);
if (old_decl != null)
shadowed = old_decl;
interp.current_decls.put (sym, this);
}
/** Remove this from Interpreter.current_decls.
* (Used at rewrite time, not eval time.)
*/
void pop (Interpreter interp)
{
if (shadowed == null)
interp.current_decls.remove (sym);
else
interp.current_decls.put (sym, shadowed);
}
} |
package uk.ac.ox.zoo.seeg.abraid.mp.modeloutputhandler.web;
import org.apache.commons.io.FileUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import uk.ac.ox.zoo.seeg.abraid.mp.common.dao.ModelRunDao;
import uk.ac.ox.zoo.seeg.abraid.mp.common.dao.NativeSQL;
import uk.ac.ox.zoo.seeg.abraid.mp.common.dao.NativeSQLConstants;
import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.CovariateInfluence;
import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.ModelRun;
import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.ModelRunStatus;
import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.SubmodelStatistic;
import uk.ac.ox.zoo.seeg.abraid.mp.common.dto.csv.CsvCovariateInfluence;
import uk.ac.ox.zoo.seeg.abraid.mp.common.dto.csv.CsvSubmodelStatistic;
import uk.ac.ox.zoo.seeg.abraid.mp.testutils.AbstractSpringIntegrationTests;
import uk.ac.ox.zoo.seeg.abraid.mp.testutils.SpringockitoWebContextLoader;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.extractProperty;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ContextConfiguration(loader = SpringockitoWebContextLoader.class, locations = {
"file:ModelOutputHandler/web/WEB-INF/abraid-servlet-beans.xml",
"file:ModelOutputHandler/web/WEB-INF/applicationContext.xml"
})
@WebAppConfiguration("file:ModelOutputHandler/web")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class MainControllerIntegrationTest extends AbstractSpringIntegrationTests {
private static final String OUTPUT_HANDLER_PATH = "/modeloutputhandler/handleoutputs";
private static final String TEST_DATA_PATH = "ModelOutputHandler/test/uk/ac/ox/zoo/seeg/abraid/mp/modeloutputhandler/web/testdata";
private static final String TEST_MODEL_RUN_NAME = "deng_2014-05-16-13-28-57_482ae3ca-ab30-414d-acce-388baae7d83c";
private static final int TEST_MODEL_RUN_DISEASE_GROUP_ID = 87;
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private MainController controller;
@Autowired
private ModelRunDao modelRunDao;
@Autowired
private NativeSQL nativeSQL;
@Before
public void setup() {
// Set up Spring test in standalone mode
this.mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
}
@Test
public void handleModelOutputsRejectsNonPOSTRequests() throws Exception {
this.mockMvc.perform(get(OUTPUT_HANDLER_PATH)).andExpect(status().isMethodNotAllowed());
this.mockMvc.perform(put(OUTPUT_HANDLER_PATH)).andExpect(status().isMethodNotAllowed());
this.mockMvc.perform(delete(OUTPUT_HANDLER_PATH)).andExpect(status().isMethodNotAllowed());
this.mockMvc.perform(patch(OUTPUT_HANDLER_PATH)).andExpect(status().isMethodNotAllowed());
}
@Ignore
@Test
public void handleModelOutputsStoresValidCompletedOutputs() throws Exception {
// Arrange
DateTime expectedResponseDate = DateTime.now();
DateTimeUtils.setCurrentMillisFixed(expectedResponseDate.getMillis());
insertModelRun(TEST_MODEL_RUN_NAME);
byte[] body = loadTestFile("valid_completed_outputs.zip");
String expectedOutputText = "test output text";
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(body))
.andExpect(status().isOk())
.andExpect(content().string(""));
// Assert
ModelRun run = modelRunDao.getByName(TEST_MODEL_RUN_NAME);
assertThat(run.getStatus()).isEqualTo(ModelRunStatus.COMPLETED);
assertThat(run.getResponseDate()).isEqualTo(expectedResponseDate);
assertThat(run.getOutputText()).isEqualTo(expectedOutputText);
assertThat(run.getErrorText()).isNullOrEmpty();
assertThatRasterInDatabaseMatchesRasterInFile(run, "mean_prediction.tif",
NativeSQLConstants.MEAN_PREDICTION_RASTER_COLUMN_NAME);
assertThatRasterInDatabaseMatchesRasterInFile(run, "prediction_uncertainty.tif",
NativeSQLConstants.PREDICTION_UNCERTAINTY_RASTER_COLUMN_NAME);
assertThatStatisticsInDatabaseMatchesFile(run, "statistics.csv");
assertThatRelativeInfluencesInDatabaseMatchesFile(run, "relative_influence.csv");
}
@Ignore
@Test
public void handleModelOutputsStoresValidFailedOutputsWithResults() throws Exception {
// Arrange
DateTime expectedResponseDate = DateTime.now();
DateTimeUtils.setCurrentMillisFixed(expectedResponseDate.getMillis());
insertModelRun(TEST_MODEL_RUN_NAME);
byte[] body = loadTestFile("valid_failed_outputs_with_results.zip");
String expectedErrorText = "test error text";
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(body))
.andExpect(status().isOk())
.andExpect(content().string(""));
// Assert
ModelRun run = modelRunDao.getByName(TEST_MODEL_RUN_NAME);
assertThat(run.getStatus()).isEqualTo(ModelRunStatus.FAILED);
assertThat(run.getResponseDate()).isEqualTo(expectedResponseDate);
assertThat(run.getOutputText()).isNullOrEmpty();
assertThat(run.getErrorText()).isEqualTo(expectedErrorText);
assertThatRasterInDatabaseMatchesRasterInFile(run, "mean_prediction.tif",
NativeSQLConstants.MEAN_PREDICTION_RASTER_COLUMN_NAME);
assertThatRasterInDatabaseMatchesRasterInFile(run, "prediction_uncertainty.tif",
NativeSQLConstants.PREDICTION_UNCERTAINTY_RASTER_COLUMN_NAME);
assertThatStatisticsInDatabaseMatchesFile(run, "statistics.csv");
assertThatRelativeInfluencesInDatabaseMatchesFile(run, "relative_influence.csv");
}
@Test
public void handleModelOutputsStoresValidFailedOutputsWithoutResults() throws Exception {
// Arrange
DateTime expectedResponseDate = DateTime.now();
DateTimeUtils.setCurrentMillisFixed(expectedResponseDate.getMillis());
insertModelRun(TEST_MODEL_RUN_NAME);
byte[] body = loadTestFile("valid_failed_outputs_without_results.zip");
String expectedErrorText = "test error text";
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(body))
.andExpect(status().isOk())
.andExpect(content().string(""));
// Assert
ModelRun run = modelRunDao.getByName(TEST_MODEL_RUN_NAME);
assertThat(run.getStatus()).isEqualTo(ModelRunStatus.FAILED);
assertThat(run.getResponseDate()).isEqualTo(expectedResponseDate);
assertThat(run.getOutputText()).isNullOrEmpty();
assertThat(run.getErrorText()).isEqualTo(expectedErrorText);
}
@Test
public void handleModelOutputsRejectsMalformedZipFile() throws Exception {
// Arrange
byte[] malformedZipFile = "This is not a zip file".getBytes();
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(malformedZipFile))
.andExpect(status().isInternalServerError())
.andExpect(content().string("Model outputs handler failed with error \"Probably not a zip file or a corrupted zip file\". See ModelOutputHandler server logs for more details."));
}
@Test
public void handleModelOutputsRejectsMissingMetadata() throws Exception {
// Arrange
insertModelRun(TEST_MODEL_RUN_NAME);
byte[] body = loadTestFile("missing_metadata.zip");
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(body))
.andExpect(status().isInternalServerError())
.andExpect(content().string("Model outputs handler failed with error \"File metadata.json missing from model run outputs\". See ModelOutputHandler server logs for more details."));
}
@Test
public void handleModelOutputsRejectsIncorrectModelRunName() throws Exception {
// Arrange
insertModelRun(TEST_MODEL_RUN_NAME);
byte[] body = loadTestFile("incorrect_model_run_name.zip");
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(body))
.andExpect(status().isInternalServerError())
.andExpect(content().string("Model outputs handler failed with error \"Model run with name deng_2014-05-13-11-26-37_0469aac2-d9b2-4104-907e-2886eff11682 does not exist\". See ModelOutputHandler server logs for more details."));
}
@Test
public void handleModelOutputsRejectsMissingMeanPredictionRasterIfStatusIsCompleted() throws Exception {
// Arrange
insertModelRun(TEST_MODEL_RUN_NAME);
byte[] body = loadTestFile("missing_mean_prediction.zip");
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(body))
.andExpect(status().isInternalServerError())
.andExpect(content().string("Model outputs handler failed with error \"File mean_prediction.tif missing from model run outputs\". See ModelOutputHandler server logs for more details."));
}
@Ignore
@Test
public void handleModelOutputsRejectsMissingPredictionUncertaintyRasterIfStatusIsCompleted() throws Exception {
// Arrange
insertModelRun(TEST_MODEL_RUN_NAME);
byte[] body = loadTestFile("missing_prediction_uncertainty.zip");
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(body))
.andExpect(status().isInternalServerError())
.andExpect(content().string("Model outputs handler failed with error \"File prediction_uncertainty.tif missing from model run outputs\". See ModelOutputHandler server logs for more details."));
}
@Test
public void handleModelOutputsRejectsMissingStatisticsIfStatusIsCompleted() throws Exception {
// Arrange
insertModelRun(TEST_MODEL_RUN_NAME);
byte[] body = loadTestFile("missing_statistics.zip");
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(body))
.andExpect(status().isInternalServerError())
.andExpect(content().string("Model outputs handler failed with error \"File statistics.csv missing from model run outputs\". See ModelOutputHandler server logs for more details."));
}
@Test
public void handleModelOutputsRejectsMissingRelativeInfluencesIfStatusIsCompleted() throws Exception {
// Arrange
insertModelRun(TEST_MODEL_RUN_NAME);
byte[] body = loadTestFile("missing_influence.zip");
// Act and assert
this.mockMvc
.perform(post(OUTPUT_HANDLER_PATH).content(body))
.andExpect(status().isInternalServerError())
.andExpect(content().string("Model outputs handler failed with error \"File relative_influence.csv missing from model run outputs\". See ModelOutputHandler server logs for more details."));
}
private void insertModelRun(String name) {
ModelRun modelRun = new ModelRun(name, TEST_MODEL_RUN_DISEASE_GROUP_ID, DateTime.now());
modelRunDao.save(modelRun);
}
private byte[] loadTestFile(String fileName) throws IOException {
return FileUtils.readFileToByteArray(new File(TEST_DATA_PATH, fileName));
}
private void assertThatRasterInDatabaseMatchesRasterInFile(ModelRun run, String fileName, String rasterColumnName) throws IOException {
byte[] expectedRaster = loadTestFile(fileName);
byte[] actualRaster = nativeSQL.loadRasterForModelRun(run.getId(), rasterColumnName);
assertThat(new String(actualRaster)).isEqualTo(new String(expectedRaster));
}
private void assertThatStatisticsInDatabaseMatchesFile(final ModelRun run, String path) throws IOException {
List<SubmodelStatistic> database = run.getSubmodelStatistics();
List<CsvSubmodelStatistic> file = CsvSubmodelStatistic.readFromCSV(FileUtils.readFileToString(new File(TEST_DATA_PATH, path)));
Collections.sort(database, new Comparator<SubmodelStatistic>() {
@Override
public int compare(SubmodelStatistic o1, SubmodelStatistic o2) {
return o1.getDeviance().compareTo(o2.getDeviance());
}
});
Collections.sort(file, new Comparator<CsvSubmodelStatistic>() {
@Override
public int compare(CsvSubmodelStatistic o1, CsvSubmodelStatistic o2) {
return o1.getDeviance().compareTo(o2.getDeviance());
}
});
assertThat(extractProperty("deviance").from(database)).isEqualTo(extractProperty("deviance").from(file));
assertThat(extractProperty("rootMeanSquareError").from(database)).isEqualTo(extractProperty("rootMeanSquareError").from(file));
assertThat(extractProperty("kappa").from(database)).isEqualTo(extractProperty("kappa").from(file));
assertThat(extractProperty("areaUnderCurve").from(database)).isEqualTo(extractProperty("areaUnderCurve").from(file));
assertThat(extractProperty("sensitivity").from(database)).isEqualTo(extractProperty("sensitivity").from(file));
assertThat(extractProperty("specificity").from(database)).isEqualTo(extractProperty("specificity").from(file));
assertThat(extractProperty("proportionCorrectlyClassified").from(database)).isEqualTo(extractProperty("proportionCorrectlyClassified").from(file));
assertThat(extractProperty("kappaStandardDeviation").from(database)).isEqualTo(extractProperty("kappaStandardDeviation").from(file));
assertThat(extractProperty("areaUnderCurveStandardDeviation").from(database)).isEqualTo(extractProperty("areaUnderCurveStandardDeviation").from(file));
assertThat(extractProperty("sensitivityStandardDeviation").from(database)).isEqualTo(extractProperty("sensitivityStandardDeviation").from(file));
assertThat(extractProperty("specificityStandardDeviation").from(database)).isEqualTo(extractProperty("specificityStandardDeviation").from(file));
assertThat(extractProperty("proportionCorrectlyClassifiedStandardDeviation").from(database)).isEqualTo(extractProperty("proportionCorrectlyClassifiedStandardDeviation").from(file));
assertThat(extractProperty("threshold").from(database)).isEqualTo(extractProperty("threshold").from(file));
}
private void assertThatRelativeInfluencesInDatabaseMatchesFile(final ModelRun run, String path) throws IOException {
List<CovariateInfluence> database = run.getCovariateInfluences();
List<CsvCovariateInfluence> file = CsvCovariateInfluence.readFromCSV(FileUtils.readFileToString(new File(TEST_DATA_PATH, path)));
Collections.sort(database, new Comparator<CovariateInfluence>() {
@Override
public int compare(CovariateInfluence o1, CovariateInfluence o2) {
return o1.getMeanInfluence().compareTo(o2.getMeanInfluence());
}
});
Collections.sort(file, new Comparator<CsvCovariateInfluence>() {
@Override
public int compare(CsvCovariateInfluence o1, CsvCovariateInfluence o2) {
return o1.getMeanInfluence().compareTo(o2.getMeanInfluence());
}
});
assertThat(extractProperty("covariateName").from(database)).isEqualTo(extractProperty("covariateName").from(file));
assertThat(extractProperty("covariateDisplayName").from(database)).isEqualTo(extractProperty("covariateDisplayName").from(file));
assertThat(extractProperty("meanInfluence").from(database)).isEqualTo(extractProperty("meanInfluence").from(file));
assertThat(extractProperty("upperQuantile").from(database)).isEqualTo(extractProperty("upperQuantile").from(file));
assertThat(extractProperty("lowerQuantile").from(database)).isEqualTo(extractProperty("lowerQuantile").from(file));
}
} |
package org.jscookie;
import java.util.Arrays;
import javax.servlet.http.Cookie;
import org.jscookie.testutils.BaseTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith( MockitoJUnitRunner.class )
public class CookiesJSONWriteTest extends BaseTest {
private Cookies cookies;
@Before
public void before() {
cookies = new Cookies( request, response );
}
@Test
public void write_int_type() throws CookieSerializationException {
cookies.set( "c", 1 );
ArgumentCaptor<Cookie> argument = ArgumentCaptor.forClass( Cookie.class );
Mockito.verify( response ).addCookie( argument.capture() );
Cookie actual = argument.getValue();
Assert.assertEquals( "1", actual.getValue() );
}
@Test
public void write_boolean_type() throws CookieSerializationException {
cookies.set( "c", true );
ArgumentCaptor<Cookie> argument = ArgumentCaptor.forClass( Cookie.class );
Mockito.verify( response ).addCookie( argument.capture() );
Cookie actual = argument.getValue();
Assert.assertEquals( "true", actual.getValue() );
}
@Test
public void write_JSON_array_with_string() throws CookieSerializationException {
cookies.set( "c", Arrays.asList( "v" ) );
ArgumentCaptor<Cookie> argument = ArgumentCaptor.forClass( Cookie.class );
Mockito.verify( response ).addCookie( argument.capture() );
Cookie actual = argument.getValue();
Assert.assertEquals( "%5B%22v%22%5D", actual.getValue() );
}
@Test
public void write_custom_type_with_string_prop() throws CookieSerializationException {
cookies.set( "c", new CustomTypeString( "v" ) );
ArgumentCaptor<Cookie> argument = ArgumentCaptor.forClass( Cookie.class );
Mockito.verify( response ).addCookie( argument.capture() );
Cookie actual = argument.getValue();
Assert.assertEquals( "%7B%22property%22%3A%22v%22%7D", actual.getValue() );
}
@Test
public void write_custom_type_with_boolean_prop() throws CookieSerializationException {
cookies.set( "c", new CustomTypeBoolean( true ) );
ArgumentCaptor<Cookie> argument = ArgumentCaptor.forClass( Cookie.class );
Mockito.verify( response ).addCookie( argument.capture() );
Cookie actual = argument.getValue();
Assert.assertEquals( "%7B%22property%22%3Atrue%7D", actual.getValue() );
}
@Test
public void write_custom_type_with_number_prop() throws CookieSerializationException {
cookies.set( "c", new CustomTypeInteger( 1 ) );
ArgumentCaptor<Cookie> argument = ArgumentCaptor.forClass( Cookie.class );
Mockito.verify( response ).addCookie( argument.capture() );
Cookie actual = argument.getValue();
Assert.assertEquals( "%7B%22property%22%3A1%7D", actual.getValue() );
}
class CustomTypeString implements CookieValue {
private String property;
private CustomTypeString( String property ) {
this.property = property;
}
public String getProperty() {
return property;
}
}
class CustomTypeBoolean implements CookieValue {
private Boolean property;
private CustomTypeBoolean( Boolean property ) {
this.property = property;
}
public Boolean getProperty() {
return property;
}
}
class CustomTypeInteger implements CookieValue {
private Integer property;
private CustomTypeInteger( Integer property ) {
this.property = property;
}
public Integer getProperty() {
return property;
}
}
} |
package org.lantern;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.UnknownHostException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.lantern.TestCategories.TrustStoreTests;
import org.lantern.util.LanternHostNameVerifier;
import org.littleshoot.proxy.KeyStoreManager;
import org.littleshoot.util.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Category(TrustStoreTests.class)
public class LanternTrustStoreTest {
private final Logger log = LoggerFactory.getLogger(getClass());
@Test
public void testFallback() throws UnknownHostException, IOException {//throws Exception {
//System.setProperty("javax.net.debug", "ssl");
final File temp = new File(String.valueOf(RandomUtils.nextInt()));
temp.deleteOnExit();
final KeyStoreManager ksm = new LanternKeyStoreManager(temp);
final LanternTrustStore trustStore = new LanternTrustStore(ksm);
final LanternSocketsUtil socketsUtil =
new LanternSocketsUtil(null, trustStore);
System.setProperty("javax.net.ssl.trustStore",
trustStore.TRUSTSTORE_FILE.getAbsolutePath());
// Higher bit cipher suites aren't enabled on littleproxy.
//Launcher.configureCipherSuites();
trustStore.listEntries();
final SSLSocketFactory socketFactory = socketsUtil.newTlsSocketFactory();
//final SSLSocket sock = (SSLSocket) socketFactory.createSocket("54.251.192.164", 11225);
final SSLSocket sock = (SSLSocket) socketFactory.createSocket("75.101.134.244", 7777);
//final SSLSocket sock = (SSLSocket) socketFactory.createSocket("192.168.0.2", 7777);
sock.isConnected();
final OutputStream os = sock.getOutputStream();
os.write("GET http:
os.flush();
final InputStream is = sock.getInputStream();
final byte[] bytes = new byte[30];
is.read(bytes);
final String response = new String(bytes);
assertTrue(response.startsWith("HTTP/1.1 200 OK"));
System.out.println(new String(bytes));
os.close();
is.close();
}
@Test
public void testSites() {//throws Exception {
//System.setProperty("javax.net.debug", "ssl");
log.debug("CONFIGURED TRUSTSTORE: "+System.getProperty("javax.net.ssl.trustStore"));
//System.setProperty("javax.net.debug", "ssl");
//final KeyStoreManager ksm = new LanternKeyStoreManager();
//final LanternTrustStore trustStore = new LanternTrustStore(null, ksm);
//final LanternSocketsUtil socketsUtil =
//new LanternSocketsUtil(null, trustStore);
//final LanternTrustStore trustStore = TestUtils.getTrustStore();
//final LanternSocketsUtil socketsUtil = TestUtils.getSocketsUtil();
//final SSLSocketFactory socketFactory =
//new SSLSocketFactory(socketsUtil.newTlsSocketFactory(),
// new LanternHostNameVerifier());
final File temp = new File(String.valueOf(RandomUtils.nextInt()));
temp.deleteOnExit();
final KeyStoreManager ksm = new LanternKeyStoreManager(temp);
final LanternTrustStore trustStore = new LanternTrustStore(ksm);
final LanternSocketsUtil socketsUtil =
new LanternSocketsUtil(null, trustStore);
System.setProperty("javax.net.ssl.trustStore",
trustStore.TRUSTSTORE_FILE.getAbsolutePath());
trustStore.listEntries();
final org.apache.http.conn.ssl.SSLSocketFactory socketFactory =
new org.apache.http.conn.ssl.SSLSocketFactory(
socketsUtil.newTlsSocketFactoryJavaCipherSuites(),
new LanternHostNameVerifier());
log.debug("CONFIGURED TRUSTSTORE: "+System.getProperty("javax.net.ssl.trustStore"));
//final SSLSocketFactory socketFactory = LanternSocketsUtil.
final Scheme sch = new Scheme("https", 443, socketFactory);
final HttpClient client = new DefaultHttpClient();
client.getConnectionManager().getSchemeRegistry().register(sch);
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
final String[] success = {"talk.google.com",
"lanternctrl.appspot.com", "docs.google.com", "www.googleapis.com"};
for (final String uri : success) {
try {
log.debug("Trying site: {}", uri);
final String body = trySite(client, uri);
log.debug("SUCCESS BODY FOR '{}': {}", uri, body.substring(0,Math.min(50, body.length())));
} catch (Exception e) {
log.error("Stack:\n"+ThreadUtils.dumpStack(e));
fail("Unexpected exception on "+uri+"!\n"+ThreadUtils.dumpStack(e)+
"\n\nFAILED ON: "+uri);
}
}
// URIs that should fail (signing certs we don't trust). Note this would
// succeed (with the test failing as a result) with the normal root CAs,
// which trust more signing certs than ours, such as verisign. We
// just try to minimize the attack surface as much aLs possible.
final String[] failure = {"chase.com"};
for (final String uri : failure) {
try {
final String body = trySite(client, uri);
log.debug("FAILURE BODY: "+body.substring(0,50));
fail("Should not have succeeded on: "+uri);
} catch (Exception e) {
log.debug("Got expected exception "+e.getMessage());
}
}
// Now we want to *modify the trust store at runtime* and make sure
// those changes take effect.
// THIS IS EXTREMELY IMPORTANT AS LANTERN RELIES ON THIS FOR ALL
// P2P CONNECTIONS!!
trustStore.deleteCert("equifaxsecureca");
final String[] noLongerSuccess = {"talk.google.com"};
for (final String uri : noLongerSuccess) {
try {
final String body = trySite(client, uri);
log.debug("SUCCESS BODY: "+body.substring(0, 50));
fail("Should not have succeeded on: "+uri);
} catch (Exception e) {
// Expected since we should no longer trust talk.google.com
}
}
// We need to add this back as otherwise it can affect other tests!
trustStore.addCert("equifaxsecureca", new File("certs/equifaxsecureca.cer"));
temp.delete();
}
private String trySite(final HttpClient client, final String uri)
throws Exception {
final HttpGet get = new HttpGet();
final String fullUri = "https://"+uri;
log.info("Hitting URI: {}", fullUri);
get.setURI(new URI(fullUri));
final HttpResponse response = client.execute(get);
final int code = response.getStatusLine().getStatusCode();
final HttpEntity entity = response.getEntity();
final String body =
IOUtils.toString(entity.getContent()).toLowerCase();
EntityUtils.consume(entity);
if (code < 200 || code > 299) {
// We use this method both for calls that should succeed and
// calls that should fail, so this is expected.
log.debug("Non-200 response code: "+code+" for "+uri+
" with body:\n"+body);
}
get.reset();
return body;
}
} |
package org.wyona.yanel.impl.resources.boost;
import java.io.InputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.wyona.yanel.servlet.AccessLog;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import org.wyona.commons.xml.XMLHelper;
import org.apache.log4j.Logger;
import org.wyona.boost.client.BoostService;
import org.wyona.boost.client.ServiceException;
import org.wyona.boost.client.BoostServiceConfig;
import org.wyona.yarep.core.Node;
import org.wyona.yarep.core.search.Searcher;
/**
* Retrieve the user profile of the current user, given his cookie id, from
* the Boost service using the Boost client library.
*/
public class PersonalizedContentResource extends BasicXMLResource {
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(PersonalizedContentResource.class);
private static final String NAMESPACE = "http:
private String boostServiceUrl = "http://localhost:9080/boost/api";
/**
* Get the XML content of this resource.
* @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String)
*/
protected InputStream getContentXML(String viewId) throws Exception {
Document doc = XMLHelper.createDocument(NAMESPACE, "personalized-content");
Element root = doc.getDocumentElement();
String service = getResourceConfigProperty("boost-service-url");
if(service != null && !"".equals(service)) {
boostServiceUrl = service;
}
// Is the user logged into Yanel?
String username = getEnvironment().getIdentity().getUsername();
if(username != null) {
Element uid = doc.createElement("yanel-user-id");
uid.appendChild(doc.createTextNode(username));
}
String realm = getRealm().getID();
String boost_domain = getRealm().getUserTrackingDomain();
Element realmEl = doc.createElementNS(NAMESPACE, "yanel-realm-id");
realmEl.appendChild(doc.createTextNode(realm));
root.appendChild(realmEl);
Element domainEl = doc.createElementNS(NAMESPACE, "boost-domain-id");
domainEl.appendChild(doc.createTextNode(boost_domain));
root.appendChild(domainEl);
// Get the cookie
HttpServletRequest req = getEnvironment().getRequest();
Cookie cookie = AccessLog.getYanelAnalyticsCookie(req);
if(cookie == null) {
root.appendChild(doc.createElementNS(NAMESPACE, "no-cookie"));
root.appendChild(doc.createElementNS(NAMESPACE, "no-profile"));
return XMLHelper.getInputStream(doc, false, false, null);
}
Element cookieEl = doc.createElementNS(NAMESPACE, "yanel-cookie-id");
cookieEl.appendChild(doc.createTextNode(cookie.getValue()));
root.appendChild(cookieEl);
Iterable<String> userInterests;
try {
userInterests = getUserInterests(cookie.getValue(), boost_domain);
} catch(ServiceException e) {
// No interests
log.error(e, e);
Element exceptionEl = doc.createElementNS(NAMESPACE, "exception");
exceptionEl.appendChild(doc.createTextNode(e.getMessage()));
root.appendChild(exceptionEl);
Element errEl = doc.createElementNS(NAMESPACE, "no-profile");
root.appendChild(errEl);
return XMLHelper.getInputStream(doc, false, false, null);
}
// Add all interests to user profile
Element interestsEl = doc.createElementNS(NAMESPACE, "interests");
for(String interest : userInterests) {
Element interestEl = doc.createElementNS(NAMESPACE, "interest");
interestEl.appendChild(doc.createTextNode(interest));
interestsEl.appendChild(interestEl);
}
root.appendChild(interestsEl);
// Search for related content in data repository
Element resultsEl = doc.createElementNS(NAMESPACE, "results");
Searcher search = getRealm().getRepository().getSearcher();
for(String interest : userInterests) {
Node[] nodes;
try {
nodes = search.search(interest);
} catch(Exception e) {
break;
}
for(Node node : nodes) {
Element res_node = doc.createElementNS(NAMESPACE, "result");
Element res_path = doc.createElementNS(NAMESPACE, "path");
Element res_name = doc.createElementNS(NAMESPACE, "name");
Element res_time = doc.createElementNS(NAMESPACE, "last-modified");
res_path.appendChild(doc.createTextNode(node.getPath()));
res_name.appendChild(doc.createTextNode(node.getName()));
res_time.appendChild(doc.createTextNode(Long.toString(node.getLastModified())));
res_node.appendChild(res_path);
resultsEl.appendChild(res_node);
}
}
root.appendChild(resultsEl);
return XMLHelper.getInputStream(doc, false, false, null);
}
/**
* Get the user profile given a cookie.
* @param cookie Unique cookie id
*/
protected Iterable<String> getUserInterests(String cookie, String realm)
throws Exception {
BoostServiceConfig bsc = new BoostServiceConfig(boostServiceUrl, realm);
BoostService boost = new BoostService(bsc);
return boost.getUserProfile(cookie);
}
/**
* Do we exist? Returns 404 if we answer no.
* @see org.wyona.yanel.core.api.attributes.ViewableV2#exists()
*/
public boolean exists() throws Exception {
return true;
}
} |
package com.jraska.falcon;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import static android.graphics.Bitmap.Config.ARGB_8888;
import static android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND;
public class Falcon {
//region Constants
private static final String TAG = "Falcon";
//endregion
//region Public API
public static File takeScreenshot(Activity activity, final File toFile) {
if (activity == null) {
throw new IllegalArgumentException("Parameter activity cannot be null.");
}
if (toFile == null) {
throw new IllegalArgumentException("Parameter toFile cannot be null.");
}
Bitmap bitmap = null;
try {
bitmap = takeBitmapUnchecked(activity);
writeBitmap(bitmap, toFile);
}
catch (Exception e) {
String message = "Unable to take screenshot to file " + toFile.getAbsolutePath()
+ " of activity " + activity.getClass().getName();
Log.e(TAG, message, e);
throw new RuntimeException(message, e);
}
finally {
if (bitmap != null) {
bitmap.recycle();
}
}
Log.d(TAG, "Screenshot captured to " + toFile.getAbsolutePath());
return toFile;
}
public static Bitmap takeScreenshotBitmap(Activity activity) {
if (activity == null) {
throw new IllegalArgumentException("Parameter activity cannot be null.");
}
try {
return takeBitmapUnchecked(activity);
}
catch (Exception e) {
String message = "Unable to take screenshot to bitmap of activity "
+ activity.getClass().getName();
Log.e(TAG, message, e);
throw new RuntimeException(message, e);
}
}
//endregion
//region Methods
private static Bitmap takeBitmapUnchecked(Activity activity) throws InterruptedException {
final List<ViewRootData> viewRoots = getRootViews(activity);
View main = activity.getWindow().getDecorView();
final Bitmap bitmap = Bitmap.createBitmap(main.getWidth(), main.getHeight(), ARGB_8888);
// We need to do it in main thread
if (Looper.myLooper() == Looper.getMainLooper()) {
drawRootsToBitmap(viewRoots, bitmap);
} else {
final CountDownLatch latch = new CountDownLatch(1);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
drawRootsToBitmap(viewRoots, bitmap);
}
finally {
latch.countDown();
}
}
});
latch.await();
}
return bitmap;
}
private static void drawRootsToBitmap(List<ViewRootData> viewRoots, Bitmap bitmap) {
for (ViewRootData rootData : viewRoots) {
drawRootToBitmap(rootData, bitmap);
}
}
private static void drawRootToBitmap(ViewRootData config, Bitmap bitmap) {
// now only dim supported
if ((config._layoutParams.flags & FLAG_DIM_BEHIND) == FLAG_DIM_BEHIND) {
Canvas dimCanvas = new Canvas(bitmap);
int alpha = (int) (255 * config._layoutParams.dimAmount);
dimCanvas.drawARGB(alpha, 0, 0, 0);
}
Canvas canvas = new Canvas(bitmap);
canvas.translate(config._winFrame.left, config._winFrame.top);
config._view.draw(canvas);
}
private static void writeBitmap(Bitmap bitmap, File toFile) throws IOException {
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(toFile));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
}
finally {
if (outputStream != null) {
outputStream.close();
}
}
}
@SuppressWarnings("unchecked") // no way to check
private static List<ViewRootData> getRootViews(Activity activity) {
List<ViewRootData> rootViews = new ArrayList<>();
Object globalWindowManager = getFieldValue("mGlobal", activity.getWindowManager());
Object rootObjects = getFieldValue("mRoots", globalWindowManager);
Object paramsObject = getFieldValue("mParams", globalWindowManager);
Object[] roots;
LayoutParams[] params;
// There was a change to ArrayList implementation in 4.4
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
roots = ((List) rootObjects).toArray();
List<LayoutParams> paramsList = (List<LayoutParams>) paramsObject;
params = paramsList.toArray(new LayoutParams[paramsList.size()]);
} else {
roots = (Object[]) rootObjects;
params = (LayoutParams[]) paramsObject;
}
for (int i = 0; i < roots.length; i++) {
Object root = roots[i];
Rect area = (Rect) getFieldValue("mWinFrame", root);
View view = (View) getFieldValue("mView", root);
rootViews.add(new ViewRootData(view, area, params[i]));
}
return rootViews;
}
private static Object getFieldValue(String fieldName, Object target) {
try {
return getFieldValueUnchecked(fieldName, target);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private static Object getFieldValueUnchecked(String fieldName, Object target)
throws NoSuchFieldException, IllegalAccessException {
// No recursion to upper classes all fields we need are directly declared by provided classes
Field field = target.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(target);
}
//endregion
//region Nested classes
private static class ViewRootData {
private final View _view;
private final Rect _winFrame;
private final LayoutParams _layoutParams;
public ViewRootData(View view, Rect winFrame, LayoutParams layoutParams) {
_view = view;
_winFrame = winFrame;
_layoutParams = layoutParams;
}
}
//endregion
} |
package ca.corefacility.bioinformatics.irida.config.workflow;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import ca.corefacility.bioinformatics.irida.config.services.IridaApiPropertyPlaceholderConfig;
import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowException;
import ca.corefacility.bioinformatics.irida.model.enums.AnalysisType;
import ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow;
import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowLoaderService;
import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService;
/**
* Class used configure workflows in Galaxy for integration testing.
*
*
*/
@Configuration
@Profile("test")
@Import({ IridaApiPropertyPlaceholderConfig.class})
public class IridaWorkflowsGalaxyIntegrationTestConfig {
@Autowired
private Environment environment;
@Autowired
private IridaWorkflowLoaderService iridaWorkflowLoaderService;
@Autowired
private IridaWorkflowsService iridaWorkflowsService;
private UUID snvPhylWorkflowId = UUID.fromString(environment.getProperty("irida.workflow.default.phylogenomics"));
/**
* Registers a production SNVPhyl workflow for testing.
*
* @return A production {@link IridaWorkflow} for testing.
* @throws IOException
* @throws URISyntaxException
* @throws IridaWorkflowException
*/
@Lazy
@Bean
public IridaWorkflow snvPhylWorkflow() throws IOException, URISyntaxException, IridaWorkflowException {
Path snvPhylProductionPath = Paths.get(AnalysisType.class.getResource("workflows/SNVPhyl").toURI());
Set<IridaWorkflow> snvPhylWorkflows = iridaWorkflowLoaderService
.loadAllWorkflowImplementations(snvPhylProductionPath);
iridaWorkflowsService.registerWorkflows(snvPhylWorkflows);
IridaWorkflow snvPhylWorkflow = iridaWorkflowsService.getIridaWorkflow(snvPhylWorkflowId);
return snvPhylWorkflow;
}
} |
package org.takes.facets.auth;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.rq.RqFake;
import org.takes.rs.RsEmpty;
import java.io.IOException;
/**
* Test case for {@link PsChain}.
* @author Aleksey Kurochka (eg04lt3r@gmail.com)
* @version $Id$
*/
public final class PsChainTest {
/**
* Check that PsChain returns proper identity
* @throws IOException
*/
@Test
public void chainExecutionTest() throws IOException {
MatcherAssert.assertThat(
new PsChain(
new PsLogout(),
new PsFake(true)
).enter(new RqFake()).next(),
Matchers.is(Identity.ANONYMOUS)
);
}
/**
* Check that exit method of PsChain returns proper response
* @throws IOException
*/
@Test
public void exitChainTest() throws IOException {
MatcherAssert.assertThat(
new PsChain(
new PsFake(true)
).exit(new RsEmpty(), Identity.ANONYMOUS)
.head().iterator().next(),
Matchers.containsString("HTTP/1.1 200 O")
);
}
} |
package org.hbird.transport.payloadcodec;
import java.util.BitSet;
import org.hbird.core.commons.data.GenericPayload;
import org.hbird.core.commons.tmtc.ParameterGroup;
import org.hbird.core.spacesystemmodel.exceptions.UnknownParameterGroupException;
import org.hbird.core.spacesystempublisher.interfaces.SpaceSystemPublisher;
/**
* TODO publisher update mechanism, the publisher needs to be able to update the payload codec.
*
* @author Mark Doyle
*
*/
public class PublisherServiceBasedPayloadCodec implements PayloadCodec {
private InMemoryPayloadCodec codec;
private SpaceSystemPublisher publisher;
public void cacheModelInformation() {
codec = new InMemoryPayloadCodec(publisher.getParameterGroups(), publisher.getEncodings(), publisher.getRestrictions());
}
public void setPublisher(final SpaceSystemPublisher publisher) {
this.publisher = publisher;
}
@Override
public ParameterGroup decode(final byte[] payload, final String payloadLayoutId, final long timeStamp) throws UnknownParameterGroupException {
return this.codec.decode(payload, payloadLayoutId, timeStamp);
}
@Override
public ParameterGroup decode(final BitSet payload, final String payloadLayoutId, final long timeStamp) throws UnknownParameterGroupException {
return this.codec.decode(payload, payloadLayoutId, timeStamp);
}
@Override
public ParameterGroup decode(final GenericPayload payload) throws UnknownParameterGroupException {
return this.codec.decode(payload);
}
@Override
public byte[] encodeToByteArray(final ParameterGroup parameterGroup) {
return this.codec.encodeToByteArray(parameterGroup);
}
@Override
public GenericPayload encodeToGenericPayload(final ParameterGroup parameterGroup) {
return this.codec.encodeToGenericPayload(parameterGroup);
}
} |
package org.apereo.cas.web.report;
import org.apereo.cas.CentralAuthenticationService;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.ticket.Ticket;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.apereo.cas.util.DateTimeUtils;
import org.apereo.cas.util.ISOStandardDateFormat;
import org.apereo.cas.web.BaseCasActuatorEndpoint;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.boot.actuate.endpoint.annotation.DeleteOperation;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
* SSO Report web controller that produces JSON data for the view.
*
* @author Misagh Moayyed
* @author Dmitriy Kopylenko
* @since 4.1
*/
@Slf4j
@ToString
@Getter
@Endpoint(id = "ssoSessions", enableByDefault = false)
public class SingleSignOnSessionsEndpoint extends BaseCasActuatorEndpoint {
private static final String STATUS = "status";
private static final String TICKET_GRANTING_TICKET = "ticketGrantingTicket";
private final CentralAuthenticationService centralAuthenticationService;
public SingleSignOnSessionsEndpoint(final CentralAuthenticationService centralAuthenticationService,
final CasConfigurationProperties casProperties) {
super(casProperties);
this.centralAuthenticationService = centralAuthenticationService;
}
/**
* Gets sso sessions.
*
* @param option the option
* @return the sso sessions
*/
private Collection<Map<String, Object>> getActiveSsoSessions(final SsoSessionReportOptions option) {
val activeSessions = new ArrayList<Map<String, Object>>();
val dateFormat = new ISOStandardDateFormat();
getNonExpiredTicketGrantingTickets().stream().map(TicketGrantingTicket.class::cast)
.filter(tgt -> !(option == SsoSessionReportOptions.DIRECT && tgt.getProxiedBy() != null))
.forEach(tgt -> {
val authentication = tgt.getAuthentication();
val principal = authentication.getPrincipal();
val sso = new HashMap<String, Object>(SsoSessionAttributeKeys.values().length);
sso.put(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.toString(), principal.getId());
sso.put(SsoSessionAttributeKeys.AUTHENTICATION_DATE.toString(), authentication.getAuthenticationDate());
sso.put(SsoSessionAttributeKeys.AUTHENTICATION_DATE_FORMATTED.toString(),
dateFormat.format(DateTimeUtils.dateOf(authentication.getAuthenticationDate())));
sso.put(SsoSessionAttributeKeys.NUMBER_OF_USES.toString(), tgt.getCountOfUses());
sso.put(SsoSessionAttributeKeys.TICKET_GRANTING_TICKET.toString(), tgt.getId());
sso.put(SsoSessionAttributeKeys.PRINCIPAL_ATTRIBUTES.toString(), principal.getAttributes());
sso.put(SsoSessionAttributeKeys.AUTHENTICATION_ATTRIBUTES.toString(), authentication.getAttributes());
if (option != SsoSessionReportOptions.DIRECT) {
if (tgt.getProxiedBy() != null) {
sso.put(SsoSessionAttributeKeys.IS_PROXIED.toString(), Boolean.TRUE);
sso.put(SsoSessionAttributeKeys.PROXIED_BY.toString(), tgt.getProxiedBy().getId());
} else {
sso.put(SsoSessionAttributeKeys.IS_PROXIED.toString(), Boolean.FALSE);
}
}
sso.put(SsoSessionAttributeKeys.AUTHENTICATED_SERVICES.toString(), tgt.getServices());
activeSessions.add(sso);
});
return activeSessions;
}
/**
* Gets non expired ticket granting tickets.
*
* @return the non expired ticket granting tickets
*/
private Collection<Ticket> getNonExpiredTicketGrantingTickets() {
return this.centralAuthenticationService.getTickets(ticket -> ticket instanceof TicketGrantingTicket && !ticket.isExpired());
}
/**
* Endpoint for getting SSO Sessions in JSON format.
*
* @param type the type
* @return the sso sessions
*/
@ReadOperation
public Map<String, Object> getSsoSessions(final String type) {
val sessionsMap = new HashMap<String, Object>(1);
val option = SsoSessionReportOptions.valueOf(type);
val activeSsoSessions = getActiveSsoSessions(option);
sessionsMap.put("activeSsoSessions", activeSsoSessions);
val totalTicketGrantingTickets = new AtomicLong();
val totalProxyGrantingTickets = new AtomicLong();
val totalUsageCount = new AtomicLong();
val uniquePrincipals = new HashSet<Object>();
for (val activeSsoSession : activeSsoSessions) {
if (activeSsoSession.containsKey(SsoSessionAttributeKeys.IS_PROXIED.toString())) {
val isProxied = Boolean.valueOf(activeSsoSession.get(SsoSessionAttributeKeys.IS_PROXIED.toString()).toString());
if (isProxied) {
totalProxyGrantingTickets.incrementAndGet();
} else {
totalTicketGrantingTickets.incrementAndGet();
val principal = activeSsoSession.get(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.toString()).toString();
uniquePrincipals.add(principal);
}
} else {
totalTicketGrantingTickets.incrementAndGet();
val principal = activeSsoSession.get(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.toString()).toString();
uniquePrincipals.add(principal);
}
val uses = Long.parseLong(activeSsoSession.get(SsoSessionAttributeKeys.NUMBER_OF_USES.toString()).toString());
totalUsageCount.getAndAdd(uses);
}
sessionsMap.put("totalProxyGrantingTickets", totalProxyGrantingTickets);
sessionsMap.put("totalTicketGrantingTickets", totalTicketGrantingTickets);
sessionsMap.put("totalTickets", totalTicketGrantingTickets.longValue() + totalProxyGrantingTickets.longValue());
sessionsMap.put("totalPrincipals", uniquePrincipals.size());
sessionsMap.put("totalUsageCount", totalUsageCount);
return sessionsMap;
}
/**
* Endpoint for destroying a single SSO Session.
*
* @param ticketGrantingTicket the ticket granting ticket
* @return result map
*/
@DeleteOperation
public Map<String, Object> destroySsoSession(@Selector final String ticketGrantingTicket) {
val sessionsMap = new HashMap<String, Object>(1);
try {
this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicket);
sessionsMap.put(STATUS, HttpServletResponse.SC_OK);
sessionsMap.put(TICKET_GRANTING_TICKET, ticketGrantingTicket);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
sessionsMap.put(STATUS, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sessionsMap.put(TICKET_GRANTING_TICKET, ticketGrantingTicket);
sessionsMap.put("message", e.getMessage());
}
return sessionsMap;
}
/**
* Destroy sso sessions map.
*
* @param type the type
* @return the map
*/
@DeleteOperation
public Map<String, Object> destroySsoSessions(final String type) {
val sessionsMap = new HashMap<String, Object>();
val failedTickets = new HashMap<String, String>();
val option = SsoSessionReportOptions.valueOf(type);
val collection = getActiveSsoSessions(option);
collection
.stream()
.map(sso -> sso.get(SsoSessionAttributeKeys.TICKET_GRANTING_TICKET.toString()).toString())
.forEach(ticketGrantingTicket -> {
try {
this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicket);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
failedTickets.put(ticketGrantingTicket, e.getMessage());
}
});
if (failedTickets.isEmpty()) {
sessionsMap.put(STATUS, HttpServletResponse.SC_OK);
} else {
sessionsMap.put(STATUS, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sessionsMap.put("failedTicketGrantingTickets", failedTickets);
}
return sessionsMap;
}
private enum SsoSessionReportOptions {
ALL("all"), PROXIED("proxied"), DIRECT("direct");
private final String type;
/**
* Instantiates a new Sso session report options.
*
* @param type the type
*/
SsoSessionReportOptions(final String type) {
this.type = type;
}
}
/**
* The enum Sso session attribute keys.
*/
@Getter
private enum SsoSessionAttributeKeys {
AUTHENTICATED_PRINCIPAL("authenticated_principal"), PRINCIPAL_ATTRIBUTES("principal_attributes"),
AUTHENTICATION_DATE("authentication_date"), AUTHENTICATION_DATE_FORMATTED("authentication_date_formatted"),
TICKET_GRANTING_TICKET("ticket_granting_ticket"), AUTHENTICATION_ATTRIBUTES("authentication_attributes"),
PROXIED_BY("proxied_by"), AUTHENTICATED_SERVICES("authenticated_services"),
IS_PROXIED("is_proxied"),
NUMBER_OF_USES("number_of_uses");
private final String attributeKey;
/**
* Instantiates a new Sso session attribute keys.
*
* @param attributeKey the attribute key
*/
SsoSessionAttributeKeys(final String attributeKey) {
this.attributeKey = attributeKey;
}
}
} |
package com.google.enterprise.adaptor;
import com.google.common.base.Strings;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The content transform factory holds all document content transformers
* and puts them in series connection.
*
* @author Dominik Weidenfeld (dominik.weidenfeld@twt.de)
*/
public class ContentTransformFactory {
private static final Logger LOG =
Logger.getLogger(ContentTransformFactory.class.getName());
private List<Map<String, String>> contentTransformers;
public ContentTransformFactory(
final List<Map<String, String>> contentTransformers) {
this.contentTransformers = contentTransformers;
}
/**
* Creates a new transformer pipeline.
*
* @param original original content stream
* @param contentType content type
* @param metadata metadata
* @return stream pipeline or original output stream
*/
public final OutputStream createPipeline(final OutputStream original,
final String contentType,
final Metadata metadata) {
if (contentTransformers.size() <= 0) {
return original;
}
DocumentContentTransformer contentTransformer = null;
for (int i = contentTransformers.size(); i >= 0; i
final Map<String, String> tConfig = contentTransformers.get(i);
final String className = tConfig.get("class");
if (Strings.isNullOrEmpty(className)) {
LOG.log(Level.SEVERE,
"Document Content Transformer class is missing {0}", className);
throw new RuntimeException(
"Document Content Transformer class is missing " + className);
}
try {
//noinspection unchecked
final Class<DocumentContentTransformer> clazz =
(Class<DocumentContentTransformer>) Class.forName(className);
final Constructor<DocumentContentTransformer> constructor =
clazz.getConstructor(Map.class,
OutputStream.class, String.class, Metadata.class);
if (null == contentTransformer) {
contentTransformer =
constructor.newInstance(tConfig, original, contentType,
metadata);
} else {
contentTransformer =
constructor.newInstance(tConfig, contentTransformer,
contentType, metadata);
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
"Cannot use document content transformer of type {0}", className);
throw new RuntimeException(
"Cannot use document content transformer of type " + className);
}
}
return contentTransformer;
}
} |
package com.markupartist.sthlmtraveling.provider.planner;
import android.location.Location;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
public class Stop implements Parcelable {
public static String TYPE_MY_LOCATION = "MY_LOCATION";
private static String NAME_RE = "[^\\p{Alnum}\\(\\)\\s]";
private String mName;
private Location mLocation;
private int mSiteId;
public Stop() {
}
public Stop(String name) {
setName(name);
}
public Stop(String name, Location location) {
setName(name);
mLocation = location;
}
public Stop(String name, double latitude, double longitude) {
setName(name);
mLocation = new Location("sthlmtraveling");
mLocation.setLatitude(latitude);
mLocation.setLongitude(longitude);
}
public Stop(Parcel parcel) {
mName = parcel.readString();
mLocation = parcel.readParcelable(null);
mSiteId = parcel.readInt();
}
/**
* Create a new Stop that is a copy of the given Stop.
* @param stop the stop
*/
public Stop(Stop stop) {
mName = stop.getName();
mLocation = stop.getLocation();
mSiteId = stop.getSiteId();
}
public String getName() {
return mName;
}
public void setName(String name) {
if (!TextUtils.isEmpty(name)) {
if (name.equals(TYPE_MY_LOCATION)) {
mName = name;
} else {
mName = name.trim().replaceAll(NAME_RE, "");
}
}
}
public boolean hasName() {
return !TextUtils.isEmpty(mName);
}
public void setLocation(Location location) {
mLocation = location;
}
public void setLocation(int latitudeE6, int longitudeE6) {
mLocation = new Location("sthlmtraveling");
mLocation.setLatitude(latitudeE6 / 1E6);
mLocation.setLongitude(longitudeE6 / 1E6);
}
public Location getLocation() {
return mLocation;
}
public boolean isMyLocation() {
return hasName() && mName.equals(TYPE_MY_LOCATION);
}
public void setSiteId(int siteId) {
mSiteId = siteId;
}
public int getSiteId() {
return mSiteId;
}
public boolean looksValid() {
return hasName();
}
public static boolean looksValid(String name) {
if (TextUtils.isEmpty(name) || TextUtils.getTrimmedLength(name) == 0) {
return false;
}
return !name.matches(NAME_RE);
}
@Override
public String toString() {
return mName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mName);
parcel.writeParcelable(mLocation, 0);
parcel.writeInt(mSiteId);
}
public static final Creator<Stop> CREATOR = new Creator<Stop>() {
public Stop createFromParcel(Parcel parcel) {
return new Stop(parcel);
}
public Stop[] newArray(int size) {
return new Stop[size];
}
};
} |
package com.monstarlab.servicedroid.util;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
public class ServiceDroidDocument {
private static final String TAG = "ServiceDroidDocument";
protected static final int SCHEMA_ATTRS = 1;
protected static final int SCHEMA_ELS = 2;
protected Document mDoc;
protected int mSchema = 0;
public ServiceDroidDocument() {
this("<ServiceDroid schema=\"" + SCHEMA_ELS + "\"></ServiceDroid>");
}
public ServiceDroidDocument(String xml) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
mDoc = builder.parse(new InputSource(new StringReader(xml)));
} catch (ParserConfigurationException e) {
e.printStackTrace();
Log.e(TAG, "Failed parsing backup file.");
Log.e(TAG, e.toString());
} catch (SAXException e) {
e.printStackTrace();
Log.e(TAG, "Failed parsing backup file.");
Log.e(TAG, e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Failed reading backup file from SD card.");
Log.e(TAG, e.toString());
} finally {
if (mDoc == null) {
} else {
mSchema = getSchema();
}
}
}
public int getSchema() {
String schema = mDoc.getDocumentElement().getAttribute("schema");
if (TextUtils.isEmpty(schema)) {
return SCHEMA_ATTRS;
} else {
return Integer.parseInt(schema);
}
}
public void addNode(String tagName, String[] attributes, String[] values) {
Element el = mDoc.createElement(tagName);
for (int i = 0; i < attributes.length; i++) {
//el.setAttribute(attributes[i], TextUtils.htmlEncode(values[i]));
String content = values[i];
if (content != null) {
Element attr = mDoc.createElement(attributes[i]);
attr.setTextContent(TextUtils.htmlEncode(content));
el.appendChild(attr);
}
}
mDoc.getDocumentElement().appendChild(el);
}
public int getNumberOfTag(String tagName) {
return mDoc.getElementsByTagName(tagName).getLength();
}
public String[][] getDataFromNode(String tagName, int index) {
Node node = mDoc.getElementsByTagName(tagName).item(index);
switch (mSchema) {
case SCHEMA_ATTRS:
return getDataFromAttributes(node);
case SCHEMA_ELS:
default:
return getDataFromChildren(node);
}
}
private String[][] getDataFromAttributes(Node node) {
NamedNodeMap attrs = node.getAttributes();
int numOfAttrs = attrs.getLength();
String[][] data = new String[2][numOfAttrs];
for (int i = 0; i < numOfAttrs; i++) {
data[0][i] = attrs.item(i).getNodeName();
data[1][i] = Html.fromHtml(attrs.item(i).getNodeValue()).toString();
}
return data;
}
private String[][] getDataFromChildren(Node node) {
NodeList children = node.getChildNodes();
// since getChildNodes returns ALL childNodes, include whitespace nodes,
// we need to do a first loop just to see how many ELEMENT nodes there are
int numOfChildEls = 0;
int length = children.getLength();
for (int i = 0; i < length; i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
numOfChildEls++;
}
}
String[][] data = new String[2][numOfChildEls];
for (int i = 0; i < length; i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
data[0][i] = child.getNodeName();
data[1][i] = Html.fromHtml(child.getTextContent().trim()).toString();
}
}
return data;
}
protected String getStringFromNode(Node root) {
StringBuilder result = new StringBuilder();
if (root.getNodeType() == Node.TEXT_NODE)
result.append(root.getNodeValue());
else {
if (root.getNodeType() != Node.DOCUMENT_NODE) {
StringBuffer attrs = new StringBuffer();
for (int k = 0; k < root.getAttributes().getLength(); ++k) {
attrs.append(" ").append(
root.getAttributes().item(k).getNodeName()).append(
"=\"").append(
root.getAttributes().item(k).getNodeValue())
.append("\" ");
}
result.append("<").append(root.getNodeName()).append(" ")
.append(attrs);
} else {
result.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
NodeList nodes = root.getChildNodes();
if (nodes.getLength() > 0) {
if (root.getNodeType() != Node.DOCUMENT_NODE) {
result.append(">");
}
for (int i = 0, j = nodes.getLength(); i < j; i++) {
Node node = nodes.item(i);
result.append(getStringFromNode(node));
}
if (root.getNodeType() != Node.DOCUMENT_NODE) {
result.append("</").append(root.getNodeName()).append(">");
}
} else {
if (root.getNodeType() != Node.DOCUMENT_NODE) {
result.append("/>");
}
}
}
return result.toString();
}
public String toString() {
return getStringFromNode(mDoc);
//return null;
}
} |
package vvk.numbers;
import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;
public class Application {
private static final BufferedReader READER;
private PAdic x;
private PAdic y;
private int base;
private PAdic addition;
private PAdic subtraction;
private PAdic multiplication;
private PAdic division;
static {
READER = new BufferedReader(new InputStreamReader(System.in));
}
public void read() throws IOException {
System.out.print("Base = ");
this.base = Integer.valueOf(READER.readLine());
String value;
System.out.print("x = ");
value = READER.readLine();
x = new PAdic(value, base);
System.out.print("y = ");
value = READER.readLine();
y = new PAdic(value, base);
}
public void calculate() {
addition = x.add(y);
subtraction = x.subtract(y);
multiplication = x.multiply(y);
if (new PAdic("0", this.base).equals(y)) {
division = null;
} else {
division = x.divide(y);
}
}
public void print() {
Map<String, PAdic> results = new LinkedHashMap<>();
results.put("| Addition |", addition);
results.put("| Substraction |", subtraction);
results.put("| Multiplication |", multiplication);
results.put("| Division |", division);
int totalLength = Math.max(Math.max(addition.toString().length(), subtraction.toString().length()), multiplication.toString().length()) + "| Multiplication |".length() + 3;
if (division != null) {
final int necessary = division.toString().length() + 3 + "| Division |".length();
if (totalLength < necessary) {
totalLength = necessary;
}
} else {
totalLength += 6;
}
final StringBuilder footer = new StringBuilder();
while (footer.length() < totalLength) {
footer.append('-');
}
footer.setCharAt(0, '+');
footer.setCharAt(17, '+');
footer.setCharAt(footer.length() - 1, '+');
System.out.println(footer.toString());
final StringBuilder nextLine = new StringBuilder();
nextLine.append("| Operation | Result");
while (nextLine.length() < totalLength - 1) {
nextLine.append(' ');
}
nextLine.append('|');
System.out.println(nextLine.toString());
System.out.println(footer.toString());
for (String key: results.keySet()) {
nextLine.delete(0, nextLine.length());
nextLine.append(key);
nextLine.append(" ").append(results.get(key));
while (nextLine.length() < totalLength - 2) {
nextLine.append(' ');
}
nextLine.append(" |");
System.out.println(nextLine.toString());
System.out.println(footer.toString());
}
}
private static void run(final Application app) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
app.read();
} catch (IOException e) {
System.out.println("Something went wrong while input was parsing.");
break;
}
app.calculate();
app.print();
}
}
}).start();
}
public static void main(String[] args) {
final Application app = new Application();
Application.run(app);
}
} |
package com.tang.intellij.lua.editor.formatter;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.TokenType;
import com.intellij.psi.formatter.common.AbstractBlock;
import com.intellij.psi.tree.TokenSet;
import com.tang.intellij.lua.psi.LuaTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class LuaScriptBlock extends AbstractBlock {
TokenSet formattingSet = TokenSet.create(
LuaTypes.BLOCK,
LuaTypes.FIELD_LIST
);
TokenSet childAttrSet = TokenSet.orSet(formattingSet, TokenSet.create(
LuaTypes.IF_STAT,
LuaTypes.DO_STAT,
LuaTypes.FUNC_BODY,
LuaTypes.TABLE_CONSTRUCTOR
));
private SpacingBuilder spacingBuilder;
private Indent indent;
protected LuaScriptBlock(@NotNull ASTNode node, @Nullable Wrap wrap, @Nullable Alignment alignment, Indent indent, SpacingBuilder spacingBuilder) {
super(node, wrap, alignment);
this.spacingBuilder = spacingBuilder;
this.indent = indent;
}
private static boolean shouldCreateBlockFor(ASTNode node) {
return node.getTextRange().getLength() != 0 && node.getElementType() != TokenType.WHITE_SPACE;
}
@Override
protected List<Block> buildChildren() {
List<Block> blocks = new ArrayList<>();
ASTNode node = myNode.getFirstChildNode();
while (node != null) {
if (shouldCreateBlockFor(node)) {
Indent childIndent = Indent.getNoneIndent();
if (formattingSet.contains(myNode.getElementType())) {
childIndent = Indent.getNormalIndent();
}
blocks.add(new LuaScriptBlock(node, null, null, childIndent, spacingBuilder));
}
node = node.getTreeNext();
}
return blocks;
}
@Nullable
@Override
public Spacing getSpacing(@Nullable Block block, @NotNull Block block1) {
return spacingBuilder.getSpacing(this, block, block1);
}
@Override
public boolean isLeaf() {
return myNode.getFirstChildNode() == null;
}
@Override
public Indent getIndent() {
return indent;
}
@NotNull
@Override
public ChildAttributes getChildAttributes(int newChildIndex) {
if (childAttrSet.contains(myNode.getElementType()))
return new ChildAttributes(Indent.getNormalIndent(), null);
return new ChildAttributes(Indent.getNoneIndent(), null);
//return super.getChildAttributes(newChildIndex);
}
} |
package org.eclipse.xtext.crossrefs.indexbased;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.index.ECrossReferenceDescriptor;
import org.eclipse.emf.index.EObjectDescriptor;
import org.eclipse.emf.index.IIndexStore;
import org.eclipse.emf.index.impl.memory.InMemoryIndex;
import org.eclipse.xtext.crossref.indexImpl.AbstractDeclarativeNameProvider;
import org.eclipse.xtext.crossref.indexImpl.INameProvider;
import org.eclipse.xtext.crossref.indexImpl.IndexAwareResourceSet;
import org.eclipse.xtext.crossrefs.ImportUriTestLanguageRuntimeModule;
import org.eclipse.xtext.crossrefs.ImportUriTestLanguageStandaloneSetup;
import org.eclipse.xtext.crossrefs.importedURI.Type;
import org.eclipse.xtext.tests.AbstractGeneratorTest;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provider;
/**
* @author Sven Efftinge - Initial contribution and API TODO this test fails with NoClassDefFound for a guice class,
* when executed as plugin test
*/
public class IndexAwareResourcesetTest extends AbstractGeneratorTest {
public void testStuff() throws Exception {
IndexAwareResourceSet set = get(IndexAwareResourceSet.class);
set.setClasspathURIContext(IndexAwareResourcesetTest.class);
URI uri = URI.createURI("classpath:/" + getClass().getName().replace('.', '/') + ".importuritestlanguage");
set.getResource(uri, true);
Iterable<EObjectDescriptor> query = set.getStore().eObjectDAO().createQuery().executeListResult();
Iterator<EObjectDescriptor> result = query.iterator();
List<String> names = new ArrayList<String>();
names.add(result.next().getName());
names.add(result.next().getName());
assertFalse(result.hasNext());
assertTrue(names.contains("A"));
assertTrue(names.contains("B"));
result = query.iterator();
List<URI> uris = new ArrayList<URI>();
uris.add(result.next().getFragmentURI());
uris.add(result.next().getFragmentURI());
Iterator<ECrossReferenceDescriptor> iter = set.getStore().eCrossReferenceDAO().createQuery()
.executeListResult().iterator();
ECrossReferenceDescriptor next = iter.next();
assertTrue(uris.contains(next.getSourceURI()));
assertTrue(uris.contains(next.getTargetURI()));
}
private final INameProvider nameProvider = new AbstractDeclarativeNameProvider() {
@SuppressWarnings("unused")
public String getName(Type type) {
return type.getName();
}
};
@Override
protected void setUp() throws Exception {
super.setUp();
with(new ImportUriTestLanguageStandaloneSetup() {
@Override
public Injector createInjector() {
return Guice.createInjector(new ImportUriTestLanguageRuntimeModule() {
@Override
public void configure(Binder binder) {
super.configure(binder);
binder.bind(INameProvider.class).toProvider(new Provider<? extends INameProvider>() {
public INameProvider get() {
return IndexAwareResourcesetTest.this.getNameProvider();
}
});
}
@SuppressWarnings("unused")
public Class<? extends IIndexStore> bindIIndexStore() {
return InMemoryIndex.class;
}
});
}
});
}
protected INameProvider getNameProvider() {
return this.nameProvider;
}
} |
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
JTree tree = new JTree() {
@Override public void updateUI() {
setCellRenderer(null);
setCellEditor(null);
super.updateUI();
//???#1: JDK 1.6.0 bug??? Nimbus LnF
setCellRenderer(new CheckBoxNodeRenderer());
setCellEditor(new CheckBoxNodeEditor());
}
};
boolean b = true;
TreeModel model = tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
Enumeration e = root.breadthFirstEnumeration();
while (e.hasMoreElements()) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
node.setUserObject(new CheckBoxNode(Objects.toString(node.getUserObject(), ""), b));
b ^= true;
}
tree.setEditable(true);
tree.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
setBorder(BorderFactory.createTitledBorder("JCheckBoxes as JTree Leaf Nodes"));
add(new JScrollPane(tree));
setPreferredSize(new Dimension(320, 240));
}
// protected static TreeModel getDefaultTreeModel() {
// DefaultMutableTreeNode root = new DefaultMutableTreeNode("JTree");
// DefaultMutableTreeNode parent;
// parent = new DefaultMutableTreeNode("colors");
// root.add(parent);
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("blue", false)));
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("violet", false)));
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("red", false)));
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("yellow", false)));
// parent = new DefaultMutableTreeNode("sports");
// root.add(parent);
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("basketball", true)));
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("soccer", true)));
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("football", true)));
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("hockey", true)));
// parent = new DefaultMutableTreeNode("food");
// root.add(parent);
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("hot dogs", false)));
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("pizza", false)));
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("ravioli", false)));
// parent.add(new DefaultMutableTreeNode(new CheckBoxNode("bananas", false)));
// return new DefaultTreeModel(root);
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
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 CheckBoxNodeRenderer implements TreeCellRenderer {
private final JCheckBox checkBox = new JCheckBox();
private final DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
@Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (leaf && value instanceof DefaultMutableTreeNode) {
checkBox.setEnabled(tree.isEnabled());
checkBox.setFont(tree.getFont());
checkBox.setOpaque(false);
checkBox.setFocusable(false);
Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
if (userObject instanceof CheckBoxNode) {
CheckBoxNode node = (CheckBoxNode) userObject;
checkBox.setText(node.text);
checkBox.setSelected(node.selected);
}
return checkBox;
}
return renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
}
}
/*/
//*/ |
package edu.umd.cs.findbugs;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.CheckForNull;
import edu.umd.cs.findbugs.cloud.CloudPlugin;
import edu.umd.cs.findbugs.updates.UpdateChecker;
import edu.umd.cs.findbugs.util.FutureValue;
import edu.umd.cs.findbugs.util.Util;
/**
* Version number and release date information.
*/
public class Version {
/**
* Major version number.
*/
public static final int MAJOR = 3;
/**
* Minor version number.
*/
public static final int MINOR = 0;
/**
* Patch level.
*/
public static final int PATCHLEVEL = 2;
/**
* Development version or release candidate?
*/
public static final boolean IS_DEVELOPMENT = true;
/**
* Release candidate number. "0" indicates that the version is not a release
* candidate.
*/
public static final int RELEASE_CANDIDATE = 0;
public static final String GIT_REVISION = System.getProperty("git.revision", "UNKNOWN");
/**
* Release date.
*/
private static final String COMPUTED_DATE;
public static final String DATE;
public static final String CORE_PLUGIN_RELEASE_DATE;
private static final String COMPUTED_ECLIPSE_DATE;
private static final String COMPUTED_PLUGIN_RELEASE_DATE;
private static String applicationName = "";
private static String applicationVersion = "";
static {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss z, dd MMMM, yyyy", Locale.ENGLISH);
SimpleDateFormat eclipseDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
SimpleDateFormat releaseDateFormat = new SimpleDateFormat(UpdateChecker.PLUGIN_RELEASE_DATE_FMT, Locale.ENGLISH);
Date now = new Date();
COMPUTED_DATE = dateFormat.format(now);
COMPUTED_ECLIPSE_DATE = eclipseDateFormat.format(now);
String tmp = releaseDateFormat.format(now);
COMPUTED_PLUGIN_RELEASE_DATE = tmp;
}
/**
* Preview release number. "0" indicates that the version is not a preview
* release.
*/
public static final int PREVIEW = 0;
private static final String RELEASE_SUFFIX_WORD;
static {
String suffix;
if (RELEASE_CANDIDATE > 0) {
suffix = "rc" + RELEASE_CANDIDATE;
} else if (PREVIEW > 0) {
suffix = "preview" + PREVIEW;
} else {
suffix = "dev-" + COMPUTED_ECLIPSE_DATE;
if (!"Unknown".equals(GIT_REVISION)) {
suffix += "-" + GIT_REVISION;
}
}
RELEASE_SUFFIX_WORD = suffix;
}
public static final String RELEASE_BASE = MAJOR + "." + MINOR + "." + PATCHLEVEL;
/**
* Release version string.
*/
public static final String COMPUTED_RELEASE = RELEASE_BASE + (IS_DEVELOPMENT ? "-" + RELEASE_SUFFIX_WORD : "");
/**
* Release version string.
*/
public static final String RELEASE;
/**
* Version of Eclipse plugin.
*/
private static final String COMPUTED_ECLIPSE_UI_VERSION = RELEASE_BASE + "." + COMPUTED_ECLIPSE_DATE;
static {
Class<Version> c = Version.class;
URL u = c.getResource(c.getSimpleName() + ".class");
boolean fromFile = "file".equals(u.getProtocol());
InputStream in = null;
String release = null;
String date = null;
String plugin_release_date = null;
if (!fromFile) {
try {
Properties versionProperties = new Properties();
in = Version.class.getResourceAsStream("version.properties");
if (in != null) {
versionProperties.load(in);
release = (String) versionProperties.get("release.number");
date = (String) versionProperties.get("release.date");
plugin_release_date = (String) versionProperties.get("plugin.release.date");
}
} catch (Exception e) {
assert true; // ignore
} finally {
Util.closeSilently(in);
}
}
if (release == null) {
release = COMPUTED_RELEASE;
}
if (date == null) {
date = COMPUTED_DATE;
}
if (plugin_release_date == null) {
plugin_release_date = COMPUTED_PLUGIN_RELEASE_DATE;
}
RELEASE = release;
DATE = date;
CORE_PLUGIN_RELEASE_DATE = plugin_release_date;
Date parsedDate;
try {
SimpleDateFormat fmt = new SimpleDateFormat(UpdateChecker.PLUGIN_RELEASE_DATE_FMT, Locale.ENGLISH);
parsedDate = fmt.parse(CORE_PLUGIN_RELEASE_DATE);
} catch (ParseException e) {
if (SystemProperties.ASSERTIONS_ENABLED) {
e.printStackTrace();
}
parsedDate = null;
}
releaseDate = parsedDate;
}
/**
* FindBugs website.
*/
public static final String WEBSITE = "http://findbugs.sourceforge.net";
/**
* Downloads website.
*/
public static final String DOWNLOADS_WEBSITE = "http://prdownloads.sourceforge.net/findbugs";
/**
* Support email.
*/
public static final String SUPPORT_EMAIL = "http://findbugs.sourceforge.net/reportingBugs.html";
private static Date releaseDate;
public static void registerApplication(String name, String version) {
applicationName = name;
applicationVersion = version;
}
public static @CheckForNull String getApplicationName() {
return applicationName;
}
public static @CheckForNull String getApplicationVersion() {
return applicationVersion;
}
public static void main(String[] argv) throws InterruptedException {
if (!IS_DEVELOPMENT && RELEASE_CANDIDATE != 0) {
throw new IllegalStateException("Non developmental version, but is release candidate " + RELEASE_CANDIDATE);
}
if (argv.length == 0) {
printVersion(false);
return;
}
String arg = argv[0];
if ("-release".equals(arg)) {
System.out.println(RELEASE);
} else if ("-date".equals(arg)) {
System.out.println(DATE);
} else if ("-props".equals(arg)) {
System.out.println("release.base=" + RELEASE_BASE);
System.out.println("release.number=" + COMPUTED_RELEASE);
System.out.println("release.date=" + COMPUTED_DATE);
System.out.println("plugin.release.date=" + COMPUTED_PLUGIN_RELEASE_DATE);
System.out.println("eclipse.ui.version=" + COMPUTED_ECLIPSE_UI_VERSION);
System.out.println("findbugs.website=" + WEBSITE);
System.out.println("findbugs.downloads.website=" + DOWNLOADS_WEBSITE);
System.out.println("findbugs.git.revision=" + GIT_REVISION);
} else if ("-plugins".equals(arg)) {
DetectorFactoryCollection.instance();
for(Plugin p : Plugin.getAllPlugins()) {
System.out.println("Plugin: " + p.getPluginId());
System.out.println(" description: " + p.getShortDescription());
System.out.println(" provider: " + p.getProvider());
String version = p.getVersion();
if (version != null && version.length() > 0) {
System.out.println(" version: " + version);
}
String website = p.getWebsite();
if (website != null && website.length() > 0) {
System.out.println(" website: " + website);
}
System.out.println();
}
} else if ("-configuration".equals(arg)){
printVersion(true);
} else {
usage();
System.exit(1);
}
}
private static void usage() {
System.err.println("Usage: " + Version.class.getName() + " [(-release|-date|-props|-configuration)]");
}
public static String getReleaseWithDateIfDev() {
if (IS_DEVELOPMENT) {
return RELEASE + " (" + DATE + ")";
}
return RELEASE;
}
public static @CheckForNull Date getReleaseDate() {
return releaseDate;
}
/**
* @param justPrintConfiguration
* @throws InterruptedException
*/
public static void printVersion(boolean justPrintConfiguration) throws InterruptedException {
System.out.println("FindBugs " + Version.COMPUTED_RELEASE);
if (justPrintConfiguration) {
for (Plugin plugin : Plugin.getAllPlugins()) {
System.out.printf("Plugin %s, version %s, loaded from %s%n", plugin.getPluginId(), plugin.getVersion(),
plugin.getPluginLoader().getURL());
if (plugin.isCorePlugin()) {
System.out.println(" is core plugin");
}
if (plugin.isInitialPlugin()) {
System.out.println(" is initial plugin");
}
if (plugin.isEnabledByDefault()) {
System.out.println(" is enabled by default");
}
if (plugin.isGloballyEnabled()) {
System.out.println(" is globally enabled");
}
Plugin parent = plugin.getParentPlugin();
if (parent != null) {
System.out.println(" has parent plugin " + parent.getPluginId());
}
for (CloudPlugin cloudPlugin : plugin.getCloudPlugins()) {
System.out.printf(" cloud %s%n", cloudPlugin.getId());
System.out.printf(" %s%n", cloudPlugin.getDescription());
}
for (DetectorFactory factory : plugin.getDetectorFactories()) {
System.out.printf(" detector %s%n", factory.getShortName());
}
System.out.println();
}
printPluginUpdates(true, 10);
} else {
printPluginUpdates(false, 3);
}
}
private static void printPluginUpdates(boolean verbose, int secondsToWait) throws InterruptedException {
DetectorFactoryCollection dfc = DetectorFactoryCollection.instance();
if (dfc.getUpdateChecker().updateChecksGloballyDisabled()) {
if (verbose) {
System.out.println();
System.out.print("Update checking globally disabled");
}
return;
}
if (verbose) {
System.out.println();
System.out.print("Checking for plugin updates...");
}
FutureValue<Collection<UpdateChecker.PluginUpdate>>
updateHolder = dfc.getUpdates();
try {
Collection<UpdateChecker.PluginUpdate> updates = updateHolder.get(secondsToWait, TimeUnit.SECONDS);
if (updates.isEmpty()) {
if (verbose) {
System.out.println("none!");
}
} else {
System.out.println();
for (UpdateChecker.PluginUpdate update : updates) {
System.out.println(update);
System.out.println();
}
}
} catch (TimeoutException e) {
if (verbose) {
System.out.println("Timeout while trying to get updates");
}
}
}
} |
package com.xpn.xwiki.plugin.spacemanager.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import org.apache.velocity.VelocityContext;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.api.Api;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.plugin.XWikiDefaultPlugin;
import com.xpn.xwiki.plugin.XWikiPluginInterface;
import com.xpn.xwiki.plugin.mailsender.Mail;
import com.xpn.xwiki.plugin.mailsender.MailSenderPlugin;
import com.xpn.xwiki.plugin.spacemanager.api.Space;
import com.xpn.xwiki.plugin.spacemanager.api.SpaceManager;
import com.xpn.xwiki.plugin.spacemanager.api.SpaceManagerException;
import com.xpn.xwiki.plugin.spacemanager.api.SpaceManagerExtension;
import com.xpn.xwiki.plugin.spacemanager.api.SpaceManagers;
import com.xpn.xwiki.plugin.spacemanager.api.SpaceUserProfile;
import com.xpn.xwiki.plugin.spacemanager.plugin.SpaceManagerPluginApi;
import com.xpn.xwiki.render.XWikiVelocityRenderer;
import com.xpn.xwiki.user.api.XWikiGroupService;
/**
* Space manager plug-in implementation class. Manages {@link Space} spaces
*
* @version $Id: $
*/
public class SpaceManagerImpl extends XWikiDefaultPlugin implements
SpaceManager {
public final static String SPACEMANAGER_EXTENSION_CFG_PROP = "xwiki.spacemanager.extension";
public final static String SPACEMANAGER_PROTECTED_SUBSPACES_PROP = "xwiki.spacemanager.protectedsubspaces";
public final static String SPACEMANAGER_DEFAULT_PROTECTED_SUBSPACES = "";
public final static String SPACEMANAGER_DEFAULT_EXTENSION = "org.xwiki.plugin.spacemanager.impl.SpaceManagerExtensionImpl";
public final static String SPACEMANAGER_DEFAULT_MAIL_NOTIFICATION = "1";
/**
* The extension that defines specific functions for this space manager
*/
protected SpaceManagerExtension spaceManagerExtension;
protected boolean mailNotification;
/**
* Space manager constructor
*
* @param name
* @param className
* @param context
*/
public SpaceManagerImpl(String name, String className, XWikiContext context) {
super(name, className, context);
String mailNotificationCfg = context.getWiki().Param(
"xwiki.spacemanager.mailnotification",
SpaceManagerImpl.SPACEMANAGER_DEFAULT_MAIL_NOTIFICATION).trim();
mailNotification = "1".equals(mailNotificationCfg);
}
/**
* {@inheritDoc}
*/
public void flushCache() {
super.flushCache();
}
/**
* @param context
* Xwiki context
* @return Returns the Space Class as defined by the extension
* @throws XWikiException
*/
protected BaseClass getSpaceClass(XWikiContext context)
throws XWikiException {
XWikiDocument doc;
XWiki xwiki = context.getWiki();
boolean needsUpdate = false;
try {
doc = xwiki.getDocument(getSpaceClassName(), context);
} catch (Exception e) {
doc = new XWikiDocument();
doc.setFullName(getSpaceClassName());
needsUpdate = true;
}
BaseClass bclass = doc.getxWikiClass();
bclass.setName(getSpaceClassName());
needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_DISPLAYTITLE,
"Display Name", 64);
needsUpdate |= bclass.addTextAreaField(SpaceImpl.SPACE_DESCRIPTION,
"Description", 45, 4);
needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_TYPE,
"Group or plain space", 32);
needsUpdate |= bclass.addTextField(SpaceImpl.SPACE_URLSHORTCUT,
"URL Shortcut", 40);
needsUpdate |= bclass.addStaticListField(SpaceImpl.SPACE_POLICY,
"Membership Policy", 1, false,
"open=Open membership|closed=Closed membership", "radio");
needsUpdate |= bclass
.addStaticListField(
SpaceImpl.SPACE_LANGUAGE,
"Language",
"en=English|zh=Chinese|nl=Dutch|fr=French|de=German|it=Italian|jp=Japanese|kr=Korean|po=Portuguese|ru=Russian|sp=Spanish");
String content = doc.getContent();
if ((content == null) || (content.equals(""))) {
needsUpdate = true;
doc.setContent("1 XWikiSpaceClass");
}
if (needsUpdate)
xwiki.saveDocument(doc, context);
return bclass;
}
/**
* {@inheritDoc}
*/
public String getSpaceTypeName() {
return getSpaceManagerExtension().getSpaceTypeName();
}
/**
* {@inheritDoc}
*/
public String getSpaceClassName() {
return getSpaceManagerExtension().getSpaceClassName();
}
/**
* Checks if this space manager has custom mapping
*
* @return
*/
public boolean hasCustomMapping() {
return getSpaceManagerExtension().hasCustomMapping();
}
/**
* {@inheritDoc}
*/
public void init(XWikiContext context) {
try {
getSpaceManagerExtension(context);
getSpaceManagerExtension().init(this, context);
SpaceManagers.addSpaceManager(this);
getSpaceClass(context);
SpaceUserProfileImpl.getSpaceUserProfileClass(context);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* {@inheritDoc}
*/
public void virtualInit(XWikiContext context) {
try {
getSpaceClass(context);
getSpaceManagerExtension().virtualInit(this, context);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* {@inheritDoc}
*/
public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) {
return new SpaceManagerPluginApi((SpaceManager) plugin, context);
}
/**
* {@inheritDoc}
*/
public SpaceManagerExtension getSpaceManagerExtension(XWikiContext context)
throws SpaceManagerException {
if (spaceManagerExtension == null) {
String extensionName = context.getWiki().Param(
SPACEMANAGER_EXTENSION_CFG_PROP,
SPACEMANAGER_DEFAULT_EXTENSION);
try {
if (extensionName != null) {
spaceManagerExtension = (SpaceManagerExtension) Class
.forName(extensionName).newInstance();
}
} catch (Throwable e) {
try {
spaceManagerExtension = (SpaceManagerExtension) Class
.forName(SPACEMANAGER_DEFAULT_EXTENSION)
.newInstance();
} catch (Throwable e2) {
}
}
}
if (spaceManagerExtension == null) {
spaceManagerExtension = new SpaceManagerExtensionImpl();
}
return spaceManagerExtension;
}
public SpaceManagerExtension getSpaceManagerExtension() {
return spaceManagerExtension;
}
/**
* {@inheritDoc}
*/
public String getName() {
return "spacemanager";
}
private Object notImplemented() throws SpaceManagerException {
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED,
"not implemented");
}
/**
* {@inheritDoc}
*/
public String getSpaceWikiName(String spaceTitle, boolean unique,
XWikiContext context) {
return getSpaceManagerExtension().getSpaceWikiName(spaceTitle, unique,
context);
}
/**
* @param spaceName
* The name of the space
* @return the name of the space document for a specific space
*/
protected String getSpaceDocumentName(String spaceName) {
return spaceName + ".WebPreferences";
}
/**
* {@inheritDoc}
*/
public String[] getProtectedSubSpaces(XWikiContext context) {
String protectedSubSpaces = context.getWiki().Param(
SPACEMANAGER_PROTECTED_SUBSPACES_PROP,
SPACEMANAGER_DEFAULT_PROTECTED_SUBSPACES);
if ((protectedSubSpaces != null) && (!protectedSubSpaces.equals(""))) {
return protectedSubSpaces.split(",");
} else {
return new String[0];
}
}
/**
* Gives a group certain rights over a space
*
* @param spaceName
* Name of the space
* @param groupName
* Name of the group that will have the value
* @param level
* Access level
* @param allow
* True if the right is allow, deny if not
*/
protected boolean addRightToGroup(String spaceName, String groupName,
String level, boolean allow, boolean global, XWikiContext context)
throws XWikiException {
final String rightsClass = global ? "XWiki.XWikiGlobalRights"
: "XWiki.XWikiRights";
final String prefDocName = spaceName + ".WebPreferences";
final String groupsField = "groups";
final String levelsField = "levels";
final String allowField = "allow";
XWikiDocument prefDoc;
prefDoc = context.getWiki().getDocument(prefDocName, context);
// checks to see if the right is not already given
boolean exists = false;
boolean isUpdated = false;
int indx = -1;
boolean foundlevel = false;
int allowInt;
if (allow)
allowInt = 1;
else
allowInt = 0;
List objs = prefDoc.getObjects(rightsClass);
if (objs != null) {
for (int i = 0; i < objs.size(); i++) {
BaseObject bobj = (BaseObject) objs.get(i);
if (bobj == null)
continue;
String groups = bobj.getStringValue(groupsField);
String levels = bobj.getStringValue(levelsField);
int allowDeny = bobj.getIntValue(allowField);
boolean allowdeny = (bobj.getIntValue(allowField) == 1);
String[] levelsarray = levels.split(" ,|");
String[] groupsarray = groups.split(" ,|");
if (ArrayUtils.contains(groupsarray, groupName)) {
exists = true;
if (!foundlevel)
indx = i;
if (ArrayUtils.contains(levelsarray, level)) {
foundlevel = true;
if (allowInt == allowDeny) {
isUpdated = true;
break;
}
}
}
}
}
// sets the rights. the aproach is to break rules/levels in as many
// XWikiRigts elements so
// we don't have to handle lots of situation when we change rights
if (!exists) {
BaseObject bobj = new BaseObject();
bobj.setClassName(rightsClass);
bobj.setName(prefDoc.getFullName());
bobj.setStringValue(groupsField, groupName);
bobj.setStringValue(levelsField, level);
bobj.setIntValue(allowField, allowInt);
prefDoc.addObject(rightsClass, bobj);
context.getWiki().saveDocument(prefDoc, context);
return true;
} else {
if (isUpdated) {
return true;
} else {
BaseObject bobj = (BaseObject) objs.get(indx);
String groups = bobj.getStringValue(groupsField);
String levels = bobj.getStringValue(levelsField);
String[] levelsarray = levels.split(" ,|");
String[] groupsarray = groups.split(" ,|");
if (levelsarray.length == 1 && groupsarray.length == 1
&& levelsarray[0] == level) {
// if there is only this group and this level in the rule
// update this rule
} else {
// if there are more groups/levels, extract this one(s)
bobj = new BaseObject();
bobj.setName(prefDoc.getFullName());
bobj.setClassName(rightsClass);
bobj.setStringValue(levelsField, level);
bobj.setIntValue(allowField, allowInt);
bobj.setStringValue(groupsField, groupName);
}
prefDoc.addObject(rightsClass, bobj);
context.getWiki().saveDocument(prefDoc, context);
return true;
}
}
}
/**
* Gives a group certain rights over a space
*
* @param spaceName
* Name of the space
* @param groupName
* Name of the group that will have the value
* @param level
* Access level
* @param allow
* True if the right is allow, deny if not
*/
protected boolean removeRightFromGroup(String spaceName, String groupName,
String level, boolean allow, boolean global, XWikiContext context)
throws XWikiException {
final String rightsClass = global ? "XWiki.XWikiGlobalRights"
: "XWiki.XWikiRights";
final String prefDocName = spaceName + ".WebPreferences";
final String groupsField = "groups";
final String levelsField = "levels";
final String allowField = "allow";
XWikiDocument prefDoc;
prefDoc = context.getWiki().getDocument(prefDocName, context);
boolean foundlevel = false;
int allowInt;
if (allow)
allowInt = 1;
else
allowInt = 0;
List objs = prefDoc.getObjects(rightsClass);
if (objs != null) {
for (int i = 0; i < objs.size(); i++) {
BaseObject bobj = (BaseObject) objs.get(i);
if (bobj == null)
continue;
String groups = bobj.getStringValue(groupsField);
String levels = bobj.getStringValue(levelsField);
int allowDeny = bobj.getIntValue(allowField);
boolean allowdeny = (bobj.getIntValue(allowField) == 1);
String[] levelsarray = levels.split(" ,|");
String[] groupsarray = groups.split(" ,|");
if (ArrayUtils.contains(groupsarray, groupName)) {
if (!foundlevel)
if (ArrayUtils.contains(levelsarray, level)) {
foundlevel = true;
if (allowInt == allowDeny) {
prefDoc.removeObject(bobj);
context.getWiki()
.saveDocument(prefDoc, context);
return true;
}
}
}
}
}
return false;
}
/**
* {@inheritDoc}
*/
public void setSpaceRights(Space newspace, XWikiContext context)
throws SpaceManagerException {
// Set admin edit rights on group prefs
try {
addRightToGroup(newspace.getSpaceName(), getAdminGroupName(newspace
.getSpaceName()), "edit", true, false, context);
// Set admin admin rights on group prefs
addRightToGroup(newspace.getSpaceName(), getAdminGroupName(newspace
.getSpaceName()), "admin", true, true, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
String[] subSpaces = getProtectedSubSpaces(context);
for (int i = 0; i < subSpaces.length; i++) {
setSubSpaceRights(newspace, subSpaces[i], context);
}
}
/**
* {@inheritDoc}
*/
public void updateSpaceRights(Space space, String oldPolicy,
String newPolicy, XWikiContext context)
throws SpaceManagerException {
try {
if (oldPolicy.equals(newPolicy))
return;
String[] subSpaces = getProtectedSubSpaces(context);
for (int i = 0; i < subSpaces.length; i++) {
if (newPolicy.equals("closed")) {
addRightToGroup(subSpaces[i] + "_" + space.getSpaceName(),
getMemberGroupName(space.getSpaceName()), "view",
true, false, context);
addRightToGroup(subSpaces[i] + "_" + space.getSpaceName(),
getMemberGroupName(space.getSpaceName()),
"comment", true, false, context);
} else if (newPolicy.equals("open")) {
removeRightFromGroup(subSpaces[i] + "_"
+ space.getSpaceName(), getMemberGroupName(space
.getSpaceName()), "view", true, false, context);
removeRightFromGroup(subSpaces[i] + "_"
+ space.getSpaceName(), getMemberGroupName(space
.getSpaceName()), "comment", true, false, context);
}
}
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public void setSubSpaceRights(Space space, String subSpace,
XWikiContext context) throws SpaceManagerException {
try {
if ((subSpace != null) && (!subSpace.equals(""))) {
// Set admin edit rights on Messages group prefs
addRightToGroup(subSpace + "_" + space.getSpaceName(),
getMemberGroupName(space.getSpaceName()), "edit", true,
true, context);
// Set admin admin rights on Messages group prefs
addRightToGroup(subSpace + "_" + space.getSpaceName(),
getAdminGroupName(space.getSpaceName()), "admin", true,
true, context);
// Set admin admin rights on Messages group prefs
addRightToGroup(subSpace + "_" + space.getSpaceName(),
getAdminGroupName(space.getSpaceName()), "edit", true,
false, context);
if ("closed".equals(space.getPolicy())) {
addRightToGroup(subSpace + "_" + space.getSpaceName(),
getMemberGroupName(space.getSpaceName()), "view",
true, false, context);
addRightToGroup(subSpace + "_" + space.getSpaceName(),
getMemberGroupName(space.getSpaceName()),
"comment", true, false, context);
}
}
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public Space createSpace(String spaceTitle, XWikiContext context)
throws SpaceManagerException {
// Init out space object by creating the space
// this will throw an exception when the space exists
Space newspace = newSpace(null, spaceTitle, true, context);
// execute precreate actions
try {
getSpaceManagerExtension().preCreateSpace(newspace.getSpaceName(),
context);
} catch (SpaceManagerException e) {
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_CREATION_ABORTED_BY_EXTENSION,
"Space creation aborted by extension", e);
}
// Make sure we set the type
newspace.setType(getSpaceTypeName());
try {
newspace.saveWithProgrammingRights();
// we need to add the creator as a member and as an admin
addAdmin(newspace.getSpaceName(), context.getUser(), context);
addMember(newspace.getSpaceName(), context.getUser(), context);
setSpaceRights(newspace, context);
// execute post space creation
getSpaceManagerExtension().postCreateSpace(newspace.getSpaceName(),
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
sendMail(SpaceAction.CREATE, newspace, context); // this should be in
// the extension's
// postcreate
return newspace;
}
/**
* {@inheritDoc}
*/
public Space createSpaceFromTemplate(String spaceTitle,
String templateSpaceName, XWikiContext context)
throws SpaceManagerException {
// Init out space object by creating the space
// this will throw an exception when the space exists
Space newspace = newSpace(null, spaceTitle, false, context);
// execute precreate actions
try {
getSpaceManagerExtension().preCreateSpace(newspace.getSpaceName(),
context);
} catch (SpaceManagerException e) {
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_CREATION_ABORTED_BY_EXTENSION,
"Space creation aborted by extension", e);
}
// Make sure this space does not already exist
if (!newspace.isNew())
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_ALREADY_EXISTS,
"Space already exists");
// Copy over template data over our current data
try {
context.getWiki()
.copyWikiWeb(templateSpaceName, context.getDatabase(),
context.getDatabase(), null, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
// Make sure we set the type
newspace.setType(getSpaceTypeName());
newspace.setDisplayTitle(spaceTitle);
newspace.setCreator(context.getUser());
newspace.setCreationDate(new Date());
try {
newspace.saveWithProgrammingRights();
// we need to add the creator as a member and as an admin
addAdmin(newspace.getSpaceName(), context.getUser(), context);
addMember(newspace.getSpaceName(), context.getUser(), context);
setSpaceRights(newspace, context);
// execute post space creation
getSpaceManagerExtension().postCreateSpace(newspace.getSpaceName(),
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
sendMail(SpaceAction.CREATE, newspace, context);
return newspace;
}
/**
* {@inheritDoc}
*/
public Space createSpaceFromApplication(String spaceTitle,
String applicationName, XWikiContext context)
throws SpaceManagerException {
notImplemented();
return null;
}
/**
* {@inheritDoc}
*/
public Space createSpaceFromRequest(String templateSpaceName,
XWikiContext context) throws SpaceManagerException {
// Init out space object by creating the space
// this will throw an exception when the space exists
String spaceTitle = context.getRequest().get(
spaceManagerExtension.getSpaceClassName() + "_0_displayTitle");
if (spaceTitle == null) {
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_TITLE_MISSING,
"Space title is missing");
}
Space newspace = newSpace(null, spaceTitle, true, context);
// execute precreate actions
try {
getSpaceManagerExtension().preCreateSpace(newspace.getSpaceName(),
context);
} catch (SpaceManagerException e) {
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_CREATION_ABORTED_BY_EXTENSION,
"Space creation aborted by extension", e);
}
newspace.updateSpaceFromRequest();
if (!newspace.validateSpaceData())
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_DATA_INVALID,
"Space data is not valid");
// Copy over template data over our current data
if (templateSpaceName != null) {
try {
List list = context.getWiki().getStore().searchDocumentsNames(
"where doc.web='" + templateSpaceName + "'", context);
for (Iterator it = list.iterator(); it.hasNext();) {
String docname = (String) it.next();
XWikiDocument doc = context.getWiki().getDocument(docname,
context);
context.getWiki().copyDocument(doc.getFullName(),
newspace.getSpaceName() + "." + doc.getName(),
null, null, null, true, false, true, context);
}
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
// Make sure we set the type
newspace.setType(getSpaceTypeName());
// we need to do it twice because data could have been overwritten by
// copyWikiWeb
newspace.updateSpaceFromRequest();
newspace.setCreator(context.getUser());
newspace.setCreationDate(new Date());
try {
newspace.saveWithProgrammingRights();
// we need to add the creator as a member and as an admin
addAdmin(newspace.getSpaceName(), context.getUser(), context);
addMember(newspace.getSpaceName(), context.getUser(), context);
setSpaceRights(newspace, context);
// execute precreate actions
getSpaceManagerExtension().postCreateSpace(newspace.getSpaceName(),
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
sendMail(SpaceAction.CREATE, newspace, context);
return newspace;
}
protected Space newSpace(String spaceName, String spaceTitle,
boolean create, XWikiContext context) throws SpaceManagerException {
return new SpaceImpl(spaceName, spaceTitle, create, this, context);
}
/**
* {@inheritDoc}
*/
public Space createSpaceFromRequest(XWikiContext context)
throws SpaceManagerException {
return createSpaceFromRequest(null, context);
}
/**
* {@inheritDoc}
*/
public void deleteSpace(String spaceName, boolean deleteData,
XWikiContext context) throws SpaceManagerException {
if (deleteData) {
// we are not implementing full delete yet
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_XWIKI_NOT_IMPLEMENTED,
"Not implemented");
}
Space space = getSpace(spaceName, context);
// execute pre delete actions
if (getSpaceManagerExtension().preDeleteSpace(space.getSpaceName(),
deleteData, context)) {
if (!space.isNew()) {
space.setType("deleted");
try {
space.saveWithProgrammingRights();
// execute post delete actions
getSpaceManagerExtension().postDeleteSpace(
space.getSpaceName(), deleteData, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
}
}
/**
* {@inheritDoc}
*/
public void deleteSpace(String spaceName, XWikiContext context)
throws SpaceManagerException {
deleteSpace(spaceName, false, context);
}
/**
* {@inheritDoc}
*/
public void undeleteSpace(String spaceName, XWikiContext context)
throws SpaceManagerException {
Space space = getSpace(spaceName, context);
if (space.isDeleted()) {
space.setType(getSpaceTypeName());
try {
space.saveWithProgrammingRights();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
}
/**
* {@inheritDoc}
*/
public Space getSpace(String spaceName, XWikiContext context)
throws SpaceManagerException {
// Init the space object but do not create anything if it does not exist
return newSpace(spaceName, spaceName, false, context);
}
/**
* {@inheritDoc}
*/
public List getSpaces(int nb, int start, XWikiContext context)
throws SpaceManagerException {
List spaceNames = getSpaceNames(nb, start, context);
return getSpaceObjects(spaceNames, context);
}
public List getSpaces(int nb, int start, String ordersql,
XWikiContext context) throws SpaceManagerException {
List spaceNames = getSpaceNames(nb, start, ordersql, context);
return getSpaceObjects(spaceNames, context);
}
/**
* Returns a list of nb space names starting at start
*
* @param context
* The XWiki Context
* @return list of Space objects
* @throws SpaceManagerException
*/
protected List getSpaceObjects(List spaceNames, XWikiContext context)
throws SpaceManagerException {
if (spaceNames == null)
return null;
List spaceList = new ArrayList();
for (int i = 0; i < spaceNames.size(); i++) {
String spaceName = (String) spaceNames.get(i);
Space space = getSpace(spaceName, context);
spaceList.add(space);
}
return spaceList;
}
public List getSpaceNames(int nb, int start, XWikiContext context)
throws SpaceManagerException {
return getSpaceNames(nb, start, "", context);
}
/**
* {@inheritDoc}
*/
public List getSpaceNames(int nb, int start, String ordersql,
XWikiContext context) throws SpaceManagerException {
String type = getSpaceTypeName();
String className = getSpaceClassName();
String sql;
if (hasCustomMapping())
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, "
+ className
+ " as space where doc.fullName = obj.name and obj.className='"
+ className
+ "' and obj.id = space.id and space.type='"
+ type + "'" + ordersql;
else
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty typeprop where doc.fullName=obj.name and obj.className = '"
+ className
+ "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='"
+ type + "'" + ordersql;
List spaceList = null;
try {
spaceList = context.getWiki().getStore().search(sql, nb, start,
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
return spaceList;
}
/**
* Performs a search for spaces
*
* @param fromsql
* The sql fragment describing the source of the search
* @param wheresql
* The sql fragment describing the where clause of the search
* @param ordersql
* The sql fragment describing the order in wich the spaces
* should be returned
* @param nb
* The number of spaces to return (limit)
* @param start
* Number of spaces to skip
* @param context
* XWiki context
* @return A list with space objects matching the search
* @throws SpaceManagerException
*/
public List searchSpaces(String fromsql, String wheresql, String ordersql,
int nb, int start, XWikiContext context)
throws SpaceManagerException {
List spaceNames = searchSpaceNames(fromsql, wheresql, ordersql, nb,
start, context);
return getSpaceObjects(spaceNames, context);
}
/**
* Performs a search for spaces. This variant returns the spaces ordered
* ascending by creation date
*
* @param fromsql
* The sql fragment describing the source of the search
* @param wheresql
* The sql fragment describing the where clause of the search
* @param nb
* The number of spaces to return (limit)
* @param start
* Number of spaces to skip
* @param context
* XWiki context
* @return A list with space objects matching the search
* @throws SpaceManagerException
*/
public List searchSpaces(String fromsql, String wheresql, int nb,
int start, XWikiContext context) throws SpaceManagerException {
return searchSpaces(fromsql, wheresql, "", nb, start, context);
}
/**
* Performs a search for space names
*
* @param fromsql
* The sql fragment describing the source of the search
* @param wheresql
* The sql fragment describing the where clause of the search
* @param ordersql
* The sql fragment describing the order in wich the spaces
* should be returned
* @param nb
* The number of spaces to return (limit)
* @param start
* Number of spaces to skip
* @param context
* XWiki context
* @return A list of strings representing the names of the spaces matching
* the search
* @throws SpaceManagerException
*/
public List searchSpaceNames(String fromsql, String wheresql,
String ordersql, int nb, int start, XWikiContext context)
throws SpaceManagerException {
String type = getSpaceTypeName();
String className = getSpaceClassName();
String sql;
if (hasCustomMapping())
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, "
+ className
+ " as space"
+ fromsql
+ " where doc.fullName = obj.name and obj.className='"
+ className
+ "' and obj.id = space.id and space.type='"
+ type + "'" + wheresql + ordersql;
else
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop"
+ fromsql
+ " where doc.fullName=obj.name and obj.className = '"
+ className
+ "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='"
+ type + "'" + wheresql + ordersql;
List spaceList = null;
try {
spaceList = context.getWiki().getStore().search(sql, nb, start,
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
return spaceList;
}
/**
* Performs a search for space names. This variant returns the spaces
* ordered ascending by creation date
*
* @param fromsql
* The sql fragment describing the source of the search
* @param wheresql
* The sql fragment describing the where clause of the search
* @param nb
* The number of spaces to return (limit)
* @param start
* Number of spaces to skip
* @param context
* XWiki context
* @return A list of strings representing the names of the spaces matching
* the search
* @throws SpaceManagerException
*/
public List searchSpaceNames(String fromsql, String wheresql, int nb,
int start, XWikiContext context) throws SpaceManagerException {
return searchSpaceNames(fromsql, wheresql, "", nb, start, context);
}
/**
* {@inheritDoc}
*/
public List getSpaces(String userName, String role, XWikiContext context)
throws SpaceManagerException {
List spaceNames = getSpaceNames(userName, role, context);
return getSpaceObjects(spaceNames, context);
}
/**
* {@inheritDoc}
*/
public List getSpaceNames(String userName, String role, XWikiContext context)
throws SpaceManagerException {
String sql;
if (role == null)
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='MemberGroup' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'"
+ " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='"
+ userName + "'";
else {
String roleGroupName = getRoleGroupName("", role).substring(1);
sql = "select distinct doc.web from XWikiDocument as doc, BaseObject as obj, StringProperty as memberprop where doc.name='"
+ roleGroupName
+ "' and doc.fullName=obj.name and obj.className = 'XWiki.XWikiGroups'"
+ " and obj.id=memberprop.id.id and memberprop.id.name='member' and memberprop.value='"
+ userName + "'";
}
List spaceList = null;
try {
spaceList = context.getWiki().getStore().search(sql, 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
return spaceList;
}
/**
* {@inheritDoc}
*/
public boolean updateSpaceFromRequest(Space space, XWikiContext context)
throws SpaceManagerException {
space.updateSpaceFromRequest();
if (space.validateSpaceData())
return true;
else
return false;
}
/**
* {@inheritDoc}
*/
public boolean validateSpaceData(Space space, XWikiContext context)
throws SpaceManagerException {
return space.validateSpaceData();
}
/**
* {@inheritDoc}
*/
public void saveSpace(Space space, XWikiContext context)
throws SpaceManagerException {
try {
space.saveWithProgrammingRights();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public void addAdmin(String spaceName, String username, XWikiContext context)
throws SpaceManagerException {
try {
addUserToGroup(username, getAdminGroupName(spaceName), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public void addAdmins(String spaceName, List usernames, XWikiContext context)
throws SpaceManagerException {
for (int i = 0; i < usernames.size(); i++) {
addAdmin(spaceName, (String) usernames.get(i), context);
}
}
/**
* {@inheritDoc}
*/
public Collection getAdmins(String spaceName, XWikiContext context)
throws SpaceManagerException {
try {
return getGroupService(context).getAllMembersNamesForGroup(
getAdminGroupName(spaceName), 0, 0, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*
* @see SpaceManager#removeAdmin(String, String, XWikiContext)
*/
public void removeAdmin(String spaceName, String userName,
XWikiContext context) throws SpaceManagerException {
try {
removeUserFromGroup(userName, getAdminGroupName(spaceName), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public boolean isAdmin(String spaceName, String userName,
XWikiContext context) throws SpaceManagerException {
try {
return isMemberOfGroup(userName, getAdminGroupName(spaceName),
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public void addUserToRole(String spaceName, String username, String role,
XWikiContext context) throws SpaceManagerException {
try {
addUserToGroup(username, getRoleGroupName(spaceName, role), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public void addUsersToRole(String spaceName, List usernames, String role,
XWikiContext context) throws SpaceManagerException {
for (int i = 0; i < usernames.size(); i++) {
addUserToRole(spaceName, (String) usernames.get(i), role, context);
}
}
/**
* {@inheritDoc}
*/
public Collection getUsersForRole(String spaceName, String role,
XWikiContext context) throws SpaceManagerException {
try {
return sortUserNames(getGroupService(context)
.getAllMembersNamesForGroup(
getRoleGroupName(spaceName, role), 0, 0, context),
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public boolean isMember(String spaceName, String username,
XWikiContext context) throws SpaceManagerException {
try {
return isMemberOfGroup(username, getMemberGroupName(spaceName),
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public void addUserToRoles(String spaceName, String username, List roles,
XWikiContext context) throws SpaceManagerException {
for (int i = 0; i < roles.size(); i++) {
addUserToRole(spaceName, username, (String) roles.get(i), context);
}
}
/**
* {@inheritDoc}
*/
public void addUsersToRoles(String spaceName, List usernames, List roles,
XWikiContext context) throws SpaceManagerException {
for (int i = 0; i < usernames.size(); i++) {
addUserToRoles(spaceName, (String) usernames.get(i), roles, context);
}
}
/**
* {@inheritDoc}
*
* @see SpaceManager#removeUserFromRoles(String, String, List, XWikiContext)
*/
public void removeUserFromRoles(String spaceName, String userName,
List roles, XWikiContext context) throws SpaceManagerException {
for (int i = 0; i < roles.size(); i++) {
removeUserFromRole(spaceName, userName, (String) roles.get(i),
context);
}
}
/**
* {@inheritDoc}
*/
public void removeUserFromRole(String spaceName, String userName,
String role, XWikiContext context) throws SpaceManagerException {
try {
removeUserFromGroup(userName, getRoleGroupName(spaceName, role),
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public void addMember(String spaceName, String username,
XWikiContext context) throws SpaceManagerException {
try {
addUserToGroup(username, getMemberGroupName(spaceName), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*
* @see SpaceManager#removeMember(String, String, XWikiContext)
*/
public void removeMember(String spaceName, String userName,
XWikiContext context) throws SpaceManagerException {
try {
// remove admin role
if (isAdmin(spaceName, userName, context)) {
removeAdmin(spaceName, userName, context);
}
// remove all the other roles
// Iterator it = getRoles(spaceName, context).iterator();
// while (it.hasNext()) {
// String role = (String) it.next();
// removeUserFromRole(spaceName, userName, role, context);
// delete space user profile
deleteSpaceUserProfile(spaceName, userName, context);
// remove member
removeUserFromGroup(userName, getMemberGroupName(spaceName),
context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
protected boolean isMemberOfGroup(String username, String groupname,
XWikiContext context) throws XWikiException {
Collection coll = context.getWiki().getGroupService(context)
.getAllGroupsNamesForMember(username, 0, 0, context);
Iterator it = coll.iterator();
while (it.hasNext()) {
if (groupname.equals((String) it.next()))
return true;
}
return false;
}
/**
* High speed user adding without resaving the whole groups doc
*
* @param username
* @param groupName
* @param context
* @throws XWikiException
*/
protected void addUserToGroup(String username, String groupName,
XWikiContext context) throws XWikiException {
// don't add if he is already a member
if (isMemberOfGroup(username, groupName, context))
return;
XWiki xwiki = context.getWiki();
BaseClass groupClass = xwiki.getGroupClass(context);
XWikiDocument groupDoc = xwiki.getDocument(groupName, context);
BaseObject memberObject = (BaseObject) groupClass.newObject(context);
memberObject.setClassName(groupClass.getName());
memberObject.setName(groupDoc.getFullName());
memberObject.setStringValue("member", username);
groupDoc.addObject(groupClass.getName(), memberObject);
String content = groupDoc.getContent();
if ((content == null) || (content.equals("")))
groupDoc.setContent("#includeForm(\"XWiki.XWikiGroupSheet\")");
xwiki.saveDocument(groupDoc, context.getMessageTool().get(
"core.comment.addedUserToGroup"), context);
/*
* if (groupDoc.isNew()) { } else {
* xwiki.getHibernateStore().saveXWikiObject(memberObject, context,
* true); } // we need to make sure we add the user to the group cache
* try { xwiki.getGroupService(context).addUserToGroup(username,
* context.getDatabase(), groupName, context); } catch (Exception e) {}
*/
}
private void removeUserFromGroup(String userName, String groupName,
XWikiContext context) throws XWikiException {
// don't remove if he's not a member
if (!isMemberOfGroup(userName, groupName, context)) {
return;
}
XWiki xwiki = context.getWiki();
BaseClass groupClass = xwiki.getGroupClass(context);
XWikiDocument groupDoc = xwiki.getDocument(groupName, context);
BaseObject memberObject = groupDoc.getObject(groupClass.getName(),
"member", userName);
if (memberObject == null) {
return;
}
groupDoc.removeObject(memberObject);
xwiki.saveDocument(groupDoc, context.getMessageTool().get(
"core.comment.removedUserFromGroup"), context);
}
/**
* {@inheritDoc}
*/
public void addMembers(String spaceName, List usernames,
XWikiContext context) throws SpaceManagerException {
for (int i = 0; i < usernames.size(); i++) {
addMember(spaceName, (String) usernames.get(i), context);
}
}
/**
* {@inheritDoc}
*
* @see SpaceManager#getMembers(String, XWikiContext)
*/
public Collection getMembers(String spaceName, XWikiContext context)
throws SpaceManagerException {
try {
return sortUserNames(getGroupService(context)
.getAllMembersNamesForGroup(getMemberGroupName(spaceName),
0, 0, context), context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
private List sortUserNames(Collection collectionOfUsers,
final XWikiContext context) {
List users = new ArrayList(collectionOfUsers);
Collections.sort(users, new Comparator() {
public int compare(Object a, Object b) {
try {
XWikiDocument aDoc = context.getWiki().getDocument(
(String) a, context);
XWikiDocument bDoc = context.getWiki().getDocument(
(String) b, context);
String aFirstName = aDoc.getObject("XWiki.XWikiUsers")
.getStringValue("first_name");
String bFirstName = bDoc.getObject("XWiki.XWikiUsers")
.getStringValue("first_name");
int cmp = aFirstName.compareToIgnoreCase(bFirstName);
if (cmp == 0) {
String aLastName = aDoc.getObject("XWiki.XWikiUsers")
.getStringValue("last_name");
String bLastName = bDoc.getObject("XWiki.XWikiUsers")
.getStringValue("last_name");
return aLastName.compareTo(bLastName);
} else {
return cmp;
}
} catch (Exception e) {
return ((String) a).compareTo((String) b);
}
}
});
return users;
}
public String getMemberGroupName(String spaceName) {
return getSpaceManagerExtension().getMemberGroupName(spaceName);
}
public String getAdminGroupName(String spaceName) {
return getSpaceManagerExtension().getAdminGroupName(spaceName);
}
public String getRoleGroupName(String spaceName, String role) {
return getSpaceManagerExtension().getRoleGroupName(spaceName, role);
}
protected XWikiGroupService getGroupService(XWikiContext context)
throws XWikiException {
return context.getWiki().getGroupService(context);
}
public SpaceUserProfile getSpaceUserProfile(String spaceName,
String username, XWikiContext context) throws SpaceManagerException {
return newUserSpaceProfile(username, spaceName, context);
}
private void deleteSpaceUserProfile(String spaceName, String userName,
XWikiContext context) throws SpaceManagerException {
try {
String docName = getSpaceUserProfilePageName(userName, spaceName);
XWikiDocument doc = context.getWiki().getDocument(docName, context);
if (!doc.isNew())
context.getWiki().deleteDocument(doc, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
public String getSpaceUserProfilePageName(String userName, String spaceName) {
return getSpaceManagerExtension().getSpaceUserProfilePageName(userName,
spaceName);
}
protected SpaceUserProfile newUserSpaceProfile(String user, String space,
XWikiContext context) throws SpaceManagerException {
try {
return new SpaceUserProfileImpl(user, space, this, context);
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public List getLastModifiedDocuments(String spaceName,
XWikiContext context, boolean recursive, int nb, int start)
throws SpaceManagerException {
notImplemented();
return null;
}
/**
* {@inheritDoc}
*/
public Collection getRoles(String spaceName, XWikiContext context)
throws SpaceManagerException {
notImplemented();
return null;
}
/**
* {@inheritDoc}
*
* @see SpaceManager#getRoles(String, String, XWikiContext)
*/
public Collection getRoles(String spaceName, String memberName,
XWikiContext context) throws SpaceManagerException {
try {
Collection memberRoles = context.getWiki().getGroupService(context)
.getAllGroupsNamesForMember(memberName, 0, 0, context);
Collection spaceRoles = getRoles(spaceName, context);
memberRoles.retainAll(spaceRoles);
return memberRoles;
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*/
public List getLastModifiedDocuments(String spaceName, XWikiContext context)
throws SpaceManagerException {
notImplemented();
return null;
}
/**
* {@inheritDoc}
*/
public List searchDocuments(String spaceName, String hql,
XWikiContext context) throws SpaceManagerException {
notImplemented();
return null;
}
/**
* {@inheritDoc}
*/
public int countSpaces(XWikiContext context) throws SpaceManagerException {
String type = getSpaceTypeName();
String className = getSpaceClassName();
String sql;
if (hasCustomMapping())
sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, "
+ className
+ " as space"
+ " where doc.fullName = obj.name and obj.className='"
+ className
+ "' and obj.id = space.id and space.type='"
+ type + "'";
else
sql = "select count(*) from XWikiDocument as doc, BaseObject as obj, StringProperty as typeprop"
+ " where doc.fullName=obj.name and obj.className = '"
+ className
+ "' and obj.id=typeprop.id.id and typeprop.id.name='type' and typeprop.value='"
+ type + "'";
try {
List result = context.getWiki().search(sql, context);
Integer res = (Integer) result.get(0);
return res.intValue();
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* {@inheritDoc}
*
* @see SpaceManager#joinSpace(String, XWikiContext)
*/
public boolean joinSpace(String spaceName, XWikiContext context)
throws SpaceManagerException {
try {
SpaceUserProfile userProfile = newUserSpaceProfile(context
.getUser(), spaceName, context);
userProfile.updateProfileFromRequest();
userProfile.saveWithProgrammingRights();
addMember(spaceName, context.getUser(), context);
sendMail(SpaceAction.JOIN, getSpace(spaceName, context), context);
return true;
} catch (XWikiException e) {
throw new SpaceManagerException(e);
}
}
/**
* Helper function to send email after a space action. This mail template
* full name is composed of the space name and the action with the following
* convention : spaceName + "." + "MailTemplate" + action + "Space", as in
* MySpace.MailTemplateJoinSpace
*
* @see getTemplateMailPageName
* @param action
* the action which triggered the mail sending. See
* {@link SpaceManager.SpaceAction} for possible actions.
* @param space
* The space on which the action has triggered the mail sending
* @throws SpaceManagerException
*/
private void sendMail(String action, Space space, XWikiContext context)
throws SpaceManagerException {
if (!mailNotification) {
return;
}
VelocityContext vContext = new VelocityContext();
vContext.put("space", space);
String fromUser = context.getWiki().getXWikiPreference("space_email",
context);
if (fromUser == null || fromUser.trim().length() == 0) {
fromUser = context.getWiki().getXWikiPreference("admin_email",
context);
}
String[] toUsers = new String[0];
if (SpaceAction.CREATE.equals(action)) {
// notify space administrators upon space creation
Collection admins = getAdmins(space.getSpaceName(), context);
toUsers = (String[]) admins.toArray(new String[admins.size()]);
} else if (SpaceAction.JOIN.equals(action)) {
// send join group confirmation e-mail
toUsers = new String[] { context.getUser() };
}
if (fromUser == null) {
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_SENDER_EMAIL_INVALID,
"Sender email is invalid");
}
boolean toUsersValid = toUsers.length > 0;
for (int i = 0; i < toUsers.length && toUsersValid; i++) {
if (!isEmailAddress(toUsers[i])) {
toUsers[i] = getEmailAddress(toUsers[i], context);
}
if (toUsers[i] == null) {
toUsersValid = false;
}
}
if (!toUsersValid) {
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_TARGET_EMAIL_INVALID,
"Target email is invalid");
}
String strToUsers = join(toUsers, ",");
MailSenderPlugin mailSender = getMailSenderPlugin(context);
try {
String templateDocFullName = getTemplateMailPageName(space
.getSpaceName(), action, context);
XWikiDocument mailDoc = context.getWiki().getDocument(
templateDocFullName, context);
XWikiDocument translatedMailDoc = mailDoc
.getTranslatedDocument(context);
mailSender.prepareVelocityContext(fromUser, strToUsers, "",
vContext, context);
vContext.put("xwiki", new com.xpn.xwiki.api.XWiki(
context.getWiki(), context));
vContext.put("context", new com.xpn.xwiki.api.Context(context));
String mailSubject = XWikiVelocityRenderer
.evaluate(translatedMailDoc.getTitle(),
templateDocFullName, vContext);
String mailContent = XWikiVelocityRenderer.evaluate(
translatedMailDoc.getContent(), templateDocFullName,
vContext);
Mail mail = new Mail(fromUser, strToUsers, null, null, mailSubject,
mailContent, null);
mailSender.sendMail(mail, context);
} catch (Exception e) {
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_SENDING_EMAIL_FAILED,
"Sending notification email failed", e);
}
}
private MailSenderPlugin getMailSenderPlugin(XWikiContext context)
throws SpaceManagerException {
MailSenderPlugin mailSender = (MailSenderPlugin) context.getWiki()
.getPlugin("mailsender", context);
if (mailSender == null)
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_MANAGER_REQUIRES_MAILSENDER_PLUGIN,
"SpaceManager requires the mail sender plugin");
return mailSender;
}
// code duplicated from InvitationManagerImpl !!!
private static final String join(String[] array, String separator) {
StringBuffer result = new StringBuffer("");
if (array.length > 0) {
result.append(array[0]);
}
for (int i = 1; i < array.length; i++) {
result.append("," + array[i]);
}
return result.toString();
}
// code duplicated from InvitationManagerImpl !!!
private boolean isEmailAddress(String str) {
return str.contains("@");
}
// code duplicated from InvitationManagerImpl !!!
private String getEmailAddress(String user, XWikiContext context)
throws SpaceManagerException {
try {
String wikiuser = (user.startsWith("XWiki.")) ? user : "XWiki."
+ user;
if (wikiuser == null)
return null;
XWikiDocument userDoc = null;
userDoc = context.getWiki().getDocument(wikiuser, context);
if (userDoc.isNew())
return null;
String email = "";
try {
email = userDoc.getObject("XWiki.XWikiUsers").getStringValue(
"email");
} catch (Exception e) {
return null;
}
if ((email == null) || (email.equals("")))
return null;
return email;
} catch (Exception e) {
throw new SpaceManagerException(
SpaceManagerException.MODULE_PLUGIN_SPACEMANAGER,
SpaceManagerException.ERROR_SPACE_CANNOT_FIND_EMAIL_ADDRESS,
"Cannot find email address of user " + user, e);
}
}
/**
* Convention based private helper to retrieve a mail template full name
* from a space name and an action name. TODO I think we should have the
* possibility to select for each action a template that is not located in
* the space itself, but in another web of the wiki. This would be to avoid
* copying this template each time we create a space if its content is not
* supposed to be modified, And thus reduce the impact of space creation on
* the db size.
*/
private String getTemplateMailPageName(String spaceName, String action,
XWikiContext context) {
String docName = spaceName + "." + "MailTemplate" + action + "Space";
try {
if (context.getWiki().getDocument(docName, context).isNew()) {
docName = null;
}
} catch (XWikiException e) {
docName = null;
}
if (docName == null) {
docName = getDefaultResourceSpace(context) + "." + "MailTemplate"
+ action + "Space";
}
return docName;
}
private String getDefaultResourceSpace(XWikiContext context) {
return context.getWiki().Param("xwiki.spacemanager.resourcespace",
SpaceManager.DEFAULT_RESOURCE_SPACE);
}
public boolean isMailNotification() {
return mailNotification;
}
public void setMailNotification(boolean mailNotification) {
this.mailNotification = mailNotification;
}
} |
package integration.forms;
import com.sun.star.uno.*;
import com.sun.star.frame.*;
import com.sun.star.lang.*;
import com.sun.star.util.*;
import com.sun.star.awt.*;
import com.sun.star.view.*;
import com.sun.star.beans.*;
import com.sun.star.container.*;
import com.sun.star.form.*;
import integration.forms.DocumentHelper;
/** provides a small wrapper around a document view
*/
class DocumentViewHelper
{
private XMultiServiceFactory m_orb;
private XController m_controller;
private DocumentHelper m_document;
final protected XController getController()
{
return m_controller;
}
final protected DocumentHelper getDocument()
{
return m_document;
}
public DocumentViewHelper( XMultiServiceFactory orb, DocumentHelper document, XController controller )
{
m_orb = orb;
m_document = document;
m_controller = controller;
}
/** Quick access to a given interface of the view
@param aInterfaceClass
the class of the interface which shall be returned
*/
public Object query( Class aInterfaceClass )
{
return UnoRuntime.queryInterface( aInterfaceClass, m_controller );
}
/** retrieves a dispatcher for the given URL, obtained at the current view of the document
@param aURL
a one-element array. The first element must contain a valid
<member scope="com.sun.star.util">URL::Complete</member> value. Upon return, the URL is correctly
parsed.
@return
the dispatcher for the URL in question
*/
public XDispatch getDispatcher( URL[] aURL ) throws java.lang.Exception
{
XDispatch xReturn = null;
// go get the current view
XController xController = (XController)query( XController.class );
// go get the dispatch provider of it's frame
XDispatchProvider xProvider = (XDispatchProvider)UnoRuntime.queryInterface(
XDispatchProvider.class, xController.getFrame() );
if ( null != xProvider )
{
// need an URLTransformer
XURLTransformer xTransformer = (XURLTransformer)UnoRuntime.queryInterface(
XURLTransformer.class, m_orb.createInstance( "com.sun.star.util.URLTransformer" ) );
xTransformer.parseStrict( aURL );
xReturn = xProvider.queryDispatch( aURL[0], new String( ), 0 );
}
return xReturn;
}
/** retrieves a dispatcher for the given URL, obtained at the current view of the document
*/
public XDispatch getDispatcher( String url ) throws java.lang.Exception
{
URL[] aURL = new URL[] { new URL() };
aURL[0].Complete = url;
return getDispatcher( aURL );
}
/** dispatches the given URL into the view, if there's a dispatcher for it
@return
<TRUE/> if the URL was successfully dispatched
*/
public boolean dispatch( String url ) throws java.lang.Exception
{
URL[] completeURL = new URL[] { new URL() };
completeURL[0].Complete = url;
XDispatch dispatcher = getDispatcher( completeURL );
if ( dispatcher == null )
return false;
PropertyValue[] aDummyArgs = new PropertyValue[] { };
dispatcher.dispatch( completeURL[0], aDummyArgs );
return true;
}
/** retrieves a control within the current view of a document
@param xModel
specifies the control model whose control should be located
@return
the control tied to the model
*/
public XControl getControl( XControlModel xModel ) throws com.sun.star.uno.Exception
{
// the current view of the document
XControlAccess xCtrlAcc = (XControlAccess)query( XControlAccess.class );
// delegate the task of looking for the control
return xCtrlAcc.getControl( xModel );
}
public XControl getControl( Object aModel ) throws com.sun.star.uno.Exception
{
XControlModel xModel = (XControlModel)UnoRuntime.queryInterface( XControlModel.class, aModel );
return getControl( xModel );
}
public Object getControl( Object aModel, Class aInterfaceClass ) throws com.sun.star.uno.Exception
{
XControlModel xModel = (XControlModel)UnoRuntime.queryInterface( XControlModel.class, aModel );
return UnoRuntime.queryInterface( aInterfaceClass, getControl( xModel ) );
}
/** toggles the design mode of the form layer of active view of our sample document
*/
protected void toggleFormDesignMode( ) throws java.lang.Exception
{
dispatch( ".uno:SwitchControlDesignMode" );
}
/** sets the focus to a specific control
@param xModel
a control model. The focus is set to that control which is part of our view
and associated with the given model.
*/
public void grabControlFocus( Object xModel ) throws com.sun.star.uno.Exception
{
// look for the control from the current view which belongs to the model
XControl xControl = getControl( xModel );
// the focus can be set to an XWindow only
XWindow xControlWindow = (XWindow)UnoRuntime.queryInterface( XWindow.class,
xControl );
// grab the focus
xControlWindow.setFocus();
}
/** sets the focus to the first control
*/
protected void grabControlFocus( ) throws java.lang.Exception
{
// the forms container of our document
XIndexContainer xForms = dbfTools.queryIndexContainer( m_document.getFormComponentTreeRoot( ) );
// the first form
XIndexContainer xForm = dbfTools.queryIndexContainer( xForms.getByIndex( 0 ) );
// the first control model which is no FixedText (FixedText's can't have the focus)
for ( int i = 0; i<xForm.getCount(); ++i )
{
XPropertySet xControlProps = dbfTools.queryPropertySet( xForm.getByIndex( i ) );
if ( FormComponentType.FIXEDTEXT != ((Short)xControlProps.getPropertyValue( "ClassId" )).shortValue() )
{
XControlModel xControlModel = (XControlModel)UnoRuntime.queryInterface(
XControlModel.class, xControlProps );
// set the focus to this control
grabControlFocus( xControlModel );
// outta here
break;
}
}
// Note that we simply took the first control model from the hierarchy. This does state nothing
// about the location of the respective control in the view. A control model is tied to a control
// shape, and the shapes are where the geometry information such as position and size is hung up.
// So you could easily have a document where the first control model is bound to a shape which
// has a greater ordinate than any other control model.
}
}; |
package uk.me.graphe.server;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import uk.me.graphe.graphmanagers.OTGraphManager2d;
import uk.me.graphe.server.messages.Message;
import uk.me.graphe.server.messages.MessageFactory;
import uk.me.graphe.server.messages.OpenGraphMessage;
/**
* reads messages from clients, and validates them. Sends client message pairs
* to the message processor for transformation
*
* @author Sam Phippen <samphippen@googlemail.com>
*
*/
public class ClientMessageHandler extends Thread {
private ClientManager mClientManager = ClientManager.getInstance();
private boolean mShutDown = false;
private MessageProcessor mProcessor;
private HeartbeatManager mHbm = new HeartbeatManager();
private static ClientMessageHandler sInstance = null;
public ClientMessageHandler() {
}
@Override
public void run() {
while (!mShutDown) {
Set<Client> availableClients = mClientManager
.waitOnReadableClients();
for (Client c : availableClients) {
List<String> messages = c.readNextMessages();
// if this returns null we disconnect the client for sending bad
// messages
List<JSONObject> jsos = validateAndParse(messages);
if (jsos == null)
mClientManager.disconnect(c);
List<Message> ops;
// malformed json == disconect
try {
ops = MessageFactory.makeOperationsFromJson(jsos);
for (Message message : ops) {
if (message.getMessage().equals("heartbeat")) {
mHbm.beatWhenPossible(c);
} else if (message.getMessage().equals("makegraph")) {
int id = DataManager.create();
c.setCurrentGraphId(id);
ClientMessageSender.getInstance().sendMessage(c, new OpenGraphMessage(id));
} else if (message.isOperation()) {
mProcessor.submit(c, message);
} else {
throw new Error("got unexpected message from client");
}
}
} catch (JSONException e) {
mClientManager.disconnect(c);
} catch (InterruptedException e) {
mClientManager.disconnect(c);
throw new Error(e);
}
}
}
}
private List<JSONObject> validateAndParse(List<String> messages) {
List<JSONObject> result = new ArrayList<JSONObject>();
for (String s : messages) {
try {
JSONObject o = new JSONObject(s);
result.add(o);
} catch (JSONException e) {
return null;
}
}
return result;
}
public static ClientMessageHandler getInstance() {
if (sInstance == null)
sInstance = new ClientMessageHandler();
return sInstance;
}
} |
package org.openhab.core.autoupdate.internal;
import org.openhab.core.autoupdate.AutoUpdateBindingProvider;
import org.openhab.core.events.AbstractEventSubscriberBinding;
import org.openhab.core.items.GenericItem;
import org.openhab.core.items.ItemNotFoundException;
import org.openhab.core.items.ItemNotUniqueException;
import org.openhab.core.items.ItemRegistry;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>The AutoUpdate-Binding is no 'normal' binding as it doesn't connect any hardware
* to openHAB. In fact it takes care of updating the State of an item with respect
* to the received command automatically or not. By default the State is getting
* updated automatically which is desired behavior in most of the cases. However
* it could be useful to disable this default behavior.</p>
* <p>For example when implementing validation steps before changing a State one
* needs to control the State update oneself.</p>
*
* @author Thomas.Eichstaedt-Engelen
* @since 0.9.1
*/
public class AutoUpdateBinding extends AbstractEventSubscriberBinding<AutoUpdateBindingProvider> {
private static final Logger logger = LoggerFactory.getLogger(AutoUpdateBinding.class);
protected ItemRegistry itemRegistry;
public void setItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = itemRegistry;
}
public void unsetItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = null;
}
/**
* <p>Iterates through all registered {@link AutoUpdateBindingProvider}s and
* checks whether an autoupdate configuration is available for <code>itemName</code>.</p>
*
* <p>If there are more then one {@link AutoUpdateBindingProvider}s providing
* a configuration the results are combined by a logical <em>OR</em>. If no
* configuration is provided at all the autoupdate defaults to <code>true</code>
* and an update is posted for the corresponding {@link State}.</p>
*
* @param itemName the item for which to find an autoupdate configuration
* @param command the command being received and posted as {@link State}
* update if <code>command</code> is instance of {@link State} as well.
*/
@Override
public void receiveCommand(String itemName, Command command) {
Boolean autoUpdate = null;
for (AutoUpdateBindingProvider provider : providers) {
Boolean au = provider.autoUpdate(itemName);
if (au != null) {
autoUpdate = au;
if (Boolean.TRUE.equals(autoUpdate)) {
break;
}
}
}
// we didn't find any autoupdate configuration, so apply the default now
if (autoUpdate == null) {
autoUpdate = Boolean.TRUE;
}
if (autoUpdate && command instanceof State) {
postUpdate(itemName, (State) command);
} else {
logger.trace("Item '{}' is not configured to update its state automatically.", itemName);
}
}
private void postUpdate(String itemName, State newStatus) {
if (itemRegistry != null) {
try {
GenericItem item = (GenericItem) itemRegistry.getItem(itemName);
if (item.getAcceptedDataTypes().contains(newStatus.getClass())) {
item.setState(newStatus);
logger.trace("Received update for item {}: {}", itemName, newStatus.toString());
} else {
logger.debug("Received update of a not accepted type ({}) for item {}", newStatus.getClass().getSimpleName(), itemName);
}
} catch (ItemNotFoundException e) {
logger.debug("Received update for non-existing item: {}", e.getMessage());
} catch (ItemNotUniqueException e) {
logger.debug("Received update for a not uniquely identifiable item: {}", e.getMessage());
}
}
}
} |
package org.openhab.designer.ui.internal.views;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.navigator.CommonNavigator;
import org.openhab.designer.core.config.ConfigurationFolderProvider;
public class ConfigNavigator extends CommonNavigator {
@Override
protected Object getInitialInput() {
try {
return ConfigurationFolderProvider.getRootConfigurationFolder().getProject();
} catch (Exception e) {
return null;
}
}
@Override
protected ActionGroup createCommonActionGroup() {
return new ConfigNavigatorActionGroup(getCommonViewer());
}
} |
package edu.tamu.tcat.account.apacheds.ad.login;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import edu.tamu.tcat.account.AccountException;
import edu.tamu.tcat.account.apacheds.ADObjectGUIDConverter;
import edu.tamu.tcat.account.apacheds.LdapAuthException;
import edu.tamu.tcat.account.apacheds.LdapException;
import edu.tamu.tcat.account.apacheds.LdapHelperReader;
import edu.tamu.tcat.account.login.LoginData;
import edu.tamu.tcat.account.login.LoginProvider;
/**
* This login provider is backed by Apache Directory libraries and uses conventions
* that exist in MS Active Directory, so may not be suitable for all LDAP uses.
*/
public class LdapLoginProvider implements LoginProvider
{
private static final Logger debug = Logger.getLogger(LdapLoginProvider.class.getName());
public static final String PROVIDER_ID = "ApacheDirAdLdapLoginProvider";
private LdapHelperReader ldapHelper;
private String username;
private String distinguishedName;
private String password;
private String instanceId;
private List<String> searchOUs;
/**
* Initialize the login provider so {@link #login()} can execute without arguments per API.
*
* @param ldapHelper
* @param username
* @param password
* @param instanceId
* @param searchOUs LDAP OU identifiers to search in order. If null or empty, the ldapHelper's internally configured
* default search OU is used.
*/
public void init(LdapHelperReader ldapHelper, String username, String password, String instanceId, List<String> searchOUs)
{
this.searchOUs = new ArrayList<>();
if (searchOUs != null)
this.searchOUs.addAll(searchOUs);
this.ldapHelper = Objects.requireNonNull(ldapHelper);
this.username = Objects.requireNonNull(username);
this.password = Objects.requireNonNull(password);
this.instanceId = Objects.requireNonNull(instanceId);
}
@Override
public LoginData login()
{
Objects.requireNonNull(ldapHelper, "LDAP Login Provider not initialized");
try
{
for (String ou : searchOUs)
{
List<String> possibleIds = ldapHelper.getMatches(ou, "sAMAccountName", username);
if (possibleIds.size() == 1)
{
distinguishedName = possibleIds.get(0);
try
{
ldapHelper.checkValidPassword(distinguishedName, password);
}
catch (LdapAuthException e)
{
return null;
}
LdapUserData rv = new LdapUserData(ldapHelper, distinguishedName, instanceId);
return rv;
}
if (possibleIds.size() > 1)
debug.warning("Found multiple LDAP entries matching name ["+username+"] in OU ["+ou+"]");
}
return null;
//throw new AccountLoginException("Failed finding single match for account name ["+username+"]");
}
catch (LdapException e)
{
throw new AccountException("Failed attempted login.", e);
}
}
/**
* Get the {@link LoginData} representing details of an identity, as requested by {@link #username}. This is useful to look up
* details, for example when performing password reset handshake operations.
*/
public LoginData unauthGetDetails(LdapHelperReader ldapHelper, String username, String instanceId, List<String> searchOUs)
{
Objects.requireNonNull(ldapHelper, "LDAP Login Provider not initialized");
try
{
for (String ou : searchOUs)
{
List<String> possibleIds = ldapHelper.getMatches(ou, "sAMAccountName", username);
if (possibleIds.size() == 1)
{
String distinguishedName = possibleIds.get(0);
LdapUserData rv = new LdapUserData(ldapHelper, distinguishedName, instanceId);
return rv;
}
if (possibleIds.size() > 1)
debug.warning("Found multiple LDAP entries matching name ["+username+"] in OU ["+ou+"]");
}
return null;
//throw new AccountLoginException("Failed finding single match for account name ["+username+"]");
}
catch (LdapException e)
{
throw new AccountException("Failed unauthenticated identity details access.", e);
}
}
/**
* Check if the credentials in this login provider match an LDAP account. This API is used to determine
* if the account exists in the system before attempting to create it if the application has such capability.
*/
public boolean identityExists()
{
Objects.requireNonNull(ldapHelper, "LDAP Login Provider not initialized");
try
{
for (String ou : searchOUs)
{
List<String> possibleIds = ldapHelper.getMatches(ou, "sAMAccountName", username);
if (possibleIds.size() > 1)
debug.warning("Found multiple LDAP entries matching account name ["+username+"] in OU ["+ou+"]");
if (possibleIds.size() > 0)
{
return true;
}
}
return false;
}
catch (LdapException e)
{
throw new AccountException("Failed check for identity.", e);
}
}
private static class LdapUserData implements LoginData
{
// these should be somewhere external
/** Named key to request a value from {@link LdapUserData} type: String */
public static final String DATA_KEY_DN = "dn";
/** Named key to request a value from {@link LdapUserData} type: byte[] */
public static final String DATA_KEY_GUID = "guid";
/** Named key to request a value from {@link LdapUserData} type: String */
public static final String DATA_KEY_USERNAME = "username";
/** Named key to request a value from {@link LdapUserData} type: String */
public static final String DATA_KEY_FIRST = "first";
/** Named key to request a value from {@link LdapUserData} type: String */
public static final String DATA_KEY_LAST = "last";
/** Named key to request a value from {@link LdapUserData} type: String */
public static final String DATA_KEY_EMAIL = "email";
/** Named key to request a value from {@link LdapUserData} type: Collection<String> */
public static final String DATA_KEY_GROUPS = "groups";
private String distinguishedName;
private String firstName;
private String lastName;
private String displayName;
private String email;
private Collection<String> groups;
private String pid;
private String userId;
private byte[] guid;
private LdapUserData(LdapHelperReader helper, String dn, String pid) throws LdapException
{
this.pid = pid;
distinguishedName = dn;
// display name
displayName = (String)helper.getAttributes(dn, "displayName").stream().findFirst().orElse(null);
if (displayName == null)
displayName = (String)helper.getAttributes(dn, "name").stream().findFirst().orElse(null);
// first
firstName = (String)helper.getAttributes(dn, "givenName").stream().findFirst().orElse(null);
// last
lastName = (String)helper.getAttributes(dn, "sn").stream().findFirst().orElse(null);
email = (String)helper.getAttributes(dn, "mail").stream().findFirst().orElse(null);
// strip CN=*, out from distinguished names here
groups = helper.getGroupNames(dn).stream()
.map(name -> name.substring(name.indexOf('=') + 1, name.indexOf(',')))
.collect(Collectors.toList());
guid = (byte[])helper.getAttributes(dn, "objectGUID").stream().findFirst().orElse(null);
// The user-id contains two parts; the first is the readable GUID, then a semicolon, then the byte string used for LDAP queries
userId = ADObjectGUIDConverter.toGuidString(guid) + ";" + ADObjectGUIDConverter.toByteString(guid);
}
@Override
public String getLoginProviderId()
{
return pid;
}
@Override
public String getLoginUserId()
{
return userId;
}
@Override
public <T> T getData(String key, Class<T> type) throws AccountException
{
//HACK: these do not check requested type
switch (key)
{
case DATA_KEY_DN:
return (T)distinguishedName;
case DATA_KEY_GUID:
return (T)guid;
case DATA_KEY_USERNAME:
return (T)displayName;
case DATA_KEY_FIRST:
return (T)firstName;
case DATA_KEY_LAST:
return (T)lastName;
case DATA_KEY_EMAIL:
return (T)email;
case DATA_KEY_GROUPS:
return (T)groups;
}
return null;
}
}
} |
package de.gurkenlabs.litiengine.graphics.animation;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.ILaunchable;
import de.gurkenlabs.litiengine.IUpdateable;
import de.gurkenlabs.litiengine.graphics.Spritesheet;
import de.gurkenlabs.litiengine.resources.Resources;
/**
* The {@code Animation} class keeps track of the current keyframe which is used to animate a visual element.
* It iterates over all defined keyframes with respect to their duration and provides information
* for the related {@code AnimationController} which keyframe should currently be rendered.
*
* @see IAnimationController#getCurrent()
*/
public class Animation implements IUpdateable, ILaunchable {
private final List<KeyFrameListener> listeners;
/**
* The default frame duration in milliseconds.
*/
public static final int DEFAULT_FRAME_DURATION = 120;
private static final Logger log = Logger.getLogger(Animation.class.getName());
private final List<KeyFrame> keyframes;
private final String name;
private Spritesheet spritesheet;
private KeyFrame currentFrame;
private long lastFrameUpdate;
private KeyFrame firstFrame;
private int frameDuration = DEFAULT_FRAME_DURATION;
private boolean loop;
private boolean paused;
private boolean playing;
/**
* Initializes a new instance of the {@code Animation} class.
*
* @param spriteSheetName
* The name of the spritesheet used by this animation.
* @param loop
* A flag indicating whether the animation should be looped or played only once.
*
* @param randomizeStart
* A flag indicating whether this animation should choose a random keyframe to start.
*
* @param keyFrameDurations
* The duration of each keyframe.
*/
public Animation(final String spriteSheetName, final boolean loop, final boolean randomizeStart, final int... keyFrameDurations) {
this(Resources.spritesheets().get(spriteSheetName), loop, randomizeStart, keyFrameDurations);
}
/**
* Initializes a new instance of the {@code Animation} class.
*
* @param spritesheet
* The spritesheet used by this animation.
* @param loop
* A flag indicating whether the animation should be looped or played only once.
*
* @param randomizeStart
* A flag indicating whether this animation should choose a random keyframe to start.
*
* @param keyFrameDurations
* The duration of each keyframe.
*/
public Animation(final Spritesheet spritesheet, final boolean loop, final boolean randomizeStart, final int... keyFrameDurations) {
this(spritesheet.getName(), spritesheet, loop, randomizeStart, keyFrameDurations);
}
/**
* Initializes a new instance of the {@code Animation} class.
*
* @param spritesheet
* The spritesheet used by this animation.
* @param loop
* A flag indicating whether the animation should be looped or played only once.
*
* @param keyFrameDurations
* The duration of each keyframe.
*/
public Animation(final Spritesheet spritesheet, final boolean loop, final int... keyFrameDurations) {
this(spritesheet.getName(), spritesheet, loop, keyFrameDurations);
}
/**
* Initializes a new instance of the {@code Animation} class.
*
* @param name
* The name of this animation.
*
* @param spritesheet
* The spritesheet used by this animation.
*
* @param loop
* A flag indicating whether the animation should be looped or played only once.
*
* @param randomizeStart
* A flag indicating whether this animation should choose a random keyframe to start.
*
* @param keyFrameDurations
* The duration of each keyframe.
*/
public Animation(final String name, final Spritesheet spritesheet, final boolean loop, final boolean randomizeStart, final int... keyFrameDurations) {
this(name, spritesheet, loop, keyFrameDurations);
if (randomizeStart && !this.keyframes.isEmpty()) {
this.firstFrame = Game.random().choose(this.getKeyframes());
}
}
/**
* Initializes a new instance of the {@code Animation} class.
*
* @param name
* The name of this animation.
*
* @param spritesheet
* The spritesheet used by this animation.
*
* @param loop
* A flag indicating whether the animation should be looped or played only once.
*
* @param keyFrameDurations
* The duration of each keyframe.
*/
public Animation(final String name, final Spritesheet spritesheet, final boolean loop, final int... keyFrameDurations) {
this.name = name;
this.spritesheet = spritesheet;
this.loop = loop;
this.keyframes = new ArrayList<>();
this.listeners = new CopyOnWriteArrayList<>();
if (spritesheet == null) {
log.log(Level.WARNING, "no spritesheet defined for animation {0}", this.getName());
return;
}
this.initKeyFrames(keyFrameDurations);
if (this.getKeyframes().isEmpty()) {
log.log(Level.WARNING, "No keyframes defined for animation {0} (spitesheet: {1})", new Object[] { this.getName(), spritesheet.getName() });
}
}
/**
* Gets to aggregated duration of all {@link KeyFrame}s in this animation.
*
* @return The total duration of a single playback.
*/
public int getTotalDuration() {
int duration = 0;
for (KeyFrame keyFrame : this.getKeyframes()) {
duration += keyFrame.getDuration();
}
return duration;
}
/**
* Gets the name of this animation.
*
* @return The name of this animation.
*/
public String getName() {
return this.name;
}
public Spritesheet getSpritesheet() {
// in case the previously sprite sheet was unloaded (removed from the loaded sprite sheets),
// try to find an updated one by the name of the previously used sprite
if (this.spritesheet != null && !this.spritesheet.isLoaded()) {
log.log(Level.INFO, "Reloading spritesheet {0} for animation {1}", new Object[] { this.spritesheet.getName(), this.getName() });
this.spritesheet = Resources.spritesheets().get(this.spritesheet.getName());
this.initKeyFrames();
}
return this.spritesheet;
}
/**
* Gets a value indicating whether this animation intended to loop.
*
* @return True if this animation will loop; otherwise false.
*/
public boolean isLooping() {
return this.loop;
}
/**
* Gets a value indicating whether this animation is currently paused.
*
* @return True if this animation is currently pause; otherwise false.
*/
public boolean isPaused() {
return this.paused;
}
/**
* Gets a value indicating whether this animation is currently playing.
*
* @return True if this animation is currently playing; otherwise false.
*/
public boolean isPlaying() {
return !this.paused && !this.keyframes.isEmpty() && this.playing;
}
/**
* Pauses the playback of this animation.
*
* @see #isPaused()
* @see #unpause()
*/
public void pause() {
this.paused = true;
}
/**
* Un-pauses the playback of this animation.
*
* @see #isPaused()
* @see #pause()
*/
public void unpause() {
this.paused = false;
}
/**
* Sets the frame duration for all keyframes in this animation to the
* specified value.
*
* @param frameDuration
* The frameduration for all keyframes.
*/
public void setDurationForAllKeyFrames(final int frameDuration) {
this.frameDuration = frameDuration;
for (final KeyFrame keyFrame : this.getKeyframes()) {
keyFrame.setDuration(this.frameDuration);
}
}
/**
* Sets the specified durations for the keyframes at the index of the defined arguments.
*
* <p>
* e.g.: If this animation defines 5 keyframes, the caller of this method can provide 5 individual durations for each
* keyframe.
* </p>
*
* @param keyFrameDurations
* The durations to be set on the keyframes of this animation.
*/
public void setKeyFrameDurations(final int... keyFrameDurations) {
if (keyFrameDurations.length == 0) {
return;
}
for (int i = 0; i < this.getKeyframes().size(); i++) {
this.getKeyframes().get(i).setDuration(keyFrameDurations[i]);
}
}
/**
* Gets an array of this animation's keyframe durations by streaming the keyframe list and mapping the durations to an int array.
*
* @return An array of this animation's keyframe durations.
*/
public int[] getKeyFrameDurations() {
return this.getKeyframes().stream().mapToInt(KeyFrame::getDuration).toArray();
}
/**
* Sets the looping behavior for this animation.
*
* @param loop
* if true, restart the animation infinitely after its last frame.
*/
public void setLooping(boolean loop) {
this.loop = loop;
}
public void onKeyFrameChanged(KeyFrameListener listener) {
this.listeners.add(listener);
}
public void removeKeyFrameListener(final KeyFrameListener listener) {
this.listeners.remove(listener);
}
@Override
public void start() {
this.playing = true;
if (this.getKeyframes().isEmpty()) {
return;
}
this.restart();
}
/**
* Restarts this animation at its first frame.
*/
public void restart() {
this.currentFrame = this.firstFrame;
this.lastFrameUpdate = Game.loop().getTicks();
}
@Override
public void terminate() {
this.playing = false;
if (this.getKeyframes().isEmpty()) {
return;
}
this.currentFrame = this.getKeyframes().get(0);
}
@Override
public void update() {
// do nothing if the animation is not playing or the current keyframe is not finished
if (!this.isPlaying() || Game.time().since(this.lastFrameUpdate) < this.getCurrentKeyFrame().getDuration()) {
return;
}
// if we are not looping and the last keyframe is finished, we terminate the animation
if (!this.isLooping() && this.isLastKeyFrame()) {
this.terminate();
return;
}
// make sure, we stay inside the keyframe list
final int newFrameIndex = (this.getKeyframes().indexOf(this.currentFrame) + 1) % this.getKeyframes().size();
final KeyFrame previousFrame = this.currentFrame;
this.currentFrame = this.getKeyframes().get(newFrameIndex);
for (KeyFrameListener listener : this.listeners) {
listener.currentFrameChanged(previousFrame, this.currentFrame);
}
this.lastFrameUpdate = Game.loop().getTicks();
}
KeyFrame getCurrentKeyFrame() {
return this.currentFrame;
}
List<KeyFrame> getKeyframes() {
return this.keyframes;
}
/**
* Initializes the animation key frames by the specified durations.
*
* <p>
* The amount of keyframes is defined by the available sprites of the assigned {@code Spritesheet}. For each
* sprite, a new keyframe will be initialized.
* </p>
*
* <p>
* If no custom durations are specified, the {@link #DEFAULT_FRAME_DURATION} will be used for each frame.
* </p>
*
* @param durations
* The custom durations for each keyframe.
*/
private void initKeyFrames(final int... durations) {
if (this.getSpritesheet() == null) {
return;
}
this.keyframes.clear();
int[] keyFrameDurations = durations;
if (keyFrameDurations.length == 0) {
// fallback to use custom keyframe durations if no specific durations are defined
keyFrameDurations = Resources.spritesheets().getCustomKeyFrameDurations(name);
}
// if no keyframes are specified, the animation takes in the whole
// spritesheet as animation and uses the DEFAULT_FRAME_DURATION for each keyframe
if (keyFrameDurations.length == 0) {
for (int i = 0; i < this.getSpritesheet().getTotalNumberOfSprites(); i++) {
this.keyframes.add(i, new KeyFrame(this.frameDuration, i));
}
} else {
for (int i = 0; i < keyFrameDurations.length; i++) {
this.keyframes.add(i, new KeyFrame(keyFrameDurations[i], i));
}
}
if (!this.keyframes.isEmpty()) {
this.firstFrame = this.getKeyframes().get(0);
}
}
private boolean isLastKeyFrame() {
return this.getKeyframes().indexOf(this.currentFrame) == this.getKeyframes().size() - 1;
}
} |
package mobi.hsz.idea.gitignore;
import com.intellij.dvcs.repo.Repository;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.impl.AbstractProjectViewPane;
import com.intellij.openapi.components.AbstractProjectComponent;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsListener;
import com.intellij.openapi.vfs.*;
import com.intellij.util.Function;
import com.intellij.util.Time;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.messages.Topic;
import git4idea.repo.GitRepository;
import mobi.hsz.idea.gitignore.file.type.IgnoreFileType;
import mobi.hsz.idea.gitignore.file.type.kind.GitExcludeFileType;
import mobi.hsz.idea.gitignore.file.type.kind.GitFileType;
import mobi.hsz.idea.gitignore.indexing.ExternalIndexableSetContributor;
import mobi.hsz.idea.gitignore.indexing.IgnoreEntryOccurrence;
import mobi.hsz.idea.gitignore.indexing.IgnoreFilesIndex;
import mobi.hsz.idea.gitignore.lang.IgnoreLanguage;
import mobi.hsz.idea.gitignore.settings.IgnoreSettings;
import mobi.hsz.idea.gitignore.util.*;
import mobi.hsz.idea.gitignore.util.exec.ExternalExec;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import static mobi.hsz.idea.gitignore.IgnoreManager.RefreshTrackedIgnoredListener.TRACKED_IGNORED_REFRESH;
import static mobi.hsz.idea.gitignore.IgnoreManager.TrackedIgnoredListener.TRACKED_IGNORED;
import static mobi.hsz.idea.gitignore.settings.IgnoreSettings.KEY;
/**
* {@link IgnoreManager} handles ignore files indexing and status caching.
*
* @author Jakub Chrzanowski <jakub@hsz.mobi>
* @since 1.0
*/
public class IgnoreManager extends AbstractProjectComponent implements DumbAware {
private static final List<IgnoreFileType> FILE_TYPES =
ContainerUtil.map(IgnoreBundle.LANGUAGES, new Function<IgnoreLanguage, IgnoreFileType>() {
@Override
public IgnoreFileType fun(@NotNull IgnoreLanguage language) {
return language.getFileType();
}
});
/** {@link VirtualFileManager} instance. */
@NotNull
private final VirtualFileManager virtualFileManager;
/** {@link IgnoreSettings} instance. */
@NotNull
private final IgnoreSettings settings;
/** {@link FileStatusManager} instance. */
@NotNull
private final FileStatusManager statusManager;
/** {@link RefreshTrackedIgnoredRunnable} instance. */
@NotNull
private final RefreshTrackedIgnoredRunnable refreshTrackedIgnoredRunnable;
/** {@link MessageBusConnection} instance. */
@Nullable
private MessageBusConnection messageBus;
/** List of the files that are ignored and also tracked by Git. */
@NotNull
private final ConcurrentMap<VirtualFile, Repository> confirmedIgnoredFiles =
ContainerUtil.createConcurrentWeakMap();
/** List of the new files that were not covered by {@link #confirmedIgnoredFiles} yet. */
@NotNull
private final HashSet<VirtualFile> notConfirmedIgnoredFiles = new HashSet<VirtualFile>();
/** References to the indexed {@link IgnoreEntryOccurrence}. */
@NotNull
private final ConcurrentMap<IgnoreFileType, Collection<IgnoreEntryOccurrence>> cachedIgnoreFilesIndex =
ContainerUtil.createConcurrentWeakMap();
/** References to the indexed outer files. */
@NotNull
private final ConcurrentMap<IgnoreFileType, Collection<VirtualFile>> cachedOuterFiles =
ContainerUtil.createConcurrentWeakMap();
@NotNull
private final ExpiringMap<VirtualFile, Boolean> expiringStatusCache =
new ExpiringMap<VirtualFile, Boolean>(Time.SECOND * 30);
/** {@link FileStatusManager#fileStatusesChanged()} method wrapped with {@link Debounced}. */
private final Debounced debouncedStatusesChanged = new Debounced(1000) {
@Override
protected void task(@Nullable Object argument) {
expiringStatusCache.clear();
cachedIgnoreFilesIndex.clear();
statusManager.fileStatusesChanged();
}
};
/** {@link FileStatusManager#fileStatusesChanged()} method wrapped with {@link Debounced}. */
private final Debounced<Boolean> debouncedRefreshTrackedIgnores = new Debounced<Boolean>(5000) {
@Override
protected void task(@Nullable Boolean refresh) {
if (Boolean.TRUE.equals(refresh)) {
refreshTrackedIgnoredRunnable.refresh();
} else {
refreshTrackedIgnoredRunnable.run();
}
}
};
/** Scheduled feature connected with {@link #debouncedStatusesChanged}. */
@NotNull
private final InterruptibleScheduledFuture statusesChangedScheduledFeature;
/** Scheduled feature connected with {@link #debouncedRefreshTrackedIgnores}. */
@NotNull
private final InterruptibleScheduledFuture refreshTrackedIgnoredFeature;
/** {@link IgnoreManager} working flag. */
private boolean working;
/** {@link VirtualFileListener} instance to check if file's content was changed. */
@NotNull
private final VirtualFileListener virtualFileListener = new VirtualFileAdapter() {
@Override
public void contentsChanged(@NotNull VirtualFileEvent event) {
handleEvent(event);
}
@Override
public void fileCreated(@NotNull VirtualFileEvent event) {
handleEvent(event);
notConfirmedIgnoredFiles.add(event.getFile());
// debouncedRefreshTrackedIgnores.run(true);
}
@Override
public void fileDeleted(@NotNull VirtualFileEvent event) {
handleEvent(event);
notConfirmedIgnoredFiles.add(event.getFile());
// debouncedRefreshTrackedIgnores.run(true);
}
@Override
public void fileMoved(@NotNull VirtualFileMoveEvent event) {
handleEvent(event);
notConfirmedIgnoredFiles.add(event.getFile());
// debouncedRefreshTrackedIgnores.run(true);
}
@Override
public void fileCopied(@NotNull VirtualFileCopyEvent event) {
handleEvent(event);
notConfirmedIgnoredFiles.add(event.getFile());
// debouncedRefreshTrackedIgnores.run(true);
}
private void handleEvent(@NotNull VirtualFileEvent event) {
final FileType fileType = event.getFile().getFileType();
if (fileType instanceof IgnoreFileType) {
cachedIgnoreFilesIndex.remove(fileType);
cachedOuterFiles.remove(fileType);
if (fileType instanceof GitExcludeFileType) {
cachedOuterFiles.remove(GitFileType.INSTANCE);
}
expiringStatusCache.clear();
debouncedStatusesChanged.run();
debouncedRefreshTrackedIgnores.run();
}
}
};
/** {@link IgnoreSettings} listener to watch changes in the plugin's settings. */
@NotNull
private final IgnoreSettings.Listener settingsListener = new IgnoreSettings.Listener() {
@Override
public void onChange(@NotNull KEY key, Object value) {
switch (key) {
case IGNORED_FILE_STATUS:
toggle((Boolean) value);
break;
case OUTER_IGNORE_RULES:
case LANGUAGES:
if (isEnabled()) {
if (working) {
debouncedStatusesChanged.run();
debouncedRefreshTrackedIgnores.run();
} else {
enable();
}
}
break;
case HIDE_IGNORED_FILES:
ProjectView.getInstance(myProject).refresh();
break;
}
}
};
/** {@link VcsListener} instance. */
@NotNull
private final VcsListener vcsListener = new VcsListener() {
@Override
public void directoryMappingChanged() {
ExternalIndexableSetContributor.invalidateCache(myProject);
}
};
/**
* Returns {@link IgnoreManager} service instance.
*
* @param project current project
* @return {@link IgnoreManager instance}
*/
@NotNull
public static IgnoreManager getInstance(@NotNull final Project project) {
return project.getComponent(IgnoreManager.class);
}
/**
* Constructor builds {@link IgnoreManager} instance.
*
* @param project current project
*/
public IgnoreManager(@NotNull final Project project) {
super(project);
this.virtualFileManager = VirtualFileManager.getInstance();
this.settings = IgnoreSettings.getInstance();
this.statusManager = FileStatusManager.getInstance(project);
this.refreshTrackedIgnoredRunnable = new RefreshTrackedIgnoredRunnable();
this.statusesChangedScheduledFeature =
new InterruptibleScheduledFuture(debouncedStatusesChanged, 5000, 15);
this.statusesChangedScheduledFeature.setTrailing(true);
this.refreshTrackedIgnoredFeature =
new InterruptibleScheduledFuture(debouncedRefreshTrackedIgnores, 10000, 5);
}
/**
* Checks if file is ignored.
*
* @param file current file
* @return file is ignored
*/
public boolean isFileIgnored(@NotNull final VirtualFile file) {
final Boolean cached = expiringStatusCache.get(file);
if (cached != null) {
return cached;
}
if (DumbService.isDumb(myProject) || !isEnabled() || !Utils.isUnder(file, myProject.getBaseDir())) {
return false;
}
boolean ignored = false;
boolean matched = false;
int valuesCount = 0;
final VcsRepositoryManager vcsRepositoryManager = VcsRepositoryManager.getInstance(myProject);
for (IgnoreFileType fileType : FILE_TYPES) {
if (!fileType.getIgnoreLanguage().isEnabled()) {
continue;
}
if (!cachedIgnoreFilesIndex.containsKey(fileType)) {
cachedIgnoreFilesIndex.put(fileType, IgnoreFilesIndex.getEntries(myProject, fileType));
}
final Collection<IgnoreEntryOccurrence> values = cachedIgnoreFilesIndex.get(fileType);
valuesCount += values.size();
for (IgnoreEntryOccurrence value : values) {
String relativePath;
final VirtualFile entryFile = value.getFile();
if (fileType instanceof GitExcludeFileType) {
VirtualFile workingDirectory = GitExcludeFileType.getWorkingDirectory(myProject, entryFile);
if (workingDirectory == null || !Utils.isUnder(file, workingDirectory)) {
continue;
}
relativePath = StringUtil.trimStart(file.getPath(), workingDirectory.getPath());
} else {
final Repository repository = vcsRepositoryManager.getRepositoryForFile(file);
if (repository != null && !Utils.isUnder(entryFile, repository.getRoot())) {
if (!cachedOuterFiles.containsKey(fileType)) {
cachedOuterFiles.put(fileType, fileType.getIgnoreLanguage().getOuterFiles(myProject));
}
if (!cachedOuterFiles.get(fileType).contains(entryFile)) {
continue;
}
}
String parentPath = entryFile.getParent().getPath();
if (!StringUtil.startsWith(file.getPath(), parentPath) &&
!ExternalIndexableSetContributor.getAdditionalFiles(myProject).contains(entryFile)) {
continue;
}
relativePath = StringUtil.trimStart(file.getPath(), parentPath);
}
relativePath = StringUtil.trimEnd(StringUtil.trimStart(relativePath, "/"), "/");
if (StringUtil.isEmpty(relativePath)) {
continue;
}
if (file.isDirectory()) {
relativePath += "/";
}
for (Pair<Matcher, Boolean> item : value.getItems()) {
if (MatcherUtil.match(item.first, relativePath)) {
ignored = !item.second;
matched = true;
}
}
}
}
if (valuesCount > 0 && !ignored && !matched) {
final VirtualFile directory = file.getParent();
if (directory != null && !directory.equals(myProject.getBaseDir())) {
for (Repository repository : vcsRepositoryManager.getRepositories()) {
if (directory.equals(repository.getRoot())) {
return expiringStatusCache.set(file, false);
}
}
return expiringStatusCache.set(file, isFileIgnored(directory));
}
}
if (ignored) {
statusesChangedScheduledFeature.cancel();
refreshTrackedIgnoredFeature.cancel();
}
return expiringStatusCache.set(file, ignored);
}
/**
* Checks if file is ignored and tracked.
*
* @param file current file
* @return file is ignored and tracked
*/
public boolean isFileTracked(@NotNull final VirtualFile file) {
return settings.isInformTrackedIgnored() && !notConfirmedIgnoredFiles.contains(file) &&
!confirmedIgnoredFiles.isEmpty() && !confirmedIgnoredFiles.containsKey(file);
}
/**
* Invoked when the project corresponding to this component instance is opened.<p>
* Note that components may be created for even unopened projects and this method can be never
* invoked for a particular component instance (for example for default project).
*/
@Override
public void projectOpened() {
if (isEnabled() && !working) {
enable();
}
}
/**
* Invoked when the project corresponding to this component instance is closed.<p>
* Note that components may be created for even unopened projects and this method can be never
* invoked for a particular component instance (for example for default project).
*/
@Override
public void projectClosed() {
disable();
}
/**
* Checks if ignored files watching is enabled.
*
* @return enabled
*/
private boolean isEnabled() {
return settings.isIgnoredFileStatus();
}
/** Enable manager. */
private void enable() {
if (working) {
return;
}
statusesChangedScheduledFeature.run();
refreshTrackedIgnoredFeature.run();
virtualFileManager.addVirtualFileListener(virtualFileListener);
settings.addListener(settingsListener);
messageBus = myProject.getMessageBus().connect();
messageBus.subscribe(RefreshStatusesListener.REFRESH_STATUSES, new RefreshStatusesListener() {
@Override
public void refresh() {
statusesChangedScheduledFeature.run();
}
});
messageBus.subscribe(TRACKED_IGNORED_REFRESH, new RefreshTrackedIgnoredListener() {
@Override
public void refresh() {
debouncedRefreshTrackedIgnores.run(false);
}
});
messageBus.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, vcsListener);
working = true;
}
/** Disable manager. */
private void disable() {
statusesChangedScheduledFeature.cancel();
virtualFileManager.removeVirtualFileListener(virtualFileListener);
settings.removeListener(settingsListener);
if (messageBus != null) {
messageBus.disconnect();
messageBus = null;
}
working = false;
}
/** Dispose and disable component. */
@Override
public void disposeComponent() {
super.disposeComponent();
disable();
}
/**
* Runs {@link #enable()} or {@link #disable()} depending on the passed value.
*
* @param enable or disable
*/
private void toggle(@NotNull Boolean enable) {
if (enable) {
enable();
} else {
disable();
}
}
/**
* Returns tracked and ignored files stored in {@link #confirmedIgnoredFiles}.
*
* @return tracked and ignored files map
*/
@NotNull
public ConcurrentMap<VirtualFile, Repository> getConfirmedIgnoredFiles() {
return confirmedIgnoredFiles;
}
/** {@link Runnable} implementation to rebuild {@link #confirmedIgnoredFiles}. */
class RefreshTrackedIgnoredRunnable implements Runnable, IgnoreManager.RefreshTrackedIgnoredListener {
/** Default {@link Runnable} run method that invokes rebuilding with bus event propagating. */
@Override
public void run() {
run(false);
}
/** Rebuilds {@link #confirmedIgnoredFiles} map in silent mode. */
@Override
public void refresh() {
this.run(true);
}
/**
* Rebuilds {@link #confirmedIgnoredFiles} map.
*
* @param silent propagate {@link IgnoreManager.TrackedIgnoredListener#TRACKED_IGNORED} event
*/
public void run(boolean silent) {
if (!settings.isInformTrackedIgnored()) {
return;
}
final VcsRepositoryManager vcsRepositoryManager = VcsRepositoryManager.getInstance(myProject);
final Collection<Repository> repositories = vcsRepositoryManager.getRepositories();
final ConcurrentMap<VirtualFile, Repository> result = ContainerUtil.createConcurrentWeakMap();
for (Repository repository : repositories) {
if (!(repository instanceof GitRepository)) {
continue;
}
final VirtualFile root = repository.getRoot();
for (String path : ExternalExec.getIgnoredFiles(repository)) {
final VirtualFile file = root.findFileByRelativePath(path);
if (file != null) {
result.put(file, repository);
}
}
}
if (!silent && !result.isEmpty()) {
myProject.getMessageBus().syncPublisher(TRACKED_IGNORED).handleFiles(result);
}
confirmedIgnoredFiles.clear();
confirmedIgnoredFiles.putAll(result);
notConfirmedIgnoredFiles.clear();
debouncedStatusesChanged.run();
for (AbstractProjectViewPane pane : Extensions.getExtensions(AbstractProjectViewPane.EP_NAME, myProject)) {
if (pane.getTreeBuilder() != null) {
pane.getTreeBuilder().queueUpdate();
}
}
}
}
/** Listener bounded with {@link TrackedIgnoredListener#TRACKED_IGNORED} topic to inform about new entries. */
public interface TrackedIgnoredListener {
/** Topic for detected tracked and indexed files. */
Topic<TrackedIgnoredListener> TRACKED_IGNORED =
Topic.create("New tracked and indexed files detected", TrackedIgnoredListener.class);
void handleFiles(@NotNull ConcurrentMap<VirtualFile, Repository> files);
}
/**
* Listener bounded with {@link RefreshTrackedIgnoredListener#TRACKED_IGNORED_REFRESH} topic to
* trigger tracked and ignored files list.
*/
public interface RefreshTrackedIgnoredListener {
/** Topic for refresh tracked and indexed files. */
Topic<RefreshTrackedIgnoredListener> TRACKED_IGNORED_REFRESH =
Topic.create("New tracked and indexed files detected", RefreshTrackedIgnoredListener.class);
void refresh();
}
public interface RefreshStatusesListener {
/** Topic to refresh files statuses using {@link MessageBusConnection}. */
Topic<RefreshStatusesListener> REFRESH_STATUSES =
new Topic<RefreshStatusesListener>("Refresh files statuses", RefreshStatusesListener.class);
void refresh();
}
/**
* Unique name of this component. If there is another component with the same name or
* name is null internal assertion will occur.
*
* @return the name of this component
*/
@NonNls
@NotNull
@Override
public String getComponentName() {
return "IgnoreManager";
}
} |
package de.st_ddt.crazyutil.compatibility;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.PluginClassLoader;
import de.st_ddt.crazyutil.resources.ResourceHelper;
public class CompatibilityLoader
{
private final static String implementation;
private final static String version;
static
{
final Server server = Bukkit.getServer();
final Class<? extends Server> serverClass = server.getClass();
final String serverClassName = serverClass.getName();
final String[] serverClassNameParts = serverClassName.split("\\.");
if (serverClassNameParts.length >= 5 && serverClassNameParts[2].equals("craftbukkit"))
{
implementation = "craftbukkit";
version = serverClassNameParts[3];
System.out.println("[CrazyCompatibility] Implementation: " + implementation + "@" + version + " found.");
}
else
{
implementation = null;
version = null;
System.err.println("[CrazyCompatibility] No compatible implementation detected for class: " + serverClassName);
}
}
public static boolean loadCompatibilityProvider(final Plugin plugin)
{
return loadCompatibilityProvider(plugin, plugin.getClass().getPackage().getName() + ".", "");
}
public static boolean loadCompatibilityProvider(final Plugin plugin, final String packagePrefix, final String packageSuffix)
{
return loadCompatibilityProvider(plugin, packagePrefix, packageSuffix, "");
}
public static boolean loadCompatibilityProvider(final Plugin plugin, final String packagePrefix, final String packageSuffix, final String fileSuffix)
{
if (implementation == null || version == null)
return false;
final File target = new File(plugin.getDataFolder(), "/compatibility/" + implementation + "/" + version + fileSuffix + ".jar");
if (!target.exists())
ResourceHelper.saveResource(plugin, "/compatibility/" + implementation + "/" + version + fileSuffix + ".jar", target);
try
{
loadClassContainer(plugin, target);
Class.forName(packagePrefix + implementation + "." + version + packageSuffix + ".CompatibilityProvider", true, plugin.getClass().getClassLoader());
System.err.println("[" + plugin.getName() + "] Loaded compatibility provider.");
return true;
}
catch (final Throwable t)
{
System.err.println("[" + plugin.getName() + "] Error loading compatibility provider!");
System.err.println(t.getMessage());
return false;
}
}
protected static void loadClassContainer(final Plugin plugin, final File file) throws MalformedURLException
{
if (!file.exists())
return;
final ClassLoader loader = plugin.getClass().getClassLoader();
final URL url = file.toURI().toURL();
((PluginClassLoader) loader).addURL(url);
}
private CompatibilityLoader()
{
}
} |
package org.eclipse.birt.chart.reportitem;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.olap.OLAPException;
import javax.olap.cursor.EdgeCursor;
import org.eclipse.birt.chart.api.ChartEngine;
import org.eclipse.birt.chart.computation.withaxes.SharedScaleContext;
import org.eclipse.birt.chart.device.EmptyUpdateNotifier;
import org.eclipse.birt.chart.device.IDeviceRenderer;
import org.eclipse.birt.chart.device.IImageMapEmitter;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.factory.GeneratedChartState;
import org.eclipse.birt.chart.factory.Generator;
import org.eclipse.birt.chart.factory.IActionEvaluator;
import org.eclipse.birt.chart.factory.IDataRowExpressionEvaluator;
import org.eclipse.birt.chart.factory.RunTimeContext;
import org.eclipse.birt.chart.log.ILogger;
import org.eclipse.birt.chart.log.Logger;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.attribute.Bounds;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.render.IActionRenderer;
import org.eclipse.birt.chart.reportitem.i18n.Messages;
import org.eclipse.birt.chart.reportitem.plugin.ChartReportItemPlugin;
import org.eclipse.birt.chart.script.ChartScriptContext;
import org.eclipse.birt.chart.script.ScriptHandler;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.chart.util.PluginSettings;
import org.eclipse.birt.chart.util.SecurityUtil;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.IHTMLActionHandler;
import org.eclipse.birt.report.engine.api.script.IReportContext;
import org.eclipse.birt.report.engine.data.dte.CubeResultSet;
import org.eclipse.birt.report.engine.extension.IBaseResultSet;
import org.eclipse.birt.report.engine.extension.ICubeResultSet;
import org.eclipse.birt.report.engine.extension.IQueryResultSet;
import org.eclipse.birt.report.engine.extension.ReportItemPresentationBase;
import org.eclipse.birt.report.engine.extension.Size;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.ModuleUtil;
import org.eclipse.birt.report.model.api.MultiViewsHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.extension.ExtendedElementException;
import org.eclipse.birt.report.model.api.extension.IReportItem;
import org.eclipse.birt.report.model.elements.interfaces.IReportItemModel;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.mozilla.javascript.EvaluatorException;
/**
* Base presentation implementation for Chart. This class can be extended for
* various implementation.
*/
public class ChartReportItemPresentationBase extends ReportItemPresentationBase
{
protected InputStream fis = null;
protected String imageMap = null;
protected String sExtension = null;
private String sSupportedFormats = null;
private String outputFormat = null;
private int outputType = -1;
protected Chart cm = null;
protected IDeviceRenderer idr = null;
protected ExtendedItemHandle handle;
protected RunTimeContext rtc = null;
private static List<String> registeredDevices = null;
protected static final ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.reportitem/trace" ); //$NON-NLS-1$
private Bounds boundsRuntime = null;
static
{
registeredDevices = new ArrayList<String>( );
try
{
String[][] formats = PluginSettings.instance( )
.getRegisteredOutputFormats( );
for ( int i = 0; i < formats.length; i++ )
{
registeredDevices.add( formats[i][0] );
}
}
catch ( ChartException e )
{
logger.log( e );
}
}
/**
* check if the format is supported by the browser and device renderer.
*/
private boolean isOutputRendererSupported( String format )
{
if ( format != null )
{
if ( sSupportedFormats != null
&& ( sSupportedFormats.indexOf( format ) != -1 ) )
{
return registeredDevices.contains( format );
}
}
return false;
}
private String getFirstSupportedFormat( String formats )
{
if ( formats != null && formats.length( ) > 0 )
{
int idx = formats.indexOf( ';' );
if ( idx == -1 )
{
if ( isOutputRendererSupported( formats ) )
{
return formats;
}
}
else
{
String ext = formats.substring( 0, idx );
if ( isOutputRendererSupported( ext ) )
{
return ext;
}
else
{
return getFirstSupportedFormat( formats.substring( idx + 1 ) );
}
}
}
// PNG as default.
return "PNG"; //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#setModelObject(org.eclipse.birt.report.model.api.ExtendedItemHandle)
*/
public void setModelObject( ExtendedItemHandle eih )
{
IReportItem item = getReportItem( eih );
if ( item == null )
{
return;
}
cm = (Chart) ( (ChartReportItemImpl) item ).getProperty( ChartReportItemConstants.PROPERTY_CHART );
handle = eih;
setChartModelObject( item );
}
protected void setChartModelObject( IReportItem item )
{
Object of = handle.getProperty( ChartReportItemConstants.PROPERTY_OUTPUT );
if ( of instanceof String )
{
outputFormat = (String) of;
}
of = item.getProperty( ChartReportItemConstants.PROPERTY_SCALE );
if ( of instanceof SharedScaleContext )
{
if ( rtc == null )
{
rtc = new RunTimeContext( );
}
rtc.setSharedScale( (SharedScaleContext) of );
}
}
protected IReportItem getReportItem( ExtendedItemHandle eih )
{
IReportItem item = null;
try
{
item = eih.getReportItem( );
}
catch ( ExtendedElementException e )
{
logger.log( e );
}
if ( item == null )
{
try
{
eih.loadExtendedElement( );
item = eih.getReportItem( );
}
catch ( ExtendedElementException eeex )
{
logger.log( eeex );
}
if ( item == null )
{
logger.log( ILogger.ERROR,
Messages.getString( "ChartReportItemPresentationImpl.log.UnableToLocateWrapper" ) ); //$NON-NLS-1$
}
}
return item;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#setLocale(java.util.Locale)
*/
public final void setLocale( Locale lcl )
{
if ( rtc == null )
{
rtc = new RunTimeContext( );
}
rtc.setLocale( lcl );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#setOutputFormat(java.lang.String)
*/
public void setOutputFormat( String sOutputFormat )
{
if ( sOutputFormat.equalsIgnoreCase( "HTML" ) ) //$NON-NLS-1$
{
if ( isOutputRendererSupported( outputFormat ) )
{
sExtension = outputFormat;
}
else if ( outputFormat != null
&& outputFormat.toUpperCase( ).equals( "GIF" ) && //$NON-NLS-1$
isOutputRendererSupported( "PNG" ) ) //$NON-NLS-1$
{
// render old GIF charts as PNG
sExtension = "PNG"; //$NON-NLS-1$
}
else if ( isOutputRendererSupported( "SVG" ) ) //$NON-NLS-1$
{
// SVG is the preferred output for HTML
sExtension = "SVG"; //$NON-NLS-1$
}
else
{
sExtension = getFirstSupportedFormat( sSupportedFormats );
}
}
else if ( sOutputFormat.equalsIgnoreCase( "PDF" ) ) //$NON-NLS-1$
{
if ( outputFormat != null
&& outputFormat.toUpperCase( ).equals( "SVG" ) ) //$NON-NLS-1$
{
// Since engine doesn't support embedding SVG, always embed PNG
sExtension = "PNG"; //$NON-NLS-1$
}
else if ( isOutputRendererSupported( outputFormat ) )
{
sExtension = outputFormat;
}
else if ( isOutputRendererSupported( "PNG" ) ) //$NON-NLS-1$
{
// PNG is the preferred output for PDF
sExtension = "PNG"; //$NON-NLS-1$
}
else
{
sExtension = getFirstSupportedFormat( sSupportedFormats );
}
}
else
{
if ( isOutputRendererSupported( outputFormat ) )
{
sExtension = outputFormat;
}
else
{
sExtension = getFirstSupportedFormat( sSupportedFormats );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#setSupportedImageFormats(java.lang.String)
*/
public void setSupportedImageFormats( String sSupportedFormats )
{
this.sSupportedFormats = sSupportedFormats;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#deserialize(java.io.InputStream)
*/
public void deserialize( InputStream is )
{
try
{
ObjectInputStream ois = new ObjectInputStream( is ) {
// Fix compatibility bug: the class ChartScriptContext is moved
// from package
// "org.eclipse.birt.chart.internal.script" to package
// "org.eclipse.birt.chart.script", which causes the stored
// instances of
// ChartScriptContext can't be de-serialized.
protected Class<?> resolveClass( ObjectStreamClass desc )
throws IOException, ClassNotFoundException
{
if ( "org.eclipse.birt.chart.internal.script.ChartScriptContext".equals( desc.getName( ) ) ) //$NON-NLS-1$
{
return ChartScriptContext.class;
}
return super.resolveClass( desc );
}
};
Object o = SecurityUtil.readObject( ois );
if ( o instanceof RunTimeContext )
{
RunTimeContext drtc = (RunTimeContext) o;
if ( rtc != null )
{
drtc.setULocale( rtc.getULocale( ) );
drtc.setSharedScale( rtc.getSharedScale( ) );
}
rtc = drtc;
// After performance fix, script context will return null model.
// cm = rtc.getScriptContext( ).getChartInstance( );
// Set back the cm into the handle from the engine, so that the
// chart inside the
// reportdesignhandle is the same as the one used during
// presentation.
// No command should be executed, since it's a runtime operation
// Set the model directly through setModel and not setProperty
if ( cm != null && handle != null )
{
IReportItem item = handle.getReportItem( );
( (ChartReportItemImpl) item ).setModel( cm );
( (ChartReportItemImpl) item ).setSharedScale( rtc.getSharedScale( ) );
}
// Get chart max row number from application context
Object oMaxRow = context.getAppContext( )
.get( EngineConstants.PROPERTY_EXTENDED_ITEM_MAX_ROW );
if ( oMaxRow != null )
{
rtc.putState( ChartUtil.CHART_MAX_ROW, oMaxRow );
}
else
{
// Get chart max row number from global variables if app
// context doesn't put it
oMaxRow = context.getGlobalVariable( EngineConstants.PROPERTY_EXTENDED_ITEM_MAX_ROW );
if ( oMaxRow != null )
{
rtc.putState( ChartUtil.CHART_MAX_ROW, oMaxRow );
}
}
}
ois.close( );
}
catch ( Exception e )
{
logger.log( e );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#getOutputType()
*/
public int getOutputType( )
{
if ( outputType == -1 )
{
if ( "SVG".equals( sExtension ) || "SWF".equals( sExtension ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
outputType = OUTPUT_AS_IMAGE;
}
else
{
outputType = OUTPUT_AS_IMAGE_WITH_MAP;
}
}
return outputType;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#getImageMIMEType()
*/
public String getImageMIMEType( )
{
if ( idr == null )
{
return null;
}
return idr.getMimeType( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#getOutputContent()
*/
public Object getOutputContent( )
{
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#finish()
*/
public void finish( )
{
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemPresentationImpl.log.finishStart" ) ); //$NON-NLS-1$
// CLOSE THE TEMP STREAM PROVIDED TO THE CALLER
try
{
// clean up the image map.
imageMap = null;
if ( fis != null )
{
fis.close( );
fis = null;
}
}
catch ( IOException ioex )
{
logger.log( ioex );
}
// Dispose renderer resources
if ( idr != null )
{
idr.dispose( );
idr = null;
}
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemPresentationImpl.log.finishEnd" ) ); //$NON-NLS-1$
}
protected Bounds computeBounds( ) throws ChartException
{
// Standard computation for chart bounds
final Bounds originalBounds = cm.getBlock( ).getBounds( );
// we must copy the bounds to avoid that setting it on one object
// unsets it on its precedent container
Bounds bounds = (Bounds) EcoreUtil.copy( originalBounds );
return bounds;
}
protected IDataRowExpressionEvaluator createEvaluator( IBaseResultSet set )
throws ChartException
{
if ( set instanceof IQueryResultSet )
{
// COMPATIBILITY REVISION: SCR#100059, 2008-04-10
// Since the DtE integration, some old report documents are not
// compatible with current evaluator of expressions, old report
// documents don't contains additional aggregation binding which
// here checks the version number( <3.2.16, before BIRT 2.3 ) of
// report model to use old evaluator logic for chart and chart
// does group/aggregation by itself.
if ( ChartReportItemUtil.isOldChartUsingInternalGroup( handle, cm ) )
{
// Version is less than 3.2.16, directly return.
return new BIRTQueryResultSetEvaluator( (IQueryResultSet) set );
}
// Here, we must use chart model to check if grouping is defined. we
// can't use grouping definitions in IQueryResultSet to check it,
// because maybe chart inherits data set from container and the data
// set contains grouping, but chart doesn't define grouping.
if ( ChartReportItemUtil.isGroupingDefined( cm )
|| ChartReportItemUtil.hasAggregation( cm ) )
{
return new BIRTGroupedQueryResultSetEvaluator( (IQueryResultSet) set,
ChartReportItemUtil.isSetSummaryAggregation( cm ),
isSubQuery( ),
cm,
handle );
}
return new BIRTQueryResultSetEvaluator( (IQueryResultSet) set );
}
else if ( set instanceof ICubeResultSet )
{
if ( ChartXTabUtil.isPlotChart( handle )
|| ChartXTabUtil.isAxisChart( handle ) )
{
return new BIRTChartXtabResultSetEvaluator( (ICubeResultSet) set,
handle );
}
// Fixed ED 28
// Sharing case/Multiple view case
ReportItemHandle itemHandle = ChartReportItemUtil.getReportItemReference( handle );
boolean isChartCubeReference = ChartReportItemUtil.isChartReportItemHandle( itemHandle );
if ( itemHandle != null && !isChartCubeReference )
{
return new SharedCubeResultSetEvaluator( (ICubeResultSet) set,
cm );
}
return new BIRTCubeResultSetEvaluator( (ICubeResultSet) set );
}
return null;
}
private boolean isSubQuery( )
{
return handle.getDataSet( ) == null;
}
protected SharedScaleContext createSharedScale( IBaseResultSet baseResultSet )
throws BirtException
{
if ( baseResultSet instanceof IQueryResultSet )
{
Object min = baseResultSet.evaluate( "row._outer[\"" //$NON-NLS-1$
+ ChartReportItemConstants.QUERY_MIN
+ "\"]" ); //$NON-NLS-1$
Object max = baseResultSet.evaluate( "row._outer[\"" //$NON-NLS-1$
+ ChartReportItemConstants.QUERY_MAX
+ "\"]" ); //$NON-NLS-1$
return SharedScaleContext.createInstance( min, max );
}
else if ( baseResultSet instanceof CubeResultSet )
{
// Gets global min/max and set the value to shared scale
try
{
List<EdgeCursor> edgeCursors = ( (CubeResultSet) baseResultSet ).getCubeCursor( )
.getOrdinateEdge( );
for ( EdgeCursor edge : edgeCursors )
{
edge.first( );
}
Axis xAxis = ( (ChartWithAxes) cm ).getAxes( ).get( 0 );
SeriesDefinition sdValue = ( (ChartWithAxes) cm ).getOrthogonalAxes( xAxis,
true )[0].getSeriesDefinitions( ).get( 0 );
Query queryValue = sdValue.getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 );
String bindingValue = ChartXTabUtil.getBindingName( queryValue.getDefinition( ),
false );
String maxBindingName = ChartReportItemConstants.QUERY_MAX
+ bindingValue;
String minBindingName = ChartReportItemConstants.QUERY_MIN
+ bindingValue;
Object min = baseResultSet.evaluate( ExpressionUtil.createJSDataExpression( minBindingName ) );
Object max = baseResultSet.evaluate( ExpressionUtil.createJSDataExpression( maxBindingName ) );
if ( min != null && max != null )
{
return SharedScaleContext.createInstance( min, max );
}
}
catch ( OLAPException e )
{
// Skip shared scale, still running
logger.log( e );
}
catch ( BirtException e )
{
// If chart doesn't use sub cube query, shared scale is not
// required. No need to get min/max
}
catch ( EvaluatorException e )
{
// If chart doesn't use sub cube query, shared scale is not
// required. No need to get min/max
}
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#getSize()
*/
public Size getSize( )
{
// Use actual bounds to set size
if ( boundsRuntime != null )
{
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemPresentationImpl.log.getSizeStart" ) ); //$NON-NLS-1$
final Size sz = new Size( );
sz.setWidth( (float) boundsRuntime.getWidth( ) );
sz.setHeight( (float) boundsRuntime.getHeight( ) );
sz.setUnit( Size.UNITS_PT );
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemPresentationImpl.log.getSizeEnd" ) ); //$NON-NLS-1$
return sz;
}
return super.getSize( );
}
/*
* Wraps the logic to bind data. Returns true if the data set is not empty,
* otherwise false.
*/
private boolean bindData( IDataRowExpressionEvaluator rowAdapter,
IActionEvaluator evaluator ) throws BirtException
{
boolean bNotEmpty = true;
try
{
// Bind Data to series
Generator.instance( ).bindData( rowAdapter, evaluator, cm, rtc );
bNotEmpty = true;
}
catch ( BirtException birtException )
{
// Check if the exception is caused by no data to display (in that
// case skip gracefully)
if ( isNoDataException( birtException ) )
{
bNotEmpty = false;
}
else
{
throw birtException;
}
}
rtc.putState( RunTimeContext.StateKey.DATA_EMPTY_KEY, !bNotEmpty );
return bNotEmpty;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.extension.IReportItemPresentation#onRowSets(org.eclipse.birt.report.engine.extension.IRowSet[])
*/
public Object onRowSets( IBaseResultSet[] baseResultSet )
throws BirtException
{
// Extract result set to render and check for null data
IBaseResultSet resultSet = getDataToRender( baseResultSet );
boolean bAutoHide = ( cm != null && !cm.getEmptyMessage( ).isVisible( ) );
// Skip gracefully if there is no data
if ( resultSet == null )
{
// Returns an object array for engine to display alt text instead of
// image when result set is null.
return new Object[]{
new byte[]{
0
}
};
}
else if ( ChartReportItemUtil.isEmpty( resultSet ) )
{
if ( bAutoHide )
{
// Returns null for engine to display empty when the result set
// empty.
return null;
}
}
// If width and height of chart is set to 0, doesn't process it.
Bounds bo = cm.getBlock( ).getBounds( );
if ( bo.getWidth( ) == 0 && bo.getHeight( ) == 0 )
{
return null;
}
try
{
// Create and set shared scale if needed
if ( rtc.getSharedScale( ) == null
&& ChartReportItemUtil.canScaleShared( handle, cm ) )
{
rtc.setSharedScale( createSharedScale( resultSet ) );
}
// Set sharing query flag.
boolean isSharingQuery = false;
if ( handle.getDataBindingReference( ) != null
|| handle.getContainer( ) instanceof MultiViewsHandle )
{
isSharingQuery = true;
}
rtc.setSharingQuery( isSharingQuery );
// Get the BIRT report context
BIRTExternalContext externalContext = new BIRTExternalContext( context );
// Initialize external context, which can be used by script during
// binding data
if ( rtc.getScriptContext( ) != null
&& rtc.getScriptContext( ) instanceof ChartScriptContext )
{
( (ChartScriptContext) rtc.getScriptContext( ) ).setExternalContext( externalContext );
}
// Initialize script handler and register birt context in scope
initializeScriptHandler( externalContext );
// Prepare Data for Series
IDataRowExpressionEvaluator rowAdapter = createEvaluator( resultSet );
// Prepare data processor for hyperlinks/tooltips
IActionEvaluator evaluator = new BIRTActionEvaluator( );
// Bind Data to series
if ( !bindData( rowAdapter, evaluator ) && bAutoHide )
{
// if autohide and data empty
return null;
}
// Prepare Device Renderer
prepareDeviceRenderer( );
// Build the chart
GeneratedChartState gcs = buildChart( rowAdapter, externalContext );
// Render the chart
renderToImageFile( gcs );
// Close the dataRow evaluator. It needs to stay opened until the
// chart is fully rendered.
rowAdapter.close( );
// Set the scale shared when scale has been computed, and store it
// in the ReportItem
if ( rtc.getSharedScale( ) != null
&& !rtc.getSharedScale( ).isShared( ) )
{
rtc.getSharedScale( ).setShared( true );
( (ChartReportItemImpl) getReportItem( handle ) ).setSharedScale( rtc.getSharedScale( ) );
}
// Returns the content to display (image or image+imagemap)
return getImageToDisplay( );
}
catch ( RuntimeException ex )
{
logger.log( ILogger.ERROR,
Messages.getString( "ChartReportItemPresentationImpl.log.onRowSetsFailed" ) ); //$NON-NLS-1$
logger.log( ex );
throw new ChartException( ChartReportItemPlugin.ID,
ChartException.GENERATION,
ex );
}
}
/**
* Check there is some data to display in the chart.
*
* @param baseResultSet
* @return null if nothing to render
*/
private IBaseResultSet getDataToRender( IBaseResultSet[] baseResultSet )
throws BirtException
{
// BIND RESULTSET TO CHART DATASETS
if ( baseResultSet == null || baseResultSet.length < 1 )
{
// if the Data rows are null/empty, just log it and returns
// null gracefully.
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemPresentationImpl.error.NoData" ) ); //$NON-NLS-1$
return null;
}
IBaseResultSet resultSet = baseResultSet[0];
if ( resultSet == null )
{
// Do nothing when IBaseResultSet is empty or null
return null;
}
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemPresentationImpl.log.onRowSetsStart" ) ); //$NON-NLS-1$
// catch unwanted null handle case
if ( handle == null )
{
assert false; // should we throw an exception here instead?
return null;
}
return resultSet;
}
private void initializeScriptHandler( BIRTExternalContext externalContext )
throws ChartException
{
String javaHandlerClass = handle.getEventHandlerClass( );
if ( javaHandlerClass != null && javaHandlerClass.length( ) > 0 )
{
// use java handler if available.
cm.setScript( javaHandlerClass );
}
rtc.setScriptClassLoader( new BIRTScriptClassLoader( appClassLoader ) );
// INITIALIZE THE SCRIPT HANDLER
// UPDATE THE CHART SCRIPT CONTEXT
ScriptHandler sh = rtc.getScriptHandler( );
if ( sh == null ) // IF NOT PREVIOUSLY DEFINED BY
// REPORTITEM ADAPTER
{
sh = new ScriptHandler( );
rtc.setScriptHandler( sh );
sh.setScriptClassLoader( rtc.getScriptClassLoader( ) );
sh.setScriptContext( rtc.getScriptContext( ) );
final String sScriptContent = cm.getScript( );
if ( externalContext != null
&& externalContext.getScriptable( ) != null )
{
sh.init( externalContext.getScriptable( ) );
}
else
{
sh.init( null );
}
sh.setRunTimeModel( cm );
if ( sScriptContent != null
&& sScriptContent.length( ) > 0
&& rtc.isScriptingEnabled( ) )
{
sh.register( ModuleUtil.getScriptUID( handle.getPropertyHandle( IReportItemModel.ON_RENDER_METHOD ) ),
sScriptContent );
}
}
}
protected GeneratedChartState buildChart(
IDataRowExpressionEvaluator rowAdapter,
BIRTExternalContext externalContext ) throws ChartException
{
final Bounds bo = computeBounds( );
initializeRuntimeContext( rowAdapter );
// Update chart model if needed
updateChartModel( );
GeneratedChartState gcs = Generator.instance( )
.build( idr.getDisplayServer( ),
cm,
bo,
externalContext,
rtc,
new ChartReportStyleProcessor( handle, true, this.style ) );
boundsRuntime = gcs.getChartModel( ).getBlock( ).getBounds( );
return gcs;
}
protected Object getImageToDisplay( )
{
if ( getOutputType( ) == OUTPUT_AS_IMAGE )
{
return fis;
}
else if ( getOutputType( ) == OUTPUT_AS_IMAGE_WITH_MAP )
{
return new Object[]{
fis, imageMap
};
}
else
throw new IllegalArgumentException( );
}
protected void renderToImageFile( GeneratedChartState gcs )
throws ChartException
{
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemPresentationImpl.log.onRowSetsRendering" ) ); //$NON-NLS-1$
ByteArrayOutputStream baos = new ByteArrayOutputStream( );
BufferedOutputStream bos = new BufferedOutputStream( baos );
idr.setProperty( IDeviceRenderer.FILE_IDENTIFIER, bos );
idr.setProperty( IDeviceRenderer.UPDATE_NOTIFIER,
new EmptyUpdateNotifier( cm, gcs.getChartModel( ) ) );
Generator.instance( ).render( idr, gcs );
// RETURN A STREAM HANDLE TO THE NEWLY CREATED IMAGE
try
{
bos.close( );
fis = new ByteArrayInputStream( baos.toByteArray( ) );
}
catch ( Exception ioex )
{
throw new ChartException( ChartReportItemPlugin.ID,
ChartException.GENERATION,
ioex );
}
if ( getOutputType( ) == OUTPUT_AS_IMAGE_WITH_MAP )
{
imageMap = ( (IImageMapEmitter) idr ).getImageMap( );
}
}
private boolean isNoDataException( BirtException birtException )
{
Throwable ex = birtException;
while ( ex.getCause( ) != null )
{
ex = ex.getCause( );
}
if ( ex instanceof ChartException
&& ( (ChartException) ex ).getType( ) == ChartException.ZERO_DATASET )
{
// if the Data set has zero lines, just
// returns null gracefully.
return true;
}
if ( ex instanceof ChartException
&& ( (ChartException) ex ).getType( ) == ChartException.ALL_NULL_DATASET )
{
// if the Data set contains all null values, just
// returns null gracefully and render nothing.
return true;
}
if ( ( ex instanceof ChartException && ( (ChartException) ex ).getType( ) == ChartException.INVALID_IMAGE_SIZE ) )
{
// if the image size is invalid, this may caused by
// Display=None, lets ignore it.
logger.log( birtException );
return true;
}
logger.log( ILogger.ERROR,
Messages.getString( "ChartReportItemPresentationImpl.log.onRowSetsFailed" ) ); //$NON-NLS-1$
logger.log( birtException );
return false;
}
private IActionRenderer createActionRenderer( DesignElementHandle eih,
IHTMLActionHandler handler, IDataRowExpressionEvaluator evaluator,
IReportContext context )
{
IAdapterManager adapterManager = Platform.getAdapterManager( );
IActionRendererFactory arFactory = (IActionRendererFactory) adapterManager.loadAdapter( this.handle,
IActionRendererFactory.class.getName( ) );
if ( arFactory != null )
{
return arFactory.createActionRenderer( eih,
handler,
evaluator,
context );
}
else
{
return new BIRTActionRenderer( eih, handler, evaluator, context );
}
}
private void initializeRuntimeContext(
IDataRowExpressionEvaluator rowAdapter )
{
rtc.setActionRenderer( createActionRenderer( this.handle,
this.ah,
rowAdapter,
this.context ) );
rtc.setMessageLookup( new BIRTMessageLookup( context ) );
// Set direction from model to chart runtime context
rtc.setRightToLeftText( handle.isDirectionRTL( ) );
// Set text direction from StyleHandle to chart runtime context
ChartReportItemImpl crii = (ChartReportItemImpl) getReportItem( handle );
rtc.setRightToLeft( crii.isLayoutDirectionRTL( ) );
rtc.setResourceFinder( crii );
rtc.setExternalizer( crii );
}
protected void prepareDeviceRenderer( ) throws ChartException
{
idr = ChartEngine.instance( ).getRenderer( "dv." //$NON-NLS-1$
+ sExtension.toUpperCase( Locale.US ) );
idr.setProperty( IDeviceRenderer.DPI_RESOLUTION, Integer.valueOf( dpi ) );
if ( "SVG".equalsIgnoreCase( sExtension ) ) //$NON-NLS-1$
{
idr.setProperty( "resize.svg", Boolean.TRUE ); //$NON-NLS-1$
}
}
/**
* Updates chart model when something needs change
*/
protected void updateChartModel( )
{
// Do nothing
}
} |
package mobi.hsz.idea.gitignore;
import com.intellij.openapi.components.AbstractProjectComponent;
import com.intellij.openapi.progress.BackgroundTaskQueue;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsListener;
import com.intellij.openapi.vfs.*;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerImpl;
import com.intellij.psi.impl.file.impl.FileManager;
import com.intellij.psi.impl.file.impl.FileManagerImpl;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.Alarm;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBusConnection;
import mobi.hsz.idea.gitignore.file.type.IgnoreFileType;
import mobi.hsz.idea.gitignore.lang.IgnoreLanguage;
import mobi.hsz.idea.gitignore.psi.IgnoreFile;
import mobi.hsz.idea.gitignore.settings.IgnoreSettings;
import mobi.hsz.idea.gitignore.util.CacheMap;
import mobi.hsz.idea.gitignore.util.Utils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
import static mobi.hsz.idea.gitignore.settings.IgnoreSettings.KEY;
/**
* {@link IgnoreManager} handles ignore files indexing and status caching.
*
* @author Jakub Chrzanowski <jakub@hsz.mobi>
* @since 1.0
*/
public class IgnoreManager extends AbstractProjectComponent {
private final CacheMap cache;
private final PsiManagerImpl psiManager;
private final VirtualFileManager virtualFileManager;
private final Alarm alarm = new Alarm();
private final BackgroundTaskQueue queue;
private final IgnoreSettings settings;
private MessageBusConnection messageBus;
private boolean working;
private final VirtualFileListener virtualFileListener = new VirtualFileAdapter() {
public boolean wasIgnoreFileType;
/**
* Fired when a virtual file is renamed from within IDEA, or its writable status is changed.
* For files renamed externally, {@link #fileCreated} and {@link #fileDeleted} events will be fired.
*
* @param event the event object containing information about the change.
*/
@Override
public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
if (event.getPropertyName().equals("name")) {
boolean isIgnoreFileType = isIgnoreFileType(event);
if (isIgnoreFileType && !wasIgnoreFileType) {
addFile(event);
} else if (!isIgnoreFileType && wasIgnoreFileType) {
removeFile(event);
}
}
}
/**
* Fired before the change of a name or writable status of a file is processed.
*
* @param event the event object containing information about the change.
*/
@Override
final public void beforePropertyChange(@NotNull VirtualFilePropertyEvent event) {
wasIgnoreFileType = isIgnoreFileType(event);
}
/**
* Fired when a virtual file is created. This event is not fired for files discovered during initial VFS initialization.
*
* @param event the event object containing information about the change.
*/
@Override
public void fileCreated(@NotNull VirtualFileEvent event) {
addFile(event);
}
@Override
public void beforeFileDeletion(@NotNull VirtualFileEvent event) {
removeFile(event);
}
/**
* Fired when a virtual file is copied from within IDEA.
*
* @param event the event object containing information about the change.
*/
@Override
public void fileCopied(@NotNull VirtualFileCopyEvent event) {
addFile(event);
}
/**
* Adds {@link IgnoreFile} to the {@link CacheMap}.
*/
private void addFile(VirtualFileEvent event) {
if (isIgnoreFileType(event)) {
IgnoreFile file = getIgnoreFile(event.getFile());
if (file != null) {
cache.add(file);
}
}
}
/**
* Removes {@link IgnoreFile} from the {@link CacheMap}.
*/
private void removeFile(VirtualFileEvent event) {
if (isIgnoreFileType(event)) {
cache.remove(getIgnoreFile(event.getFile()));
}
}
/**
* Checks if event was fired on the {@link IgnoreFileType} file.
*
* @param event current event
* @return event called on {@link IgnoreFileType}
*/
protected boolean isIgnoreFileType(VirtualFileEvent event) {
return event.getFile().getFileType() instanceof IgnoreFileType;
}
};
private final PsiTreeChangeListener psiTreeChangeListener = new PsiTreeChangeAdapter() {
@Override
public void childrenChanged(@NotNull PsiTreeChangeEvent event) {
if (event.getParent() instanceof IgnoreFile) {
IgnoreFile ignoreFile = (IgnoreFile) event.getParent();
if (((IgnoreLanguage) ignoreFile.getLanguage()).isEnabled()) {
cache.hasChanged(ignoreFile);
}
}
}
};
private final IgnoreSettings.Listener settingsListener = new IgnoreSettings.Listener() {
@Override
public void onChange(@NotNull KEY key, Object value) {
switch (key) {
case IGNORED_FILE_STATUS:
toggle((Boolean) value);
break;
case OUTER_IGNORE_RULES:
case LANGUAGES:
if (isEnabled()) {
if (working) {
cache.clear();
retrieve();
} else {
enable();
}
}
break;
}
}
};
private final VcsListener vcsListener = new VcsListener() {
private boolean initialized;
@Override
public void directoryMappingChanged() {
if (working && initialized) {
cache.clear();
retrieve();
}
initialized = true;
}
};
/**
* Returns {@link IgnoreManager} service instance.
*
* @param project current project
* @return {@link IgnoreManager instance}
*/
public static IgnoreManager getInstance(@NotNull final Project project) {
return project.getComponent(IgnoreManager.class);
}
/**
* Constructor builds {@link IgnoreManager} instance.
*
* @param project current project
*/
public IgnoreManager(@NotNull final Project project) {
super(project);
cache = new CacheMap(project);
psiManager = (PsiManagerImpl) PsiManager.getInstance(project);
virtualFileManager = VirtualFileManager.getInstance();
queue = new BackgroundTaskQueue(project, IgnoreBundle.message("cache.indexing"));
settings = IgnoreSettings.getInstance();
}
/**
* Helper for fetching {@link IgnoreFile} using {@link VirtualFile}.
*
* @param file current file
* @return {@link IgnoreFile}
*/
@Nullable
private IgnoreFile getIgnoreFile(@Nullable VirtualFile file) {
if (file == null || !file.exists()) {
return null;
}
PsiFile psiFile = psiManager.findFile(file);
if (psiFile == null || !(psiFile instanceof IgnoreFile)) {
return null;
}
return (IgnoreFile) psiFile;
}
/**
* Checks if file is ignored.
*
* @param file current file
* @return file is ignored
*/
public boolean isFileIgnored(@NotNull final VirtualFile file) {
return isEnabled() && cache.isFileIgnored(file);
}
/**
* Checks if file's parents are ignored.
*
* @param file current file
* @return file's parents are ignored
*/
public boolean isParentIgnored(@NotNull final VirtualFile file) {
if (!isEnabled()) {
return false;
}
VirtualFile parent = file.getParent();
while (parent != null && Utils.isInProject(parent, myProject)) {
if (isFileIgnored(parent)) {
return true;
}
parent = parent.getParent();
}
return false;
}
/**
* Checks if ignored files watching is enabled.
*
* @return enabled
*/
private boolean isEnabled() {
return settings.isIgnoredFileStatus();
}
/**
* Invoked when the project corresponding to this component instance is opened.<p>
* Note that components may be created for even unopened projects and this method can be never
* invoked for a particular component instance (for example for default project).
*/
@Override
public void projectOpened() {
if (isEnabled() && !working) {
enable();
}
}
/**
* Enable manager.
*/
private void enable() {
if (working) {
return;
}
virtualFileManager.addVirtualFileListener(virtualFileListener);
psiManager.addPsiTreeChangeListener(psiTreeChangeListener);
settings.addListener(settingsListener);
messageBus = myProject.getMessageBus().connect();
messageBus.subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, vcsListener);
working = true;
retrieve();
}
/**
* Invoked when the project corresponding to this component instance is closed.<p>
* Note that components may be created for even unopened projects and this method can be never
* invoked for a particular component instance (for example for default project).
*/
@Override
public void projectClosed() {
disable();
}
/**
* Disable manager.
*/
private void disable() {
alarm.cancelAllRequests();
virtualFileManager.removeVirtualFileListener(virtualFileListener);
psiManager.removePsiTreeChangeListener(psiTreeChangeListener);
settings.removeListener(settingsListener);
if (messageBus != null) {
messageBus.disconnect();
}
cache.clear();
working = false;
}
/**
* Runs {@link #enable()} or {@link #disable()} depending on the passed value.
*
* @param enable or disable
*/
private void toggle(Boolean enable) {
if (enable) {
enable();
} else {
disable();
}
}
/**
* Triggers caching actions.
*/
private void retrieve() {
if (!Alarm.isEventDispatchThread()) {
return;
}
alarm.cancelAllRequests();
alarm.addRequest(new Runnable() {
@Override
public void run() {
FileManager fileManager = psiManager.getFileManager();
if (!(fileManager instanceof FileManagerImpl)) {
return;
}
if (((FileManagerImpl) psiManager.getFileManager()).isInitialized()) {
alarm.cancelAllRequests();
queue.clear();
// Search for Ignore files in the project
final GlobalSearchScope scope = GlobalSearchScope.allScope(myProject);
final List<IgnoreFile> files = ContainerUtil.newArrayList();
for (final IgnoreLanguage language : IgnoreBundle.LANGUAGES) {
if (language.isEnabled()) {
try {
Collection<VirtualFile> virtualFiles = FileTypeIndex.getFiles(language.getFileType(), scope);
for (VirtualFile virtualFile : virtualFiles) {
ContainerUtil.addIfNotNull(getIgnoreFile(virtualFile), files);
}
} catch (IndexOutOfBoundsException ignored) {
}
}
}
Utils.ignoreFilesSort(files);
addTasksFor(files);
// Search for outer files
if (settings.isOuterIgnoreRules()) {
for (IgnoreLanguage language : IgnoreBundle.LANGUAGES) {
if (!language.isEnabled()) {
continue;
}
VirtualFile outerFile = language.getOuterFile(myProject);
if (outerFile != null) {
PsiFile psiFile = psiManager.findFile(outerFile);
if (psiFile != null) {
IgnoreFile outerIgnoreFile = (IgnoreFile) PsiFileFactory.getInstance(myProject)
.createFileFromText(language.getFilename(), language, psiFile.getText());
outerIgnoreFile.setOriginalFile(psiFile);
addTaskFor(outerIgnoreFile);
}
}
}
}
}
}
/**
* Adds {@link IgnoreFile} to the cache processor queue.
*
* @param files to cache
*/
private void addTasksFor(@NotNull final List<IgnoreFile> files) {
if (files.isEmpty()) {
return;
}
addTaskFor(files.remove(0), files);
}
/**
* Adds {@link IgnoreFile} to the cache processor queue.
*
* @param file to cache
*/
private void addTaskFor(@Nullable final IgnoreFile file) {
addTaskFor(file, null);
}
/**
* Adds {@link IgnoreFile} to the cache processor queue.
*
* @param file to cache
* @param dependentFiles files to cache if not ignored by given file
*/
private void addTaskFor(@Nullable final IgnoreFile file, @Nullable final List<IgnoreFile> dependentFiles) {
if (file == null) {
return;
}
queue.run(new Task.Backgroundable(myProject, IgnoreBundle.message("cache.indexing")) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final VirtualFile virtualFile = file.getVirtualFile();
VirtualFile projectDir = myProject.getBaseDir();
if ((!file.isOuter() && (virtualFile == null || isFileIgnored(virtualFile))) || projectDir == null) {
indicator.cancel();
} else {
String path = Utils.getRelativePath(projectDir, file.getVirtualFile());
indicator.setText(path);
cache.add(file);
}
if (dependentFiles == null || dependentFiles.isEmpty()) {
return;
}
for (IgnoreFile dependentFile : dependentFiles) {
VirtualFile dependentVirtualFile = dependentFile.getVirtualFile();
if (dependentVirtualFile != null && !isFileIgnored(dependentVirtualFile) && !isParentIgnored(dependentVirtualFile)) {
addTaskFor(dependentFile);
}
}
}
});
}
}, 200);
}
/**
* Unique name of this component. If there is another component with the same name or
* name is null internal assertion will occur.
*
* @return the name of this component
*/
@NonNls
@NotNull
@Override
public String getComponentName() {
return "IgnoreManager";
}
} |
package edu.psu.compbio.seqcode.projects.chexmix;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentCondition;
import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentManager;
import edu.psu.compbio.seqcode.deepseq.experiments.ExptConfig;
import edu.psu.compbio.seqcode.genome.GenomeConfig;
import edu.psu.compbio.seqcode.genome.location.Region;
import edu.psu.compbio.seqcode.genome.location.StrandedPoint;
import edu.psu.compbio.seqcode.gse.datasets.motifs.WeightMatrix;
import edu.psu.compbio.seqcode.gse.gsebricks.verbs.sequence.SequenceGenerator;
import edu.psu.compbio.seqcode.gse.utils.sequence.SequenceUtils;
import edu.psu.compbio.seqcode.projects.multigps.utilities.Utils;
public class XLQuantifier {
protected ExperimentManager manager;
protected GenomeConfig gconfig;
protected ExptConfig econfig;
protected ChExMixConfig cconfig;
protected ProteinDNAInteractionModel model;
protected CompositeModelMixture mixtureModel;
protected CompositeModelEM EMtrainer;
protected CompositeTagDistribution signalComposite;
protected CompositeTagDistribution controlComposite;
protected List<StrandedPoint> compositePoints;
private final char[] LETTERS = {'A','C','G','T'};
public XLQuantifier(GenomeConfig gcon, ExptConfig econ, ChExMixConfig ccon){
gconfig = gcon;
econfig = econ;
cconfig = ccon;
cconfig.makeChExMixOutputDirs(true);
manager = new ExperimentManager(econfig);
}
public void execute(){
//Load appropriate data
model = ProteinDNAInteractionModel.loadFromFile(cconfig, new File(cconfig.getModelFilename()));
compositePoints = cconfig.getCompositePoints();
int winSize = cconfig.getCompositeWinSize();
//Build the composite distribution(s)
signalComposite = new CompositeTagDistribution(compositePoints, manager, winSize, true);
//controlComposite = new CompositeTagDistribution(points, manager, winSize, false);
controlComposite =null;
//Initialize the mixture model
mixtureModel = new CompositeModelMixture(signalComposite, controlComposite, gconfig, econfig, cconfig, manager);
//Set the loaded model
mixtureModel.setModel(model);
//Set composite-level responsibilities in model
EMtrainer = new CompositeModelEM(signalComposite, cconfig, manager);
try {
EMtrainer.train(model, 0, false);
} catch (Exception e) {
e.printStackTrace();
}
//ML assignment at per-site level
System.err.println("ML assignment");
mixtureModel.assignML(true);
//Get the per-site assignments
List<CompositeModelSiteAssignment> assignments = mixtureModel.getSiteAssignments();
Map<StrandedPoint, String> pointSeqs = retrieveSequences(assignments, signalComposite.getWinSize());
//Build per-XL-point weighted PWMs
Map<CompositeModelComponent, WeightMatrix> componentMotifs = getPerComponentWeightMatrices(assignments, pointSeqs, 20, false);
Map<CompositeModelComponent, WeightMatrix> componentMotifsMaxPeaksOnly = getPerComponentWeightMatrices(assignments, pointSeqs, 20, true);
WeightMatrix allSiteMotif = getAllPointWeightMatrix(pointSeqs, 100);
//Estimate corrected XL tag counts
for(ExperimentCondition cond : manager.getConditions()){
String correctionFilename = cconfig.getOutputParentDir()+File.separator+cconfig.getOutBase()
+"_XL-bias-correction."+cond.getName()+".txt";
correctXLBias(cond, assignments, new File(correctionFilename));
}
//Report
for(ExperimentCondition cond : manager.getConditions()){
String compositeFileName = cconfig.getOutputParentDir()+File.separator+cconfig.getOutBase()
+"_composite."+cond.getName()+".txt";
signalComposite.printProbsToFile(cond, compositeFileName);
String perSiteRespFileName = cconfig.getOutputParentDir()+File.separator+cconfig.getOutBase()
+"_site-component-ML."+cond.getName()+".txt";
mixtureModel.printPerSiteComponentResponsibilitiesToFile(cond, perSiteRespFileName);
}
mixtureModel.saveCompositePlots();
//Print motif logos
for(CompositeModelComponent comp : componentMotifs.keySet()){
String motifFileName = cconfig.getOutputImagesDir()+File.separator+cconfig.getOutBase()
+"_xl-bias-motif."+(comp.getPosition()-signalComposite.getCenterOffset())+".png";
WeightMatrix motif = componentMotifs.get(comp);
String motifLabel = cconfig.getOutBase()+" "+(comp.getPosition()-signalComposite.getCenterOffset())+" XL bias motif";
Utils.printMotifLogo(motif, new File(motifFileName), 150, motifLabel, true);
String motifFileNameMaxOnly = cconfig.getOutputImagesDir()+File.separator+cconfig.getOutBase()
+"_xl-bias-motif-max-only."+(comp.getPosition()-signalComposite.getCenterOffset())+".png";
motif = componentMotifsMaxPeaksOnly.get(comp);
motifLabel = cconfig.getOutBase()+" "+(comp.getPosition()-signalComposite.getCenterOffset())+" XL bias motif (max XL only)";
Utils.printMotifLogo(motif, new File(motifFileNameMaxOnly), 150, motifLabel, true);
}
String allMotifFileName = cconfig.getOutputImagesDir()+File.separator+cconfig.getOutBase()
+"_all-site-motif.png";
String motifLabel = cconfig.getOutBase()+" all site motif";
Utils.printMotifLogo(allSiteMotif, new File(allMotifFileName), 710, motifLabel, true);
}
/**
* Get sequences corresponding to the stranded points in the site assignments
* @param siteAssignments
* @param seqWin
* @return
*/
protected Map<StrandedPoint, String> retrieveSequences(List<CompositeModelSiteAssignment> siteAssignments, int seqWin){
Map<StrandedPoint, String> pointSequences = new HashMap<StrandedPoint, String>();
SequenceGenerator<Region> seqgen = gconfig.getSequenceGenerator();
for(CompositeModelSiteAssignment sa : siteAssignments){
Region reg = sa.getPoint().expand(seqWin/2);
String seq = seqgen.execute(reg);
if(sa.getPoint().getStrand()=='-')
seq = SequenceUtils.reverseComplement(seq);
pointSequences.put(sa.getPoint(), seq);
}
return pointSequences;
}
/**
* Calculate weighted motifs for each non-zero XL component
* @return
*/
protected WeightMatrix getAllPointWeightMatrix(Map<StrandedPoint, String> pointSeqs, int motifWidth){
int motifStartPos = signalComposite.getCenterOffset() - (motifWidth/2)+1;
float[][] freq = new float[motifWidth][WeightMatrix.MAXLETTERVAL];
float[][] pwm = new float[motifWidth][WeightMatrix.MAXLETTERVAL];
float[] sum = new float[motifWidth];
float pseudoCount=(float) 0.01;
for(int x=0; x<motifWidth; x++){
sum[x]=0;
for (int b=0;b<LETTERS.length;b++){
freq[x][LETTERS[b]]=0;
}}
for(StrandedPoint pt : pointSeqs.keySet()){
String currSeq = pointSeqs.get(pt).toUpperCase();
for(int x=0; x<motifWidth; x++){
char letter = currSeq.charAt(motifStartPos+x);
freq[x][letter]++;
sum[x]++;
}
}
//Normalize freq matrix
//Log-odds over expected motif
for(int x=0; x<motifWidth; x++){
for (int b=0;b<LETTERS.length;b++){
freq[x][LETTERS[b]]/=sum[x];
}
for (int b=0;b<LETTERS.length;b++){
freq[x][LETTERS[b]] = (freq[x][LETTERS[b]]+pseudoCount)/(1+(4*pseudoCount));
pwm[x][LETTERS[b]] = (float) (Math.log((double)freq[x][LETTERS[b]] / 0.25) / Math.log(2.0));
}}
//Save as WeightMatrix
WeightMatrix motif = new WeightMatrix(pwm);
return motif;
}
/**
* Calculate weighted motifs for each non-zero XL component
* @return
*/
protected Map<CompositeModelComponent, WeightMatrix> getPerComponentWeightMatrices(List<CompositeModelSiteAssignment> siteAssignments, Map<StrandedPoint, String> pointSeqs, int motifWidth, boolean motifWeightedByMaxCompsOnly){
Map<CompositeModelComponent, WeightMatrix> xlComponentMotifs = new HashMap<CompositeModelComponent, WeightMatrix>();
double maxWeightProp = 0.05; //cap per-site motif weights as 5% of total component tag count
for(CompositeModelComponent xlComp : model.getXLComponents()){ if(xlComp.isNonZero()){
int compOffset = xlComp.getPosition();
int motifStartPos = compOffset - (motifWidth/2)+1;
float[][] freq = new float[motifWidth][WeightMatrix.MAXLETTERVAL];
float[][] freqWeight = new float[motifWidth][WeightMatrix.MAXLETTERVAL];
float[][] pwm = new float[motifWidth][WeightMatrix.MAXLETTERVAL];
float[] sum = new float[motifWidth];
float[] sumWeight = new float[motifWidth];
float pseudoCount=(float) 0.01;
for(int x=0; x<motifWidth; x++){
sum[x]=0; sumWeight[x]=0;
for (int b=0;b<LETTERS.length;b++){
freq[x][LETTERS[b]]=0; freqWeight[x][LETTERS[b]]=0;
}}
int numCountedSites=0;
//Sum of weights (for capping weights)
float sumWeights=0;
for(CompositeModelSiteAssignment sa : siteAssignments){
for(ExperimentCondition cond : manager.getConditions()){
sumWeights+= sa.getCompResponsibility(cond, xlComp.getIndex());
}
}
//Weighted freq matrix
for(CompositeModelSiteAssignment sa : siteAssignments){
StrandedPoint pt = sa.getPoint();
String currSeq = pointSeqs.get(pt).toUpperCase();
for(ExperimentCondition cond : manager.getConditions()){
//This block weights XL sites by proportion of total XL tags
/*
double currWeight =0;
double currResp = sa.getCompResponsibility(cond, xlComp.getIndex());
double totXLResp =0;
if(currResp>10){
for(CompositeModelComponent comp : model.getXLComponents()){ if(comp.isNonZero()){
totXLResp+=sa.getCompResponsibility(cond, comp.getIndex());
}}
currWeight=currResp/totXLResp;
}*/
double currWeight =0;
if(motifWeightedByMaxCompsOnly){
//This block weights XL sites as component tags iff they are strongest XL site
double currResp = sa.getCompResponsibility(cond, xlComp.getIndex());
double maxXLResp =0;
for(CompositeModelComponent comp : model.getXLComponents()){ if(comp.isNonZero()){
if(sa.getCompResponsibility(cond, comp.getIndex())>maxXLResp)
maxXLResp =sa.getCompResponsibility(cond, comp.getIndex());
}}
//currWeight=(currResp==maxXLResp && currResp>1) ? currResp : 0;
currWeight=(currResp==maxXLResp && currResp>1) ? 1 : 0;
}else{
//Weight = XL tags at this component
double currResp = sa.getCompResponsibility(cond, xlComp.getIndex());
currWeight = currResp>1 ? sa.getCompResponsibility(cond, xlComp.getIndex()) : 0;
currWeight/=sumWeights;
if(currWeight>maxWeightProp)
currWeight=maxWeightProp;
}
if(currWeight>0)
numCountedSites++;
for(int x=0; x<motifWidth; x++){
char letter = currSeq.charAt(motifStartPos+x);
freqWeight[x][letter]+=currWeight;
sumWeight[x]+=currWeight;
freq[x][letter]++;
sum[x]++;
}
}
}
//Normalize freq matrix
//Log-odds over expected motif
for(int x=0; x<motifWidth; x++){
for (int b=0;b<LETTERS.length;b++){
freq[x][LETTERS[b]]/=sum[x];
freqWeight[x][LETTERS[b]]/=sumWeight[x];
}
for (int b=0;b<LETTERS.length;b++){
freq[x][LETTERS[b]] = (freq[x][LETTERS[b]]+pseudoCount)/(1+(4*pseudoCount));
freqWeight[x][LETTERS[b]] = (freqWeight[x][LETTERS[b]]+pseudoCount)/(1+(4*pseudoCount));
pwm[x][LETTERS[b]] = (float) (Math.log((double)freqWeight[x][LETTERS[b]] / (double)freq[x][LETTERS[b]]) / Math.log(2.0));
}}
//Save as WeightMatrix
WeightMatrix motif = new WeightMatrix(pwm);
xlComponentMotifs.put(xlComp, motif);
//Temp print
System.out.println("XLComponent motif: "+(xlComp.getPosition()-signalComposite.getCenterOffset()));
for(int x=0; x<motifWidth; x++){
System.out.println(x+"\t"+pwm[x]['A']+"\t"+pwm[x]['C']+"\t"+pwm[x]['G']+"\t"+pwm[x]['T']);
//System.out.println(x+"\t"+freqWeight[x]['A']+"\t"+freqWeight[x]['C']+"\t"+freqWeight[x]['G']+"\t"+freqWeight[x]['T']);
//System.out.println(x+"\t"+freq[x]['A']+"\t"+freq[x]['C']+"\t"+freq[x]['G']+"\t"+freq[x]['T']);
}System.out.println("");
System.out.println("Component "+(xlComp.getPosition()-signalComposite.getCenterOffset())+": motif created using "+numCountedSites);
}
}
return xlComponentMotifs;
}
/**
* Attempt to correct XL tag counts for XL bias.
* The intuition here is if an XL component is taking proportionally more responsibility for tags than
* it does on average, it must be compensating for inefficient crosslinking at other components.
* Therefore, this method infers total XL tag counts from the over-strength XL components.
*
* @param siteAssignments
*/
protected void correctXLBias(ExperimentCondition cond, List<CompositeModelSiteAssignment> siteAssignments, File correctedOutFile){
try{
FileWriter fout = new FileWriter(correctedOutFile);
fout.write("#Point\tObsXLTags\tEstXLTags\n");
//Find the expected/average XL proportions.
double totalXLpi = 0;
double[] expectedXLProps = new double[model.getXLComponents().size()];
Map<CompositeModelComponent, Integer> component2Index = new HashMap<CompositeModelComponent, Integer>();
int i=0;
for(CompositeModelComponent xlComp : model.getXLComponents()){
totalXLpi+=xlComp.getPi();
expectedXLProps[i]=xlComp.getPi();
component2Index.put(xlComp, i);
i++;
}
for(int x=0; x<expectedXLProps.length; x++)
expectedXLProps[x]/=totalXLpi;
//Examine actual XL proportions for each ML assigned site
for(CompositeModelSiteAssignment sa : siteAssignments){
StrandedPoint pt = sa.getPoint();
//Calculate observed XL proportions & counts for this site
double siteXLtotal = 0;
double[] obsXLProps = new double[model.getXLComponents().size()];
double[] obsXLCounts = new double[model.getXLComponents().size()];
for(CompositeModelComponent xlComp : model.getXLComponents()){ if(xlComp.isNonZero()){
siteXLtotal+=sa.getCompResponsibility(cond, xlComp.getIndex());
obsXLProps[component2Index.get(xlComp)]=sa.getCompResponsibility(cond, xlComp.getIndex());
obsXLCounts[component2Index.get(xlComp)]=sa.getCompResponsibility(cond, xlComp.getIndex());
}}
for(CompositeModelComponent xlComp : model.getXLComponents()){ if(xlComp.isNonZero()){
obsXLProps[component2Index.get(xlComp)]/=siteXLtotal;
}}
//For over-strength XL components, estimate totals
double sumEstTot = 0, count=0;
for(CompositeModelComponent xlComp : model.getXLComponents()){ if(xlComp.isNonZero()){
if(obsXLProps[component2Index.get(xlComp)] > expectedXLProps[component2Index.get(xlComp)]){
sumEstTot+=obsXLCounts[component2Index.get(xlComp)]/expectedXLProps[component2Index.get(xlComp)];;
count++;
}
}}
double estimatedXLtotal = count>0 ? sumEstTot/count : siteXLtotal;
fout.write(pt.toString()+"\t"+siteXLtotal+"\t"+estimatedXLtotal+"\n");
}
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
System.setProperty("java.awt.headless", "true");
System.err.println("ChExMix version: "+ChExMixConfig.version);
GenomeConfig gcon = new GenomeConfig(args);
ExptConfig econ = new ExptConfig(gcon.getGenome(), args);
//econ.setLoadRead2(false);//Enforce for chip-exo
ChExMixConfig ccon = new ChExMixConfig(gcon, args);
if(ccon.helpWanted()){
System.err.println(ccon.getArgsList());
}else if(ccon.getModelFilename()==null){
System.err.println("Error: no ChExMix model provided. Use --model");
}else{
XLQuantifier xlQuant = new XLQuantifier(gcon, econ, ccon);
xlQuant.execute();
}
}
} |
package mobi.hsz.idea.gitignore.util;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
import mobi.hsz.idea.gitignore.psi.IgnoreEntry;
import mobi.hsz.idea.gitignore.psi.IgnoreFile;
import mobi.hsz.idea.gitignore.psi.IgnoreVisitor;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* {@link HashMap} cache helper.
*
* @author Jakub Chrzanowski <jakub@hsz.mobi>
* @since 1.0.2
*/
public class CacheMap {
private final ConcurrentMap<IgnoreFile, Pair<Set<Integer>, List<Pair<Matcher, Boolean>>>> map = ContainerUtil.newConcurrentMap();
/** Cache {@link HashMap} to store files statuses. */
private final HashMap<VirtualFile, Status> statuses = new HashMap<VirtualFile, Status>();
/** Current project. */
private final Project project;
/** {@link FileStatusManager} instance. */
private final FileStatusManager statusManager;
/** Status of the file. */
private enum Status {
IGNORED, UNIGNORED, UNTOUCHED
}
public CacheMap(Project project) {
this.project = project;
this.statusManager = FileStatusManager.getInstance(project);
}
/**
* Adds new {@link IgnoreFile} to the cache and builds its hashCode and patterns sets.
*
* @param file to add
*/
public void add(@NotNull final IgnoreFile file) {
final Set<Integer> set = ContainerUtil.newHashSet();
runVisitorInReadAction(file, new IgnoreVisitor() {
@Override
public void visitEntry(@NotNull IgnoreEntry entry) {
set.add(entry.getText().trim().hashCode());
}
});
add(file, set);
}
/**
* Adds new {@link IgnoreFile} to the cache and builds its hashCode and patterns sets.
*
* @param file to add
* @param set entries hashCodes set
*/
protected void add(@NotNull final IgnoreFile file, Set<Integer> set) {
final List<Pair<Matcher, Boolean>> matchers = ContainerUtil.newArrayList();
runVisitorInReadAction(file, new IgnoreVisitor() {
@Override
public void visitEntry(@NotNull IgnoreEntry entry) {
Pattern pattern = Glob.createPattern(entry);
if (pattern != null) {
matchers.add(Pair.create(pattern.matcher(""), entry.isNegated()));
}
}
});
map.put(file, Pair.create(set, matchers));
statuses.clear();
statusManager.fileStatusesChanged();
}
/**
* Checks if {@link IgnoreFile} has changed and rebuilds its cache.
*
* @param file to check
*/
public void hasChanged(@NotNull IgnoreFile file) {
final Pair<Set<Integer>, List<Pair<Matcher, Boolean>>> recent = map.get(file);
final Set<Integer> set = ContainerUtil.newHashSet();
file.acceptChildren(new IgnoreVisitor() {
@Override
public void visitEntry(@NotNull IgnoreEntry entry) {
set.add(entry.getText().trim().hashCode());
}
});
if (recent == null || !set.equals(recent.getFirst())) {
add(file, set);
}
}
/**
* Simple wrapper for running read action
*
* @param file {@link IgnoreFile} to run visitor on it
* @param visitor {@link IgnoreVisitor}
*/
private void runVisitorInReadAction(@NotNull final IgnoreFile file, @NotNull final IgnoreVisitor visitor) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null && (virtualFile instanceof LightVirtualFile
|| (virtualFile instanceof VirtualFileWithId && ((VirtualFileWithId) virtualFile).getId() > 0))) {
file.acceptChildren(visitor);
}
}
});
}
/**
* Checks if given {@link VirtualFile} is ignored.
*
* @param file to check
* @return file is ignored
*/
public boolean isFileIgnored(@NotNull VirtualFile file) {
Status status = statuses.get(file);
if (status == null || status.equals(Status.UNTOUCHED)) {
status = getParentStatus(file);
statuses.put(file, status);
}
final List<IgnoreFile> files = ContainerUtil.reverse(Utils.ignoreFilesSort(ContainerUtil.newArrayList(map.keySet())));
final ProjectLevelVcsManager projectLevelVcsManager = ProjectLevelVcsManager.getInstance(project);
for (final IgnoreFile ignoreFile : files) {
boolean outer = ignoreFile.isOuter();
final VirtualFile ignoreFileParent = ignoreFile.getVirtualFile().getParent();
if (!outer) {
if (ignoreFileParent == null || !Utils.isUnder(file, ignoreFileParent)) {
continue;
}
VirtualFile vcsRoot = projectLevelVcsManager.getVcsRootFor(file);
if (vcsRoot != null && !vcsRoot.equals(file) && !Utils.isUnder(ignoreFile.getVirtualFile(), vcsRoot)) {
continue;
}
}
final String path = Utils.getRelativePath(outer ? project.getBaseDir() : ignoreFileParent, file);
if (StringUtil.isEmpty(path)) {
continue;
}
List<Pair<Matcher, Boolean>> matchers = map.get(ignoreFile).getSecond();
for (Pair<Matcher, Boolean> pair : ContainerUtil.reverse(matchers)) {
if (MatcherUtil.match(pair.getFirst(), path)) {
status = pair.getSecond() ? Status.UNIGNORED : Status.IGNORED;
break;
}
}
if (!status.equals(Status.UNTOUCHED)) {
break;
}
}
statuses.put(file, status);
return status.equals(Status.IGNORED);
}
/**
* Returns the status of the parent.
*
* @param file to check
* @return any of the parents is ignored
*/
@NotNull
protected Status getParentStatus(@NotNull VirtualFile file) {
VirtualFile parent = file.getParent();
VirtualFile vcsRoot = ProjectLevelVcsManager.getInstance(project).getVcsRootFor(file);
while (parent != null && !parent.equals(project.getBaseDir()) && (vcsRoot == null || !vcsRoot.equals(parent))) {
if (statuses.containsKey(parent) && statuses.get(parent) != null) {
return statuses.get(parent);
}
parent = parent.getParent();
}
return Status.UNTOUCHED;
}
/**
* Clears cache.
*/
public void clear() {
map.clear();
statuses.clear();
statusManager.fileStatusesChanged();
}
/**
* Wrapper for {link #map.remove}.
*
* @param file to remove
* @return removed value
*/
public Pair<Set<Integer>, List<Pair<Matcher, Boolean>>> remove(IgnoreFile file) {
return map.remove(file);
}
} |
package edu.stanford.nlp.naturalli.entail;
import edu.stanford.nlp.classify.Classifier;
import edu.stanford.nlp.classify.LinearClassifier;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.io.RuntimeIOException;
import edu.stanford.nlp.naturalli.ProcessPremise;
import edu.stanford.nlp.naturalli.ProcessQuery;
import edu.stanford.nlp.naturalli.QRewrite;
import edu.stanford.nlp.naturalli.SentenceFragment;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.simple.Sentence;
import edu.stanford.nlp.stats.Counter;
import edu.stanford.nlp.util.*;
import edu.stanford.nlp.util.logging.Redwood;
import java.io.*;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static edu.stanford.nlp.util.logging.Redwood.Util.*;
/**
* An interface for calling NaturalLI in alignment mode.
*
* @author Gabor Angeli
*/
public class NaturalLIClassifier implements EntailmentClassifier {
@Execution.Option(name="naturalli.use", gloss="If true, incorporate input from NaturalLI")
private static boolean USE_NATURALLI = true;
@Execution.Option(name="naturalli.weight", gloss="The weight to incorporate NaturalLI with")
private static double ALIGNMENT_WEIGHT = 0.00;
static final String COUNT_ALIGNED = "count_aligned";
static final String COUNT_ALIGNABLE = "count_alignable";
static final String COUNT_UNALIGNED = "count_unaligned";
static final String COUNT_UNALIGNABLE_PREMISE = "count_unalignable_premise";
static final String COUNT_UNALIGNABLE_CONCLUSION = "count_unalignable_conclusion";
static final String COUNT_UNALIGNABLE_JOINT = "count_unalignable_joint";
static final String COUNT_PREMISE = "count_premise";
static final String COUNT_CONCLUSION = "count_conclusion";
static final String PERCENT_ALIGNABLE_PREMISE = "percent_alignable_premise";
static final String PERCENT_ALIGNABLE_CONCLUSION = "percent_alignable_conclusion";
static final String PERCENT_ALIGNABLE_JOINT = "percent_alignable_joint";
static final String PERCENT_ALIGNED_PREMISE = "percent_aligned_premise";
static final String PERCENT_ALIGNED_CONCLUSION = "percent_aligned_conclusion";
static final String PERCENT_ALIGNED_JOINT = "percent_aligned_joint";
static final String PERCENT_UNALIGNED_PREMISE = "percent_unaligned_premise";
static final String PERCENT_UNALIGNED_CONCLUSION = "percent_unaligned_conclusion";
static final String PERCENT_UNALIGNED_JOINT = "percent_unaligned_joint";
static final String PERCENT_UNALIGNABLE_PREMISE = "percent_unalignable_premise";
static final String PERCENT_UNALIGNABLE_CONCLUSION = "percent_unalignable_conclusion";
static final String PERCENT_UNALIGNABLE_JOINT = "percent_unalignable_joint";
private static final Pattern truthPattern = Pattern.compile("\"truth\": *([0-9\\.]+)");
private static final Pattern alignmentIndexPattern = Pattern.compile("\"closestSoftAlignment\": *([0-9]+)");
private static final Pattern alignmentScoresPattern = Pattern.compile("\"closestSoftAlignmentScores\": *\\[ *((:?-?(:?[0-9\\.]+|inf), *)*-?(:?[0-9\\.]+|inf)) *\\]");
private static final Pattern alignmentSearchCostsPattern = Pattern.compile("\"closestSoftAlignmentSearchCosts\": *\\[ *((:?-?(:?[1-9\\.]+|inf), *)*-?(:?[0-9\\.]+|inf)) *\\]");
public final String searchProgram;
public final Classifier<Trilean, String> impl;
public final EntailmentFeaturizer featurizer;
private BufferedReader fromNaturalLI;
private OutputStreamWriter toNaturalLI;
private final Counter<String> weights;
private final Lazy<StanfordCoreNLP> pipeline = Lazy.of(() -> ProcessPremise.constructPipeline("depparse") );
private final Map<Pair<String, String>, Pair<Double, Double>> naturalliCache = new HashMap<>();
private PrintWriter naturalliWriteCache;
NaturalLIClassifier(String naturalliSearch, EntailmentFeaturizer featurizer, Classifier<Trilean, String> impl) {
this.searchProgram = naturalliSearch;
this.impl = impl;
this.featurizer = featurizer;
this.weights = ((LinearClassifier<Trilean,String>) impl).weightsAsMapOfCounters().get(Trilean.TRUE);
init();
}
NaturalLIClassifier(String naturalliSearch, EntailmentClassifier underlyingImpl) {
this.searchProgram = naturalliSearch;
if (underlyingImpl instanceof SimpleEntailmentClassifier) {
this.impl = ((SimpleEntailmentClassifier) underlyingImpl).impl;
this.featurizer = ((SimpleEntailmentClassifier) underlyingImpl).featurizer;
} else {
throw new IllegalArgumentException("Cannot create NaturalLI classifier from " + underlyingImpl.getClass());
}
this.weights = ((LinearClassifier<Trilean,String>) impl).weightsAsMapOfCounters().get(Trilean.TRUE);
init();
}
/**
* Initialize the pipe to NaturalLI.
*/
private synchronized void init() {
try {
if (new File("tmp/naturalli_classifier_search.cache").exists()) {
Arrays.stream(IOUtils.slurpFile("tmp/naturalli_classifier_search.cache").split("\n")).map(x -> x.split("\t"))
.forEach(triple ->
naturalliCache.put(Pair.makePair(triple[0].toLowerCase().replace(" ", ""), triple[1].toLowerCase().replace(" ", "")),
Pair.makePair(Double.parseDouble(triple[2]), Double.parseDouble(triple[3]))));
}
naturalliWriteCache = new PrintWriter(new FileWriter("tmp/naturalli_classifier_search_2.cache"));
forceTrack("Creating connection to NaturalLI");
ProcessBuilder searcherBuilder = new ProcessBuilder(searchProgram);
final Process searcher = searcherBuilder.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
searcher.destroy();
}
});
// Gobble naturalli.stderr to real stderr
Writer errWriter = new BufferedWriter(new FileWriter(new File("/dev/null")));
// Writer errWriter = new BufferedWriter(new OutputStreamWriter(System.err));
StreamGobbler errGobbler = new StreamGobbler(searcher.getErrorStream(), errWriter);
errGobbler.start();
// Create the pipe
fromNaturalLI = new BufferedReader(new InputStreamReader(searcher.getInputStream()));
toNaturalLI = new OutputStreamWriter(new BufferedOutputStream(searcher.getOutputStream()));
// Set some parameters
toNaturalLI.write("%defaultCosts = true\n");
// toNaturalLI.write("%skipNegationSearch=true\n");
toNaturalLI.write("%maxTicks=500000\n");
toNaturalLI.flush();
endTrack("Creating connection to NaturalLI");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** Convert a plain-text string to a CoNLL parse tree that can be fed into NaturalLI */
private String toParseTree(String text) {
Pointer<String> debug = new Pointer<>();
try {
String annotated = ProcessQuery.annotate(QRewrite.FOR_PREMISE, text, pipeline.get(), debug, true);
return annotated;
} catch (AssertionError e) {
err("Assertion error when processing sentence: " + text);
return "cats\t0\troot\t0";
}
}
/** Convert a comma-separated list to a list of doubles */
private List<Double> parseDoubleList(String list) {
return Arrays.stream(list.split(" *, *")).map(x -> {switch (x) {
case "-inf": return Double.NEGATIVE_INFINITY;
case "inf": return Double.POSITIVE_INFINITY;
default: return Double.parseDouble(x);
}}).collect(Collectors.toList());
}
/**
* Get the best alignment score between the hypothesis and the best premise.
* @param premises The premises to possibly align to.
* @param hypothesis The hypothesis we are testing.
* @return A triple: the truth of the hypothesis, the best alignment, and the best soft alignment scores.
* @throws IOException Thrown if the pipe to NaturalLI is broken.
*/
private synchronized Triple<Double, Integer, List<Double>> getBestAlignment(List<String> premises, String hypothesis) throws IOException {
Function<String,Pair<String,String>> key = x -> Pair.makePair(x.toLowerCase().replace(" ", ""), hypothesis.toLowerCase().replace(" ", ""));
if (premises.stream().allMatch(x -> naturalliCache.containsKey(key.apply(x)))) {
return Triple.makeTriple(naturalliCache.get(key.apply(premises.get(0))).first, -1, premises.stream().map(x -> naturalliCache.get(key.apply(x)).second).collect(Collectors.toList()));
}
// Write the premises
List<Double> premiseAlignmentCosts = new ArrayList<>();
for (String premise : premises) {
for (SentenceFragment entailment : ProcessPremise.forwardEntailments(premise, pipeline.get())) {
try {
String tree = ProcessQuery.conllDump(entailment.parseTree, false, true);
if (tree.split("\n").length > 30) {
// Tree is too long; don't write it or else the program will crash
toNaturalLI.write(toParseTree("cats have tails"));
} else {
toNaturalLI.write(tree);
}
toNaturalLI.write("\n");
premiseAlignmentCosts.add(Double.NEGATIVE_INFINITY);
} catch (Exception e) {
err("Caught exception: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
// Write the query
toNaturalLI.write(toParseTree(hypothesis));
// Start the search
toNaturalLI.write("\n\n");
toNaturalLI.flush();
// Read the result
Matcher matcher;
String json = fromNaturalLI.readLine();
// (alignment index)
if (json == null || !(matcher = alignmentIndexPattern.matcher(json)).find()) {
throw new IllegalArgumentException("Invalid JSON response: " + json);
}
int alignmentIndex = Integer.parseInt(matcher.group(1));
// (truth)
if (!(matcher = truthPattern.matcher(json)).find()) {
throw new IllegalArgumentException("Invalid JSON response: " + json);
}
double prob = Double.parseDouble(matcher.group(1));
// (scores)
if (!(matcher = alignmentScoresPattern.matcher(json)).find()) {
throw new IllegalArgumentException("Invalid JSON response: " + json);
}
List<Double> alignmentScores = parseDoubleList(matcher.group(1));
for (int i = 0; i < alignmentScores.size(); ++i) {
premiseAlignmentCosts.set(i, alignmentScores.get(i));
}
// (search costs)
// if (!(matcher = alignmentSearchCostsPattern.matcher(json)).find()) {
// List<Double> alignmentSearchCosts = parseDoubleList(matcher.group(1));
// Return
for (int i = 0; i < premises.size(); ++i) {
naturalliWriteCache.println(premises.get(i) + "\t" + hypothesis + "\t" + prob + "\t" + premiseAlignmentCosts.get(i));
naturalliWriteCache.flush();
}
return Triple.makeTriple(prob, alignmentIndex, premiseAlignmentCosts);
}
private double scoreBeforeNaturalli(Counter<String> features) {
double sum = 0.0;
for (Map.Entry<String, Double> entry : features.entrySet()) {
switch (entry.getKey()) {
case COUNT_ALIGNED: // this is the one that gets changed most
case PERCENT_ALIGNED_PREMISE:
case PERCENT_ALIGNED_CONCLUSION:
case PERCENT_ALIGNED_JOINT:
break;
default:
sum += weights.getCount(entry.getKey()) * features.getCount(entry.getKey());
}
}
return sum;
}
private double scoreAlignmentSimple(Counter<String> features) {
double sum = 0.0;
for (Map.Entry<String, Double> entry : features.entrySet()) {
switch(entry.getKey()) {
case COUNT_ALIGNED:
case PERCENT_ALIGNED_PREMISE:
case PERCENT_ALIGNED_CONCLUSION:
case PERCENT_ALIGNED_JOINT:
sum += weights.getCount(entry.getKey()) * features.getCount(entry.getKey());
break;
default:
// do nothing
}
}
return sum;
}
@Override
public Pair<Sentence, Double> bestScore(List<String> premisesText, String hypothesisText,
Optional<String> focus, Optional<List<Double>> luceneScores,
Function<Integer, Double> decay) {
double max = Double.NEGATIVE_INFINITY;
int argmax = -1;
Sentence hypothesis = new Sentence(hypothesisText);
List<Sentence> premises = premisesText.stream().map(Sentence::new).collect(Collectors.toList());
// Query NaturalLI
Triple<Double, Integer, List<Double>> bestNaturalLIScores;
try {
bestNaturalLIScores = getBestAlignment(premisesText, hypothesisText);
} catch (IOException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < premises.size(); ++i) {
// Featurize the pair
Sentence premise = premises.get(i);
Optional<Double> luceneScore = luceneScores.isPresent() ? Optional.of(luceneScores.get().get(i)) : Optional.empty();
Counter<String> features = featurizer.featurize(new EntailmentPair(Trilean.UNKNOWN, premise, hypothesis, focus, luceneScore), Optional.empty());
// Get the raw score
double score = scoreBeforeNaturalli(features);
double naturalLIScore = 0.0;
if (USE_NATURALLI) {
naturalLIScore = bestNaturalLIScores.third.get(i);
} else {
// double naturalLIScore = scoreAlignmentSimple(features);
}
score += naturalLIScore * ALIGNMENT_WEIGHT;
assert !Double.isNaN(score);
assert Double.isFinite(score);
// Computer the probability
double prob = 1.0 / (1.0 + Math.exp(-score));
// Discount the score if the focus is not present
if (focus.isPresent()) {
if (focus.get().contains(" ")) {
if (!premise.text().toLowerCase().replaceAll("\\s+", " ").contains(focus.get().toLowerCase().replaceAll("\\s+", " "))) {
prob *= 0.75; // Slight penalty for not matching a long focus
}
} else {
if (!premise.text().toLowerCase().replaceAll("\\s+", " ").contains(focus.get().toLowerCase().replaceAll("\\s+", " "))) {
prob *= 0.25; // Big penalty for not matching a short focus.
}
}
}
// Discount the score if NaturalLI thinks this conclusion is false
if (USE_NATURALLI) {
if (bestNaturalLIScores.first < 0.48) {
prob *= 0.1;
} else if (bestNaturalLIScores.first < 0.5) {
prob *= 0.9;
}
}
// Take the argmax
if (prob > max) {
max = prob;
argmax = i;
}
}
return Pair.makePair(premises.get(argmax), max);
}
@Override
public double truthScore(Sentence premise, Sentence hypothesis, Optional<String> focus, Optional<Double> luceneScore) {
return bestScore(Collections.singletonList(premise.text()), hypothesis.text(), focus,
luceneScore.isPresent() ? Optional.of(Collections.singletonList(luceneScore.get())) : Optional.empty(), i -> 1.0).second;
}
@Override
public Trilean classify(Sentence premise, Sentence hypothesis, Optional<String> focus, Optional<Double> luceneScore) {
return truthScore(premise, hypothesis, focus, luceneScore) >= 0.5 ? Trilean.TRUE : Trilean.FALSE;
}
@Override
public Object serialize() {
return Triple.makeTriple(searchProgram, featurizer, impl);
}
@SuppressWarnings("unchecked")
public static NaturalLIClassifier deserialize(Object model) {
Triple<String, EntailmentFeaturizer, Classifier<Trilean, String>> data = (Triple) model;
return new NaturalLIClassifier(data.first, data.second, data.third());
}
} |
package org.camunda.bpm.extension.process_test_coverage.listeners;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import org.camunda.bpm.engine.impl.bpmn.helper.BpmnProperties;
import org.camunda.bpm.engine.impl.event.CompensationEventHandler;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.EventSubscriptionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
import org.camunda.bpm.extension.process_test_coverage.junit.rules.CoverageTestRunState;
import org.camunda.bpm.extension.process_test_coverage.model.CoveredFlowNode;
import org.camunda.bpm.extension.process_test_coverage.util.Api;
/**
* Compensation event handler registering compensation tasks and their source
* boundary events.
*
* @author z0rbas
*
*/
public class CompensationEventCoverageHandler extends CompensationEventHandler {
private CoverageTestRunState coverageTestRunState;
/**
* @since 7.10.0
*/
@Override
public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, Object localPayload,
String businessKey, CommandContext commandContext) {
addCompensationEventCoverage(eventSubscription);
super.handleEvent(eventSubscription, payload, localPayload, businessKey, commandContext);
}
private void addCompensationEventCoverage(EventSubscriptionEntity eventSubscription) {
if (Api.Camunda.supportsCompensationEventCoverage()) {
final ActivityImpl activity = eventSubscription.getActivity();
// Get process definition key
final ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) activity.getProcessDefinition();
final String processDefinitionKey = processDefinition.getKey();
// Get compensation boundary event ID
final ActivityImpl sourceEvent = (ActivityImpl) activity.getProperty(
BpmnProperties.COMPENSATION_BOUNDARY_EVENT.getName());
if (sourceEvent != null) {
final String sourceEventId = sourceEvent.getActivityId();
// Register covered element
final CoveredFlowNode compensationBoundaryEvent = new CoveredFlowNode(processDefinitionKey, sourceEventId);
compensationBoundaryEvent.setEnded(true);
coverageTestRunState.addCoveredElement(compensationBoundaryEvent);
}
}
}
public void setCoverageTestRunState(CoverageTestRunState coverageTestRunState) {
this.coverageTestRunState = coverageTestRunState;
}
/**
* Implementation for older Camunda versions prior to 7.10.0
*/
public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) {
addCompensationEventCoverage(eventSubscription);
// invoke super.handleEvent() in a backwards compatible way
try {
MethodHandle handleEvent = MethodHandles.lookup()
.findSpecial(CompensationEventHandler.class, "handleEvent",
MethodType.methodType(void.class, EventSubscriptionEntity.class, Object.class, CommandContext.class),
CompensationEventCoverageHandler.class);
handleEvent.invoke(this, eventSubscription, payload, commandContext);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
} |
package ethanjones.cubes.input;
import ethanjones.cubes.core.event.entity.living.player.PlayerMovementEvent;
import ethanjones.cubes.core.logging.Log;
import ethanjones.cubes.entity.living.player.Player;
import ethanjones.cubes.item.ItemStack;
import ethanjones.cubes.networking.NetworkingManager;
import ethanjones.cubes.networking.packets.PacketButton;
import ethanjones.cubes.networking.packets.PacketKey;
import ethanjones.cubes.networking.packets.PacketPlayerInfo;
import ethanjones.cubes.side.common.Cubes;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad;
import com.badlogic.gdx.utils.IntIntMap;
public class CameraController extends InputAdapter {
private final Camera camera;
private final IntIntMap keys = new IntIntMap();
private final Vector3 tmp = new Vector3();
public Touchpad touchpad; //movement on android
private int STRAFE_LEFT = Input.Keys.A;
private int STRAFE_RIGHT = Input.Keys.D;
private int FORWARD = Input.Keys.W;
private int BACKWARD = Input.Keys.S;
private float speed = 5;
private float degreesPerPixel = 0.5f;
private Vector3 prevPosition = new Vector3();
private Vector3 prevDirection = new Vector3();
public float jump;
public CameraController(Camera camera) {
this.camera = camera;
camera.position.set(0, 6.5f, 0);
camera.direction.set(1, 0, 0);
camera.update();
}
@Override
public boolean keyDown(int keycode) {
if (keycode == Input.Keys.SPACE && jump == 0) jump = 0.25f;
keys.put(keycode, keycode);
PacketKey packetKey = new PacketKey();
packetKey.action = PacketKey.KEY_DOWN;
packetKey.key = keycode;
NetworkingManager.sendPacketToServer(packetKey);
return true;
}
@Override
public boolean keyUp(int keycode) {
keys.remove(keycode, 0);
PacketKey packetKey = new PacketKey();
packetKey.action = PacketKey.KEY_UP;
packetKey.key = keycode;
NetworkingManager.sendPacketToServer(packetKey);
return true;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if (Cubes.getClient().renderer.guiRenderer.touch(screenX, screenY, pointer, button)) return true;
PacketButton packetButton = new PacketButton();
packetButton.action = PacketButton.BUTTON_DOWN;
packetButton.button = button;
NetworkingManager.sendPacketToServer(packetButton);
ItemStack itemStack = Cubes.getClient().player.getInventory().selectedItemStack();
if (itemStack != null)
itemStack.item.onButtonPress(button, itemStack, Cubes.getClient().player, Cubes.getClient().player.getInventory().hotbarSelected);
return true;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
PacketButton packetButton = new PacketButton();
packetButton.action = PacketButton.BUTTON_UP;
packetButton.button = button;
NetworkingManager.sendPacketToServer(packetButton);
return true;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return mouseMoved(screenX, screenY);
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
if (Cubes.getClient().renderer.guiRenderer.noCursorCatching()) return false;
float deltaX = -Gdx.input.getDeltaX() * degreesPerPixel;
float deltaY = -Gdx.input.getDeltaY() * degreesPerPixel;
camera.direction.rotate(camera.up, deltaX);
tmp.set(camera.direction).crs(camera.up).nor();
camera.direction.rotate(tmp, deltaY);
return true;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public void update() {
if (Cubes.getClient().renderer.guiRenderer.noCursorCatching()) return;
if (touchpad != null) {
float knobPercentY = touchpad.getKnobPercentY();
float up = knobPercentY > 0 ? knobPercentY : 0;
float down = knobPercentY < 0 ? -knobPercentY : 0;
float knobPercentX = touchpad.getKnobPercentX();
float right = knobPercentX > 0 ? knobPercentX : 0;
float left = knobPercentX < 0 ? -knobPercentX : 0;
update(up, down, left, right);
} else {
update(keys.containsKey(FORWARD) ? 1f : 0f, keys.containsKey(BACKWARD) ? 1f : 0f, keys.containsKey(STRAFE_LEFT) ? 1f : 0f, keys.containsKey(STRAFE_RIGHT) ? 1f : 0f);
}
}
private void update(float forward, float backward, float left, float right) {
float deltaTime = Gdx.graphics.getRawDeltaTime();
if (forward > 0) {
tmp.set(camera.direction.x, 0, camera.direction.z).nor().nor().scl(deltaTime * speed * forward);
tryMove();
}
if (backward > 0) {
tmp.set(camera.direction.x, 0, camera.direction.z).nor().scl(-deltaTime * speed * backward);
tryMove();
}
if (left > 0) {
tmp.set(camera.direction.x, 0, camera.direction.z).crs(camera.up).nor().scl(-deltaTime * speed * left);
tryMove();
}
if (right > 0) {
tmp.set(camera.direction.x, 0, camera.direction.z).crs(camera.up).nor().scl(deltaTime * speed * right);
tryMove();
}
if (deltaTime > 0f && jump > 0) {
float f = deltaTime * 6;
if (!new PlayerMovementEvent(camera.position.cpy().add(0, f, 0)).post().isCanceled()) {
camera.position.y += f;
}
jump -= deltaTime;
if (jump < 0) jump = 0;
}
camera.update(true);
}
private void tryMove() {
Vector3 vector3 = new Vector3(camera.position).add(tmp);
if (!new PlayerMovementEvent(vector3).post().isCanceled()) {
camera.position.add(tmp);
}
}
public void tick() {
Player player = Cubes.getClient().player;
if (!player.position.equals(prevPosition) || !player.angle.equals(prevDirection)) {
NetworkingManager.sendPacketToServer(new PacketPlayerInfo(player));
prevPosition.set(player.position);
prevDirection.set(player.angle);
}
}
} |
package uk.ac.ebi.spot.goci.curation.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import uk.ac.ebi.spot.goci.builder.AssociationBuilder;
import uk.ac.ebi.spot.goci.builder.SecureUserBuilder;
import uk.ac.ebi.spot.goci.builder.StudyBuilder;
import uk.ac.ebi.spot.goci.curation.model.AssociationEventView;
import uk.ac.ebi.spot.goci.curation.model.AssociationUploadErrorView;
import uk.ac.ebi.spot.goci.curation.model.AssociationValidationView;
import uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation;
import uk.ac.ebi.spot.goci.curation.model.MappingDetails;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationStandardMultiForm;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationTableView;
import uk.ac.ebi.spot.goci.curation.service.AssociationDeletionService;
import uk.ac.ebi.spot.goci.curation.service.AssociationDownloadService;
import uk.ac.ebi.spot.goci.curation.service.AssociationEventsViewService;
import uk.ac.ebi.spot.goci.curation.service.AssociationOperationsService;
import uk.ac.ebi.spot.goci.curation.service.AssociationUploadService;
import uk.ac.ebi.spot.goci.curation.service.AssociationValidationReportService;
import uk.ac.ebi.spot.goci.curation.service.CheckEfoTermAssignmentService;
import uk.ac.ebi.spot.goci.curation.service.CurrentUserDetailsService;
import uk.ac.ebi.spot.goci.curation.service.SingleSnpMultiSnpAssociationService;
import uk.ac.ebi.spot.goci.curation.service.SnpAssociationTableViewService;
import uk.ac.ebi.spot.goci.curation.service.SnpInteractionAssociationService;
import uk.ac.ebi.spot.goci.curation.service.StudyAssociationBatchDeletionEventService;
import uk.ac.ebi.spot.goci.exception.EnsemblMappingException;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.SecureUser;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.EfoTraitRepository;
import uk.ac.ebi.spot.goci.repository.StudyRepository;
import uk.ac.ebi.spot.goci.service.MappingService;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
@RunWith(MockitoJUnitRunner.class)
public class AssociationControllerTest {
private MockMvc mockMvc;
@Mock
private AssociationRepository associationRepository;
@Mock
private StudyRepository studyRepository;
@Mock
private EfoTraitRepository efoTraitRepository;
@Mock
private AssociationDownloadService associationDownloadService;
@Mock
private SnpAssociationTableViewService snpAssociationTableViewService;
@Mock
private SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService;
@Mock
private SnpInteractionAssociationService snpInteractionAssociationService;
@Mock
private CheckEfoTermAssignmentService checkEfoTermAssignmentService;
@Mock
private AssociationOperationsService associationOperationsService;
@Mock
private MappingService mappingService;
@Mock
private AssociationUploadService associationUploadService;
@Mock
private CurrentUserDetailsService currentUserDetailsService;
@Mock
private AssociationValidationReportService associationValidationReportService;
@Mock
private AssociationDeletionService associationDeletionService;
@Mock
private AssociationEventsViewService associationsEventsViewService;
@Mock
private StudyAssociationBatchDeletionEventService studyAssociationBatchDeletionEventService;
private static final SecureUser SECURE_USER =
new SecureUserBuilder().setId(564L).setEmail("test@test.com").setPasswordHash("738274$$").build();
private static final Study STUDY = new StudyBuilder().setId(1234L).build();
private static final Association ASSOCIATION =
new AssociationBuilder().setId(100L)
.setStudy(STUDY)
.build();
private static final Association EDITED_ASSOCIATION =
new AssociationBuilder()
.setStudy(STUDY)
.build();
@Before
public void setUp() throws Exception {
AssociationController associationController = new AssociationController(associationRepository,
studyRepository,
efoTraitRepository,
associationDownloadService,
snpAssociationTableViewService,
singleSnpMultiSnpAssociationService,
snpInteractionAssociationService,
checkEfoTermAssignmentService,
associationOperationsService,
associationUploadService,
currentUserDetailsService,
associationValidationReportService,
associationDeletionService,
associationsEventsViewService,
studyAssociationBatchDeletionEventService);
mockMvc = MockMvcBuilders.standaloneSetup(associationController).build();
}
@Test
public void viewStudySnps() throws Exception {
SnpAssociationTableView snpAssociationTableView = new SnpAssociationTableView();
LastViewedAssociation lastViewedAssociation = new LastViewedAssociation();
when(associationRepository.findByStudyId(STUDY.getId())).thenReturn(Collections.singletonList(ASSOCIATION));
when(snpAssociationTableViewService.createSnpAssociationTableView(ASSOCIATION)).thenReturn(
snpAssociationTableView);
when(associationOperationsService.getLastViewedAssociation(Matchers.anyLong())).thenReturn(lastViewedAssociation);
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
mockMvc.perform(get("/studies/1234/associations").accept(MediaType.TEXT_HTML_VALUE))
.andExpect(status().isOk())
.andExpect(model().attribute("snpAssociationTableViews", hasSize(1)))
.andExpect(model().attribute("snpAssociationTableViews", instanceOf(Collection.class)))
.andExpect(model().attribute("lastViewedAssociation", instanceOf(LastViewedAssociation.class)))
.andExpect(model().attribute("totalAssociations", 1))
.andExpect(model().attributeExists("study"))
.andExpect(view().name("study_association"));
verify(associationRepository, times(1)).findByStudyId(STUDY.getId());
verify(snpAssociationTableViewService, times(1)).createSnpAssociationTableView(ASSOCIATION);
verify(associationOperationsService, times(1)).getLastViewedAssociation(Matchers.anyLong());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
}
@Test
public void getAssociationEvents() throws Exception {
AssociationEventView eventView =
new AssociationEventView("EVENT", new Date(), (long) 121, "test@email.com", "rs123, rs456");
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(associationsEventsViewService.createViews(STUDY.getId())).thenReturn(Collections.singletonList(eventView));
mockMvc.perform(get("/studies/1234/association_tracking").accept(MediaType.TEXT_HTML_VALUE))
.andExpect(status().isOk())
.andExpect(model().attributeExists("study"))
.andExpect(model().attribute("events", hasSize(1)))
.andExpect(model().attribute("events", instanceOf(List.class)))
.andExpect(view().name("association_events"));
}
@Test
public void uploadStudySnpsFileWithError() throws Exception {
// Create objects required for testing
MockMultipartFile file =
new MockMultipartFile("file", "filename.txt", "text/plain", "TEST".getBytes());
AssociationUploadErrorView associationUploadErrorView1 =
new AssociationUploadErrorView(1, "OR", "Value is not empty", false, "data");
List<AssociationUploadErrorView> uploadErrorViews = Collections.singletonList(associationUploadErrorView1);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationUploadService.upload(file, STUDY, SECURE_USER)).thenReturn(uploadErrorViews);
mockMvc.perform(fileUpload("/studies/1234/associations/upload").file(file).param("studyId", "1234"))
.andExpect(status().isOk())
.andExpect(model().attribute("fileName", file.getOriginalFilename()))
.andExpect(model().attribute("fileErrors", instanceOf(List.class)))
.andExpect(model().attribute("fileErrors", hasSize(1)))
.andExpect(model().attributeExists("study"))
.andExpect(view().name("error_pages/association_file_upload_error"));
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(associationUploadService, times(1)).upload(file, STUDY, SECURE_USER);
}
@Test
public void uploadStudySnpsFileWithNoError() throws Exception {
// Create objects required for testing
MockMultipartFile file =
new MockMultipartFile("file", "filename.txt", "text/plain", "TEST".getBytes());
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationUploadService.upload(file, STUDY, SECURE_USER)).thenReturn(Collections.EMPTY_LIST);
mockMvc.perform(fileUpload("/studies/1234/associations/upload").file(file).param("studyId", "1234"))
.andExpect(status().is3xxRedirection())
.andExpect(model().attributeExists("study"))
.andExpect(view().name("redirect:/studies/1234/associations"));
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
}
@Test
public void uploadStudySnpsFileWithMappingError() throws Exception {
// Create objects required for testing
MockMultipartFile file =
new MockMultipartFile("file", "filename.txt", "text/plain", "TEST".getBytes());
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationUploadService.upload(file, STUDY, SECURE_USER)).thenThrow(EnsemblMappingException.class);
mockMvc.perform(fileUpload("/studies/1234/associations/upload").file(file).param("studyId", "1234"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("study"))
.andExpect(view().name("ensembl_mapping_failure"));
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
}
@Test
public void addStandardSnpsWithRowErrors() throws Exception {
// Row errors prevent saving
AssociationValidationView associationValidationView =
new AssociationValidationView("SNP", "Value is empty", false);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(associationOperationsService.checkSnpAssociationFormErrors(Matchers.any(SnpAssociationStandardMultiForm.class),
Matchers.anyString()))
.thenReturn(errors);
mockMvc.perform(post("/studies/1234/associations/add_standard").param("measurementType", "or"))
.andExpect(status().isOk())
.andExpect(model().attribute("form", instanceOf(SnpAssociationStandardMultiForm.class)))
.andExpect(model().attribute("errors", instanceOf(List.class)))
.andExpect(model().attribute("errors", hasSize(1)))
.andExpect(model().attributeExists("study"))
.andExpect(model().attributeExists("measurementType"))
.andExpect(view().name("add_standard_snp_association"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationStandardMultiForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationStandardMultiForm.class);
verify(associationOperationsService).checkSnpAssociationFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verifyZeroInteractions(singleSnpMultiSnpAssociationService);
verify(associationOperationsService, never()).saveAssociationCreatedFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.any(SecureUser.class));
verifyZeroInteractions(currentUserDetailsService);
}
@Test
public void addStandardSnpsWithErrors() throws Exception {
AssociationValidationView associationValidationView =
new AssociationValidationView("OR", "Value is empty", false);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationOperationsService.checkSnpAssociationFormErrors(Matchers.any(SnpAssociationStandardMultiForm.class),
Matchers.anyString()))
.thenReturn(Collections.EMPTY_LIST);
when(singleSnpMultiSnpAssociationService.createAssociation(Matchers.any(SnpAssociationStandardMultiForm.class)))
.thenReturn(ASSOCIATION);
when(associationOperationsService.saveAssociationCreatedFromForm(STUDY, ASSOCIATION, SECURE_USER)).thenReturn(
errors);
mockMvc.perform(post("/studies/1234/associations/add_standard").param("measurementType", "or"))
.andExpect(status().isOk())
.andExpect(model().attribute("form", instanceOf(SnpAssociationStandardMultiForm.class)))
.andExpect(model().attribute("errors", instanceOf(List.class)))
.andExpect(model().attribute("errors", hasSize(1)))
.andExpect(model().attributeExists("study"))
.andExpect(model().attributeExists("measurementType"))
.andExpect(view().name("add_standard_snp_association"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationStandardMultiForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationStandardMultiForm.class);
verify(associationOperationsService).checkSnpAssociationFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(singleSnpMultiSnpAssociationService).createAssociation(formArgumentCaptor.capture());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(currentUserDetailsService, times(1)).getUserFromRequest(Matchers.any(HttpServletRequest.class));
verify(associationOperationsService, times(1)).saveAssociationCreatedFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.any(SecureUser.class));
}
@Test
public void addStandardSnpsWithNoErrors() throws Exception {
AssociationValidationView associationValidationView =
new AssociationValidationView("SNP", "SNP identifier rs34tt is not valid", true);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationOperationsService.checkSnpAssociationFormErrors(Matchers.any(SnpAssociationStandardMultiForm.class),
Matchers.anyString()))
.thenReturn(Collections.EMPTY_LIST);
when(singleSnpMultiSnpAssociationService.createAssociation(Matchers.any(SnpAssociationStandardMultiForm.class)))
.thenReturn(ASSOCIATION);
when(associationOperationsService.saveAssociationCreatedFromForm(STUDY, ASSOCIATION, SECURE_USER)).thenReturn(
errors);
mockMvc.perform(post("/studies/1234/associations/add_standard").param("measurementType", "or"))
.andExpect(status().is3xxRedirection())
.andExpect(model().attributeExists("study"))
.andExpect(model().attributeExists("measurementType"))
.andExpect(view().name("redirect:/associations/100"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationStandardMultiForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationStandardMultiForm.class);
verify(associationOperationsService).checkSnpAssociationFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(singleSnpMultiSnpAssociationService).createAssociation(formArgumentCaptor.capture());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(currentUserDetailsService, times(1)).getUserFromRequest(Matchers.any(HttpServletRequest.class));
verify(associationOperationsService, times(1)).saveAssociationCreatedFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.any(SecureUser.class));
}
@Test
public void addMultiSnpsWithRowErrors() throws Exception {
AssociationValidationView associationValidationView =
new AssociationValidationView("SNP", "Value is empty", false);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(associationOperationsService.checkSnpAssociationFormErrors(Matchers.any(SnpAssociationStandardMultiForm.class),
Matchers.anyString()))
.thenReturn(errors);
mockMvc.perform(post("/studies/1234/associations/add_multi").param("measurementType", "or"))
.andExpect(status().isOk())
.andExpect(model().attribute("form", instanceOf(SnpAssociationStandardMultiForm.class)))
.andExpect(model().attribute("errors", instanceOf(List.class)))
.andExpect(model().attribute("errors", hasSize(1)))
.andExpect(model().attributeExists("study"))
.andExpect(model().attributeExists("measurementType"))
.andExpect(view().name("add_multi_snp_association"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationStandardMultiForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationStandardMultiForm.class);
verify(associationOperationsService).checkSnpAssociationFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verifyZeroInteractions(singleSnpMultiSnpAssociationService);
verifyZeroInteractions(currentUserDetailsService);
verify(associationOperationsService, never()).saveAssociationCreatedFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.any(SecureUser.class));
}
@Test
public void addMultiSnpsWithErrors() throws Exception {
AssociationValidationView associationValidationView =
new AssociationValidationView("OR", "Value is empty", false);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationOperationsService.checkSnpAssociationFormErrors(Matchers.any(SnpAssociationStandardMultiForm.class),
Matchers.anyString()))
.thenReturn(Collections.EMPTY_LIST);
when(singleSnpMultiSnpAssociationService.createAssociation(Matchers.any(SnpAssociationStandardMultiForm.class)))
.thenReturn(ASSOCIATION);
when(associationOperationsService.saveAssociationCreatedFromForm(STUDY, ASSOCIATION, SECURE_USER)).thenReturn(
errors);
mockMvc.perform(post("/studies/1234/associations/add_multi").param("measurementType", "or"))
.andExpect(status().isOk())
.andExpect(model().attribute("form", instanceOf(SnpAssociationStandardMultiForm.class)))
.andExpect(model().attribute("errors", instanceOf(List.class)))
.andExpect(model().attribute("errors", hasSize(1)))
.andExpect(model().attributeExists("study"))
.andExpect(model().attributeExists("measurementType"))
.andExpect(view().name("add_multi_snp_association"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationStandardMultiForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationStandardMultiForm.class);
verify(associationOperationsService).checkSnpAssociationFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(singleSnpMultiSnpAssociationService).createAssociation(formArgumentCaptor.capture());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(currentUserDetailsService, times(1)).getUserFromRequest(Matchers.any(HttpServletRequest.class));
verify(associationOperationsService, times(1)).saveAssociationCreatedFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.any(SecureUser.class));
}
@Test
public void addMultiSnpsWithNoErrors() throws Exception {
AssociationValidationView associationValidationView =
new AssociationValidationView("SNP", "SNP identifier rs34tt is not valid", true);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationOperationsService.checkSnpAssociationFormErrors(Matchers.any(SnpAssociationStandardMultiForm.class),
Matchers.anyString()))
.thenReturn(Collections.EMPTY_LIST);
when(singleSnpMultiSnpAssociationService.createAssociation(Matchers.any(SnpAssociationStandardMultiForm.class)))
.thenReturn(ASSOCIATION);
when(associationOperationsService.saveAssociationCreatedFromForm(STUDY, ASSOCIATION, SECURE_USER)).thenReturn(
errors);
mockMvc.perform(post("/studies/1234/associations/add_multi").param("measurementType", "or"))
.andExpect(status().is3xxRedirection())
.andExpect(model().attributeExists("study"))
.andExpect(model().attributeExists("measurementType"))
.andExpect(view().name("redirect:/associations/100"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationStandardMultiForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationStandardMultiForm.class);
verify(associationOperationsService).checkSnpAssociationFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(singleSnpMultiSnpAssociationService).createAssociation(formArgumentCaptor.capture());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(currentUserDetailsService, times(1)).getUserFromRequest(Matchers.any(HttpServletRequest.class));
verify(associationOperationsService, times(1)).saveAssociationCreatedFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.any(SecureUser.class));
}
@Test
public void addSnpInteractionWithRowErrors() throws Exception {
AssociationValidationView associationValidationView =
new AssociationValidationView("SNP", "Value is empty", false);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(associationOperationsService.checkSnpAssociationInteractionFormErrors(Matchers.any(
SnpAssociationInteractionForm.class), Matchers.anyString()))
.thenReturn(errors);
mockMvc.perform(post("/studies/1234/associations/add_interaction").param("measurementType", "or"))
.andExpect(status().isOk())
.andExpect(model().attribute("form", instanceOf(SnpAssociationInteractionForm.class)))
.andExpect(model().attribute("errors", instanceOf(List.class)))
.andExpect(model().attribute("errors", hasSize(1)))
.andExpect(model().attributeExists("study"))
.andExpect(model().attributeExists("measurementType"))
.andExpect(view().name("add_snp_interaction_association"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationInteractionForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationInteractionForm.class);
verify(associationOperationsService).checkSnpAssociationInteractionFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verifyZeroInteractions(snpInteractionAssociationService);
verifyZeroInteractions(currentUserDetailsService);
}
@Test
public void addSnpInteractionWithErrors() throws Exception {
AssociationValidationView associationValidationView =
new AssociationValidationView("OR", "Value is empty", false);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationOperationsService.checkSnpAssociationInteractionFormErrors(Matchers.any(
SnpAssociationInteractionForm.class), Matchers.anyString()))
.thenReturn(Collections.EMPTY_LIST);
when(snpInteractionAssociationService.createAssociation(Matchers.any(SnpAssociationInteractionForm.class)))
.thenReturn(ASSOCIATION);
when(associationOperationsService.saveAssociationCreatedFromForm(STUDY, ASSOCIATION, SECURE_USER)).thenReturn(
errors);
mockMvc.perform(post("/studies/1234/associations/add_interaction").param("measurementType", "or"))
.andExpect(status().isOk())
.andExpect(model().attribute("form", instanceOf(SnpAssociationInteractionForm.class)))
.andExpect(model().attribute("errors", instanceOf(List.class)))
.andExpect(model().attribute("errors", hasSize(1)))
.andExpect(model().attributeExists("study"))
.andExpect(model().attributeExists("measurementType"))
.andExpect(view().name("add_snp_interaction_association"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationInteractionForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationInteractionForm.class);
verify(associationOperationsService).checkSnpAssociationInteractionFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(snpInteractionAssociationService).createAssociation(formArgumentCaptor.capture());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(currentUserDetailsService, times(1)).getUserFromRequest(Matchers.any(HttpServletRequest.class));
verify(associationOperationsService, times(1)).saveAssociationCreatedFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.any(SecureUser.class));
}
@Test
public void addSnpInteractionsWithNoErrors() throws Exception {
AssociationValidationView associationValidationView =
new AssociationValidationView("SNP", "SNP identifier rs34tt is not valid", true);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationOperationsService.checkSnpAssociationInteractionFormErrors(Matchers.any(
SnpAssociationInteractionForm.class), Matchers.anyString()))
.thenReturn(Collections.EMPTY_LIST);
when(snpInteractionAssociationService.createAssociation(Matchers.any(SnpAssociationInteractionForm.class)))
.thenReturn(ASSOCIATION);
when(associationOperationsService.saveAssociationCreatedFromForm(STUDY, ASSOCIATION, SECURE_USER)).thenReturn(
errors);
mockMvc.perform(post("/studies/1234/associations/add_interaction").param("measurementType", "or"))
.andExpect(status().is3xxRedirection())
.andExpect(model().attributeExists("study"))
.andExpect(model().attributeExists("measurementType"))
.andExpect(view().name("redirect:/associations/100"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationInteractionForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationInteractionForm.class);
verify(associationOperationsService).checkSnpAssociationInteractionFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(snpInteractionAssociationService).createAssociation(formArgumentCaptor.capture());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(currentUserDetailsService, times(1)).getUserFromRequest(Matchers.any(HttpServletRequest.class));
verify(associationOperationsService, times(1)).saveAssociationCreatedFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.any(SecureUser.class));
}
@Test
public void viewAssociation() throws Exception {
}
@Test
public void editAssociationWithWarnings() throws Exception {
// Warnings will not prevent a save
AssociationValidationView associationValidationView =
new AssociationValidationView("SNP", "SNP identifier rs34tt is not valid", true);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(associationRepository.findOne(Matchers.anyLong())).thenReturn(ASSOCIATION);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationOperationsService.checkSnpAssociationFormErrors(Matchers.any(SnpAssociationStandardMultiForm.class),
Matchers.anyString()))
.thenReturn(Collections.EMPTY_LIST);
when(singleSnpMultiSnpAssociationService.createAssociation(Matchers.any(SnpAssociationStandardMultiForm.class)))
.thenReturn(EDITED_ASSOCIATION);
when(associationOperationsService.saveEditedAssociationFromForm(STUDY,
EDITED_ASSOCIATION,
ASSOCIATION.getId(),
SECURE_USER)).thenReturn(errors);
mockMvc.perform(post("/associations/100").param("associationtype", "multi"))
.andExpect(status().is3xxRedirection())
.andExpect(model().attributeExists("study"))
.andExpect(view().name("redirect:/associations/100"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationStandardMultiForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationStandardMultiForm.class);
verify(associationOperationsService).checkSnpAssociationFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(singleSnpMultiSnpAssociationService).createAssociation(formArgumentCaptor.capture());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(associationRepository, times(1)).findOne(Matchers.anyLong());
verify(currentUserDetailsService, times(1)).getUserFromRequest(Matchers.any(HttpServletRequest.class));
verify(associationOperationsService, times(1)).saveEditedAssociationFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.anyLong(),
Matchers.any(SecureUser.class));
}
@Test
public void editAssociationNonCriticalErrors() throws Exception {
// This error should prevent a save
AssociationValidationView associationValidationView =
new AssociationValidationView("P-value exponent", "Value is empty", false);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
MappingDetails mappingDetails = new MappingDetails();
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(associationRepository.findOne(Matchers.anyLong())).thenReturn(ASSOCIATION);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
when(associationOperationsService.checkSnpAssociationInteractionFormErrors(Matchers.any(
SnpAssociationInteractionForm.class), Matchers.anyString()))
.thenReturn(Collections.EMPTY_LIST);
when(snpInteractionAssociationService.createAssociation(Matchers.any(SnpAssociationInteractionForm.class)))
.thenReturn(EDITED_ASSOCIATION);
when(associationOperationsService.saveEditedAssociationFromForm(STUDY,
EDITED_ASSOCIATION,
ASSOCIATION.getId(),
SECURE_USER)).thenReturn(errors);
when(associationOperationsService.determineIfAssociationIsOrType(Matchers.any(Association.class))).thenReturn(
"or");
when(associationOperationsService.createMappingDetails(Matchers.any(Association.class))).thenReturn(
mappingDetails);
mockMvc.perform(post("/associations/100").param("associationtype", "interaction"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("study"))
.andExpect(model().attribute("measurementType", "or"))
.andExpect(model().attributeExists("mappingDetails"))
.andExpect(model().attribute("form", instanceOf(SnpAssociationInteractionForm.class)))
.andExpect(model().attribute("errors", instanceOf(List.class)))
.andExpect(model().attribute("errors", hasSize(1)))
.andExpect(view().name("edit_snp_interaction_association"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationInteractionForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationInteractionForm.class);
verify(associationOperationsService).checkSnpAssociationInteractionFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(snpInteractionAssociationService).createAssociation(formArgumentCaptor.capture());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(associationRepository, times(1)).findOne(Matchers.anyLong());
verify(currentUserDetailsService, times(1)).getUserFromRequest(Matchers.any(HttpServletRequest.class));
verify(associationOperationsService, times(1)).saveEditedAssociationFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.anyLong(),
Matchers.any(SecureUser.class));
verify(associationOperationsService, times(1)).determineIfAssociationIsOrType(Matchers.any(Association.class));
verify(associationOperationsService, times(1)).createMappingDetails(Matchers.any(Association.class));
verify(snpInteractionAssociationService,
times(1)).createAssociation(Matchers.any(SnpAssociationInteractionForm.class));
verifyZeroInteractions(singleSnpMultiSnpAssociationService);
}
@Test
public void editAssociationCriticalErrors() throws Exception {
AssociationValidationView associationValidationView =
new AssociationValidationView("SNP", "Value is empty", false);
List<AssociationValidationView> errors = Collections.singletonList(associationValidationView);
MappingDetails mappingDetails = new MappingDetails();
// Stubbing
when(studyRepository.findOne(Matchers.anyLong())).thenReturn(STUDY);
when(associationRepository.findOne(Matchers.anyLong())).thenReturn(ASSOCIATION);
when(associationOperationsService.checkSnpAssociationInteractionFormErrors(Matchers.any(
SnpAssociationInteractionForm.class), Matchers.anyString())).thenReturn(errors);
when(associationOperationsService.determineIfAssociationIsOrType(Matchers.any(Association.class))).thenReturn(
"or");
when(associationOperationsService.createMappingDetails(Matchers.any(Association.class))).thenReturn(
mappingDetails);
mockMvc.perform(post("/associations/100").param("associationtype", "interaction"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("study"))
.andExpect(model().attribute("measurementType", "or"))
.andExpect(model().attributeExists("mappingDetails"))
.andExpect(model().attribute("form", instanceOf(SnpAssociationInteractionForm.class)))
.andExpect(model().attribute("errors", instanceOf(List.class)))
.andExpect(model().attribute("errors", hasSize(1)))
.andExpect(view().name("edit_snp_interaction_association"));
//verify properties of bound object
ArgumentCaptor<SnpAssociationInteractionForm> formArgumentCaptor =
ArgumentCaptor.forClass(SnpAssociationInteractionForm.class);
verify(associationOperationsService).checkSnpAssociationInteractionFormErrors(formArgumentCaptor.capture(),
Matchers.anyString());
verify(studyRepository, times(1)).findOne(Matchers.anyLong());
verify(associationRepository, times(1)).findOne(Matchers.anyLong());
verify(associationOperationsService, times(1)).checkSnpAssociationInteractionFormErrors(Matchers.any(
SnpAssociationInteractionForm.class), Matchers.anyString());
verify(associationOperationsService, never()).saveEditedAssociationFromForm(Matchers.any(Study.class),
Matchers.any(Association.class),
Matchers.anyLong(),
Matchers.any(SecureUser.class));
verify(associationOperationsService, times(1)).determineIfAssociationIsOrType(Matchers.any(Association.class));
verify(associationOperationsService, times(1)).createMappingDetails(Matchers.any(Association.class));
verify(snpInteractionAssociationService,
never()).createAssociation(Matchers.any(SnpAssociationInteractionForm.class));
verifyZeroInteractions(singleSnpMultiSnpAssociationService);
}
@Test
public void deleteAllAssociations() throws Exception {
when(associationRepository.findByStudyId(STUDY.getId())).thenReturn(Collections.singletonList(ASSOCIATION));
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
mockMvc.perform(get("/studies/1234/associations/delete_all").accept(MediaType.TEXT_HTML_VALUE))
.andExpect(status().is3xxRedirection());
verify(associationRepository, times(1)).findByStudyId(STUDY.getId());
verify(currentUserDetailsService, times(1)).getUserFromRequest(Matchers.any(HttpServletRequest.class));
verify(studyAssociationBatchDeletionEventService, times(1)).createBatchUploadEvent(STUDY.getId(),
1,
SECURE_USER);
verify(associationDeletionService, times(1)).deleteAssociation(ASSOCIATION, SECURE_USER);
}
@Test
public void deleteAllAssociationsWhereStudyHasNoAssociations() throws Exception {
// Case where study has no association attached
when(associationRepository.findByStudyId(STUDY.getId())).thenReturn(Collections.EMPTY_LIST);
when(currentUserDetailsService.getUserFromRequest(Matchers.any(HttpServletRequest.class))).thenReturn(
SECURE_USER);
mockMvc.perform(get("/studies/1234/associations/delete_all").accept(MediaType.TEXT_HTML_VALUE))
.andExpect(status().is3xxRedirection());
verify(associationRepository, times(1)).findByStudyId(STUDY.getId());
verifyZeroInteractions(currentUserDetailsService);
verifyZeroInteractions(studyAssociationBatchDeletionEventService);
verifyZeroInteractions(associationDeletionService);
}
@Test
public void deleteChecked() throws Exception {
}
@Test
public void approveSnpAssociation() throws Exception {
}
@Test
public void unapproveSnpAssociation() throws Exception {
}
@Test
public void approveChecked() throws Exception {
}
@Test
public void unapproveChecked() throws Exception {
}
@Test
public void approveAll() throws Exception {
}
@Test
public void validateAll() throws Exception {
}
@Test
public void downloadStudySnps() throws Exception {
}
@Test
public void applyStudyEFOtraitToSnps() throws Exception {
}
@Test
public void handleDataIntegrityException() throws Exception {
}
@Test
public void handleInvalidFormatExceptionAndInvalidOperationException() throws Exception {
}
@Test
public void handleIOException() throws Exception {
}
@Test
public void handleFileUploadException() throws Exception {
}
@Test
public void handleFileNotFound() throws Exception {
}
@Test
public void populateEfoTraits() throws Exception {
}
} |
package org.innovateuk.ifs.application.repository;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.domain.FundingDecisionStatus;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.workflow.resource.State;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
public interface ApplicationRepository extends PagingAndSortingRepository<Application, Long> {
List<Application> findByName(@Param("name") String name);
String COMP_NOT_STATUS_FILTER = "SELECT a FROM Application a WHERE " +
"a.competition.id = :compId " +
"AND (a.applicationProcess.activityState.state NOT IN :states) " +
"AND (str(a.id) LIKE CONCAT('%', :filter, '%'))";
String COMP_STATUS_FILTER = "SELECT a FROM Application a WHERE " +
"a.competition.id = :compId " +
"AND (a.applicationProcess.activityState.state IN :states) " +
"AND (str(a.id) LIKE CONCAT('%', :filter, '%')) " +
"AND (:funding IS NULL " +
" OR (str(:funding) = 'UNDECIDED' AND a.fundingDecision IS NULL)" +
" OR (a.fundingDecision = :funding)) " +
"AND (:inAssessmentReviewPanel IS NULL OR a.inAssessmentReviewPanel = :inAssessmentReviewPanel)";
String COMP_FUNDING_FILTER = "SELECT a FROM Application a WHERE " +
"a.competition.id = :compId " +
"AND (a.fundingDecision IS NOT NULL) " +
"AND (str(a.id) LIKE CONCAT('%', :filter, '%')) " +
"AND (:sent IS NULL " +
" OR (:sent = true AND a.manageFundingEmailDate IS NOT NULL) " +
" OR (:sent = false AND a.manageFundingEmailDate IS NULL))" +
"AND (:funding IS NULL " +
" OR (a.fundingDecision = :funding))";
String SEARCH_BY_ID_LIKE = " SELECT a from Application a " +
" WHERE str(a.id) LIKE CONCAT('%', :searchString, '%') ";
@Override
List<Application> findAll();
Page<Application> findByCompetitionId(long competitionId, Pageable pageable);
@Query(SEARCH_BY_ID_LIKE)
Page<Application> searchByIdLike(@Param("searchString") String searchString, Pageable pageable);
List<Application> findByCompetitionId(long competitionId);
@Query(COMP_STATUS_FILTER)
Page<Application> findByCompetitionIdAndApplicationProcessActivityStateStateInAndIdLike(@Param("compId") long competitionId,
@Param("states") Collection<State> applicationStates,
@Param("filter") String filter,
@Param("funding") FundingDecisionStatus funding,
@Param("inAssessmentReviewPanel") Boolean inAssessmentReviewPanel,
Pageable pageable);
@Query(COMP_STATUS_FILTER)
List<Application> findByCompetitionIdAndApplicationProcessActivityStateStateInAndIdLike(@Param("compId") long competitionId,
@Param("states") Collection<State> applicationStates,
@Param("filter") String filter,
@Param("funding") FundingDecisionStatus funding,
@Param("inAssessmentReviewPanel") Boolean inAssessmentReviewPanel);
@Query(COMP_NOT_STATUS_FILTER)
Page<Application> findByCompetitionIdAndApplicationProcessActivityStateStateNotIn(@Param("compId") long competitionId,
@Param("states") Collection<State> applicationStates,
@Param("filter") String filter,
Pageable pageable);
List<Application> findByCompetitionIdAndApplicationProcessActivityStateStateIn(long competitionId, Collection<State> applicationStates);
Stream<Application> findByApplicationProcessActivityStateStateIn(Collection<State> applicationStates);
Page<Application> findByCompetitionIdAndApplicationProcessActivityStateStateIn(long competitionId, Collection<State> applicationStates, Pageable pageable);
@Query(COMP_NOT_STATUS_FILTER)
List<Application> findByCompetitionIdAndApplicationProcessActivityStateStateNotIn(@Param("compId") long competitionId,
@Param("states") Collection<State> applicationStates,
@Param("filter") String filter);
@Query(COMP_FUNDING_FILTER)
Page<Application> findByCompetitionIdAndFundingDecisionIsNotNull(@Param("compId") long competitionId,
@Param("filter") String filter,
@Param("sent") Boolean sent,
@Param("funding") FundingDecisionStatus funding,
Pageable pageable);
@Query(COMP_FUNDING_FILTER)
List<Application> findByCompetitionIdAndFundingDecisionIsNotNull(@Param("compId") long competitionId,
@Param("filter") String filter,
@Param("sent") Boolean sent,
@Param("funding") FundingDecisionStatus funding);
int countByCompetitionIdAndFundingDecisionIsNotNullAndManageFundingEmailDateIsNotNull(long competitionId);
int countByCompetitionIdAndFundingDecisionIsNotNullAndManageFundingEmailDateIsNull(long competitionId);
int countByCompetitionId(long competitionId);
int countByCompetitionIdAndApplicationProcessActivityStateState(long competitionId, State applicationState);
int countByCompetitionIdAndApplicationProcessActivityStateStateIn(long competitionId, Collection<State> submittedStates);
int countByCompetitionIdAndApplicationProcessActivityStateStateNotInAndCompletionGreaterThan(Long competitionId, Collection<State> submittedStates, BigDecimal limit);
int countByCompetitionIdAndApplicationProcessActivityStateStateInAndCompletionLessThanEqual(long competitionId, Collection<State> submittedStates, BigDecimal limit);
int countByProcessRolesUserIdAndCompetitionId(long userId, long competitionId);
List<Application> findByCompetitionIdAndInAssessmentReviewPanelTrueAndApplicationProcessActivityStateState(long competitionId, State applicationState);
List<Application> findByCompetitionAndInAssessmentReviewPanelTrueAndApplicationProcessActivityStateState(Competition competition, State applicationState);
} |
package com.questdb.cairo.map;
import com.questdb.cairo.CairoException;
import com.questdb.cairo.ColumnTypes;
import com.questdb.cairo.RecordSink;
import com.questdb.cairo.TableUtils;
import com.questdb.cairo.sql.Record;
import com.questdb.common.ColumnType;
import com.questdb.std.*;
import org.jetbrains.annotations.NotNull;
import java.util.Iterator;
public class FastMap implements Map {
private static final HashFunction DEFAULT_HASH = Hash::hashMem;
private static final int MIN_INITIAL_CAPACITY = 128;
private final double loadFactor;
private final Key key = new Key();
private final FastMapValue value;
private final FastMapCursor iterator;
private final FastMapRecord record;
private final int valueColumnCount;
private final HashFunction hashFunction;
private long address;
private long capacity;
private int keyBlockOffset;
private int keyDataOffset;
private DirectLongList offsets;
private long kStart;
private long kLimit;
private long kPos;
private int free;
private int keyCapacity;
private int size = 0;
private int mask;
public FastMap(int pageSize,
@Transient @NotNull ColumnTypes keyTypes,
int keyCapacity,
double loadFactor
) {
this(pageSize, keyTypes, null, keyCapacity, loadFactor, DEFAULT_HASH);
}
public FastMap(int pageSize,
@Transient @NotNull ColumnTypes keyTypes,
@Transient @NotNull ColumnTypes valueTypes,
int keyCapacity,
double loadFactor
) {
this(pageSize, keyTypes, valueTypes, keyCapacity, loadFactor, DEFAULT_HASH);
}
FastMap(int pageSize,
@Transient ColumnTypes keyTypes,
@Transient ColumnTypes valueTypes,
int keyCapacity,
double loadFactor,
HashFunction hashFunction
) {
assert pageSize > 3;
assert loadFactor > 0 && loadFactor < 1d;
this.loadFactor = loadFactor;
this.address = Unsafe.malloc(this.capacity = (pageSize + Unsafe.CACHE_LINE_SIZE));
this.kStart = kPos = this.address + (this.address & (Unsafe.CACHE_LINE_SIZE - 1));
this.kLimit = kStart + pageSize;
this.keyCapacity = (int) (keyCapacity / loadFactor);
this.keyCapacity = this.keyCapacity < MIN_INITIAL_CAPACITY ? MIN_INITIAL_CAPACITY : Numbers.ceilPow2(this.keyCapacity);
this.mask = this.keyCapacity - 1;
this.free = (int) (this.keyCapacity * loadFactor);
this.offsets = new DirectLongList(this.keyCapacity);
this.offsets.setPos(this.keyCapacity);
this.offsets.zero(-1);
this.hashFunction = hashFunction;
int[] valueOffsets;
int offset = 4;
if (valueTypes != null) {
this.valueColumnCount = valueTypes.getColumnCount();
final int columnSplit = valueColumnCount;
valueOffsets = new int[columnSplit];
for (int i = 0; i < columnSplit; i++) {
valueOffsets[i] = offset;
switch (valueTypes.getColumnType(i)) {
case ColumnType.BYTE:
case ColumnType.BOOLEAN:
offset++;
break;
case ColumnType.SHORT:
offset += 2;
break;
case ColumnType.INT:
case ColumnType.FLOAT:
offset += 4;
break;
case ColumnType.LONG:
case ColumnType.DOUBLE:
case ColumnType.DATE:
case ColumnType.TIMESTAMP:
offset += 8;
break;
default:
close();
throw CairoException.instance(0).put("value type is not supported: ").put(ColumnType.nameOf(valueTypes.getColumnType(i)));
}
}
this.value = new FastMapValue(valueOffsets);
this.keyBlockOffset = offset;
this.keyDataOffset = this.keyBlockOffset + 4 * keyTypes.getColumnCount();
this.record = new FastMapRecord(valueOffsets, columnSplit, keyDataOffset, keyBlockOffset, value, keyTypes);
} else {
this.valueColumnCount = 0;
this.value = new FastMapValue(null);
this.keyBlockOffset = offset;
this.keyDataOffset = this.keyBlockOffset + 4 * keyTypes.getColumnCount();
this.record = new FastMapRecord(null, 0, keyDataOffset, keyBlockOffset, value, keyTypes);
}
this.iterator = new FastMapCursor(record);
}
@Override
public void clear() {
kPos = kStart;
free = (int) (keyCapacity * loadFactor);
size = 0;
offsets.zero(-1);
}
@Override
public final void close() {
offsets = Misc.free(offsets);
if (address != 0) {
Unsafe.free(address, capacity);
address = 0;
}
}
@Override
@NotNull
public Iterator<MapRecord> iterator() {
return iterator.init(kStart, size);
}
@Override
public MapRecord recordAt(long rowid) {
return record.of(rowid);
}
@Override
public long size() {
return size;
}
@Override
public MapKey withKey() {
return key.init();
}
@Override
public MapKey withKeyAsLong(long value) {
key.startAddress = kPos;
key.appendAddress = kPos + keyDataOffset;
// we need nextColOffset in case we need to resize
if (key.appendAddress + 8 > kLimit) {
key.nextColOffset = kPos + keyBlockOffset;
resize(8);
}
Unsafe.getUnsafe().putLong(key.appendAddress, value);
key.appendAddress += 8;
return key;
}
private FastMapValue asNew(Key keyWriter, int index) {
kPos = keyWriter.appendAddress;
offsets.set(index, keyWriter.startAddress - kStart);
if (--free == 0) {
rehash();
}
size++;
return value.of(keyWriter.startAddress, true);
}
private boolean eq(Key keyWriter, long offset) {
long a = kStart + offset;
long b = keyWriter.startAddress;
// check length first
if (Unsafe.getUnsafe().getInt(a) != Unsafe.getUnsafe().getInt(b)) {
return false;
}
long lim = b + keyWriter.len;
// skip to the data
a += keyDataOffset;
b += keyDataOffset;
while (b < lim - 8) {
if (Unsafe.getUnsafe().getLong(a) != Unsafe.getUnsafe().getLong(b)) {
return false;
}
a += 8;
b += 8;
}
while (b < lim) {
if (Unsafe.getUnsafe().getByte(a++) != Unsafe.getUnsafe().getByte(b++)) {
return false;
}
}
return true;
}
long getAppendOffset() {
return kPos;
}
int getValueColumnCount() {
return valueColumnCount;
}
private int keyIndex() {
return hashFunction.hash(key.startAddress + keyDataOffset, key.len - keyDataOffset) & mask;
}
private FastMapValue probe0(Key keyWriter, int index) {
long offset;
while ((offset = offsets.get(index = (++index & mask))) != -1) {
if (eq(keyWriter, offset)) {
return value.of(kStart + offset, false);
}
}
return asNew(keyWriter, index);
}
private FastMapValue probeReadOnly(Key keyWriter, int index) {
long offset;
while ((offset = offsets.get(index = (++index & mask))) != -1) {
if (eq(keyWriter, offset)) {
return value.of(kStart + offset, false);
}
}
return null;
}
private void rehash() {
int capacity = keyCapacity << 1;
mask = capacity - 1;
DirectLongList pointers = new DirectLongList(capacity);
pointers.setPos(capacity);
pointers.zero(-1);
for (int i = 0, k = this.offsets.size(); i < k; i++) {
long offset = this.offsets.get(i);
if (offset == -1) {
continue;
}
int index = hashFunction.hash(kStart + offset + keyDataOffset, Unsafe.getUnsafe().getInt(kStart + offset) - keyDataOffset) & mask;
while (pointers.get(index) != -1) {
index = (index + 1) & mask;
}
pointers.set(index, offset);
}
this.offsets.close();
this.offsets = pointers;
this.free += (capacity - keyCapacity) * loadFactor;
this.keyCapacity = capacity;
}
private void resize(int size) {
long kCapacity = (kLimit - kStart) << 1;
long target = key.appendAddress + size - kStart;
if (kCapacity < target) {
kCapacity = Numbers.ceilPow2(target);
}
long kAddress = Unsafe.malloc(kCapacity + Unsafe.CACHE_LINE_SIZE);
long kStart = kAddress + (kAddress & (Unsafe.CACHE_LINE_SIZE - 1));
Unsafe.getUnsafe().copyMemory(this.kStart, kStart, (kLimit - this.kStart));
Unsafe.free(this.address, this.capacity);
this.capacity = kCapacity + Unsafe.CACHE_LINE_SIZE;
long d = kStart - this.kStart;
kPos += d;
long colOffsetDelta = key.nextColOffset - key.startAddress;
key.startAddress += d;
key.appendAddress += d;
key.nextColOffset = key.startAddress + colOffsetDelta;
assert kPos > 0;
assert key.startAddress > 0;
assert key.appendAddress > 0;
assert key.nextColOffset > 0;
this.address = kAddress;
this.kStart = kStart;
this.kLimit = kStart + kCapacity;
}
@FunctionalInterface
public interface HashFunction {
int hash(long address, int len);
}
public class Key implements MapKey {
private long startAddress;
private long appendAddress;
private int len;
private long nextColOffset;
public MapValue createValue() {
commit();
// calculate hash remembering "key" structure
// [ len | value block | key offset block | key data block ]
int index = keyIndex();
long offset = offsets.get(index);
if (offset == -1) {
return asNew(this, index);
} else if (eq(this, offset)) {
return value.of(kStart + offset, false);
} else {
return probe0(this, index);
}
}
public MapValue findValue() {
commit();
int index = keyIndex();
long offset = offsets.get(index);
if (offset == -1) {
return null;
} else if (eq(this, offset)) {
return value.of(kStart + offset, false);
} else {
return probeReadOnly(this, index);
}
}
@Override
public void putBin(BinarySequence value) {
if (value == null) {
putNull();
} else {
long len = value.length() + 4;
if (len > Integer.MAX_VALUE) {
throw CairoException.instance(0).put("binary column is too large");
}
checkSize((int) len);
int l = (int) (len - 4);
long offset = 4L;
long pos = 0;
Unsafe.getUnsafe().putInt(appendAddress, l);
while (true) {
long copied = value.copyTo(appendAddress + offset, pos, l);
if (copied == l) {
break;
}
l -= copied;
pos += copied;
offset += copied;
}
appendAddress += len;
writeOffset();
}
}
@Override
public void putBool(boolean value) {
checkSize(1);
Unsafe.getUnsafe().putByte(appendAddress, (byte) (value ? 1 : 0));
appendAddress += 1;
writeOffset();
}
@Override
public void putByte(byte value) {
checkSize(1);
Unsafe.getUnsafe().putByte(appendAddress, value);
appendAddress += 1;
writeOffset();
}
@Override
public void putDate(long value) {
putLong(value);
}
@Override
public void putDouble(double value) {
checkSize(8);
Unsafe.getUnsafe().putDouble(appendAddress, value);
appendAddress += 8;
writeOffset();
}
@Override
public void putFloat(float value) {
checkSize(4);
Unsafe.getUnsafe().putFloat(appendAddress, value);
appendAddress += 4;
writeOffset();
}
@Override
public void putInt(int value) {
checkSize(4);
Unsafe.getUnsafe().putInt(appendAddress, value);
appendAddress += 4;
writeOffset();
}
@Override
public void putLong(long value) {
checkSize(8);
Unsafe.getUnsafe().putLong(appendAddress, value);
appendAddress += 8;
writeOffset();
}
@Override
public void put(Record record, RecordSink sink) {
sink.copy(record, this);
}
@Override
public void putShort(short value) {
checkSize(2);
Unsafe.getUnsafe().putShort(appendAddress, value);
appendAddress += 2;
writeOffset();
}
@Override
public void putStr(CharSequence value) {
if (value == null) {
putNull();
return;
}
int len = value.length();
checkSize((len << 1) + 4);
Unsafe.getUnsafe().putInt(appendAddress, len);
appendAddress += 4;
for (int i = 0; i < len; i++) {
Unsafe.getUnsafe().putChar(appendAddress + (i << 1), value.charAt(i));
}
appendAddress += len << 1;
writeOffset();
}
@Override
@SuppressWarnings("unused")
public void putTimestamp(long value) {
putLong(value);
}
public Key init() {
startAddress = kPos;
appendAddress = kPos + keyDataOffset;
nextColOffset = kPos + keyBlockOffset;
return this;
}
private void checkSize(int size) {
if (appendAddress + size > kLimit) {
resize(size);
}
}
private void commit() {
Unsafe.getUnsafe().putInt(startAddress, len = (int) (appendAddress - startAddress));
}
private void putNull() {
checkSize(4);
Unsafe.getUnsafe().putInt(appendAddress, TableUtils.NULL_LEN);
appendAddress += 4;
writeOffset();
}
private void writeOffset() {
long len = appendAddress - startAddress;
if (len > Integer.MAX_VALUE) {
throw CairoException.instance(0).put("row data is too large");
}
Unsafe.getUnsafe().putInt(nextColOffset, (int) len);
nextColOffset += 4;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.