answer stringlengths 17 10.2M |
|---|
package org.junit.gen5.launcher.main;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.gen5.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assertions.expectThrows;
import static org.junit.gen5.engine.FilterResult.excluded;
import static org.junit.gen5.engine.discovery.ClassSelector.forClass;
import static org.junit.gen5.engine.discovery.ClassSelector.forClassName;
import static org.junit.gen5.engine.discovery.MethodSelector.forMethod;
import static org.junit.gen5.engine.discovery.PackageSelector.forPackageName;
import static org.junit.gen5.engine.discovery.UniqueIdSelector.forUniqueId;
import static org.junit.gen5.launcher.main.TestDiscoveryRequestBuilder.request;
import java.io.File;
import java.lang.reflect.Method;
import java.util.List;
import org.assertj.core.util.Files;
import org.junit.gen5.api.Nested;
import org.junit.gen5.api.Test;
import org.junit.gen5.commons.util.PreconditionViolationException;
import org.junit.gen5.engine.DiscoveryFilter;
import org.junit.gen5.engine.discovery.ClassSelector;
import org.junit.gen5.engine.discovery.ClasspathSelector;
import org.junit.gen5.engine.discovery.MethodSelector;
import org.junit.gen5.engine.discovery.PackageSelector;
import org.junit.gen5.engine.discovery.UniqueIdSelector;
import org.junit.gen5.launcher.DiscoveryFilterStub;
import org.junit.gen5.launcher.EngineIdFilter;
import org.junit.gen5.launcher.PostDiscoveryFilter;
import org.junit.gen5.launcher.PostDiscoveryFilterStub;
import org.junit.gen5.launcher.TestDiscoveryRequest;
/**
* @since 5.0
*/
public class TestDiscoveryRequestBuilderTests {
@Nested
class DiscoverySelectionTests {
@Test
public void packagesAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
forPackageName("org.junit.gen5.engine")
).build();
// @formatter:on
List<String> packageSelectors = discoveryRequest.getSelectorsByType(PackageSelector.class).stream().map(
PackageSelector::getPackageName).collect(toList());
assertThat(packageSelectors).contains("org.junit.gen5.engine");
}
@Test
public void classesAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
forClassName(TestDiscoveryRequestBuilderTests.class.getName()),
forClass(SampleTestClass.class)
)
.build();
// @formatter:on
List<Class<?>> classes = discoveryRequest.getSelectorsByType(ClassSelector.class).stream().map(
ClassSelector::getTestClass).collect(toList());
assertThat(classes).contains(SampleTestClass.class, TestDiscoveryRequestBuilderTests.class);
}
@Test
public void methodsByNameAreStoredInDiscoveryRequest() throws Exception {
Class<?> testClass = SampleTestClass.class;
Method testMethod = testClass.getMethod("test");
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(forMethod(SampleTestClass.class.getName(), "test"))
.build();
// @formatter:on
List<MethodSelector> methodSelectors = discoveryRequest.getSelectorsByType(MethodSelector.class);
assertThat(methodSelectors).hasSize(1);
MethodSelector methodSelector = methodSelectors.get(0);
assertThat(methodSelector.getTestClass()).isEqualTo(testClass);
assertThat(methodSelector.getTestMethod()).isEqualTo(testMethod);
}
@Test
public void methodsByClassAreStoredInDiscoveryRequest() throws Exception {
Class<?> testClass = SampleTestClass.class;
Method testMethod = testClass.getMethod("test");
// @formatter:off
DiscoveryRequest discoveryRequest = (DiscoveryRequest) request()
.select(
MethodSelector.forMethod(SampleTestClass.class, "test")
).build();
// @formatter:on
List<MethodSelector> methodSelectors = discoveryRequest.getSelectorsByType(MethodSelector.class);
assertThat(methodSelectors).hasSize(1);
MethodSelector methodSelector = methodSelectors.get(0);
assertThat(methodSelector.getTestClass()).isEqualTo(testClass);
assertThat(methodSelector.getTestMethod()).isEqualTo(testMethod);
}
@Test
public void unavailableFoldersAreNotStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
ClasspathSelector.forPath("/some/local/path")
).build();
// @formatter:on
List<String> folders = discoveryRequest.getSelectorsByType(ClasspathSelector.class).stream().map(
ClasspathSelector::getClasspathRoot).map(File::getAbsolutePath).collect(toList());
assertThat(folders).isEmpty();
}
@Test
public void availableFoldersAreStoredInDiscoveryRequest() throws Exception {
File temporaryFolder = Files.newTemporaryFolder();
try {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
ClasspathSelector.forPath(temporaryFolder.getAbsolutePath())
).build();
// @formatter:on
List<String> folders = discoveryRequest.getSelectorsByType(ClasspathSelector.class).stream().map(
ClasspathSelector::getClasspathRoot).map(File::getAbsolutePath).collect(toList());
assertThat(folders).contains(temporaryFolder.getAbsolutePath());
}
finally {
temporaryFolder.delete();
}
}
@Test
public void uniqueIdsAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.select(
forUniqueId("engine:bla:foo:bar:id1"),
forUniqueId("engine:bla:foo:bar:id2")
).build();
// @formatter:on
List<String> uniqueIds = discoveryRequest.getSelectorsByType(UniqueIdSelector.class).stream().map(
UniqueIdSelector::getUniqueId).collect(toList());
assertThat(uniqueIds).contains("engine:bla:foo:bar:id1", "engine:bla:foo:bar:id2");
}
}
@Nested
class DiscoveryFilterTests {
@Test
public void engineFiltersAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.filter(
EngineIdFilter.byEngineId("engine1"),
EngineIdFilter.byEngineId("engine2")
).build();
// @formatter:on
List<String> engineIds = discoveryRequest.getEngineIdFilters().stream().map(
EngineIdFilter::getEngineId).collect(toList());
assertThat(engineIds).hasSize(2);
assertThat(engineIds).contains("engine1", "engine2");
}
@Test
@SuppressWarnings("rawtypes")
public void discoveryFiltersAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.filter(
new DiscoveryFilterStub("filter1"),
new DiscoveryFilterStub("filter2")
).build();
// @formatter:on
List<String> filterStrings = discoveryRequest.getDiscoveryFiltersByType(DiscoveryFilter.class).stream().map(
DiscoveryFilter::toString).collect(toList());
assertThat(filterStrings).hasSize(2);
assertThat(filterStrings).contains("filter1", "filter2");
}
@Test
public void postDiscoveryFiltersAreStoredInDiscoveryRequest() throws Exception {
// @formatter:off
TestDiscoveryRequest discoveryRequest = request()
.filter(
new PostDiscoveryFilterStub("postFilter1"),
new PostDiscoveryFilterStub("postFilter2")
).build();
// @formatter:on
List<String> filterStrings = discoveryRequest.getPostDiscoveryFilters().stream().map(
PostDiscoveryFilter::toString).collect(toList());
assertThat(filterStrings).hasSize(2);
assertThat(filterStrings).contains("postFilter1", "postFilter2");
}
@Test
public void exceptionForIllegalFilterClass() throws Exception {
PreconditionViolationException exception = expectThrows(PreconditionViolationException.class,
() -> request().filter(o -> excluded("reason")));
assertEquals("Filter must implement EngineIdFilter, PostDiscoveryFilter or DiscoveryFilter.",
exception.getMessage());
}
}
private static class SampleTestClass {
@Test
public void test() {
}
}
} |
package com.codespair.kafka.navigator.kafkanavigatorbe.kafka.jmx;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.management.AttributeList;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.util.*;
@Slf4j
@Service
@Scope("prototype")
@Getter
public class KafkaJMX {
private JMXServiceURL jmxServiceURL;
private List<String> jmxDomains;
private boolean connected;
private MBeanServerConnection mbsc;
/**
* Connects with kafka jmx and return true if successful, false otherwise.
*
* @param jmxUrl the url of a broker to connect with using JMX.
* @return a list of available JMX Bean domain names to be navigated.
*/
public boolean connect(String jmxUrl) {
String url = "service:jmx:rmi:///jndi/rmi://" + jmxUrl + "/jmxrmi";
try {
mbsc = mBeanServerConnection(url);
connected = true;
} catch (IOException e) {
log.error("could not connect to jmx kafka server: {}", e.getMessage(), e);
}
return isConnected();
}
/**
* Recover a list of jmx domains of this kafka server
* @return a List with strings each representing a jmx domain from the kafka broker
*/
public Optional<List<String>> getJmxDomains() {
String domains[];
try {
domains = mbsc.getDomains();
jmxDomains = Arrays.asList(domains);
logDomains(domains);
return Optional.of(jmxDomains);
} catch (IOException e) {
log.error("Error recovering JMX Domains: {}", e.getMessage(), e);
return Optional.empty();
}
}
/**
* Recover the Broker id
*
* @return an Integer representing the Broker id
*/
public Optional<Integer> getBrokerId() {
try {
ObjectName objectName = new ObjectName("kafka.server:type=app-info");
return Optional.of((Integer) (mbsc.getAttribute(objectName, "id")));
} catch (Exception e) {
log.error("Error getting Broker id: {}", e.getMessage(), e);
return Optional.empty();
}
}
/**
* Get general topic metrics for broker
* @return AttributeList with topic metrics from broker.
*/
public Optional<AttributeList> getTopicMetrics() {
try {
ObjectName objectName = new ObjectName("kafka.server:type=BrokerTopicMetrics");
return Optional.of(mbsc.getAttributes(objectName, topicMetricsAttributes()));
} catch (Exception e) {
log.error("Erorr recovering Topic Metrics for Broker: {}",
getBrokerId().get());
return Optional.empty();
}
}
private String[] topicMetricsAttributes() {
final String[] attributes = {
"BytesInPerSec",
"BytesOutPerSec",
"BytesRejectPerSec",
"FailedFetchRequestsPerSec",
"FailedProduceRequestsPerSec",
"MessagesInPerSec",
"TotalFetchRequestsPerSec",
"TotalProduceRequestsPerSec"
};
return attributes;
}
private MBeanServerConnection mBeanServerConnection(String url) throws IOException {
log.info("connecting to mbeanserver url: {}", url);
jmxServiceURL = new JMXServiceURL(url);
JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceURL, defaultJMXConnectorProperties());
return jmxc.getMBeanServerConnection();
}
private void logDomains(String[] domains) {
Arrays.sort(domains);
for (String domain : domains) {
log.info("\tDomain = " + domain);
}
}
private Map<String, String> defaultJMXConnectorProperties() {
Map<String, String> props = new HashMap<>();
props.put("jmx.remote.x.request.waiting.timeout", "3000");
props.put("jmx.remote.x.notification.fetch.timeout", "3000");
props.put("sun.rmi.transport.connectionTimeout", "3000");
props.put("sun.rmi.transport.tcp.handshakeTimeout", "3000");
props.put("sun.rmi.transport.tcp.responseTimeout", "3000");
return props;
}
} |
package org.vertexium.serializer.kryo;
import org.junit.Before;
import org.junit.Test;
import org.vertexium.VertexiumSerializer;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import static org.junit.Assert.assertEquals;
public class KryoVertexiumSerializerTest {
@Before
public void before() {
System.gc();
}
@Test
public void testObjectToValue() {
byte[] valBytes = new KryoVertexiumSerializer().objectToBytes(new Date());
assertEquals(10, valBytes.length);
}
@Test
public void testString() {
System.out.println("testString");
timeItString(new KryoVertexiumSerializer());
long quickKryoTime = timeItString(new QuickKryoVertexiumSerializer());
long kryoTime = timeItString(new KryoVertexiumSerializer());
assertTiming(quickKryoTime, kryoTime);
}
private long timeItString(VertexiumSerializer serializer) {
long startTime = System.currentTimeMillis();
long bytes = 0;
for (int i = 0; i < 1000000; i++) {
byte[] v = serializer.objectToBytes("yo mamma");
assertEquals("yo mamma", serializer.bytesToObject(v));
bytes += v.length;
}
long endTime = System.currentTimeMillis();
System.out.println(serializer.getClass().getName() + " time: " + (endTime - startTime) + "ms (size: " + new DecimalFormat("#,##0").format(bytes) + ")");
return endTime - startTime;
}
@Test
public void testBigDecimal() {
System.out.println("testBigDecimal");
timeItBigDecimal(new KryoVertexiumSerializer());
long quickKryoTime = timeItBigDecimal(new QuickKryoVertexiumSerializer());
long kryoTime = timeItBigDecimal(new KryoVertexiumSerializer());
assertTiming(quickKryoTime, kryoTime);
}
private long timeItBigDecimal(VertexiumSerializer serializer) {
long startTime = System.currentTimeMillis();
long bytes = 0;
for (int i = 0; i < 1000000; i++) {
byte[] v = serializer.objectToBytes(new BigDecimal("42.987654321"));
assertEquals(new BigDecimal("42.987654321"), serializer.bytesToObject(v));
bytes += v.length;
}
long endTime = System.currentTimeMillis();
System.out.println(serializer.getClass().getName() + " time: " + (endTime - startTime) + "ms (size: " + new DecimalFormat("#,##0").format(bytes) + ")");
return endTime - startTime;
}
@Test
public void testDate() {
System.out.println("testDate");
timeItDate(new KryoVertexiumSerializer());
long quickKryoTime = timeItDate(new QuickKryoVertexiumSerializer());
long kryoTime = timeItDate(new KryoVertexiumSerializer());
assertTiming(quickKryoTime, kryoTime);
}
private long timeItDate(VertexiumSerializer serializer) {
long startTime = System.currentTimeMillis();
long bytes = 0;
for (int i = 0; i < 1000000; i++) {
Date date = new Date();
byte[] v = serializer.objectToBytes(date);
assertEquals(date, serializer.bytesToObject(v));
bytes += v.length;
}
long endTime = System.currentTimeMillis();
System.out.println(serializer.getClass().getName() + " time: " + (endTime - startTime) + "ms (size: " + new DecimalFormat("#,##0").format(bytes) + ")");
return endTime - startTime;
}
@Test
public void testLong() {
System.out.println("testLong");
timeItLong(new KryoVertexiumSerializer());
long quickKryoTime = timeItLong(new QuickKryoVertexiumSerializer());
long kryoTime = timeItLong(new KryoVertexiumSerializer());
assertTiming(quickKryoTime, kryoTime);
}
private long timeItLong(VertexiumSerializer serializer) {
long startTime = System.currentTimeMillis();
long bytes = 0;
for (int i = 0; i < 1000000; i++) {
Long l = 123456L;
byte[] v = serializer.objectToBytes(l);
assertEquals(l, serializer.bytesToObject(v));
bytes += v.length;
}
long endTime = System.currentTimeMillis();
System.out.println(serializer.getClass().getName() + " time: " + (endTime - startTime) + "ms (size: " + new DecimalFormat("#,##0").format(bytes) + ")");
return endTime - startTime;
}
@Test
public void testDouble() {
System.out.println("testDouble");
timeItDouble(new KryoVertexiumSerializer());
long quickKryoTime = timeItDouble(new QuickKryoVertexiumSerializer());
long kryoTime = timeItDouble(new KryoVertexiumSerializer());
assertTiming(quickKryoTime, kryoTime);
}
private long timeItDouble(VertexiumSerializer serializer) {
long startTime = System.currentTimeMillis();
long bytes = 0;
for (int i = 0; i < 1000000; i++) {
double d = 3.1415;
byte[] v = serializer.objectToBytes(d);
assertEquals(d, serializer.bytesToObject(v));
bytes += v.length;
}
long endTime = System.currentTimeMillis();
System.out.println(serializer.getClass().getName() + " time: " + (endTime - startTime) + "ms (size: " + new DecimalFormat("#,##0").format(bytes) + ")");
return endTime - startTime;
}
@Test
public void testTestClass() {
TestClass testClass = new TestClass("value1", 42);
KryoVertexiumSerializer serializer = new KryoVertexiumSerializer();
byte[] v = serializer.objectToBytes(testClass);
assertEquals(testClass, serializer.bytesToObject(v));
}
@Test
public void testTestClassQuick() {
TestClass testClass = new TestClass("value1", 42);
QuickKryoVertexiumSerializer serializer = new QuickKryoVertexiumSerializer();
byte[] v = serializer.objectToBytes(testClass);
assertEquals(testClass, serializer.bytesToObject(v));
}
private void assertTiming(long quickKryoTime, long kryoTime) {
// we can't fail when the timing is off because sometimes it's the JVMs fault doing garbage collection or something
if (quickKryoTime > kryoTime) {
System.err.println("WARNING: quick (" + quickKryoTime + "ms) was slower than Kryo (" + kryoTime + "ms)");
}
}
public static class TestClass {
private String field1;
private long field2;
public TestClass(String field1, int field2) {
this.field1 = field1;
this.field2 = field2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestClass testClass = (TestClass) o;
if (field2 != testClass.field2) return false;
if (field1 != null ? !field1.equals(testClass.field1) : testClass.field1 != null) return false;
return true;
}
@Override
public int hashCode() {
int result = field1 != null ? field1.hashCode() : 0;
result = 31 * result + (int) (field2 ^ (field2 >>> 32));
return result;
}
}
} |
package com.prolificinteractive.materialcalendarview;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.ArrayRes;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter;
import com.prolificinteractive.materialcalendarview.format.DateFormatTitleFormatter;
import com.prolificinteractive.materialcalendarview.format.DayFormatter;
import com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter;
import com.prolificinteractive.materialcalendarview.format.TitleFormatter;
import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
* <p>
* This class is a calendar widget for displaying and selecting dates.
* The range of dates supported by this calendar is configurable.
* A user can select a date by taping on it and can page the calendar to a desired date.
* </p>
* <p>
* By default, the range of dates shown is from 200 years in the past to 200 years in the future.
* This can be extended or shortened by configuring the minimum and maximum dates.
* </p>
* <p>
* When selecting a date out of range, or when the range changes so the selection becomes outside,
* The date closest to the previous selection will become selected. This will also trigger the
* {@linkplain OnDateSelectedListener}
* </p>
* <p>
* <strong>Note:</strong> if this view's size isn't divisible by 7,
* the contents will be centered inside such that the days in the calendar are equally square.
* For example, 600px isn't divisible by 7, so a tile size of 85 is choosen, making the calendar
* 595px wide. The extra 5px are distributed left and right to get to 600px.
* </p>
*/
public class MaterialCalendarView extends ViewGroup {
public static final int INVALID_TILE_DIMENSION = -10;
/**
* {@linkplain IntDef} annotation for selection mode.
*
* @see #setSelectionMode(int)
* @see #getSelectionMode()
*/
@Retention(RetentionPolicy.RUNTIME)
@IntDef({SELECTION_MODE_NONE, SELECTION_MODE_SINGLE, SELECTION_MODE_MULTIPLE, SELECTION_MODE_RANGE})
public @interface SelectionMode {
}
/**
* Selection mode that disallows all selection.
* When changing to this mode, current selection will be cleared.
*/
public static final int SELECTION_MODE_NONE = 0;
/**
* Selection mode that allows one selected date at one time. This is the default mode.
* When switching from {@linkplain #SELECTION_MODE_MULTIPLE}, this will select the same date
* as from {@linkplain #getSelectedDate()}, which should be the last selected date
*/
public static final int SELECTION_MODE_SINGLE = 1;
/**
* Selection mode which allows more than one selected date at one time.
*/
public static final int SELECTION_MODE_MULTIPLE = 2;
/**
* Selection mode which allows selection of a range between two dates
*/
public static final int SELECTION_MODE_RANGE = 3;
/**
* {@linkplain IntDef} annotation for showOtherDates.
*
* @see #setShowOtherDates(int)
* @see #getShowOtherDates()
*/
@SuppressLint("UniqueConstants")
@Retention(RetentionPolicy.RUNTIME)
@IntDef(flag = true, value = {
SHOW_NONE, SHOW_ALL, SHOW_DEFAULTS,
SHOW_OUT_OF_RANGE, SHOW_OTHER_MONTHS, SHOW_DECORATED_DISABLED
})
public @interface ShowOtherDates {
}
/**
* Do not show any non-enabled dates
*/
public static final int SHOW_NONE = 0;
/**
* Show dates from the proceeding and successive months, in a disabled state.
* This flag also enables the {@link #SHOW_OUT_OF_RANGE} flag to prevent odd blank areas.
*/
public static final int SHOW_OTHER_MONTHS = 1;
/**
* Show dates that are outside of the min-max range.
* This will only show days from the current month unless {@link #SHOW_OTHER_MONTHS} is enabled.
*/
public static final int SHOW_OUT_OF_RANGE = 2;
/**
* Show days that are individually disabled with decorators.
* This will only show dates in the current month and inside the minimum and maximum date range.
*/
public static final int SHOW_DECORATED_DISABLED = 4;
/**
* The default flags for showing non-enabled dates. Currently only shows {@link #SHOW_DECORATED_DISABLED}
*/
public static final int SHOW_DEFAULTS = SHOW_DECORATED_DISABLED;
/**
* Show all the days
*/
public static final int SHOW_ALL = SHOW_OTHER_MONTHS | SHOW_OUT_OF_RANGE | SHOW_DECORATED_DISABLED;
/**
* Use this orientation to animate the title vertically
*/
public static final int VERTICAL = 0;
/**
* Use this orientation to animate the title horizontally
*/
public static final int HORIZONTAL = 1;
/**
* Default tile size in DIPs. This is used in cases where there is no tile size specificed and the view is set to {@linkplain ViewGroup.LayoutParams#WRAP_CONTENT WRAP_CONTENT}
*/
public static final int DEFAULT_TILE_SIZE_DP = 44;
private static final int DEFAULT_DAYS_IN_WEEK = 7;
private static final int DEFAULT_MAX_WEEKS = 6;
private static final int DAY_NAMES_ROW = 1;
private static final TitleFormatter DEFAULT_TITLE_FORMATTER = new DateFormatTitleFormatter();
private final TitleChanger titleChanger;
private final TextView title;
private final DirectionButton buttonPast;
private final DirectionButton buttonFuture;
private final CalendarPager pager;
private CalendarPagerAdapter<?> adapter;
private CalendarDay currentMonth;
private LinearLayout topbar;
private CalendarMode calendarMode;
/**
* Used for the dynamic calendar height.
*/
private boolean mDynamicHeightEnabled;
private final ArrayList<DayViewDecorator> dayViewDecorators = new ArrayList<>();
private final OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (v == buttonFuture) {
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
} else if (v == buttonPast) {
pager.setCurrentItem(pager.getCurrentItem() - 1, true);
}
}
};
private final ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
titleChanger.setPreviousMonth(currentMonth);
currentMonth = adapter.getItem(position);
updateUi();
dispatchOnMonthChanged(currentMonth);
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
};
private CalendarDay minDate = null;
private CalendarDay maxDate = null;
private OnDateSelectedListener listener;
private OnMonthChangedListener monthListener;
private OnRangeSelectedListener rangeListener;
private OnClickListener titleListener;
CharSequence calendarContentDescription;
private int accentColor = 0;
private int arrowColor = Color.BLACK;
private Drawable leftArrowMask;
private Drawable rightArrowMask;
private int tileHeight = INVALID_TILE_DIMENSION;
private int tileWidth = INVALID_TILE_DIMENSION;
@SelectionMode
private int selectionMode = SELECTION_MODE_SINGLE;
private boolean allowClickDaysOutsideCurrentMonth = true;
private int firstDayOfWeek;
private State state;
public MaterialCalendarView(Context context) {
this(context, null);
}
public MaterialCalendarView(Context context, AttributeSet attrs) {
super(context, attrs);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//If we're on good Android versions, turn off clipping for cool effects
setClipToPadding(false);
setClipChildren(false);
} else {
//Old Android does not like _not_ clipping view pagers, we need to clip
setClipChildren(true);
setClipToPadding(true);
}
buttonPast = new DirectionButton(getContext());
buttonPast.setContentDescription(getContext().getString(R.string.previous));
title = new TextView(getContext());
buttonFuture = new DirectionButton(getContext());
buttonFuture.setContentDescription(getContext().getString(R.string.next));
pager = new CalendarPager(getContext());
buttonPast.setOnClickListener(onClickListener);
buttonFuture.setOnClickListener(onClickListener);
titleChanger = new TitleChanger(title);
titleChanger.setTitleFormatter(DEFAULT_TITLE_FORMATTER);
pager.setOnPageChangeListener(pageChangeListener);
pager.setPageTransformer(false, new ViewPager.PageTransformer() {
@Override
public void transformPage(View page, float position) {
position = (float) Math.sqrt(1 - Math.abs(position));
page.setAlpha(position);
}
});
TypedArray a = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.MaterialCalendarView, 0, 0);
try {
int calendarModeIndex = a.getInteger(
R.styleable.MaterialCalendarView_mcv_calendarMode,
0
);
firstDayOfWeek = a.getInteger(
R.styleable.MaterialCalendarView_mcv_firstDayOfWeek,
-1
);
titleChanger.setOrientation(
a.getInteger(R.styleable.MaterialCalendarView_mcv_titleAnimationOrientation,
VERTICAL));
if (firstDayOfWeek < 0) {
//Allowing use of Calendar.getInstance() here as a performance optimization
firstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek();
}
newState()
.setFirstDayOfWeek(firstDayOfWeek)
.setCalendarDisplayMode(CalendarMode.values()[calendarModeIndex])
.commit();
final int tileSize = a.getLayoutDimension(R.styleable.MaterialCalendarView_mcv_tileSize, INVALID_TILE_DIMENSION);
if (tileSize > INVALID_TILE_DIMENSION) {
setTileSize(tileSize);
}
final int tileWidth = a.getLayoutDimension(R.styleable.MaterialCalendarView_mcv_tileWidth, INVALID_TILE_DIMENSION);
if (tileWidth > INVALID_TILE_DIMENSION) {
setTileWidth(tileWidth);
}
final int tileHeight = a.getLayoutDimension(R.styleable.MaterialCalendarView_mcv_tileHeight, INVALID_TILE_DIMENSION);
if (tileHeight > INVALID_TILE_DIMENSION) {
setTileHeight(tileHeight);
}
setArrowColor(a.getColor(
R.styleable.MaterialCalendarView_mcv_arrowColor,
Color.BLACK
));
Drawable leftMask = a.getDrawable(
R.styleable.MaterialCalendarView_mcv_leftArrowMask
);
if (leftMask == null) {
leftMask = getResources().getDrawable(R.drawable.mcv_action_previous);
}
setLeftArrowMask(leftMask);
Drawable rightMask = a.getDrawable(
R.styleable.MaterialCalendarView_mcv_rightArrowMask
);
if (rightMask == null) {
rightMask = getResources().getDrawable(R.drawable.mcv_action_next);
}
setRightArrowMask(rightMask);
setSelectionColor(
a.getColor(
R.styleable.MaterialCalendarView_mcv_selectionColor,
getThemeAccentColor(context)
)
);
CharSequence[] array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_weekDayLabels);
if (array != null) {
setWeekDayFormatter(new ArrayWeekDayFormatter(array));
}
array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_monthLabels);
if (array != null) {
setTitleFormatter(new MonthArrayTitleFormatter(array));
}
setHeaderTextAppearance(a.getResourceId(
R.styleable.MaterialCalendarView_mcv_headerTextAppearance,
R.style.TextAppearance_MaterialCalendarWidget_Header
));
setWeekDayTextAppearance(a.getResourceId(
R.styleable.MaterialCalendarView_mcv_weekDayTextAppearance,
R.style.TextAppearance_MaterialCalendarWidget_WeekDay
));
setDateTextAppearance(a.getResourceId(
R.styleable.MaterialCalendarView_mcv_dateTextAppearance,
R.style.TextAppearance_MaterialCalendarWidget_Date
));
//noinspection ResourceType
setShowOtherDates(a.getInteger(
R.styleable.MaterialCalendarView_mcv_showOtherDates,
SHOW_DEFAULTS
));
setAllowClickDaysOutsideCurrentMonth(a.getBoolean(
R.styleable.MaterialCalendarView_mcv_allowClickDaysOutsideCurrentMonth,
true
));
} catch (Exception e) {
e.printStackTrace();
} finally {
a.recycle();
}
// Adapter is created while parsing the TypedArray attrs, so setup has to happen after
adapter.setTitleFormatter(DEFAULT_TITLE_FORMATTER);
setupChildren();
currentMonth = CalendarDay.today();
setCurrentDate(currentMonth);
if (isInEditMode()) {
removeView(pager);
MonthView monthView = new MonthView(this, currentMonth, getFirstDayOfWeek());
monthView.setSelectionColor(getSelectionColor());
monthView.setDateTextAppearance(adapter.getDateTextAppearance());
monthView.setWeekDayTextAppearance(adapter.getWeekDayTextAppearance());
monthView.setShowOtherDates(getShowOtherDates());
addView(monthView, new LayoutParams(calendarMode.visibleWeeksCount + DAY_NAMES_ROW));
}
}
private void setupChildren() {
topbar = new LinearLayout(getContext());
topbar.setOrientation(LinearLayout.HORIZONTAL);
topbar.setClipChildren(false);
topbar.setClipToPadding(false);
addView(topbar, new LayoutParams(1));
buttonPast.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
topbar.addView(buttonPast, new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1));
title.setGravity(Gravity.CENTER);
topbar.addView(title, new LinearLayout.LayoutParams(
0, LayoutParams.MATCH_PARENT, DEFAULT_DAYS_IN_WEEK - 2
));
buttonFuture.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
topbar.addView(buttonFuture, new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1));
pager.setId(R.id.mcv_pager);
pager.setOffscreenPageLimit(1);
addView(pager, new LayoutParams(calendarMode.visibleWeeksCount + DAY_NAMES_ROW));
}
private void updateUi() {
titleChanger.change(currentMonth);
buttonPast.setEnabled(canGoBack());
buttonFuture.setEnabled(canGoForward());
}
/**
* Change the selection mode of the calendar. The default mode is {@linkplain #SELECTION_MODE_SINGLE}
*
* @param mode the selection mode to change to. This must be one of
* {@linkplain #SELECTION_MODE_NONE}, {@linkplain #SELECTION_MODE_SINGLE},
* {@linkplain #SELECTION_MODE_RANGE} or {@linkplain #SELECTION_MODE_MULTIPLE}.
* Unknown values will act as {@linkplain #SELECTION_MODE_SINGLE}
* @see #getSelectionMode()
* @see #SELECTION_MODE_NONE
* @see #SELECTION_MODE_SINGLE
* @see #SELECTION_MODE_MULTIPLE
* @see #SELECTION_MODE_RANGE
*/
public void setSelectionMode(final @SelectionMode int mode) {
final @SelectionMode int oldMode = this.selectionMode;
this.selectionMode = mode;
switch (mode) {
case SELECTION_MODE_RANGE:
clearSelection();
break;
case SELECTION_MODE_MULTIPLE:
break;
case SELECTION_MODE_SINGLE:
if (oldMode == SELECTION_MODE_MULTIPLE || oldMode == SELECTION_MODE_RANGE) {
//We should only have one selection now, so we should pick one
List<CalendarDay> dates = getSelectedDates();
if (!dates.isEmpty()) {
setSelectedDate(getSelectedDate());
}
}
break;
default:
case SELECTION_MODE_NONE:
this.selectionMode = SELECTION_MODE_NONE;
if (oldMode != SELECTION_MODE_NONE) {
//No selection! Clear out!
clearSelection();
}
break;
}
adapter.setSelectionEnabled(selectionMode != SELECTION_MODE_NONE);
}
/**
* Go to previous month or week without using the button {@link #buttonPast}. Should only go to
* previous if {@link #canGoBack()} is true, meaning it's possible to go to the previous month
* or week.
*/
public void goToPrevious() {
if (canGoBack()) {
pager.setCurrentItem(pager.getCurrentItem() - 1, true);
}
}
/**
* Go to next month or week without using the button {@link #buttonFuture}. Should only go to
* next if {@link #canGoForward()} is enabled, meaning it's possible to go to the next month or
* week.
*/
public void goToNext() {
if (canGoForward()) {
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
}
}
/**
* Get the current selection mode. The default mode is {@linkplain #SELECTION_MODE_SINGLE}
*
* @return the current selection mode
* @see #setSelectionMode(int)
* @see #SELECTION_MODE_NONE
* @see #SELECTION_MODE_SINGLE
* @see #SELECTION_MODE_MULTIPLE
* @see #SELECTION_MODE_RANGE
*/
@SelectionMode
public int getSelectionMode() {
return selectionMode;
}
/**
* Use {@link #getTileWidth()} or {@link #getTileHeight()} instead. This method is deprecated
* and will just return the largest of the two sizes.
*
* @return tile height or width, whichever is larger
*/
@Deprecated
public int getTileSize() {
return Math.max(tileHeight, tileWidth);
}
/**
* Set the size of each tile that makes up the calendar.
* Each day is 1 tile, so the widget is 7 tiles wide and 7 or 8 tiles tall
* depending on the visibility of the {@link #topbar}.
*
* @param size the new size for each tile in pixels
*/
public void setTileSize(int size) {
this.tileWidth = size;
this.tileHeight = size;
requestLayout();
}
/**
* @param tileSizeDp the new size for each tile in dips
* @see #setTileSize(int)
*/
public void setTileSizeDp(int tileSizeDp) {
setTileSize(dpToPx(tileSizeDp));
}
/**
* @return the height of tiles in pixels
*/
public int getTileHeight() {
return tileHeight;
}
/**
* Set the height of each tile that makes up the calendar.
*
* @param height the new height for each tile in pixels
*/
public void setTileHeight(int height) {
this.tileHeight = height;
requestLayout();
}
/**
* @param tileHeightDp the new height for each tile in dips
* @see #setTileHeight(int)
*/
public void setTileHeightDp(int tileHeightDp) {
setTileHeight(dpToPx(tileHeightDp));
}
/**
* @return the width of tiles in pixels
*/
public int getTileWidth() {
return tileWidth;
}
/**
* Set the width of each tile that makes up the calendar.
*
* @param width the new width for each tile in pixels
*/
public void setTileWidth(int width) {
this.tileWidth = width;
requestLayout();
}
/**
* @param tileWidthDp the new width for each tile in dips
* @see #setTileWidth(int)
*/
public void setTileWidthDp(int tileWidthDp) {
setTileWidth(dpToPx(tileWidthDp));
}
private int dpToPx(int dp) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()
);
}
/**
* TODO should this be public?
*
* @return true if there is a future month that can be shown
*/
public boolean canGoForward() {
return pager.getCurrentItem() < (adapter.getCount() - 1);
}
/**
* Pass all touch events to the pager so scrolling works on the edges of the calendar view.
*
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
return pager.dispatchTouchEvent(event);
}
/**
* TODO should this be public?
*
* @return true if there is a previous month that can be shown
*/
public boolean canGoBack() {
return pager.getCurrentItem() > 0;
}
/**
* @return the color used for the selection
*/
public int getSelectionColor() {
return accentColor;
}
/**
* @param color The selection color
*/
public void setSelectionColor(int color) {
if (color == 0) {
if (!isInEditMode()) {
return;
} else {
color = Color.GRAY;
}
}
accentColor = color;
adapter.setSelectionColor(color);
invalidate();
}
/**
* @return color used to draw arrows
*/
public int getArrowColor() {
return arrowColor;
}
/**
* @param color the new color for the paging arrows
*/
public void setArrowColor(int color) {
if (color == 0) {
return;
}
arrowColor = color;
buttonPast.setColor(color);
buttonFuture.setColor(color);
invalidate();
}
/**
* Set content description for button past
*
* @param description String to use as content description
*/
public void setContentDescriptionArrowPast(final CharSequence description) {
buttonPast.setContentDescription(description);
}
/**
* Set content description for button future
*
* @param description String to use as content description
*/
public void setContentDescriptionArrowFuture(final CharSequence description) {
buttonFuture.setContentDescription(description);
}
/**
* Set content description for calendar
*
* @param description String to use as content description
*/
public void setContentDescriptionCalendar(final CharSequence description) {
calendarContentDescription = description;
}
/**
* Get content description for calendar
*
* @return calendar's content description
*/
public CharSequence getCalendarContentDescription() {
return calendarContentDescription != null
? calendarContentDescription
: getContext().getString(R.string.calendar);
}
/**
* @return icon used for the left arrow
*/
public Drawable getLeftArrowMask() {
return leftArrowMask;
}
/**
* @param icon the new icon to use for the left paging arrow
*/
public void setLeftArrowMask(Drawable icon) {
leftArrowMask = icon;
buttonPast.setImageDrawable(icon);
}
/**
* @return icon used for the right arrow
*/
public Drawable getRightArrowMask() {
return rightArrowMask;
}
/**
* @param icon the new icon to use for the right paging arrow
*/
public void setRightArrowMask(Drawable icon) {
rightArrowMask = icon;
buttonFuture.setImageDrawable(icon);
}
/**
* @param resourceId The text appearance resource id.
*/
public void setHeaderTextAppearance(int resourceId) {
title.setTextAppearance(getContext(), resourceId);
}
/**
* @param resourceId The text appearance resource id.
*/
public void setDateTextAppearance(int resourceId) {
adapter.setDateTextAppearance(resourceId);
}
/**
* @param resourceId The text appearance resource id.
*/
public void setWeekDayTextAppearance(int resourceId) {
adapter.setWeekDayTextAppearance(resourceId);
}
/**
* @return the selected day, or null if no selection. If in multiple selection mode, this
* will return the last selected date
*/
public CalendarDay getSelectedDate() {
List<CalendarDay> dates = adapter.getSelectedDates();
if (dates.isEmpty()) {
return null;
} else {
return dates.get(dates.size() - 1);
}
}
/**
* @return all of the currently selected dates
*/
@NonNull
public List<CalendarDay> getSelectedDates() {
return adapter.getSelectedDates();
}
/**
* Clear the currently selected date(s)
*/
public void clearSelection() {
List<CalendarDay> dates = getSelectedDates();
adapter.clearSelections();
for (CalendarDay day : dates) {
dispatchOnDateSelected(day, false);
}
}
/**
* @param calendar a Calendar set to a day to select. Null to clear selection
*/
public void setSelectedDate(@Nullable Calendar calendar) {
setSelectedDate(CalendarDay.from(calendar));
}
/**
* @param date a Date to set as selected. Null to clear selection
*/
public void setSelectedDate(@Nullable Date date) {
setSelectedDate(CalendarDay.from(date));
}
/**
* @param date a Date to set as selected. Null to clear selection
*/
public void setSelectedDate(@Nullable CalendarDay date) {
clearSelection();
if (date != null) {
setDateSelected(date, true);
}
}
/**
* @param calendar a Calendar to change. Passing null does nothing
* @param selected true if day should be selected, false to deselect
*/
public void setDateSelected(@Nullable Calendar calendar, boolean selected) {
setDateSelected(CalendarDay.from(calendar), selected);
}
/**
* @param date a Date to change. Passing null does nothing
* @param selected true if day should be selected, false to deselect
*/
public void setDateSelected(@Nullable Date date, boolean selected) {
setDateSelected(CalendarDay.from(date), selected);
}
/**
* @param day a CalendarDay to change. Passing null does nothing
* @param selected true if day should be selected, false to deselect
*/
public void setDateSelected(@Nullable CalendarDay day, boolean selected) {
if (day == null) {
return;
}
adapter.setDateSelected(day, selected);
}
/**
* @param calendar a Calendar set to a day to focus the calendar on. Null will do nothing
*/
public void setCurrentDate(@Nullable Calendar calendar) {
setCurrentDate(CalendarDay.from(calendar));
}
/**
* @param date a Date to focus the calendar on. Null will do nothing
*/
public void setCurrentDate(@Nullable Date date) {
setCurrentDate(CalendarDay.from(date));
}
/**
* @return The current month shown, will be set to first day of the month
*/
public CalendarDay getCurrentDate() {
return adapter.getItem(pager.getCurrentItem());
}
/**
* @param day a CalendarDay to focus the calendar on. Null will do nothing
*/
public void setCurrentDate(@Nullable CalendarDay day) {
setCurrentDate(day, true);
}
/**
* @param day a CalendarDay to focus the calendar on. Null will do nothing
* @param useSmoothScroll use smooth scroll when changing months.
*/
public void setCurrentDate(@Nullable CalendarDay day, boolean useSmoothScroll) {
if (day == null) {
return;
}
int index = adapter.getIndexForDay(day);
pager.setCurrentItem(index, useSmoothScroll);
updateUi();
}
/**
* @return the minimum selectable date for the calendar, if any
*/
public CalendarDay getMinimumDate() {
return minDate;
}
/**
* @return the maximum selectable date for the calendar, if any
*/
public CalendarDay getMaximumDate() {
return maxDate;
}
/**
* The default value is {@link #SHOW_DEFAULTS}, which currently is just {@link #SHOW_DECORATED_DISABLED}.
* This means that the default visible days are of the current month, in the min-max range.
*
* @param showOtherDates flags for showing non-enabled dates
* @see #SHOW_ALL
* @see #SHOW_NONE
* @see #SHOW_DEFAULTS
* @see #SHOW_OTHER_MONTHS
* @see #SHOW_OUT_OF_RANGE
* @see #SHOW_DECORATED_DISABLED
*/
public void setShowOtherDates(@ShowOtherDates int showOtherDates) {
adapter.setShowOtherDates(showOtherDates);
}
/**
* Allow the user to click on dates from other months that are not out of range. Go to next or
* previous month if a day outside the current month is clicked. The day still need to be
* enabled to be selected.
* Default value is true. Should be used with {@link #SHOW_OTHER_MONTHS}.
*
* @param enabled True to allow the user to click on a day outside current month displayed
*/
public void setAllowClickDaysOutsideCurrentMonth(final boolean enabled) {
this.allowClickDaysOutsideCurrentMonth = enabled;
}
/**
* Set a formatter for weekday labels.
*
* @param formatter the new formatter, null for default
*/
public void setWeekDayFormatter(WeekDayFormatter formatter) {
adapter.setWeekDayFormatter(formatter == null ? WeekDayFormatter.DEFAULT : formatter);
}
/**
* Set a formatter for day labels.
*
* @param formatter the new formatter, null for default
*/
public void setDayFormatter(DayFormatter formatter) {
adapter.setDayFormatter(formatter == null ? DayFormatter.DEFAULT : formatter);
}
/**
* Set a {@linkplain com.prolificinteractive.materialcalendarview.format.WeekDayFormatter}
* with the provided week day labels
*
* @param weekDayLabels Labels to use for the days of the week
* @see com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter
* @see #setWeekDayFormatter(com.prolificinteractive.materialcalendarview.format.WeekDayFormatter)
*/
public void setWeekDayLabels(CharSequence[] weekDayLabels) {
setWeekDayFormatter(new ArrayWeekDayFormatter(weekDayLabels));
}
/**
* Set a {@linkplain com.prolificinteractive.materialcalendarview.format.WeekDayFormatter}
* with the provided week day labels
*
* @param arrayRes String array resource of week day labels
* @see com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter
* @see #setWeekDayFormatter(com.prolificinteractive.materialcalendarview.format.WeekDayFormatter)
*/
public void setWeekDayLabels(@ArrayRes int arrayRes) {
setWeekDayLabels(getResources().getTextArray(arrayRes));
}
/**
* @return int of flags used for showing non-enabled dates
* @see #SHOW_ALL
* @see #SHOW_NONE
* @see #SHOW_DEFAULTS
* @see #SHOW_OTHER_MONTHS
* @see #SHOW_OUT_OF_RANGE
* @see #SHOW_DECORATED_DISABLED
*/
@ShowOtherDates
public int getShowOtherDates() {
return adapter.getShowOtherDates();
}
/**
* @return true if allow click on days outside current month displayed
*/
public boolean allowClickDaysOutsideCurrentMonth() {
return allowClickDaysOutsideCurrentMonth;
}
/**
* Set a custom formatter for the month/year title
*
* @param titleFormatter new formatter to use, null to use default formatter
*/
public void setTitleFormatter(TitleFormatter titleFormatter) {
if (titleFormatter == null) {
titleFormatter = DEFAULT_TITLE_FORMATTER;
}
titleChanger.setTitleFormatter(titleFormatter);
adapter.setTitleFormatter(titleFormatter);
updateUi();
}
/**
* Set a {@linkplain com.prolificinteractive.materialcalendarview.format.TitleFormatter}
* using the provided month labels
*
* @param monthLabels month labels to use
* @see com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter
* @see #setTitleFormatter(com.prolificinteractive.materialcalendarview.format.TitleFormatter)
*/
public void setTitleMonths(CharSequence[] monthLabels) {
setTitleFormatter(new MonthArrayTitleFormatter(monthLabels));
}
/**
* Set a {@linkplain com.prolificinteractive.materialcalendarview.format.TitleFormatter}
* using the provided month labels
*
* @param arrayRes String array resource of month labels to use
* @see com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter
* @see #setTitleFormatter(com.prolificinteractive.materialcalendarview.format.TitleFormatter)
*/
public void setTitleMonths(@ArrayRes int arrayRes) {
setTitleMonths(getResources().getTextArray(arrayRes));
}
/**
* Change the title animation orientation to have a different look and feel.
*
* @param orientation {@link MaterialCalendarView#VERTICAL} or {@link MaterialCalendarView#HORIZONTAL}
*/
public void setTitleAnimationOrientation(final int orientation) {
titleChanger.setOrientation(orientation);
}
/**
* Get the orientation of the animation of the title.
*
* @return Title animation orientation {@link MaterialCalendarView#VERTICAL} or {@link MaterialCalendarView#HORIZONTAL}
*/
public int getTitleAnimationOrientation() {
return titleChanger.getOrientation();
}
/**
* Sets the visibility {@link #topbar}, which contains
* the previous month button {@link #buttonPast}, next month button {@link #buttonFuture},
* and the month title {@link #title}.
*
* @param visible Boolean indicating if the topbar is visible
*/
public void setTopbarVisible(boolean visible) {
topbar.setVisibility(visible ? View.VISIBLE : View.GONE);
requestLayout();
}
/**
* @return true if the topbar is visible
*/
public boolean getTopbarVisible() {
return topbar.getVisibility() == View.VISIBLE;
}
@Override
protected Parcelable onSaveInstanceState() {
SavedState ss = new SavedState(super.onSaveInstanceState());
ss.color = getSelectionColor();
ss.dateTextAppearance = adapter.getDateTextAppearance();
ss.weekDayTextAppearance = adapter.getWeekDayTextAppearance();
ss.showOtherDates = getShowOtherDates();
ss.allowClickDaysOutsideCurrentMonth = allowClickDaysOutsideCurrentMonth();
ss.minDate = getMinimumDate();
ss.maxDate = getMaximumDate();
ss.selectedDates = getSelectedDates();
ss.firstDayOfWeek = getFirstDayOfWeek();
ss.orientation = getTitleAnimationOrientation();
ss.selectionMode = getSelectionMode();
ss.tileWidthPx = getTileWidth();
ss.tileHeightPx = getTileHeight();
ss.topbarVisible = getTopbarVisible();
ss.calendarMode = calendarMode;
ss.dynamicHeightEnabled = mDynamicHeightEnabled;
ss.currentMonth = currentMonth;
ss.saveCurrentPosition = state.saveCurrentPosition;
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
newState()
.setFirstDayOfWeek(ss.firstDayOfWeek)
.setCalendarDisplayMode(ss.calendarMode)
.setMinimumDate(ss.minDate)
.setMaximumDate(ss.maxDate)
.setSaveCurrentPosition(ss.saveCurrentPosition)
.commit();
setSelectionColor(ss.color);
setDateTextAppearance(ss.dateTextAppearance);
setWeekDayTextAppearance(ss.weekDayTextAppearance);
setShowOtherDates(ss.showOtherDates);
setAllowClickDaysOutsideCurrentMonth(ss.allowClickDaysOutsideCurrentMonth);
clearSelection();
for (CalendarDay calendarDay : ss.selectedDates) {
setDateSelected(calendarDay, true);
}
setTitleAnimationOrientation(ss.orientation);
setTileWidth(ss.tileWidthPx);
setTileHeight(ss.tileHeightPx);
setTopbarVisible(ss.topbarVisible);
setSelectionMode(ss.selectionMode);
setDynamicHeightEnabled(ss.dynamicHeightEnabled);
setCurrentDate(ss.currentMonth);
}
@Override
protected void dispatchSaveInstanceState(@NonNull SparseArray<Parcelable> container) {
dispatchFreezeSelfOnly(container);
}
@Override
protected void dispatchRestoreInstanceState(@NonNull SparseArray<Parcelable> container) {
dispatchThawSelfOnly(container);
}
private void setRangeDates(CalendarDay min, CalendarDay max) {
CalendarDay c = currentMonth;
adapter.setRangeDates(min, max);
currentMonth = c;
if (min != null) {
currentMonth = min.isAfter(currentMonth) ? min : currentMonth;
}
int position = adapter.getIndexForDay(c);
pager.setCurrentItem(position, false);
updateUi();
}
public static class SavedState extends BaseSavedState {
int color = 0;
int dateTextAppearance = 0;
int weekDayTextAppearance = 0;
int showOtherDates = SHOW_DEFAULTS;
boolean allowClickDaysOutsideCurrentMonth = true;
CalendarDay minDate = null;
CalendarDay maxDate = null;
List<CalendarDay> selectedDates = new ArrayList<>();
int firstDayOfWeek = Calendar.SUNDAY;
int orientation = 0;
int tileWidthPx = -1;
int tileHeightPx = -1;
boolean topbarVisible = true;
int selectionMode = SELECTION_MODE_SINGLE;
boolean dynamicHeightEnabled = false;
CalendarMode calendarMode = CalendarMode.MONTHS;
CalendarDay currentMonth = null;
boolean saveCurrentPosition;
SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(@NonNull Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(color);
out.writeInt(dateTextAppearance);
out.writeInt(weekDayTextAppearance);
out.writeInt(showOtherDates);
out.writeByte((byte) (allowClickDaysOutsideCurrentMonth ? 1 : 0));
out.writeParcelable(minDate, 0);
out.writeParcelable(maxDate, 0);
out.writeTypedList(selectedDates);
out.writeInt(firstDayOfWeek);
out.writeInt(orientation);
out.writeInt(tileWidthPx);
out.writeInt(tileHeightPx);
out.writeInt(topbarVisible ? 1 : 0);
out.writeInt(selectionMode);
out.writeInt(dynamicHeightEnabled ? 1 : 0);
out.writeInt(calendarMode == CalendarMode.WEEKS ? 1 : 0);
out.writeParcelable(currentMonth, 0);
out.writeByte((byte) (saveCurrentPosition ? 1 : 0));
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
private SavedState(Parcel in) {
super(in);
color = in.readInt();
dateTextAppearance = in.readInt();
weekDayTextAppearance = in.readInt();
showOtherDates = in.readInt();
allowClickDaysOutsideCurrentMonth = in.readByte() != 0;
ClassLoader loader = CalendarDay.class.getClassLoader();
minDate = in.readParcelable(loader);
maxDate = in.readParcelable(loader);
in.readTypedList(selectedDates, CalendarDay.CREATOR);
firstDayOfWeek = in.readInt();
orientation = in.readInt();
tileWidthPx = in.readInt();
tileHeightPx = in.readInt();
topbarVisible = in.readInt() == 1;
selectionMode = in.readInt();
dynamicHeightEnabled = in.readInt() == 1;
calendarMode = in.readInt() == 1 ? CalendarMode.WEEKS : CalendarMode.MONTHS;
currentMonth = in.readParcelable(loader);
saveCurrentPosition = in.readByte() != 0;
}
}
private static int getThemeAccentColor(Context context) {
int colorAttr;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
colorAttr = android.R.attr.colorAccent;
} else {
//Get colorAccent defined for AppCompat
colorAttr = context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName());
}
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(colorAttr, outValue, true);
return outValue.data;
}
/**
* @return The first day of the week as a {@linkplain Calendar} day constant.
*/
public int getFirstDayOfWeek() {
return firstDayOfWeek;
}
/**
* By default, the calendar will take up all the space needed to show any month (6 rows).
* By enabling dynamic height, the view will change height dependant on the visible month.
* <p>
* This means months that only need 5 or 4 rows to show the entire month will only take up
* that many rows, and will grow and shrink as necessary.
*
* @param useDynamicHeight true to have the view different heights based on the visible month
*/
public void setDynamicHeightEnabled(boolean useDynamicHeight) {
this.mDynamicHeightEnabled = useDynamicHeight;
}
/**
* @return the dynamic height state - true if enabled.
*/
public boolean isDynamicHeightEnabled() {
return mDynamicHeightEnabled;
}
/**
* Add a collection of day decorators
*
* @param decorators decorators to add
*/
public void addDecorators(Collection<? extends DayViewDecorator> decorators) {
if (decorators == null) {
return;
}
dayViewDecorators.addAll(decorators);
adapter.setDecorators(dayViewDecorators);
}
/**
* Add several day decorators
*
* @param decorators decorators to add
*/
public void addDecorators(DayViewDecorator... decorators) {
addDecorators(Arrays.asList(decorators));
}
/**
* Add a day decorator
*
* @param decorator decorator to add
*/
public void addDecorator(DayViewDecorator decorator) {
if (decorator == null) {
return;
}
dayViewDecorators.add(decorator);
adapter.setDecorators(dayViewDecorators);
}
/**
* Remove all decorators
*/
public void removeDecorators() {
dayViewDecorators.clear();
adapter.setDecorators(dayViewDecorators);
}
/**
* Remove a specific decorator instance. Same rules as {@linkplain List#remove(Object)}
*
* @param decorator decorator to remove
*/
public void removeDecorator(DayViewDecorator decorator) {
dayViewDecorators.remove(decorator);
adapter.setDecorators(dayViewDecorators);
}
/**
* Invalidate decorators after one has changed internally. That is, if a decorator mutates, you
* should call this method to update the widget.
*/
public void invalidateDecorators() {
adapter.invalidateDecorators();
}
/*
* Listener/Callback Code
*/
/**
* Sets the listener to be notified upon selected date changes.
*
* @param listener thing to be notified
*/
public void setOnDateChangedListener(OnDateSelectedListener listener) {
this.listener = listener;
}
/**
* Sets the listener to be notified upon month changes.
*
* @param listener thing to be notified
*/
public void setOnMonthChangedListener(OnMonthChangedListener listener) {
this.monthListener = listener;
}
/**
* Sets the listener to be notified upon a range has been selected.
*
* @param listener thing to be notified
*/
public void setOnRangeSelectedListener(OnRangeSelectedListener listener) {
this.rangeListener = listener;
}
/**
* Add listener to the title or null to remove it.
*
* @param listener Listener to be notified.
*/
public void setOnTitleClickListener(final OnClickListener listener) {
if (listener != null) {
title.setOnClickListener(listener);
}
}
/**
* Dispatch date change events to a listener, if set
*
* @param day the day that was selected
* @param selected true if the day is now currently selected, false otherwise
*/
protected void dispatchOnDateSelected(final CalendarDay day, final boolean selected) {
OnDateSelectedListener l = listener;
if (l != null) {
l.onDateSelected(MaterialCalendarView.this, day, selected);
}
}
/**
* Dispatch a range of days to a listener, if set. First day must be before last Day.
*
* @param firstDay first day enclosing a range
* @param lastDay last day enclosing a range
*/
protected void dispatchOnRangeSelected(final CalendarDay firstDay, final CalendarDay lastDay) {
final OnRangeSelectedListener listener = rangeListener;
final List<CalendarDay> days = new ArrayList<>();
final Calendar counter = Calendar.getInstance();
counter.setTime(firstDay.getDate()); // start from the first day and increment
final Calendar end = Calendar.getInstance();
end.setTime(lastDay.getDate()); // for comparison
while (counter.before(end) || counter.equals(end)) {
final CalendarDay current = CalendarDay.from(counter);
adapter.setDateSelected(current, true);
days.add(current);
counter.add(Calendar.DATE, 1);
}
if (listener != null) {
listener.onRangeSelected(MaterialCalendarView.this, days);
}
}
/**
* Dispatch date change events to a listener, if set
*
* @param day first day of the new month
*/
protected void dispatchOnMonthChanged(final CalendarDay day) {
OnMonthChangedListener l = monthListener;
if (l != null) {
l.onMonthChanged(MaterialCalendarView.this, day);
}
}
/**
* Call by {@link CalendarPagerView} to indicate that a day was clicked and we should handle it.
* This method will always process the click to the selected date.
*
* @param date date of the day that was clicked
* @param nowSelected true if the date is now selected, false otherwise
*/
protected void onDateClicked(@NonNull CalendarDay date, boolean nowSelected) {
switch (selectionMode) {
case SELECTION_MODE_MULTIPLE: {
adapter.setDateSelected(date, nowSelected);
dispatchOnDateSelected(date, nowSelected);
}
break;
case SELECTION_MODE_RANGE: {
adapter.setDateSelected(date, nowSelected);
if (adapter.getSelectedDates().size() > 2) {
adapter.clearSelections();
adapter.setDateSelected(date, nowSelected); // re-set because adapter has been cleared
dispatchOnDateSelected(date, nowSelected);
} else if (adapter.getSelectedDates().size() == 2) {
final List<CalendarDay> dates = adapter.getSelectedDates();
if (dates.get(0).isAfter(dates.get(1))) {
dispatchOnRangeSelected(dates.get(1), dates.get(0));
} else {
dispatchOnRangeSelected(dates.get(0), dates.get(1));
}
} else {
adapter.setDateSelected(date, nowSelected);
dispatchOnDateSelected(date, nowSelected);
}
}
break;
default:
case SELECTION_MODE_SINGLE: {
adapter.clearSelections();
adapter.setDateSelected(date, true);
dispatchOnDateSelected(date, true);
}
break;
}
}
/**
* Select a fresh range of date including first day and last day.
*
* @param firstDay first day of the range to select
* @param lastDay last day of the range to select
*/
public void selectRange(final CalendarDay firstDay, final CalendarDay lastDay) {
clearSelection();
if (firstDay.isAfter(lastDay)) {
dispatchOnRangeSelected(lastDay, firstDay);
} else {
dispatchOnRangeSelected(firstDay, lastDay);
}
}
/**
* Call by {@link CalendarPagerView} to indicate that a day was clicked and we should handle it
*
* @param dayView
*/
protected void onDateClicked(final DayView dayView) {
final CalendarDay currentDate = getCurrentDate();
final CalendarDay selectedDate = dayView.getDate();
final int currentMonth = currentDate.getMonth();
final int selectedMonth = selectedDate.getMonth();
if (calendarMode == CalendarMode.MONTHS
&& allowClickDaysOutsideCurrentMonth
&& currentMonth != selectedMonth) {
if (currentDate.isAfter(selectedDate)) {
goToPrevious();
} else if (currentDate.isBefore(selectedDate)) {
goToNext();
}
}
onDateClicked(dayView.getDate(), !dayView.isChecked());
}
/**
* Called by the adapter for cases when changes in state result in dates being unselected
*
* @param date date that should be de-selected
*/
protected void onDateUnselected(CalendarDay date) {
dispatchOnDateSelected(date, false);
}
/*
* Show Other Dates Utils
*/
/**
* @param showOtherDates int flag for show other dates
* @return true if the other months flag is set
*/
public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) {
return (showOtherDates & SHOW_OTHER_MONTHS) != 0;
}
/**
* @param showOtherDates int flag for show other dates
* @return true if the out of range flag is set
*/
public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) {
return (showOtherDates & SHOW_OUT_OF_RANGE) != 0;
}
/**
* @param showOtherDates int flag for show other dates
* @return true if the decorated disabled flag is set
*/
public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) {
return (showOtherDates & SHOW_DECORATED_DISABLED) != 0;
}
/*
* Custom ViewGroup Code
*/
/**
* {@inheritDoc}
*/
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(1);
}
/**
* {@inheritDoc}
*/
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final int specWidthSize = MeasureSpec.getSize(widthMeasureSpec);
final int specWidthMode = MeasureSpec.getMode(widthMeasureSpec);
final int specHeightSize = MeasureSpec.getSize(heightMeasureSpec);
final int specHeightMode = MeasureSpec.getMode(heightMeasureSpec);
//We need to disregard padding for a while. This will be added back later
final int desiredWidth = specWidthSize - getPaddingLeft() - getPaddingRight();
final int desiredHeight = specHeightSize - getPaddingTop() - getPaddingBottom();
final int weekCount = getWeekCountBasedOnMode();
final int viewTileHeight = getTopbarVisible() ? (weekCount + 1) : weekCount;
//Calculate independent tile sizes for later
int desiredTileWidth = desiredWidth / DEFAULT_DAYS_IN_WEEK;
int desiredTileHeight = desiredHeight / viewTileHeight;
int measureTileSize = -1;
int measureTileWidth = -1;
int measureTileHeight = -1;
if (this.tileWidth != INVALID_TILE_DIMENSION || this.tileHeight != INVALID_TILE_DIMENSION) {
if (this.tileWidth > 0) {
//We have a tileWidth set, we should use that
measureTileWidth = this.tileWidth;
} else {
measureTileWidth = desiredTileWidth;
}
if (this.tileHeight > 0) {
//We have a tileHeight set, we should use that
measureTileHeight = this.tileHeight;
} else {
measureTileHeight = desiredTileHeight;
}
} else if (specWidthMode == MeasureSpec.EXACTLY) {
if (specHeightMode == MeasureSpec.EXACTLY) {
//Pick the larger of the two explicit sizes
measureTileSize = Math.max(desiredTileWidth, desiredTileHeight);
} else {
//Be the width size the user wants
measureTileSize = desiredTileWidth;
}
} else if (specHeightMode == MeasureSpec.EXACTLY) {
//Be the height size the user wants
measureTileSize = desiredTileHeight;
}
if (measureTileSize > 0) {
//Use measureTileSize if set
measureTileHeight = measureTileSize;
measureTileWidth = measureTileSize;
} else if (measureTileSize <= 0) {
if (measureTileWidth <= 0) {
//Set width to default if no value were set
measureTileWidth = dpToPx(DEFAULT_TILE_SIZE_DP);
}
if (measureTileHeight <= 0) {
//Set height to default if no value were set
measureTileHeight = dpToPx(DEFAULT_TILE_SIZE_DP);
}
}
//Calculate our size based off our measured tile size
int measuredWidth = measureTileWidth * DEFAULT_DAYS_IN_WEEK;
int measuredHeight = measureTileHeight * viewTileHeight;
//Put padding back in from when we took it away
measuredWidth += getPaddingLeft() + getPaddingRight();
measuredHeight += getPaddingTop() + getPaddingBottom();
//Contract fulfilled, setting out measurements
setMeasuredDimension(
//We clamp inline because we want to use un-clamped versions on the children
clampSize(measuredWidth, widthMeasureSpec),
clampSize(measuredHeight, heightMeasureSpec)
);
int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
LayoutParams p = (LayoutParams) child.getLayoutParams();
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
DEFAULT_DAYS_IN_WEEK * measureTileWidth,
MeasureSpec.EXACTLY
);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
p.height * measureTileHeight,
MeasureSpec.EXACTLY
);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
private int getWeekCountBasedOnMode() {
int weekCount = calendarMode.visibleWeeksCount;
boolean isInMonthsMode = calendarMode.equals(CalendarMode.MONTHS);
if (isInMonthsMode && mDynamicHeightEnabled && adapter != null && pager != null) {
Calendar cal = (Calendar) adapter.getItem(pager.getCurrentItem()).getCalendar().clone();
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
//noinspection ResourceType
cal.setFirstDayOfWeek(getFirstDayOfWeek());
weekCount = cal.get(Calendar.WEEK_OF_MONTH);
}
return weekCount + DAY_NAMES_ROW;
}
/**
* Clamp the size to the measure spec.
*
* @param size Size we want to be
* @param spec Measure spec to clamp against
* @return the appropriate size to pass to {@linkplain View#setMeasuredDimension(int, int)}
*/
private static int clampSize(int size, int spec) {
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
switch (specMode) {
case MeasureSpec.EXACTLY: {
return specSize;
}
case MeasureSpec.AT_MOST: {
return Math.min(size, specSize);
}
case MeasureSpec.UNSPECIFIED:
default: {
return size;
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int count = getChildCount();
final int parentLeft = getPaddingLeft();
final int parentWidth = right - left - parentLeft - getPaddingRight();
int childTop = getPaddingTop();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == View.GONE) {
continue;
}
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int delta = (parentWidth - width) / 2;
int childLeft = parentLeft + delta;
child.layout(childLeft, childTop, childLeft + width, childTop + height);
childTop += height;
}
}
/**
* {@inheritDoc}
*/
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(1);
}
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(1);
}
@Override
public void onInitializeAccessibilityEvent(@NonNull AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(MaterialCalendarView.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(MaterialCalendarView.class.getName());
}
/**
* Simple layout params for MaterialCalendarView. The only variation for layout is height.
*/
protected static class LayoutParams extends MarginLayoutParams {
/**
* Create a layout that matches parent width, and is X number of tiles high
*
* @param tileHeight view height in number of tiles
*/
public LayoutParams(int tileHeight) {
super(MATCH_PARENT, tileHeight);
}
}
/**
* Enable or disable the ability to swipe between months.
*
* @param pagingEnabled pass false to disable paging, true to enable (default)
*/
public void setPagingEnabled(boolean pagingEnabled) {
pager.setPagingEnabled(pagingEnabled);
updateUi();
}
/**
* @return true if swiping months is enabled, false if disabled. Default is true.
*/
public boolean isPagingEnabled() {
return pager.isPagingEnabled();
}
/**
* Preserve the current parameters of the Material Calendar View.
*/
public State state() {
return state;
}
/**
* Initialize the parameters from scratch.
*/
public StateBuilder newState() {
return new StateBuilder();
}
public class State {
public final CalendarMode calendarMode;
public final int firstDayOfWeek;
public final CalendarDay minDate;
public final CalendarDay maxDate;
public final boolean saveCurrentPosition;
public State(StateBuilder builder) {
calendarMode = builder.calendarMode;
firstDayOfWeek = builder.firstDayOfWeek;
minDate = builder.minDate;
maxDate = builder.maxDate;
saveCurrentPosition = builder.saveCurrentPosition;
}
/**
* Modify parameters from current state.
*/
public StateBuilder edit() {
return new StateBuilder(this);
}
}
public class StateBuilder {
private CalendarMode calendarMode = CalendarMode.MONTHS;
private int firstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek();
public CalendarDay minDate = null;
public CalendarDay maxDate = null;
public boolean saveCurrentPosition = false;
public StateBuilder() {
}
private StateBuilder(final State state) {
calendarMode = state.calendarMode;
firstDayOfWeek = state.firstDayOfWeek;
minDate = state.minDate;
maxDate = state.maxDate;
saveCurrentPosition = state.saveCurrentPosition;
}
/**
* Sets the first day of the week.
* <p>
* Uses the java.util.Calendar day constants.
*
* @param day The first day of the week as a java.util.Calendar day constant.
* @see java.util.Calendar
*/
public StateBuilder setFirstDayOfWeek(int day) {
this.firstDayOfWeek = day;
return this;
}
/**
* Set calendar display mode. The default mode is Months.
* When switching between modes will select todays date, or the selected date,
* if selection mode is single.
*
* @param mode - calendar mode
*/
public StateBuilder setCalendarDisplayMode(CalendarMode mode) {
this.calendarMode = mode;
return this;
}
/**
* @param calendar set the minimum selectable date, null for no minimum
*/
public StateBuilder setMinimumDate(@Nullable Calendar calendar) {
setMinimumDate(CalendarDay.from(calendar));
return this;
}
/**
* @param date set the minimum selectable date, null for no minimum
*/
public StateBuilder setMinimumDate(@Nullable Date date) {
setMinimumDate(CalendarDay.from(date));
return this;
}
/**
* @param calendar set the minimum selectable date, null for no minimum
*/
public StateBuilder setMinimumDate(@Nullable CalendarDay calendar) {
minDate = calendar;
return this;
}
/**
* @param calendar set the maximum selectable date, null for no maximum
*/
public StateBuilder setMaximumDate(@Nullable Calendar calendar) {
setMaximumDate(CalendarDay.from(calendar));
return this;
}
/**
* @param date set the maximum selectable date, null for no maximum
*/
public StateBuilder setMaximumDate(@Nullable Date date) {
setMaximumDate(CalendarDay.from(date));
return this;
}
/**
* @param calendar set the maximum selectable date, null for no maximum
*/
public StateBuilder setMaximumDate(@Nullable CalendarDay calendar) {
maxDate = calendar;
return this;
}
/**
* Use this method to enable saving the current position when switching
* between week and month mode.
*
* @param saveCurrentPosition Set to true to save the current position, false otherwise.
*/
public StateBuilder setSaveCurrentPosition(final boolean saveCurrentPosition) {
this.saveCurrentPosition = saveCurrentPosition;
return this;
}
public void commit() {
MaterialCalendarView.this.commit(new State(this));
}
}
private void commit(State state) {
// Use the calendarDayToShow to determine which date to focus on for the case of switching between month and week views
CalendarDay calendarDayToShow = null;
if (adapter != null && state.saveCurrentPosition) {
calendarDayToShow = adapter.getItem(pager.getCurrentItem());
if (calendarMode != state.calendarMode) {
CalendarDay currentlySelectedDate = getSelectedDate();
if (calendarMode == CalendarMode.MONTHS && currentlySelectedDate != null) {
// Going from months to weeks
Calendar lastVisibleCalendar = calendarDayToShow.getCalendar();
lastVisibleCalendar.add(Calendar.MONTH, 1);
CalendarDay lastVisibleCalendarDay = CalendarDay.from(lastVisibleCalendar);
if (currentlySelectedDate.equals(calendarDayToShow) ||
(currentlySelectedDate.isAfter(calendarDayToShow) && currentlySelectedDate.isBefore(lastVisibleCalendarDay))) {
// Currently selected date is within view, so center on that
calendarDayToShow = currentlySelectedDate;
}
} else if (calendarMode == CalendarMode.WEEKS) {
// Going from weeks to months
Calendar lastVisibleCalendar = calendarDayToShow.getCalendar();
lastVisibleCalendar.add(Calendar.DAY_OF_WEEK, 6);
CalendarDay lastVisibleCalendarDay = CalendarDay.from(lastVisibleCalendar);
if (currentlySelectedDate != null &&
(currentlySelectedDate.equals(calendarDayToShow) || currentlySelectedDate.equals(lastVisibleCalendarDay) ||
(currentlySelectedDate.isAfter(calendarDayToShow) && currentlySelectedDate.isBefore(lastVisibleCalendarDay)))) {
// Currently selected date is within view, so center on that
calendarDayToShow = currentlySelectedDate;
} else {
calendarDayToShow = lastVisibleCalendarDay;
}
}
}
}
this.state = state;
// Save states parameters
calendarMode = state.calendarMode;
firstDayOfWeek = state.firstDayOfWeek;
minDate = state.minDate;
maxDate = state.maxDate;
// Recreate adapter
final CalendarPagerAdapter<?> newAdapter;
switch (calendarMode) {
case MONTHS:
newAdapter = new MonthPagerAdapter(this);
break;
case WEEKS:
newAdapter = new WeekPagerAdapter(this);
break;
default:
throw new IllegalArgumentException("Provided display mode which is not yet implemented");
}
if (adapter == null) {
adapter = newAdapter;
} else {
adapter = adapter.migrateStateAndReturn(newAdapter);
}
pager.setAdapter(adapter);
setRangeDates(minDate, maxDate);
// Reset height params after mode change
pager.setLayoutParams(new LayoutParams(calendarMode.visibleWeeksCount + DAY_NAMES_ROW));
setCurrentDate(
selectionMode == SELECTION_MODE_SINGLE && !adapter.getSelectedDates().isEmpty()
? adapter.getSelectedDates().get(0)
: CalendarDay.today());
if (calendarDayToShow != null) {
pager.setCurrentItem(adapter.getIndexForDay(calendarDayToShow));
}
invalidateDecorators();
updateUi();
}
} |
package com.prolificinteractive.materialcalendarview;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.ArrayRes;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter;
import com.prolificinteractive.materialcalendarview.format.DateFormatTitleFormatter;
import com.prolificinteractive.materialcalendarview.format.DayFormatter;
import com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter;
import com.prolificinteractive.materialcalendarview.format.TitleFormatter;
import com.prolificinteractive.materialcalendarview.format.WeekDayFormatter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
* <p>
* This class is a calendar widget for displaying and selecting dates.
* The range of dates supported by this calendar is configurable.
* A user can select a date by taping on it and can page the calendar to a desired date.
* </p>
* <p>
* By default, the range of dates shown is from 200 years in the past to 200 years in the future.
* This can be extended or shortened by configuring the minimum and maximum dates.
* </p>
* <p>
* When selecting a date out of range, or when the range changes so the selection becomes outside,
* The date closest to the previous selection will become selected. This will also trigger the
* {@linkplain OnDateSelectedListener}
* </p>
* <p>
* <strong>Note:</strong> if this view's size isn't divisible by 7,
* the contents will be centered inside such that the days in the calendar are equally square.
* For example, 600px isn't divisible by 7, so a tile size of 85 is choosen, making the calendar
* 595px wide. The extra 5px are distributed left and right to get to 600px.
* </p>
*/
public class MaterialCalendarView extends ViewGroup {
/**
* {@linkplain IntDef} annotation for selection mode.
*
* @see #setSelectionMode(int)
* @see #getSelectionMode()
*/
@Retention(RetentionPolicy.RUNTIME)
@IntDef({SELECTION_MODE_NONE, SELECTION_MODE_SINGLE, SELECTION_MODE_MULTIPLE})
public @interface SelectionMode {
}
/**
* Selection mode that disallows all selection.
* When changing to this mode, current selection will be cleared.
*/
public static final int SELECTION_MODE_NONE = 0;
/**
* Selection mode that allows one selected date at one time. This is the default mode.
* When switching from {@linkplain #SELECTION_MODE_MULTIPLE}, this will select the same date
* as from {@linkplain #getSelectedDate()}, which should be the last selected date
*/
public static final int SELECTION_MODE_SINGLE = 1;
/**
* Selection mode which allows more than one selected date at one time.
*/
public static final int SELECTION_MODE_MULTIPLE = 2;
/**
* {@linkplain IntDef} annotation for showOtherDates.
*
* @see #setShowOtherDates(int)
* @see #getShowOtherDates()
*/
@SuppressLint("UniqueConstants")
@Retention(RetentionPolicy.RUNTIME)
@IntDef(flag = true, value = {
SHOW_NONE, SHOW_ALL, SHOW_DEFAULTS,
SHOW_OUT_OF_RANGE, SHOW_OTHER_MONTHS, SHOW_DECORATED_DISABLED
})
public @interface ShowOtherDates {
}
/**
* Do not show any non-enabled dates
*/
public static final int SHOW_NONE = 0;
/**
* Show dates from the proceeding and successive months, in a disabled state.
* This flag also enables the {@link #SHOW_OUT_OF_RANGE} flag to prevent odd blank areas.
*/
public static final int SHOW_OTHER_MONTHS = 1;
/**
* Show dates that are outside of the min-max range.
* This will only show days from the current month unless {@link #SHOW_OTHER_MONTHS} is enabled.
*/
public static final int SHOW_OUT_OF_RANGE = 2;
/**
* Show days that are individually disabled with decorators.
* This will only show dates in the current month and inside the minimum and maximum date range.
*/
public static final int SHOW_DECORATED_DISABLED = 4;
/**
* The default flags for showing non-enabled dates. Currently only shows {@link #SHOW_DECORATED_DISABLED}
*/
public static final int SHOW_DEFAULTS = SHOW_DECORATED_DISABLED;
/**
* Show all the days
*/
public static final int SHOW_ALL = SHOW_OTHER_MONTHS | SHOW_OUT_OF_RANGE | SHOW_DECORATED_DISABLED;
/**
* Default tile size in DIPs. This is used in cases where there is no tile size specificed and the view is set to {@linkplain ViewGroup.LayoutParams#WRAP_CONTENT WRAP_CONTENT}
*/
public static final int DEFAULT_TILE_SIZE_DP = 44;
private static final int DEFAULT_DAYS_IN_WEEK = 7;
private static final int DAY_NAMES_ROW = 1;
private static final TitleFormatter DEFAULT_TITLE_FORMATTER = new DateFormatTitleFormatter();
private final TitleChanger titleChanger;
private final TextView title;
private final DirectionButton buttonPast;
private final DirectionButton buttonFuture;
private final CalendarPager pager;
private CalendarPagerAdapter<?> adapter;
private CalendarDay currentMonth;
private LinearLayout topbar;
private CalendarMode calendarMode = CalendarMode.MONTHS;
/**
* Used for the dynamic calendar height.
*/
private boolean mDynamicHeightEnabled;
private final ArrayList<DayViewDecorator> dayViewDecorators = new ArrayList<>();
private final OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (v == buttonFuture) {
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
} else if (v == buttonPast) {
pager.setCurrentItem(pager.getCurrentItem() - 1, true);
}
}
};
private final ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
titleChanger.setPreviousMonth(currentMonth);
currentMonth = adapter.getItem(position);
updateUi();
dispatchOnMonthChanged(currentMonth);
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
};
private CalendarDay minDate = null;
private CalendarDay maxDate = null;
private OnDateSelectedListener listener;
private OnMonthChangedListener monthListener;
private int accentColor = 0;
private int arrowColor = Color.BLACK;
private Drawable leftArrowMask;
private Drawable rightArrowMask;
private int tileSize = -1;
@SelectionMode
private int selectionMode = SELECTION_MODE_SINGLE;
public MaterialCalendarView(Context context) {
this(context, null);
}
public MaterialCalendarView(Context context, AttributeSet attrs) {
super(context, attrs);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//If we're on good Android versions, turn off clipping for cool effects
setClipToPadding(false);
setClipChildren(false);
} else {
//Old Android does not like _not_ clipping view pagers, we need to clip
setClipChildren(true);
setClipToPadding(true);
}
buttonPast = new DirectionButton(getContext());
title = new TextView(getContext());
buttonFuture = new DirectionButton(getContext());
pager = new CalendarPager(getContext());
setupChildren();
title.setOnClickListener(onClickListener);
buttonPast.setOnClickListener(onClickListener);
buttonFuture.setOnClickListener(onClickListener);
titleChanger = new TitleChanger(title);
titleChanger.setTitleFormatter(DEFAULT_TITLE_FORMATTER);
adapter = new MonthPagerAdapter(this);
adapter.setTitleFormatter(DEFAULT_TITLE_FORMATTER);
pager.setAdapter(adapter);
pager.setOnPageChangeListener(pageChangeListener);
pager.setPageTransformer(false, new ViewPager.PageTransformer() {
@Override
public void transformPage(View page, float position) {
position = (float) Math.sqrt(1 - Math.abs(position));
page.setAlpha(position);
}
});
TypedArray a = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.MaterialCalendarView, 0, 0);
try {
int tileSize = a.getDimensionPixelSize(R.styleable.MaterialCalendarView_mcv_tileSize, -1);
if (tileSize > 0) {
setTileSize(tileSize);
}
setArrowColor(a.getColor(
R.styleable.MaterialCalendarView_mcv_arrowColor,
Color.BLACK
));
Drawable leftMask = a.getDrawable(
R.styleable.MaterialCalendarView_mcv_leftArrowMask
);
if (leftMask == null) {
leftMask = getResources().getDrawable(R.drawable.mcv_action_previous);
}
setLeftArrowMask(leftMask);
Drawable rightMask = a.getDrawable(
R.styleable.MaterialCalendarView_mcv_rightArrowMask
);
if (rightMask == null) {
rightMask = getResources().getDrawable(R.drawable.mcv_action_next);
}
setRightArrowMask(rightMask);
setSelectionColor(
a.getColor(
R.styleable.MaterialCalendarView_mcv_selectionColor,
getThemeAccentColor(context)
)
);
CharSequence[] array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_weekDayLabels);
if (array != null) {
setWeekDayFormatter(new ArrayWeekDayFormatter(array));
}
array = a.getTextArray(R.styleable.MaterialCalendarView_mcv_monthLabels);
if (array != null) {
setTitleFormatter(new MonthArrayTitleFormatter(array));
}
setHeaderTextAppearance(a.getResourceId(
R.styleable.MaterialCalendarView_mcv_headerTextAppearance,
R.style.TextAppearance_MaterialCalendarWidget_Header
));
setWeekDayTextAppearance(a.getResourceId(
R.styleable.MaterialCalendarView_mcv_weekDayTextAppearance,
R.style.TextAppearance_MaterialCalendarWidget_WeekDay
));
setDateTextAppearance(a.getResourceId(
R.styleable.MaterialCalendarView_mcv_dateTextAppearance,
R.style.TextAppearance_MaterialCalendarWidget_Date
));
//noinspection ResourceType
setShowOtherDates(a.getInteger(
R.styleable.MaterialCalendarView_mcv_showOtherDates,
SHOW_DEFAULTS
));
int firstDayOfWeek = a.getInteger(
R.styleable.MaterialCalendarView_mcv_firstDayOfWeek,
-1
);
if (firstDayOfWeek < 0) {
//Allowing use of Calendar.getInstance() here as a performance optimization
firstDayOfWeek = Calendar.getInstance().getFirstDayOfWeek();
}
setFirstDayOfWeek(firstDayOfWeek);
} catch (Exception e) {
e.printStackTrace();
} finally {
a.recycle();
}
currentMonth = CalendarDay.today();
setCurrentDate(currentMonth);
if (isInEditMode()) {
removeView(pager);
MonthView monthView = new MonthView(this, currentMonth, getFirstDayOfWeek());
monthView.setSelectionColor(getSelectionColor());
monthView.setDateTextAppearance(adapter.getDateTextAppearance());
monthView.setWeekDayTextAppearance(adapter.getWeekDayTextAppearance());
monthView.setShowOtherDates(getShowOtherDates());
addView(monthView, new LayoutParams(calendarMode.visibleWeeksCount + DAY_NAMES_ROW));
}
}
private void setupChildren() {
topbar = new LinearLayout(getContext());
topbar.setOrientation(LinearLayout.HORIZONTAL);
topbar.setClipChildren(false);
topbar.setClipToPadding(false);
addView(topbar, new LayoutParams(1));
buttonPast.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
buttonPast.setImageResource(R.drawable.mcv_action_previous);
topbar.addView(buttonPast, new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1));
title.setGravity(Gravity.CENTER);
topbar.addView(title, new LinearLayout.LayoutParams(
0, LayoutParams.MATCH_PARENT, DEFAULT_DAYS_IN_WEEK - 2
));
buttonFuture.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
buttonFuture.setImageResource(R.drawable.mcv_action_next);
topbar.addView(buttonFuture, new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1));
pager.setId(R.id.mcv_pager);
pager.setOffscreenPageLimit(1);
addView(pager, new LayoutParams(calendarMode.visibleWeeksCount + DAY_NAMES_ROW));
}
private void updateUi() {
titleChanger.change(currentMonth);
buttonPast.setEnabled(canGoBack());
buttonFuture.setEnabled(canGoForward());
}
/**
* Change the selection mode of the calendar. The default mode is {@linkplain #SELECTION_MODE_SINGLE}
*
* @param mode the selection mode to change to. This must be one of
* {@linkplain #SELECTION_MODE_NONE}, {@linkplain #SELECTION_MODE_SINGLE}, or {@linkplain #SELECTION_MODE_MULTIPLE}.
* Unknown values will act as {@linkplain #SELECTION_MODE_SINGLE}
* @see #getSelectionMode()
* @see #SELECTION_MODE_NONE
* @see #SELECTION_MODE_SINGLE
* @see #SELECTION_MODE_MULTIPLE
*/
public void setSelectionMode(final @SelectionMode int mode) {
final @SelectionMode int oldMode = this.selectionMode;
switch (mode) {
case SELECTION_MODE_MULTIPLE: {
this.selectionMode = SELECTION_MODE_MULTIPLE;
}
break;
default:
case SELECTION_MODE_SINGLE: {
this.selectionMode = SELECTION_MODE_SINGLE;
if (oldMode == SELECTION_MODE_MULTIPLE) {
//We should only have one selection now, so we should pick one
List<CalendarDay> dates = getSelectedDates();
if (!dates.isEmpty()) {
setSelectedDate(getSelectedDate());
}
}
}
break;
case SELECTION_MODE_NONE: {
this.selectionMode = SELECTION_MODE_NONE;
if (oldMode != SELECTION_MODE_NONE) {
//No selection! Clear out!
clearSelection();
}
}
break;
}
adapter.setSelectionEnabled(selectionMode != SELECTION_MODE_NONE);
}
/**
* Set calendar display mode. The default mode is Months.
* When switching between modes will select todays date, or the selected date,
* if selection mode is single.
*
* @param mode - calendar mode
*/
public void setCalendarDisplayMode(CalendarMode mode) {
if (calendarMode.equals(mode)) {
return;
}
CalendarPagerAdapter<?> newAdapter;
switch (mode) {
case MONTHS:
newAdapter = new MonthPagerAdapter(this);
break;
case WEEKS:
newAdapter = new WeekPagerAdapter(this);
break;
default:
throw new IllegalArgumentException("Provided display mode which is not yet implemented");
}
adapter = adapter.migrateStateAndReturn(newAdapter);
pager.setAdapter(adapter);
calendarMode = mode;
setCurrentDate(
selectionMode == SELECTION_MODE_SINGLE && !adapter.getSelectedDates().isEmpty()
? adapter.getSelectedDates().get(0)
: CalendarDay.today());
invalidateDecorators();
updateUi();
}
/**
* Get the current selection mode. The default mode is {@linkplain #SELECTION_MODE_SINGLE}
*
* @return the current selection mode
* @see #setSelectionMode(int)
* @see #SELECTION_MODE_NONE
* @see #SELECTION_MODE_SINGLE
* @see #SELECTION_MODE_MULTIPLE
*/
@SelectionMode
public int getSelectionMode() {
return selectionMode;
}
/**
* @return the size of tiles in pixels
*/
public int getTileSize() {
return tileSize;
}
/**
* Set the size of each tile that makes up the calendar.
* Each day is 1 tile, so the widget is 7 tiles wide and 7 or 8 tiles tall
* depending on the visibility of the {@link #topbar}.
*
* @param size the new size for each tile in pixels
*/
public void setTileSize(int size) {
this.tileSize = size;
requestLayout();
}
/**
* @param tileSizeDp the new size for each tile in dips
* @see #setTileSize(int)
*/
public void setTileSizeDp(int tileSizeDp) {
setTileSize(dpToPx(tileSizeDp));
}
private int dpToPx(int dp) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()
);
}
/**
* TODO should this be public?
*
* @return true if there is a future month that can be shown
*/
private boolean canGoForward() {
return pager.getCurrentItem() < (adapter.getCount() - 1);
}
/**
* Pass all touch events to the pager so scrolling works on the edges of the calendar view.
*
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
return pager.dispatchTouchEvent(event);
}
/**
* TODO should this be public?
*
* @return true if there is a previous month that can be shown
*/
private boolean canGoBack() {
return pager.getCurrentItem() > 0;
}
/**
* @return the color used for the selection
*/
public int getSelectionColor() {
return accentColor;
}
/**
* @param color The selection color
*/
public void setSelectionColor(int color) {
if (color == 0) {
if (!isInEditMode()) {
return;
} else {
color = Color.GRAY;
}
}
accentColor = color;
adapter.setSelectionColor(color);
invalidate();
}
/**
* @return color used to draw arrows
*/
public int getArrowColor() {
return arrowColor;
}
/**
* @param color the new color for the paging arrows
*/
public void setArrowColor(int color) {
if (color == 0) {
return;
}
arrowColor = color;
buttonPast.setColor(color);
buttonFuture.setColor(color);
invalidate();
}
/**
* @return icon used for the left arrow
*/
public Drawable getLeftArrowMask() {
return leftArrowMask;
}
/**
* @param icon the new icon to use for the left paging arrow
*/
public void setLeftArrowMask(Drawable icon) {
leftArrowMask = icon;
buttonPast.setImageDrawable(icon);
}
/**
* @return icon used for the right arrow
*/
public Drawable getRightArrowMask() {
return rightArrowMask;
}
/**
* @param icon the new icon to use for the right paging arrow
*/
public void setRightArrowMask(Drawable icon) {
rightArrowMask = icon;
buttonFuture.setImageDrawable(icon);
}
/**
* @param resourceId The text appearance resource id.
*/
public void setHeaderTextAppearance(int resourceId) {
title.setTextAppearance(getContext(), resourceId);
}
/**
* @param resourceId The text appearance resource id.
*/
public void setDateTextAppearance(int resourceId) {
adapter.setDateTextAppearance(resourceId);
}
/**
* @param resourceId The text appearance resource id.
*/
public void setWeekDayTextAppearance(int resourceId) {
adapter.setWeekDayTextAppearance(resourceId);
}
/**
* @return the selected day, or null if no selection. If in multiple selection mode, this
* will return the last selected date
*/
public CalendarDay getSelectedDate() {
List<CalendarDay> dates = adapter.getSelectedDates();
if (dates.isEmpty()) {
return null;
} else {
return dates.get(dates.size() - 1);
}
}
/**
* @return all of the currently selected dates
*/
@NonNull
public List<CalendarDay> getSelectedDates() {
return adapter.getSelectedDates();
}
/**
* Clear the currently selected date(s)
*/
public void clearSelection() {
List<CalendarDay> dates = getSelectedDates();
adapter.clearSelections();
for (CalendarDay day : dates) {
dispatchOnDateSelected(day, false);
}
}
/**
* @param calendar a Calendar set to a day to select. Null to clear selection
*/
public void setSelectedDate(@Nullable Calendar calendar) {
setSelectedDate(CalendarDay.from(calendar));
}
/**
* @param date a Date to set as selected. Null to clear selection
*/
public void setSelectedDate(@Nullable Date date) {
setSelectedDate(CalendarDay.from(date));
}
/**
* @param date a Date to set as selected. Null to clear selection
*/
public void setSelectedDate(@Nullable CalendarDay date) {
clearSelection();
if (date != null) {
setDateSelected(date, true);
}
}
/**
* @param calendar a Calendar to change. Passing null does nothing
* @param selected true if day should be selected, false to deselect
*/
public void setDateSelected(@Nullable Calendar calendar, boolean selected) {
setDateSelected(CalendarDay.from(calendar), selected);
}
/**
* @param date a Date to change. Passing null does nothing
* @param selected true if day should be selected, false to deselect
*/
public void setDateSelected(@Nullable Date date, boolean selected) {
setDateSelected(CalendarDay.from(date), selected);
}
/**
* @param day a CalendarDay to change. Passing null does nothing
* @param selected true if day should be selected, false to deselect
*/
public void setDateSelected(@Nullable CalendarDay day, boolean selected) {
if (day == null) {
return;
}
adapter.setDateSelected(day, selected);
}
/**
* @param calendar a Calendar set to a day to focus the calendar on. Null will do nothing
*/
public void setCurrentDate(@Nullable Calendar calendar) {
setCurrentDate(CalendarDay.from(calendar));
}
/**
* @param date a Date to focus the calendar on. Null will do nothing
*/
public void setCurrentDate(@Nullable Date date) {
setCurrentDate(CalendarDay.from(date));
}
/**
* @return The current month shown, will be set to first day of the month
*/
public CalendarDay getCurrentDate() {
return adapter.getItem(pager.getCurrentItem());
}
/**
* @param day a CalendarDay to focus the calendar on. Null will do nothing
*/
public void setCurrentDate(@Nullable CalendarDay day) {
setCurrentDate(day, true);
}
/**
* @param day a CalendarDay to focus the calendar on. Null will do nothing
* @param useSmoothScroll use smooth scroll when changing months.
*/
public void setCurrentDate(@Nullable CalendarDay day, boolean useSmoothScroll) {
if (day == null) {
return;
}
int index = adapter.getIndexForDay(day);
pager.setCurrentItem(index, useSmoothScroll);
updateUi();
}
/**
* @return the minimum selectable date for the calendar, if any
*/
public CalendarDay getMinimumDate() {
return minDate;
}
/**
* @param calendar set the minimum selectable date, null for no minimum
*/
public void setMinimumDate(@Nullable Calendar calendar) {
setMinimumDate(CalendarDay.from(calendar));
}
/**
* @param date set the minimum selectable date, null for no minimum
*/
public void setMinimumDate(@Nullable Date date) {
setMinimumDate(CalendarDay.from(date));
}
/**
* @param calendar set the minimum selectable date, null for no minimum
*/
public void setMinimumDate(@Nullable CalendarDay calendar) {
minDate = calendar;
setRangeDates(minDate, maxDate);
}
/**
* @return the maximum selectable date for the calendar, if any
*/
public CalendarDay getMaximumDate() {
return maxDate;
}
/**
* @param calendar set the maximum selectable date, null for no maximum
*/
public void setMaximumDate(@Nullable Calendar calendar) {
setMaximumDate(CalendarDay.from(calendar));
}
/**
* @param date set the maximum selectable date, null for no maximum
*/
public void setMaximumDate(@Nullable Date date) {
setMaximumDate(CalendarDay.from(date));
}
/**
* @param calendar set the maximum selectable date, null for no maximum
*/
public void setMaximumDate(@Nullable CalendarDay calendar) {
maxDate = calendar;
setRangeDates(minDate, maxDate);
}
/**
* The default value is {@link #SHOW_DEFAULTS}, which currently is just {@link #SHOW_DECORATED_DISABLED}.
* This means that the default visible days are of the current month, in the min-max range.
*
* @param showOtherDates flags for showing non-enabled dates
* @see #SHOW_ALL
* @see #SHOW_NONE
* @see #SHOW_DEFAULTS
* @see #SHOW_OTHER_MONTHS
* @see #SHOW_OUT_OF_RANGE
* @see #SHOW_DECORATED_DISABLED
*/
public void setShowOtherDates(@ShowOtherDates int showOtherDates) {
adapter.setShowOtherDates(showOtherDates);
}
/**
* Set a formatter for weekday labels.
*
* @param formatter the new formatter, null for default
*/
public void setWeekDayFormatter(WeekDayFormatter formatter) {
adapter.setWeekDayFormatter(formatter == null ? WeekDayFormatter.DEFAULT : formatter);
}
/**
* Set a formatter for day labels.
*
* @param formatter the new formatter, null for default
*/
public void setDayFormatter(DayFormatter formatter) {
adapter.setDayFormatter(formatter == null ? DayFormatter.DEFAULT : formatter);
}
/**
* Set a {@linkplain com.prolificinteractive.materialcalendarview.format.WeekDayFormatter}
* with the provided week day labels
*
* @param weekDayLabels Labels to use for the days of the week
* @see com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter
* @see #setWeekDayFormatter(com.prolificinteractive.materialcalendarview.format.WeekDayFormatter)
*/
public void setWeekDayLabels(CharSequence[] weekDayLabels) {
setWeekDayFormatter(new ArrayWeekDayFormatter(weekDayLabels));
}
/**
* Set a {@linkplain com.prolificinteractive.materialcalendarview.format.WeekDayFormatter}
* with the provided week day labels
*
* @param arrayRes String array resource of week day labels
* @see com.prolificinteractive.materialcalendarview.format.ArrayWeekDayFormatter
* @see #setWeekDayFormatter(com.prolificinteractive.materialcalendarview.format.WeekDayFormatter)
*/
public void setWeekDayLabels(@ArrayRes int arrayRes) {
setWeekDayLabels(getResources().getTextArray(arrayRes));
}
/**
* @return int of flags used for showing non-enabled dates
* @see #SHOW_ALL
* @see #SHOW_NONE
* @see #SHOW_DEFAULTS
* @see #SHOW_OTHER_MONTHS
* @see #SHOW_OUT_OF_RANGE
* @see #SHOW_DECORATED_DISABLED
*/
@ShowOtherDates
public int getShowOtherDates() {
return adapter.getShowOtherDates();
}
/**
* Set a custom formatter for the month/year title
*
* @param titleFormatter new formatter to use, null to use default formatter
*/
public void setTitleFormatter(TitleFormatter titleFormatter) {
if (titleFormatter == null) {
titleFormatter = DEFAULT_TITLE_FORMATTER;
}
titleChanger.setTitleFormatter(titleFormatter);
adapter.setTitleFormatter(titleFormatter);
updateUi();
}
/**
* Set a {@linkplain com.prolificinteractive.materialcalendarview.format.TitleFormatter}
* using the provided month labels
*
* @param monthLabels month labels to use
* @see com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter
* @see #setTitleFormatter(com.prolificinteractive.materialcalendarview.format.TitleFormatter)
*/
public void setTitleMonths(CharSequence[] monthLabels) {
setTitleFormatter(new MonthArrayTitleFormatter(monthLabels));
}
/**
* Set a {@linkplain com.prolificinteractive.materialcalendarview.format.TitleFormatter}
* using the provided month labels
*
* @param arrayRes String array resource of month labels to use
* @see com.prolificinteractive.materialcalendarview.format.MonthArrayTitleFormatter
* @see #setTitleFormatter(com.prolificinteractive.materialcalendarview.format.TitleFormatter)
*/
public void setTitleMonths(@ArrayRes int arrayRes) {
setTitleMonths(getResources().getTextArray(arrayRes));
}
/**
* Sets the visibility {@link #topbar}, which contains
* the previous month button {@link #buttonPast}, next month button {@link #buttonFuture},
* and the month title {@link #title}.
*
* @param visible Boolean indicating if the topbar is visible
*/
public void setTopbarVisible(boolean visible) {
topbar.setVisibility(visible ? View.VISIBLE : View.GONE);
requestLayout();
}
/**
* @return true if the topbar is visible
*/
public boolean getTopbarVisible() {
return topbar.getVisibility() == View.VISIBLE;
}
@Override
protected Parcelable onSaveInstanceState() {
SavedState ss = new SavedState(super.onSaveInstanceState());
ss.color = getSelectionColor();
ss.dateTextAppearance = adapter.getDateTextAppearance();
ss.weekDayTextAppearance = adapter.getWeekDayTextAppearance();
ss.showOtherDates = getShowOtherDates();
ss.minDate = getMinimumDate();
ss.maxDate = getMaximumDate();
ss.selectedDates = getSelectedDates();
ss.firstDayOfWeek = getFirstDayOfWeek();
ss.selectionMode = getSelectionMode();
ss.tileSizePx = getTileSize();
ss.topbarVisible = getTopbarVisible();
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
setSelectionColor(ss.color);
setDateTextAppearance(ss.dateTextAppearance);
setWeekDayTextAppearance(ss.weekDayTextAppearance);
setShowOtherDates(ss.showOtherDates);
setRangeDates(ss.minDate, ss.maxDate);
clearSelection();
for (CalendarDay calendarDay : ss.selectedDates) {
setDateSelected(calendarDay, true);
}
setFirstDayOfWeek(ss.firstDayOfWeek);
setTileSize(ss.tileSizePx);
setTopbarVisible(ss.topbarVisible);
setSelectionMode(ss.selectionMode);
setDynamicHeightEnabled(ss.dynamicHeightEnabled);
}
@Override
protected void dispatchSaveInstanceState(@NonNull SparseArray<Parcelable> container) {
dispatchFreezeSelfOnly(container);
}
@Override
protected void dispatchRestoreInstanceState(@NonNull SparseArray<Parcelable> container) {
dispatchThawSelfOnly(container);
}
private void setRangeDates(CalendarDay min, CalendarDay max) {
CalendarDay c = currentMonth;
adapter.setRangeDates(min, max);
currentMonth = c;
int position = adapter.getIndexForDay(c);
pager.setCurrentItem(position, false);
updateUi();
}
public static class SavedState extends BaseSavedState {
int color = 0;
int dateTextAppearance = 0;
int weekDayTextAppearance = 0;
int showOtherDates = SHOW_DEFAULTS;
CalendarDay minDate = null;
CalendarDay maxDate = null;
List<CalendarDay> selectedDates = new ArrayList<>();
int firstDayOfWeek = Calendar.SUNDAY;
int tileSizePx = -1;
boolean topbarVisible = true;
int selectionMode = SELECTION_MODE_SINGLE;
boolean dynamicHeightEnabled = false;
SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(@NonNull Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(color);
out.writeInt(dateTextAppearance);
out.writeInt(weekDayTextAppearance);
out.writeInt(showOtherDates);
out.writeParcelable(minDate, 0);
out.writeParcelable(maxDate, 0);
out.writeTypedList(selectedDates);
out.writeInt(firstDayOfWeek);
out.writeInt(tileSizePx);
out.writeInt(topbarVisible ? 1 : 0);
out.writeInt(selectionMode);
out.writeInt(dynamicHeightEnabled ? 1 : 0);
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
private SavedState(Parcel in) {
super(in);
color = in.readInt();
dateTextAppearance = in.readInt();
weekDayTextAppearance = in.readInt();
showOtherDates = in.readInt();
ClassLoader loader = CalendarDay.class.getClassLoader();
minDate = in.readParcelable(loader);
maxDate = in.readParcelable(loader);
in.readTypedList(selectedDates, CalendarDay.CREATOR);
firstDayOfWeek = in.readInt();
tileSizePx = in.readInt();
topbarVisible = in.readInt() == 1;
selectionMode = in.readInt();
dynamicHeightEnabled = in.readInt() == 1;
}
}
private static int getThemeAccentColor(Context context) {
int colorAttr;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
colorAttr = android.R.attr.colorAccent;
} else {
//Get colorAccent defined for AppCompat
colorAttr = context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName());
}
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(colorAttr, outValue, true);
return outValue.data;
}
/**
* Sets the first day of the week.
* <p/>
* Uses the java.util.Calendar day constants.
*
* @param day The first day of the week as a java.util.Calendar day constant.
* @see java.util.Calendar
*/
public void setFirstDayOfWeek(int day) {
adapter.setFirstDayOfWeek(day);
}
/**
* @return The first day of the week as a {@linkplain Calendar} day constant.
*/
public int getFirstDayOfWeek() {
return adapter.getFirstDayOfWeek();
}
/**
* By default, the calendar will take up all the space needed to show any month (6 rows).
* By enabling dynamic height, the view will change height dependant on the visible month.
* <p/>
* This means months that only need 5 or 4 rows to show the entire month will only take up
* that many rows, and will grow and shrink as necessary.
*
* @param useDynamicHeight true to have the view different heights based on the visible month
*/
public void setDynamicHeightEnabled(boolean useDynamicHeight) {
this.mDynamicHeightEnabled = useDynamicHeight;
}
/**
* @return the dynamic height state - true if enabled.
*/
public boolean isDynamicHeightEnabled() {
return mDynamicHeightEnabled;
}
/**
* Add a collection of day decorators
*
* @param decorators decorators to add
*/
public void addDecorators(Collection<? extends DayViewDecorator> decorators) {
if (decorators == null) {
return;
}
dayViewDecorators.addAll(decorators);
adapter.setDecorators(dayViewDecorators);
}
/**
* Add several day decorators
*
* @param decorators decorators to add
*/
public void addDecorators(DayViewDecorator... decorators) {
addDecorators(Arrays.asList(decorators));
}
/**
* Add a day decorator
*
* @param decorator decorator to add
*/
public void addDecorator(DayViewDecorator decorator) {
if (decorator == null) {
return;
}
dayViewDecorators.add(decorator);
adapter.setDecorators(dayViewDecorators);
}
/**
* Remove all decorators
*/
public void removeDecorators() {
dayViewDecorators.clear();
adapter.setDecorators(dayViewDecorators);
}
/**
* Remove a specific decorator instance. Same rules as {@linkplain List#remove(Object)}
*
* @param decorator decorator to remove
*/
public void removeDecorator(DayViewDecorator decorator) {
dayViewDecorators.remove(decorator);
adapter.setDecorators(dayViewDecorators);
}
/**
* Invalidate decorators after one has changed internally. That is, if a decorator mutates, you
* should call this method to update the widget.
*/
public void invalidateDecorators() {
adapter.invalidateDecorators();
}
/*
* Listener/Callback Code
*/
/**
* Sets the listener to be notified upon selected date changes.
*
* @param listener thing to be notified
*/
public void setOnDateChangedListener(OnDateSelectedListener listener) {
this.listener = listener;
}
/**
* Sets the listener to be notified upon month changes.
*
* @param listener thing to be notified
*/
public void setOnMonthChangedListener(OnMonthChangedListener listener) {
this.monthListener = listener;
}
/**
* Dispatch date change events to a listener, if set
*
* @param day the day that was selected
* @param selected true if the day is now currently selected, false otherwise
*/
protected void dispatchOnDateSelected(final CalendarDay day, final boolean selected) {
OnDateSelectedListener l = listener;
if (l != null) {
l.onDateSelected(MaterialCalendarView.this, day, selected);
}
}
/**
* Dispatch date change events to a listener, if set
*
* @param day first day of the new month
*/
protected void dispatchOnMonthChanged(final CalendarDay day) {
OnMonthChangedListener l = monthListener;
if (l != null) {
l.onMonthChanged(MaterialCalendarView.this, day);
}
}
/**
* Call by MonthView to indicate that a day was clicked and we should handle it
*
* @param date date of the day that was clicked
* @param nowSelected true if the date is now selected, false otherwise
*/
protected void onDateClicked(@NonNull CalendarDay date, boolean nowSelected) {
switch (selectionMode) {
case SELECTION_MODE_MULTIPLE: {
adapter.setDateSelected(date, nowSelected);
dispatchOnDateSelected(date, nowSelected);
}
break;
default:
case SELECTION_MODE_SINGLE: {
adapter.clearSelections();
adapter.setDateSelected(date, true);
dispatchOnDateSelected(date, true);
}
break;
}
}
/**
* Called by the adapter for cases when changes in state result in dates being unselected
*
* @param date date that should be de-selected
*/
protected void onDateUnselected(CalendarDay date) {
dispatchOnDateSelected(date, false);
}
/*
* Show Other Dates Utils
*/
/**
* @param showOtherDates int flag for show other dates
* @return true if the other months flag is set
*/
public static boolean showOtherMonths(@ShowOtherDates int showOtherDates) {
return (showOtherDates & SHOW_OTHER_MONTHS) != 0;
}
/**
* @param showOtherDates int flag for show other dates
* @return true if the out of range flag is set
*/
public static boolean showOutOfRange(@ShowOtherDates int showOtherDates) {
return (showOtherDates & SHOW_OUT_OF_RANGE) != 0;
}
/**
* @param showOtherDates int flag for show other dates
* @return true if the decorated disabled flag is set
*/
public static boolean showDecoratedDisabled(@ShowOtherDates int showOtherDates) {
return (showOtherDates & SHOW_DECORATED_DISABLED) != 0;
}
/*
* Custom ViewGroup Code
*/
/**
* {@inheritDoc}
*/
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(1);
}
/**
* {@inheritDoc}
*/
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final int specWidthSize = MeasureSpec.getSize(widthMeasureSpec);
final int specWidthMode = MeasureSpec.getMode(widthMeasureSpec);
final int specHeightSize = MeasureSpec.getSize(heightMeasureSpec);
final int specHeightMode = MeasureSpec.getMode(heightMeasureSpec);
//We need to disregard padding for a while. This will be added back later
final int desiredWidth = specWidthSize - getPaddingLeft() - getPaddingRight();
final int desiredHeight = specHeightSize - getPaddingTop() - getPaddingBottom();
final int weekCount = getWeekCountBasedOnMode();
final int viewTileHeight = getTopbarVisible() ? (weekCount + 1) : weekCount;
//Calculate independent tile sizes for later
int desiredTileWidth = desiredWidth / DEFAULT_DAYS_IN_WEEK;
int desiredTileHeight = desiredHeight / viewTileHeight;
int measureTileSize = -1;
if (this.tileSize > 0) {
//We have a tileSize set, we should use that
measureTileSize = this.tileSize;
} else if (specWidthMode == MeasureSpec.EXACTLY) {
if (specHeightMode == MeasureSpec.EXACTLY) {
//Pick the larger of the two explicit sizes
measureTileSize = Math.max(desiredTileWidth, desiredTileHeight);
} else {
//Be the width size the user wants
measureTileSize = desiredTileWidth;
}
} else if (specHeightMode == MeasureSpec.EXACTLY) {
//Be the height size the user wants
measureTileSize = desiredTileHeight;
}
//Uh oh! We need to default to something, quick!
if (measureTileSize <= 0) {
measureTileSize = dpToPx(DEFAULT_TILE_SIZE_DP);
}
//Calculate our size based off our measured tile size
int measuredWidth = measureTileSize * DEFAULT_DAYS_IN_WEEK;
int measuredHeight = measureTileSize * viewTileHeight;
//Put padding back in from when we took it away
measuredWidth += getPaddingLeft() + getPaddingRight();
measuredHeight += getPaddingTop() + getPaddingBottom();
//Contract fulfilled, setting out measurements
setMeasuredDimension(
//We clamp inline because we want to use un-clamped versions on the children
clampSize(measuredWidth, widthMeasureSpec),
clampSize(measuredHeight, heightMeasureSpec)
);
int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
LayoutParams p = (LayoutParams) child.getLayoutParams();
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
DEFAULT_DAYS_IN_WEEK * measureTileSize,
MeasureSpec.EXACTLY
);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
p.height * measureTileSize,
MeasureSpec.EXACTLY
);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
private int getWeekCountBasedOnMode() {
int weekCount = calendarMode.visibleWeeksCount;
boolean isInMonthsMode = calendarMode.equals(CalendarMode.MONTHS);
if (isInMonthsMode && mDynamicHeightEnabled && adapter != null && pager != null) {
Calendar cal = (Calendar) adapter.getItem(pager.getCurrentItem()).getCalendar().clone();
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
//noinspection ResourceType
cal.setFirstDayOfWeek(getFirstDayOfWeek());
weekCount = cal.get(Calendar.WEEK_OF_MONTH);
}
return weekCount + DAY_NAMES_ROW;
}
/**
* Clamp the size to the measure spec.
*
* @param size Size we want to be
* @param spec Measure spec to clamp against
* @return the appropriate size to pass to {@linkplain View#setMeasuredDimension(int, int)}
*/
private static int clampSize(int size, int spec) {
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
switch (specMode) {
case MeasureSpec.EXACTLY: {
return specSize;
}
case MeasureSpec.AT_MOST: {
return Math.min(size, specSize);
}
case MeasureSpec.UNSPECIFIED:
default: {
return size;
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int count = getChildCount();
final int parentLeft = getPaddingLeft();
final int parentWidth = right - left - parentLeft - getPaddingRight();
int childTop = getPaddingTop();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == View.GONE) {
continue;
}
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int delta = (parentWidth - width) / 2;
int childLeft = parentLeft + delta;
child.layout(childLeft, childTop, childLeft + width, childTop + height);
childTop += height;
}
}
/**
* {@inheritDoc}
*/
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(1);
}
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(1);
}
@Override
public void onInitializeAccessibilityEvent(@NonNull AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(MaterialCalendarView.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(MaterialCalendarView.class.getName());
}
/**
* Simple layout params for MaterialCalendarView. The only variation for layout is height.
*/
protected static class LayoutParams extends MarginLayoutParams {
/**
* Create a layout that matches parent width, and is X number of tiles high
*
* @param tileHeight view height in number of tiles
*/
public LayoutParams(int tileHeight) {
super(MATCH_PARENT, tileHeight);
}
}
/**
* Enable or disable the ability to swipe between months.
*
* @param pagingEnabled pass false to disable paging, true to enable (default)
*/
public void setPagingEnabled(boolean pagingEnabled) {
pager.setPagingEnabled(pagingEnabled);
updateUi();
}
/**
* @return true if swiping months is enabled, false if disabled. Default is true.
*/
public boolean isPagingEnabled() {
return pager.isPagingEnabled();
}
} |
package com.salesforce.androidsdk.smartsync.manager;
import android.text.TextUtils;
import com.salesforce.androidsdk.rest.ApiVersionStrings;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.smartstore.store.IndexSpec;
import com.salesforce.androidsdk.smartstore.store.QuerySpec;
import com.salesforce.androidsdk.smartstore.store.SmartStore;
import com.salesforce.androidsdk.smartsync.util.Constants;
import com.salesforce.androidsdk.smartsync.util.SOQLBuilder;
import com.salesforce.androidsdk.smartsync.util.SoqlSyncDownTarget;
import com.salesforce.androidsdk.smartsync.util.SyncDownTarget;
import com.salesforce.androidsdk.smartsync.util.SyncOptions;
import com.salesforce.androidsdk.smartsync.util.SyncState;
import com.salesforce.androidsdk.smartsync.util.SyncState.MergeMode;
import com.salesforce.androidsdk.smartsync.util.SyncTarget;
import com.salesforce.androidsdk.smartsync.util.SyncUpTarget;
import com.salesforce.androidsdk.smartsync.util.SyncUpdateCallbackQueue;
import com.salesforce.androidsdk.util.test.JSONTestHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Test class for SyncState.
*/
public class SyncManagerTest extends ManagerTestCase {
private static final String TYPE = "type";
private static final String RECORDS = "records";
private static final String LID = "id"; // lower case id in create response
// Local
private static final String LOCAL_ID_PREFIX = "local_";
private static final String ACCOUNTS_SOUP = "accounts";
// Misc
private static final int COUNT_TEST_ACCOUNTS = 10;
private Map<String, String> idToNames;
@Override
public void setUp() throws Exception {
super.setUp();
createAccountsSoup();
idToNames = createAccountsOnServer(COUNT_TEST_ACCOUNTS);
}
@Override
public void tearDown() throws Exception {
deleteAccountsOnServer(idToNames.keySet().toArray(new String[0]));
dropAccountsSoup();
deleteSyncs();
super.tearDown();
}
/**
* getSyncStatus should return null for invalid sync id
* @throws JSONException
*/
public void testGetSyncStatusForInvalidSyncId() throws JSONException {
SyncState sync = syncManager.getSyncStatus(-1);
assertNull("Sync status should be null", sync);
}
/**
* Sync down the test accounts, check smart store, check status during sync
*/
public void testSyncDown() throws Exception {
// first sync down
trySyncDown(MergeMode.OVERWRITE);
// Check that db was correctly populated
checkDb(idToNames);
}
/**
* Sync down the test accounts, make some local changes, sync down again with merge mode LEAVE_IF_CHANGED then sync down with merge mode OVERWRITE
*/
public void testSyncDownWithoutOverwrite() throws Exception {
// first sync down
trySyncDown(MergeMode.OVERWRITE);
// Make some local change
Map<String, String> idToNamesLocallyUpdated = makeSomeLocalChanges();
// sync down again with MergeMode.LEAVE_IF_CHANGED
trySyncDown(MergeMode.LEAVE_IF_CHANGED);
// Check db
Map<String, String> idToNamesExpected = new HashMap<String, String>(idToNames);
idToNamesExpected.putAll(idToNamesLocallyUpdated);
checkDb(idToNamesExpected);
// sync down again with MergeMode.OVERWRITE
trySyncDown(MergeMode.OVERWRITE);
// Check db
checkDb(idToNames);
}
/**
* Sync down the test accounts, modify a few on the server, re-sync, make sure only the updated ones are downloaded
*/
public void testReSync() throws Exception {
// first sync down
long syncId = trySyncDown(MergeMode.OVERWRITE);
// Check sync time stamp
SyncState sync = syncManager.getSyncStatus(syncId);
SyncDownTarget target = (SyncDownTarget) sync.getTarget();
SyncOptions options = sync.getOptions();
long maxTimeStamp = sync.getMaxTimeStamp();
assertTrue("Wrong time stamp", maxTimeStamp > 0);
// Make some remote change
Thread.sleep(1000); // time stamp precision is in seconds
Map<String, String> idToNamesUpdated = new HashMap<String, String>();
String[] allIds = idToNames.keySet().toArray(new String[0]);
String[] ids = new String[]{allIds[0], allIds[2]};
for (int i = 0; i < ids.length; i++) {
String id = ids[i];
idToNamesUpdated.put(id, idToNames.get(id) + "_updated");
}
updateAccountsOnServer(idToNamesUpdated);
// Call reSync
SyncUpdateCallbackQueue queue = new SyncUpdateCallbackQueue();
syncManager.reSync(syncId, queue);
// Check status updates
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncDown, syncId, target, options, SyncState.Status.RUNNING, 0, -1);
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncDown, syncId, target, options, SyncState.Status.RUNNING, 0, idToNamesUpdated.size());
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncDown, syncId, target, options, SyncState.Status.DONE, 100, idToNamesUpdated.size());
// Check db
checkDb(idToNamesUpdated);
// Check sync time stamp
assertTrue("Wrong time stamp", syncManager.getSyncStatus(syncId).getMaxTimeStamp() > maxTimeStamp);
}
/**
* Sync down the test accounts, modify a few, sync up, check smartstore and server afterwards
*/
public void testSyncUpWithLocallyUpdatedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Update a few entries locally
Map<String, String> idToNamesLocallyUpdated = makeSomeLocalChanges();
// Sync up
trySyncUp(3, MergeMode.OVERWRITE);
// Check that db doesn't show entries as locally modified anymore
Set<String> ids = idToNamesLocallyUpdated.keySet();
checkDbStateFlags(ids, false, false, false);
// Check server
checkServer(idToNamesLocallyUpdated);
}
/**
* Sync down the test accounts, modify a few, sync up with merge mode LEAVE_IF_CHANGED, check smartstore and server afterwards
*/
public void testSyncUpWithLocallyUpdatedRecordsWithoutOverwrite() throws Exception {
// First sync down
trySyncDown(MergeMode.LEAVE_IF_CHANGED);
// Update a few entries locally
Map<String, String> idToNamesLocallyUpdated = makeSomeLocalChanges();
// Update entries on server
Thread.sleep(1000); // time stamp precision is in seconds
final Map<String, String> idToNamesRemotelyUpdated = new HashMap<String, String>();
final Set<String> ids = idToNamesLocallyUpdated.keySet();
assertNotNull("List of IDs should not be null", ids);
for (final String id : ids) {
idToNamesRemotelyUpdated.put(id,
idToNamesLocallyUpdated.get(id) + "_updated_again");
}
updateAccountsOnServer(idToNamesRemotelyUpdated);
// Sync up
trySyncUp(3, MergeMode.LEAVE_IF_CHANGED);
// Check that db shows entries as locally modified
checkDbStateFlags(ids, false, true, false);
// Check server
checkServer(idToNamesRemotelyUpdated);
}
/**
* Create accounts locally, sync up, check smartstore and server afterwards
*/
public void testSyncUpWithLocallyCreatedRecords() throws Exception {
// Create a few entries locally
String[] names = new String[] { createAccountName(), createAccountName(), createAccountName() };
createAccountsLocally(names);
// Sync up
trySyncUp(3, MergeMode.OVERWRITE);
// Check that db doesn't show entries as locally created anymore and that they use sfdc id
Map<String, String> idToNamesCreated = getIdsForNames(names);
checkDbStateFlags(idToNamesCreated.keySet(), false, false, false);
// Check server
checkServer(idToNamesCreated);
// Adding to idToNames so that they get deleted in tearDown
idToNames.putAll(idToNamesCreated);
}
/**
* Sync down the test accounts, delete a few, sync up, check smartstore and server afterwards
*/
public void testSyncUpWithLocallyDeletedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Delete a few entries locally
String[] allIds = idToNames.keySet().toArray(new String[0]);
String[] idsLocallyDeleted = new String[] { allIds[0], allIds[1], allIds[2] };
deleteAccountsLocally(idsLocallyDeleted);
// Sync up
trySyncUp(3, MergeMode.OVERWRITE);
// Check that db doesn't contain those entries anymore
checkDbDeleted(idsLocallyDeleted);
// Check server
checkServerDeleted(idsLocallyDeleted);
}
/**
* Sync down the test accounts, delete a few, sync up with merge mode LEAVE_IF_CHANGED, check smartstore and server afterwards
*/
public void testSyncUpWithLocallyDeletedRecordsWithoutOverwrite() throws Exception {
// First sync down
trySyncDown(MergeMode.LEAVE_IF_CHANGED);
// Delete a few entries locally
String[] allIds = idToNames.keySet().toArray(new String[0]);
String[] idsLocallyDeleted = new String[] { allIds[0], allIds[1], allIds[2] };
deleteAccountsLocally(idsLocallyDeleted);
// Update entries on server
Thread.sleep(1000); // time stamp precision is in seconds
final Map<String, String> idToNamesRemotelyUpdated = new HashMap<String, String>();
for (int i = 0; i < idsLocallyDeleted.length; i++) {
String id = idsLocallyDeleted[i];
idToNamesRemotelyUpdated.put(id, idToNames.get(id) + "_updated");
}
updateAccountsOnServer(idToNamesRemotelyUpdated);
// Sync up
trySyncUp(3, MergeMode.LEAVE_IF_CHANGED);
// Check that db still contains those entries
checkDbStateFlags(Arrays.asList(idsLocallyDeleted), false, false, true);
// Check server
checkServer(idToNamesRemotelyUpdated);
}
/**
* Sync down the test accounts, modify a few, sync up using TestSyncUpTarget, check smartstore
*/
public void testCustomSyncUpWithLocallyUpdatedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Update a few entries locally
Map<String, String> idToNamesLocallyUpdated = makeSomeLocalChanges();
// Sync up
TestSyncUpTarget.ActionCollector collector = new TestSyncUpTarget.ActionCollector();
TestSyncUpTarget target = new TestSyncUpTarget(TestSyncUpTarget.SyncBehavior.NO_FAIL);
TestSyncUpTarget.setActionCollector(collector);
trySyncUp(target, 3, MergeMode.OVERWRITE);
// Check that db doesn't show entries as locally modified anymore
Set<String> ids = idToNamesLocallyUpdated.keySet();
checkDbStateFlags(ids, false, false, false);
// Check what got synched up
List<String> idsUpdatedByTarget = collector.updatedRecordIds;
assertEquals("Wrong number of records updated by target", 3, idsUpdatedByTarget.size());
for (String idUpdatedByTarget : idsUpdatedByTarget) {
assertTrue("Unexpected id:" + idUpdatedByTarget, idToNamesLocallyUpdated.containsKey(idUpdatedByTarget));
}
}
/**
* Create accounts locally, sync up using TestSyncUpTarget, check smartstore
*/
public void testCustomSyncUpWithLocallyCreatedRecords() throws Exception {
// Create a few entries locally
String[] names = new String[]{createAccountName(), createAccountName(), createAccountName()};
createAccountsLocally(names);
// Sync up
TestSyncUpTarget.ActionCollector collector = new TestSyncUpTarget.ActionCollector();
TestSyncUpTarget target = new TestSyncUpTarget(TestSyncUpTarget.SyncBehavior.NO_FAIL);
TestSyncUpTarget.setActionCollector(collector);
trySyncUp(target, 3, MergeMode.OVERWRITE);
// Check that db doesn't show entries as locally created anymore and that they use sfdc id
Map<String, String> idToNamesCreated = getIdsForNames(names);
checkDbStateFlags(idToNamesCreated.keySet(), false, false, false);
// Check what got synched up
List<String> idsCreatedByTarget = collector.createdRecordIds;
assertEquals("Wrong number of records created by target", 3, idsCreatedByTarget.size());
for (String idCreatedByTarget : idsCreatedByTarget) {
assertTrue("Unexpected id:" + idCreatedByTarget, idToNamesCreated.containsKey(idCreatedByTarget));
}
}
/**
* Sync down the test accounts, delete a few, sync up using TestSyncUpTarget, check smartstore
*/
public void testCustomSyncUpWithLocallyDeletedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Delete a few entries locally
String[] allIds = idToNames.keySet().toArray(new String[0]);
String[] idsLocallyDeleted = new String[] { allIds[0], allIds[1], allIds[2] };
deleteAccountsLocally(idsLocallyDeleted);
// Sync up
TestSyncUpTarget.ActionCollector collector = new TestSyncUpTarget.ActionCollector();
TestSyncUpTarget target = new TestSyncUpTarget(TestSyncUpTarget.SyncBehavior.NO_FAIL);
TestSyncUpTarget.setActionCollector(collector);
trySyncUp(target, 3, MergeMode.OVERWRITE);
// Check that db doesn't contain those entries anymore
checkDbDeleted(idsLocallyDeleted);
// Check what got synched up
List<String> idsDeletedByTarget = collector.deletedRecordIds;
assertEquals("Wrong number of records created by target", 3, idsDeletedByTarget.size());
for (String idDeleted : idsLocallyDeleted) {
assertTrue("Id not synched up" + idDeleted, idsDeletedByTarget.contains(idDeleted));
}
}
/**
* Sync down the test accounts, modify a few, sync up using a soft failing TestSyncUpTarget, check smartstore
*/
public void testSoftFailingCustomSyncUpWithLocallyUpdatedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Update a few entries locally
Map<String, String> idToNamesLocallyUpdated = makeSomeLocalChanges();
// Sync up
TestSyncUpTarget.ActionCollector collector = new TestSyncUpTarget.ActionCollector();
TestSyncUpTarget target = new TestSyncUpTarget(TestSyncUpTarget.SyncBehavior.SOFT_FAIL_ON_SYNC);
TestSyncUpTarget.setActionCollector(collector);
trySyncUp(target, 3, MergeMode.OVERWRITE);
// Check that db still shows entries as locally modified anymore
Set<String> ids = idToNamesLocallyUpdated.keySet();
checkDbStateFlags(ids, false, true, false);
// Check what got synched up
List<String> idsUpdatedByTarget = collector.updatedRecordIds;
assertEquals("Wrong number of records updated by target", 0, idsUpdatedByTarget.size());
}
/**
* Sync down the test accounts, modify a few, sync up using a hard failing TestSyncUpTarget, check smartstore
*/
public void testHardFailingCustomSyncUpWithLocallyUpdatedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Update a few entries locally
Map<String, String> idToNamesLocallyUpdated = makeSomeLocalChanges();
// Sync up
TestSyncUpTarget.ActionCollector collector = new TestSyncUpTarget.ActionCollector();
TestSyncUpTarget target = new TestSyncUpTarget(TestSyncUpTarget.SyncBehavior.HARD_FAIL_ON_SYNC);
TestSyncUpTarget.setActionCollector(collector);
trySyncUp(target, 3, MergeMode.OVERWRITE, true /* expect failure */);
// Check that db still shows entries as locally modified anymore
Set<String> ids = idToNamesLocallyUpdated.keySet();
checkDbStateFlags(ids, false, true, false);
// Check what got synched up
List<String> idsUpdatedByTarget = collector.updatedRecordIds;
assertEquals("Wrong number of records updated by target", 0, idsUpdatedByTarget.size());
}
/**
* Create accounts locally, sync up using soft failing TestSyncUpTarget, check smartstore
*/
public void testSoftFailingCustomSyncUpWithLocallyCreatedRecords() throws Exception {
// Create a few entries locally
String[] names = new String[]{createAccountName(), createAccountName(), createAccountName()};
createAccountsLocally(names);
// Sync up
TestSyncUpTarget.ActionCollector collector = new TestSyncUpTarget.ActionCollector();
TestSyncUpTarget target = new TestSyncUpTarget(TestSyncUpTarget.SyncBehavior.SOFT_FAIL_ON_SYNC);
TestSyncUpTarget.setActionCollector(collector);
trySyncUp(target, 3, MergeMode.OVERWRITE);
// Check that db still show show entries as locally created anymore and that they use sfdc id
Map<String, String> idToNamesCreated = getIdsForNames(names);
checkDbStateFlags(idToNamesCreated.keySet(), true, false, false);
// Check what got synched up
List<String> idsCreatedByTarget = collector.createdRecordIds;
assertEquals("Wrong number of records created by target", 0, idsCreatedByTarget.size());
}
/**
* Create accounts locally, sync up using hard failing TestSyncUpTarget, check smartstore
*/
public void testHardFailingCustomSyncUpWithLocallyCreatedRecords() throws Exception {
// Create a few entries locally
String[] names = new String[]{createAccountName(), createAccountName(), createAccountName()};
createAccountsLocally(names);
// Sync up
TestSyncUpTarget.ActionCollector collector = new TestSyncUpTarget.ActionCollector();
TestSyncUpTarget target = new TestSyncUpTarget(TestSyncUpTarget.SyncBehavior.HARD_FAIL_ON_SYNC);
TestSyncUpTarget.setActionCollector(collector);
trySyncUp(target, 3, MergeMode.OVERWRITE, true /* expect failure */);
// Check that db still show show entries as locally created anymore and that they use sfdc id
Map<String, String> idToNamesCreated = getIdsForNames(names);
checkDbStateFlags(idToNamesCreated.keySet(), true, false, false);
// Check what got synched up
List<String> idsCreatedByTarget = collector.createdRecordIds;
assertEquals("Wrong number of records created by target", 0, idsCreatedByTarget.size());
}
/**
* Sync down the test accounts, delete a few, sync up using soft failing TestSyncUpTarget, check smartstore
*/
public void testSoftFailingCustomSyncUpWithLocallyDeletedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Delete a few entries locally
String[] allIds = idToNames.keySet().toArray(new String[0]);
String[] idsLocallyDeleted = new String[] { allIds[0], allIds[1], allIds[2] };
deleteAccountsLocally(idsLocallyDeleted);
// Sync up
TestSyncUpTarget.ActionCollector collector = new TestSyncUpTarget.ActionCollector();
TestSyncUpTarget target = new TestSyncUpTarget(TestSyncUpTarget.SyncBehavior.SOFT_FAIL_ON_SYNC);
TestSyncUpTarget.setActionCollector(collector);
trySyncUp(target, 3, MergeMode.OVERWRITE);
// Check that db still contains those entries
Collection<String> ids = Arrays.asList(idsLocallyDeleted);
checkDbStateFlags(ids, false, false, true);
// Check what got synched up
List<String> idsDeletedByTarget = collector.deletedRecordIds;
assertEquals("Wrong number of records created by target", 0, idsDeletedByTarget.size());
}
/**
* Sync down the test accounts, delete a few, sync up using hard failing TestSyncUpTarget, check smartstore
*/
public void testHardFailingCustomSyncUpWithLocallyDeletedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Delete a few entries locally
String[] allIds = idToNames.keySet().toArray(new String[0]);
String[] idsLocallyDeleted = new String[] { allIds[0], allIds[1], allIds[2] };
deleteAccountsLocally(idsLocallyDeleted);
// Sync up
TestSyncUpTarget.ActionCollector collector = new TestSyncUpTarget.ActionCollector();
TestSyncUpTarget target = new TestSyncUpTarget(TestSyncUpTarget.SyncBehavior.HARD_FAIL_ON_SYNC);
TestSyncUpTarget.setActionCollector(collector);
trySyncUp(target, 3, MergeMode.OVERWRITE, true /* expect failure */);
// Check that db still contains those entries
Collection<String> ids = Arrays.asList(idsLocallyDeleted);
checkDbStateFlags(ids, false, false, true);
// Check what got synched up
List<String> idsDeletedByTarget = collector.deletedRecordIds;
assertEquals("Wrong number of records created by target", 0, idsDeletedByTarget.size());
}
/**
* Sync down the test accounts, delete record on server and locally, sync up, check smartstore and server afterwards
*/
public void testSyncUpWithLocallyDeletedRemotelyDeletedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Delete record locally
String[] allIds = idToNames.keySet().toArray(new String[0]);
String[] idsLocallyDeleted = new String[] { allIds[0], allIds[1], allIds[2] };
deleteAccountsLocally(idsLocallyDeleted);
// Delete same records on server
deleteAccountsOnServer(idsLocallyDeleted);
// Sync up
trySyncUp(3, MergeMode.OVERWRITE);
// Check that db doesn't contain those entries anymore
checkDbDeleted(idsLocallyDeleted);
// Check server
checkServerDeleted(idsLocallyDeleted);
}
/**
* Sync down the test accounts, delete record on server and update same record locally, sync up, check smartstore and server afterwards
*/
public void testSyncUpWithLocallyUpdatedRemotelyDeletedRecords() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Update a few entries locally
Map<String, String> idToNamesLocallyUpdated = makeSomeLocalChanges();
// Delete record on server
String remotelyDeletedId = idToNamesLocallyUpdated.keySet().toArray(new String[0])[0];
deleteAccountsOnServer(new String[]{remotelyDeletedId});
// Name of locally recorded record that was deleted on server
String locallyUpdatedRemotelyDeletedName = idToNamesLocallyUpdated.get(remotelyDeletedId);
// Sync up
trySyncUp(3, MergeMode.OVERWRITE);
// Getting id / names of updated records looking up by name
Map<String, String> idToNamesUpdated = getIdsForNames(idToNamesLocallyUpdated.values().toArray(new String[0]));
// Check db
checkDb(idToNamesUpdated);
// Expect 3 records
assertEquals(3, idToNamesUpdated.size());
// Expect remotely deleted record to have a new id
assertFalse(idToNamesUpdated.containsKey(remotelyDeletedId));
for (Entry<String, String> idName : idToNamesUpdated.entrySet()) {
String accountId = idName.getKey();
String accountName = idName.getValue();
// Check that locally updated / remotely deleted record has new id (not in idToNames)
if (accountName.equals(locallyUpdatedRemotelyDeletedName)) {
assertFalse(idToNames.containsKey(accountId));
}
// Otherwise should be a known id (in idToNames)
else {
assertTrue(idToNames.containsKey(accountId));
}
}
// Check server
checkServer(idToNamesUpdated);
}
/**
* Sync down the test accounts, delete record on server and update same record locally, sync up with merge mode LEAVE_IF_CHANGED, check smartstore and server afterwards
*/
public void testSyncUpWithLocallyUpdatedRemotelyDeletedRecordsWithoutOverwrite() throws Exception {
// First sync down
trySyncDown(MergeMode.OVERWRITE);
// Update a few entries locally
Map<String, String> idToNamesLocallyUpdated = makeSomeLocalChanges();
// Delete record on server
String remotelyDeletedId = idToNamesLocallyUpdated.keySet().toArray(new String[0])[0];
deleteAccountsOnServer(new String[]{remotelyDeletedId});
// Sync up
trySyncUp(3, MergeMode.LEAVE_IF_CHANGED);
// Getting id / names of updated records looking up by name
Map<String, String> idToNamesUpdated = getIdsForNames(idToNamesLocallyUpdated.values().toArray(new String[0]));
// Expect 3 records
assertEquals(3, idToNamesUpdated.size());
// Expect remotely deleted record to be there
assertTrue(idToNamesUpdated.containsKey(remotelyDeletedId));
// Checking the remotely deleted record locally
checkDbStateFlags(Arrays.asList(new String[]{remotelyDeletedId}), false, true, false);
// Check the other 2 records in db
idToNamesUpdated.remove(remotelyDeletedId);
checkDb(idToNamesUpdated);
// Check server
checkServer(idToNamesUpdated);
checkServerDeleted(new String[]{remotelyDeletedId});
}
/**
* Test addFilterForReSync with various queries
*/
public void testAddFilterForResync() {
Date date = new Date();
long dateLong = date.getTime();
String dateStr = Constants.TIMESTAMP_FORMAT.format(date);
assertEquals("Wrong result for addFilterForReSync", "select Id from Account where LastModifiedDate > " + dateStr, SoqlSyncDownTarget.addFilterForReSync("select Id from Account", dateLong));
assertEquals("Wrong result for addFilterForReSync", "select Id from Account where LastModifiedDate > " + dateStr + " limit 100", SoqlSyncDownTarget.addFilterForReSync("select Id from Account limit 100", dateLong));
assertEquals("Wrong result for addFilterForReSync", "select Id from Account where LastModifiedDate > " + dateStr + " and Name = 'John'", SoqlSyncDownTarget.addFilterForReSync("select Id from Account where Name = 'John'", dateLong));
assertEquals("Wrong result for addFilterForReSync", "select Id from Account where LastModifiedDate > " + dateStr + " and Name = 'John' limit 100", SoqlSyncDownTarget.addFilterForReSync("select Id from Account where Name = 'John' limit 100", dateLong));
assertEquals("Wrong result for addFilterForReSync", "SELECT Id FROM Account where LastModifiedDate > " + dateStr, SoqlSyncDownTarget.addFilterForReSync("SELECT Id FROM Account", dateLong));
assertEquals("Wrong result for addFilterForReSync", "SELECT Id FROM Account where LastModifiedDate > " + dateStr + " LIMIT 100", SoqlSyncDownTarget.addFilterForReSync("SELECT Id FROM Account LIMIT 100", dateLong));
assertEquals("Wrong result for addFilterForReSync", "SELECT Id FROM Account WHERE LastModifiedDate > " + dateStr + " and Name = 'John'", SoqlSyncDownTarget.addFilterForReSync("SELECT Id FROM Account WHERE Name = 'John'", dateLong));
assertEquals("Wrong result for addFilterForReSync", "SELECT Id FROM Account WHERE LastModifiedDate > " + dateStr + " and Name = 'John' LIMIT 100", SoqlSyncDownTarget.addFilterForReSync("SELECT Id FROM Account WHERE Name = 'John' LIMIT 100", dateLong));
}
/**
* Test reSync while sync is running
*/
public void testReSyncRunningSync() throws JSONException {
// Create sync
SlowSoqlSyncDownTarget target = new SlowSoqlSyncDownTarget("SELECT Id, Name, LastModifiedDate FROM Account WHERE Id IN " + makeInClause(idToNames.keySet()));
SyncOptions options = SyncOptions.optionsForSyncDown(MergeMode.LEAVE_IF_CHANGED);
SyncState sync = SyncState.createSyncDown(smartStore, target, options, ACCOUNTS_SOUP);
long syncId = sync.getId();
checkStatus(sync, SyncState.Type.syncDown, syncId, target, options, SyncState.Status.NEW, 0, -1);
// Run sync - will freeze during fetch
SyncUpdateCallbackQueue queue = new SyncUpdateCallbackQueue();
syncManager.runSync(sync, queue);
// Wait for sync to be running
queue.getNextSyncUpdate();
// Calling reSync -- expect exception
try {
syncManager.reSync(syncId, null);
fail("Re sync should have failed");
} catch (SyncManager.SmartSyncException e) {
assertTrue("Re sync should have failed because sync is already running", e.getMessage().contains("still running"));
}
// Wait for sync to complete successfully
while (!queue.getNextSyncUpdate().isDone());
// Calling reSync again -- does not expect exception
try {
syncManager.reSync(syncId, queue);
} catch (SyncManager.SmartSyncException e) {
fail("Re sync should not have failed");
}
// Waiting for reSync to complete successfully
while (!queue.getNextSyncUpdate().isDone());
}
public void testAddMissingFieldsToSOQLTarget() throws Exception {
final String soqlQueryWithSpecialFields = SOQLBuilder.getInstanceWithFields("Id, LastModifiedDate, FirstName, LastName")
.from(Constants.CONTACT).limit(10).build();
final String soqlQueryWithoutSpecialFields = SOQLBuilder.getInstanceWithFields("FirstName, LastName")
.from(Constants.CONTACT).limit(10).build();
final SoqlSyncDownTarget target = new SoqlSyncDownTarget(soqlQueryWithoutSpecialFields);
final String targetSoqlQuery = target.getQuery();
assertEquals("SOQL query should contain Id and LastModifiedDate fields", soqlQueryWithSpecialFields, targetSoqlQuery);
}
/**
* Sync down helper
* @throws JSONException
* @param mergeMode
*/
private long trySyncDown(MergeMode mergeMode) throws JSONException {
// Create sync
SyncDownTarget target = new SoqlSyncDownTarget("SELECT Id, Name, LastModifiedDate FROM Account WHERE Id IN " + makeInClause(idToNames.keySet()));
SyncOptions options = SyncOptions.optionsForSyncDown(mergeMode);
SyncState sync = SyncState.createSyncDown(smartStore, target, options, ACCOUNTS_SOUP);
long syncId = sync.getId();
checkStatus(sync, SyncState.Type.syncDown, syncId, target, options, SyncState.Status.NEW, 0, -1);
// Run sync
SyncUpdateCallbackQueue queue = new SyncUpdateCallbackQueue();
syncManager.runSync(sync, queue);
// Check status updates
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncDown, syncId, target, options, SyncState.Status.RUNNING, 0, -1); // we get an update right away before getting records to sync
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncDown, syncId, target, options, SyncState.Status.RUNNING, 0, idToNames.size());
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncDown, syncId, target, options, SyncState.Status.DONE, 100, idToNames.size());
return syncId;
}
/**
* Sync up helper
* @param numberChanges
* @param mergeMode
* @throws JSONException
*/
private void trySyncUp(int numberChanges, MergeMode mergeMode) throws JSONException {
trySyncUp(new SyncUpTarget(), numberChanges, mergeMode);
}
/**
* Sync up helper
* @oaram target
* @param numberChanges
* @param mergeMode
* @throws JSONException
*/
private void trySyncUp(SyncUpTarget target, int numberChanges, MergeMode mergeMode) throws JSONException {
trySyncUp(target, numberChanges, mergeMode, false);
}
/**
* Sync up helper
* @param target
* @param numberChanges
* @param mergeMode
* @param expectSyncFailure - if true, we expect the sync to end up in the FAILED state
* @throws JSONException
*/
private void trySyncUp(SyncUpTarget target, int numberChanges, MergeMode mergeMode, boolean expectSyncFailure) throws JSONException {
// Create sync
SyncOptions options = SyncOptions.optionsForSyncUp(Arrays.asList(new String[] { Constants.NAME }), mergeMode);
SyncState sync = SyncState.createSyncUp(smartStore, target, options, ACCOUNTS_SOUP);
long syncId = sync.getId();
checkStatus(sync, SyncState.Type.syncUp, syncId, target, options, SyncState.Status.NEW, 0, -1);
// Run sync
SyncUpdateCallbackQueue queue = new SyncUpdateCallbackQueue();
syncManager.runSync(sync, queue);
// Check status updates
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncUp, syncId, target, options, SyncState.Status.RUNNING, 0, -1); // we get an update right away before getting records to sync
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncUp, syncId, target, options, SyncState.Status.RUNNING, 0, numberChanges);
if (expectSyncFailure) {
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncUp, syncId, target, options, SyncState.Status.FAILED, 0, numberChanges);
}
else {
for (int i = 1; i < numberChanges; i++) {
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncUp, syncId, target, options, SyncState.Status.RUNNING, i * 100 / numberChanges, numberChanges);
}
checkStatus(queue.getNextSyncUpdate(), SyncState.Type.syncUp, syncId, target, options, SyncState.Status.DONE, 100, numberChanges);
}
}
/**
* Helper method to check sync state
* @param sync
* @param expectedType
* @param expectedId
* @param expectedTarget
* @param expectedOptions
* @param expectedStatus
* @param expectedProgress
* @throws JSONException
*/
private void checkStatus(SyncState sync, SyncState.Type expectedType, long expectedId, SyncTarget expectedTarget, SyncOptions expectedOptions, SyncState.Status expectedStatus, int expectedProgress, int expectedTotalSize) throws JSONException {
assertEquals("Wrong type", expectedType, sync.getType());
assertEquals("Wrong id", expectedId, sync.getId());
JSONTestHelper.assertSameJSON("Wrong target", (expectedTarget == null ? null : expectedTarget.asJSON()), (sync.getTarget() == null ? null : sync.getTarget().asJSON()));
JSONTestHelper.assertSameJSON("Wrong options", (expectedOptions == null ? null : expectedOptions.asJSON()), (sync.getOptions() == null ? null : sync.getOptions().asJSON()));
assertEquals("Wrong status", expectedStatus, sync.getStatus());
assertEquals("Wrong progress", expectedProgress, sync.getProgress());
assertEquals("Wrong total size", expectedTotalSize, sync.getTotalSize());
}
/**
* Helper methods to create "count" test accounts
* @param count
* @return map of id to name for the created accounts
* @throws Exception
*/
private Map<String, String> createAccountsOnServer(int count) throws Exception {
Map<String, String> idToNames = new HashMap<String, String>();
for (int i=0; i<count; i++) {
// Request
String name = createAccountName();
Map<String, Object> fields = new HashMap<String, Object>();
fields.put(Constants.NAME, name);
RestRequest request = RestRequest.getRequestForCreate(ApiVersionStrings.VERSION_NUMBER, Constants.ACCOUNT, fields);
// Response
RestResponse response = restClient.sendSync(request);
String id = response.asJSONObject().getString(LID);
idToNames.put(id, name);
}
return idToNames;
}
/**
* Delete accounts specified in idToNames
* @param ids
* @throws Exception
*/
private void deleteAccountsOnServer(String[] ids) throws Exception {
for (String id : ids) {
RestRequest request = RestRequest.getRequestForDelete(ApiVersionStrings.VERSION_NUMBER, Constants.ACCOUNT, id);
restClient.sendSync(request);
}
}
/**
* @return account name of the form SyncManagerTest<random number left-padded to be 8 digits long>
*/
@SuppressWarnings("resource")
private String createAccountName() {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("SyncManagerTest%08d", (int) (Math.random()*10000000));
String name = sb.toString();
return name;
}
/**
* @return local id of the form local_<random number left-padded to be 8 digits long>
*/
@SuppressWarnings("resource")
private String createLocalId() {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format(LOCAL_ID_PREFIX + "%08d", (int) (Math.random()*10000000));
String name = sb.toString();
return name;
}
/**
* Create soup for accounts
*/
private void createAccountsSoup() {
final IndexSpec[] indexSpecs = {
new IndexSpec(Constants.ID, SmartStore.Type.string),
new IndexSpec(Constants.NAME, SmartStore.Type.string),
new IndexSpec(SyncManager.LOCAL, SmartStore.Type.string)
};
smartStore.registerSoup(ACCOUNTS_SOUP, indexSpecs);
}
/**
* Drop soup for accounts
*/
private void dropAccountsSoup() {
smartStore.dropSoup(ACCOUNTS_SOUP);
}
/**
* Delete all syncs in syncs_soup
*/
private void deleteSyncs() {
smartStore.clearSoup(SyncState.SYNCS_SOUP);
}
/**
* Create accounts locally
* @param names
* @throws JSONException
*/
private void createAccountsLocally(String[] names) throws JSONException {
JSONObject attributes = new JSONObject();
attributes.put(TYPE, Constants.ACCOUNT);
for (String name : names) {
JSONObject account = new JSONObject();
account.put(Constants.ID, createLocalId());
account.put(Constants.NAME, name);
account.put(Constants.ATTRIBUTES, attributes);
account.put(SyncManager.LOCAL, true);
account.put(SyncManager.LOCALLY_CREATED, true);
account.put(SyncManager.LOCALLY_DELETED, false);
account.put(SyncManager.LOCALLY_UPDATED, false);
smartStore.create(ACCOUNTS_SOUP, account);
}
}
/**
* Update accounts locally
* @param idToNamesLocallyUpdated
* @throws JSONException
*/
private void updateAccountsLocally(Map<String, String> idToNamesLocallyUpdated) throws JSONException {
for (Entry<String, String> idAndName : idToNamesLocallyUpdated.entrySet()) {
String id = idAndName.getKey();
String updatedName = idAndName.getValue();
JSONObject account = smartStore.retrieve(ACCOUNTS_SOUP, smartStore.lookupSoupEntryId(ACCOUNTS_SOUP, Constants.ID, id)).getJSONObject(0);
account.put(Constants.NAME, updatedName);
account.put(SyncManager.LOCAL, true);
account.put(SyncManager.LOCALLY_CREATED, false);
account.put(SyncManager.LOCALLY_DELETED, false);
account.put(SyncManager.LOCALLY_UPDATED, true);
smartStore.upsert(ACCOUNTS_SOUP, account);
}
}
/**
* Update accounts on server
* @param idToNamesUpdated
* @throws Exception
*/
private void updateAccountsOnServer(Map<String, String> idToNamesUpdated) throws Exception {
for (Entry<String, String> idAndName : idToNamesUpdated.entrySet()) {
String id = idAndName.getKey();
String updatedName = idAndName.getValue();
Map<String, Object> fields = new HashMap<String, Object>();
fields.put(Constants.NAME, updatedName);
RestRequest request = RestRequest.getRequestForUpdate(ApiVersionStrings.VERSION_NUMBER, Constants.ACCOUNT, id, fields);
// Response
RestResponse response = restClient.sendSync(request);
assertTrue("Updated failed", response.isSuccess());
}
}
/**
* Delete accounts locally
* @param idsLocallyDeleted
* @throws JSONException
*/
private void deleteAccountsLocally(String[] idsLocallyDeleted) throws JSONException {
for (String id : idsLocallyDeleted) {
JSONObject account = smartStore.retrieve(ACCOUNTS_SOUP, smartStore.lookupSoupEntryId(ACCOUNTS_SOUP, Constants.ID, id)).getJSONObject(0);
account.put(SyncManager.LOCAL, true);
account.put(SyncManager.LOCALLY_CREATED, false);
account.put(SyncManager.LOCALLY_DELETED, true);
account.put(SyncManager.LOCALLY_UPDATED, false);
smartStore.upsert(ACCOUNTS_SOUP, account);
}
}
/**
* Check records in db
* @throws JSONException
* @param expectedIdToNames
*/
private void checkDb(Map<String, String> expectedIdToNames) throws JSONException {
QuerySpec smartStoreQuery = QuerySpec.buildSmartQuerySpec("SELECT {accounts:Id}, {accounts:Name} FROM {accounts} WHERE {accounts:Id} IN " + makeInClause(expectedIdToNames.keySet()), COUNT_TEST_ACCOUNTS);
JSONArray accountsFromDb = smartStore.query(smartStoreQuery, 0);
JSONObject idToNamesFromDb = new JSONObject();
for (int i=0; i<accountsFromDb.length(); i++) {
JSONArray row = accountsFromDb.getJSONArray(i);
idToNamesFromDb.put(row.getString(0), row.getString(1));
}
JSONTestHelper.assertSameJSONObject("Wrong data in db", new JSONObject(expectedIdToNames), idToNamesFromDb);
}
/**
* Check records state in db
* @param ids
* @param expectLocallyCreated true if records are expected to be marked as locally created
* @param expectLocallyUpdated true if records are expected to be marked as locally updated
* @param expectLocallyDeleted true if records are expected to be marked as locally deleted
* @throws JSONException
*/
private void checkDbStateFlags(Collection<String> ids, boolean expectLocallyCreated, boolean expectLocallyUpdated, boolean expectLocallyDeleted) throws JSONException {
QuerySpec smartStoreQuery = QuerySpec.buildSmartQuerySpec("SELECT {accounts:_soup} FROM {accounts} WHERE {accounts:Id} IN " + makeInClause(ids), ids.size());
JSONArray accountsFromDb = smartStore.query(smartStoreQuery, 0);
for (int i=0; i<accountsFromDb.length(); i++) {
JSONArray row = accountsFromDb.getJSONArray(i);
JSONObject soupElt = row.getJSONObject(0);
String id = soupElt.getString(Constants.ID);
assertEquals("Wrong local flag", expectLocallyCreated || expectLocallyUpdated || expectLocallyDeleted, soupElt.getBoolean(SyncManager.LOCAL));
assertEquals("Wrong local flag", expectLocallyCreated, soupElt.getBoolean(SyncManager.LOCALLY_CREATED));
assertEquals("Id was not updated", expectLocallyCreated, id.startsWith(LOCAL_ID_PREFIX));
assertEquals("Wrong local flag", expectLocallyUpdated, soupElt.getBoolean(SyncManager.LOCALLY_UPDATED));
assertEquals("Wrong local flag", expectLocallyDeleted, soupElt.getBoolean(SyncManager.LOCALLY_DELETED));
}
}
/**
* Check that records were deleted from db
* @param ids
* @throws JSONException
*/
private void checkDbDeleted(String[] ids) throws JSONException {
QuerySpec smartStoreQuery = QuerySpec.buildSmartQuerySpec("SELECT {accounts:_soup}, {accounts:Name} FROM {accounts} WHERE {accounts:Id} IN " + makeInClause(ids), ids.length);
JSONArray accountsFromDb = smartStore.query(smartStoreQuery, 0);
assertEquals("No accounts should have been returned from smartstore",0, accountsFromDb.length());
}
/**
* Check records on server
* @param idToNames
* @throws IOException
* @throws JSONException
*/
private void checkServer(Map<String, String> idToNames) throws IOException, JSONException {
String soql = "SELECT Id, Name FROM Account WHERE Id IN " + makeInClause(idToNames.keySet());
RestRequest request = RestRequest.getRequestForQuery(ApiVersionStrings.VERSION_NUMBER, soql);
JSONObject idToNamesFromServer = new JSONObject();
RestResponse response = restClient.sendSync(request);
JSONArray records = response.asJSONObject().getJSONArray(RECORDS);
for (int i=0; i<records.length(); i++) {
JSONObject row = records.getJSONObject(i);
idToNamesFromServer.put(row.getString(Constants.ID), row.getString(Constants.NAME));
}
JSONTestHelper.assertSameJSONObject("Wrong data on server", new JSONObject(idToNames), idToNamesFromServer);
}
/**
* Check that records were deleted from server
* @param ids
* @throws IOException
*/
private void checkServerDeleted(String[] ids) throws IOException, JSONException {
String soql = "SELECT Id, Name FROM Account WHERE Id IN " + makeInClause(ids);
RestRequest request = RestRequest.getRequestForQuery(ApiVersionStrings.VERSION_NUMBER, soql);
RestResponse response = restClient.sendSync(request);
JSONArray records = response.asJSONObject().getJSONArray(RECORDS);
assertEquals("No accounts should have been returned from server", 0, records.length());
}
/**
* Make local changes
* @throws JSONException
*/
private Map<String, String> makeSomeLocalChanges() throws JSONException {
Map<String, String> idToNamesLocallyUpdated = new HashMap<String, String>();
String[] allIds = idToNames.keySet().toArray(new String[0]);
String[] ids = new String[] { allIds[0], allIds[1], allIds[2] };
for (int i = 0; i < ids.length; i++) {
String id = ids[i];
idToNamesLocallyUpdated.put(id, idToNames.get(id) + "_updated");
}
updateAccountsLocally(idToNamesLocallyUpdated);
return idToNamesLocallyUpdated;
}
/**
* Return map of id to name given records names
* @param names
* @throws JSONException
*/
private Map<String, String> getIdsForNames(String[] names) throws JSONException {
QuerySpec smartStoreQuery = QuerySpec.buildSmartQuerySpec("SELECT {accounts:_soup} FROM {accounts} WHERE {accounts:Name} IN " + makeInClause(names), names.length);
JSONArray accountsFromDb = smartStore.query(smartStoreQuery, 0);
Map<String, String> idToNames = new HashMap<String, String>();
for (int i=0; i<accountsFromDb.length(); i++) {
JSONArray row = accountsFromDb.getJSONArray(i);
JSONObject soupElt = row.getJSONObject(0);
String id = soupElt.getString(Constants.ID);
idToNames.put(id, soupElt.getString(Constants.NAME));
}
return idToNames;
}
private String makeInClause(String[] values) {
return makeInClause(Arrays.asList(values));
}
private String makeInClause(Collection<String> values) {
return "('" + TextUtils.join("', '", values) + "')";
}
/**
Soql sync down target that pauses for a second at the beginning of the fetch
*/
static class SlowSoqlSyncDownTarget extends SoqlSyncDownTarget {
public SlowSoqlSyncDownTarget(String query) throws JSONException {
super(query);
this.queryType = QueryType.custom;
}
public SlowSoqlSyncDownTarget(JSONObject target) throws JSONException {
super(target);
}
@Override
public JSONArray startFetch(SyncManager syncManager, long maxTimeStamp) throws IOException, JSONException {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return super.startFetch(syncManager, maxTimeStamp);
}
}
} |
package org.openlmis.web.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.openlmis.core.domain.*;
import org.openlmis.core.exception.DataException;
import org.openlmis.core.service.MessageService;
import org.openlmis.core.service.RoleRightsService;
import org.openlmis.db.categories.UnitTests;
import org.openlmis.web.response.OpenLmisResponse;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import java.util.*;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.openlmis.authentication.web.UserAuthenticationSuccessHandler.USER_ID;
import static org.openlmis.core.domain.Right.CONFIGURE_RNR;
import static org.openlmis.core.domain.Right.CREATE_REQUISITION;
import static org.openlmis.core.matchers.Matchers.facilityMatcher;
import static org.openlmis.core.matchers.Matchers.programMatcher;
import static org.openlmis.web.controller.RoleRightsController.*;
import static org.openlmis.web.response.OpenLmisResponse.SUCCESS;
@Category(UnitTests.class)
@RunWith(PowerMockRunner.class)
public class RoleRightsControllerTest {
Role role;
private static final Long LOGGED_IN_USERID = 11L;
private MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
@Mock
RoleRightsService roleRightsService;
@Mock
MessageService messageService;
@InjectMocks
private RoleRightsController controller;
@Before
public void setUp() throws Exception {
initMocks(this);
MockHttpSession mockHttpSession = new MockHttpSession();
httpServletRequest.setSession(mockHttpSession);
mockHttpSession.setAttribute(USER_ID, LOGGED_IN_USERID);
role = new Role("test role", "test role description");
}
@Test
public void shouldFetchAllRightsInSystem() throws Exception {
Set<Right> rights = new HashSet<>();
when(roleRightsService.getAllRights()).thenReturn(rights);
ResponseEntity<OpenLmisResponse> result = controller.getAllRights();
assertThat((Set<Right>) result.getBody().getData().get(RIGHTS), is(rights));
verify(roleRightsService).getAllRights();
}
@Test
public void shouldSaveRole() throws Exception {
when(messageService.message("message.role.created.success", "test role")).thenReturn("'test role' created successfully");
ResponseEntity<OpenLmisResponse> responseEntity = controller.createRole(role, httpServletRequest);
verify(roleRightsService).saveRole(role);
String successMsg = (String) responseEntity.getBody().getData().get(SUCCESS);
assertThat(successMsg, is("'test role' created successfully"));
}
@Test
public void shouldGiveErrorIfRoleNotSaved() throws Exception {
doThrow(new DataException("Error message")).when(roleRightsService).saveRole(role);
ResponseEntity<OpenLmisResponse> responseEntity = controller.createRole(role, httpServletRequest);
verify(roleRightsService).saveRole(role);
assertThat(responseEntity.getBody().getErrorMsg(), is("Error message"));
assertThat(responseEntity.getStatusCode(), is(HttpStatus.CONFLICT));
}
@Test
public void shouldGetAllRolesWithRights() throws Exception {
Map<String, List<Role>> roles_map = new HashMap<>();
when(roleRightsService.getAllRolesMap()).thenReturn(roles_map);
OpenLmisResponse response = controller.getAll().getBody();
verify(roleRightsService).getAllRoles();
}
@Test
public void shouldGetRoleById() throws Exception {
Role role = new Role();
Long roleId = 1L;
when(roleRightsService.getRole(roleId)).thenReturn(role);
OpenLmisResponse response = controller.get(roleId).getBody();
assertThat((Role) response.getData().get(ROLE), is(role));
verify(roleRightsService).getRole(roleId);
}
@Test
public void shouldGetRightTypeForRoleId() throws Exception {
Role role = new Role();
Long roleId = 1L;
when(roleRightsService.getRole(roleId)).thenReturn(role);
when(roleRightsService.getRightTypeForRoleId(roleId)).thenReturn(RightType.ADMIN);
OpenLmisResponse response = controller.get(roleId).getBody();
assertThat((Role) response.getData().get(ROLE), is(role));
assertThat((RightType) response.getData().get(RIGHT_TYPE), is(RightType.ADMIN));
verify(roleRightsService).getRole(roleId);
verify(roleRightsService).getRightTypeForRoleId(roleId);
}
@Test
public void shouldUpdateRoleAndRights() throws Exception {
Role role = new Role("Role Name", "Desc", new HashSet<>(asList(CONFIGURE_RNR)));
when(messageService.message("message.role.updated.success", "Role Name")).thenReturn("Role Name updated successfully");
OpenLmisResponse response = controller.updateRole(role.getId(), role, httpServletRequest).getBody();
assertThat(response.getSuccessMsg(), is("Role Name updated successfully"));
verify(roleRightsService).updateRole(role);
}
@Test
public void shouldReturnErrorMsgIfUpdateFails() throws Exception {
Role role = new Role("Role Name", "Desc", null);
doThrow(new DataException("Duplicate Role found")).when(roleRightsService).updateRole(role);
ResponseEntity<OpenLmisResponse> responseEntity = controller.updateRole(role.getId(), role, httpServletRequest);
assertThat(responseEntity.getStatusCode(), is(HttpStatus.CONFLICT));
assertThat(responseEntity.getBody().getErrorMsg(), is("Duplicate Role found"));
}
@Test
public void shouldGetRightsForUserAndFacilityProgram() throws Exception {
Set<Right> rights = new HashSet<Right>() {{
add(CREATE_REQUISITION);
}};
Long facilityId = 1L;
Long programId = 1L;
when(roleRightsService.getRightsForUserAndFacilityProgram(eq(LOGGED_IN_USERID), any(Facility.class), any(Program.class))).thenReturn(rights);
ResponseEntity<OpenLmisResponse> response = controller.getRightsForUserAndFacilityProgram(facilityId, programId, httpServletRequest);
assertThat((Set<Right>) response.getBody().getData().get("rights"), is(rights));
verify(roleRightsService).getRightsForUserAndFacilityProgram(eq(LOGGED_IN_USERID), argThat(facilityMatcher(facilityId)), argThat(programMatcher(programId)));
}
} |
package org.jboss.test.ws.jaxws.cxf.jaxbintros;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.configuration.Configurer;
import org.jboss.jaxb.intros.BindingCustomizationFactory;
import org.jboss.wsf.spi.binding.BindingCustomization;
import org.jboss.wsf.spi.binding.JAXBBindingCustomization;
import org.jboss.wsf.stack.cxf.client.configuration.JBossWSConfigurer;
import org.jboss.wsf.test.ClientHelper;
/**
* Test the JAXBIntroduction features.
*
* jaxb-intros.xml can reside under META-INF or WEB-INF and should be
* picked up by JAXBIntroduction deployment aspect on server side.
*
* @author alessio.soldano@jboss.com
*/
public class Helper implements ClientHelper
{
private String endpointAddress;
private URL jaxbIntroUrl;
public Helper()
{
}
public Helper(String endpointAddress)
{
this.setTargetEndpoint(endpointAddress);
}
public boolean testEndpoint() throws Exception
{
Bus bus = setBindingCustomizationOnClientSide();
try
{
URL wsdlURL = new URL(endpointAddress + "?wsdl");
QName serviceName = new QName("http://org.jboss.ws/cxf/jaxbintros", "EndpointBeanService");
Service service = Service.create(wsdlURL, serviceName);
Endpoint port = service.getPort(Endpoint.class);
UserType user = new UserType();
QName qname = new QName("ns", "local", "prefix");
user.setQname(qname);
user.setString("Foo");
UserType result = port.echo(user);
if (!"Foo".equals(result.getString())) {
return false;
}
if (!qname.equals(result.getQname())) {
return false;
}
}
finally
{
bus.shutdown(true);
}
return true;
}
public boolean testAnnotatedUserEndpoint() throws Exception
{
URL wsdlURL = new URL(endpointAddress + "?wsdl");
QName serviceName = new QName("http://org.jboss.ws/cxf/jaxbintros", "EndpointBeanService");
Service service = Service.create(wsdlURL, serviceName);
AnnotatedUserEndpoint port = service.getPort(AnnotatedUserEndpoint.class);
AnnotatedUserType user = new AnnotatedUserType();
QName qname = new QName("ns", "local", "prefix");
user.setQname(qname);
user.setString("Foo");
AnnotatedUserType result = port.echo(user);
if (!"Foo".equals(result.getString())) {
return false;
}
if (!qname.equals(result.getQname())) {
return false;
}
return true;
}
/**
* Setup binding customization on client side using the JBossWSConfigurer
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
private Bus setBindingCustomizationOnClientSide() throws Exception
{
BindingCustomization jaxbCustomizations = new JAXBBindingCustomization();
if (jaxbIntroUrl == null)
{
jaxbIntroUrl = Thread.currentThread().getContextClassLoader().getResource("jaxb-intros.xml");
}
BindingCustomizationFactory.populateBindingCustomization(jaxbIntroUrl.openStream(), jaxbCustomizations);
Bus bus = BusFactory.newInstance().createBus();
BusFactory.setThreadDefaultBus(bus);
JBossWSConfigurer configurer = (JBossWSConfigurer)bus.getExtension(Configurer.class);
configurer.getCustomizer().setBindingCustomization(jaxbCustomizations);
return bus;
}
public void setJAXBIntroURL(URL url)
{
this.jaxbIntroUrl = url;
}
@Override
public void setTargetEndpoint(String address)
{
this.endpointAddress = address;
}
} |
package org.navalplanner.web.planner.order;
import static org.navalplanner.business.common.AdHocTransactionService.readOnlyProxy;
import static org.navalplanner.web.I18nHelper._;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.hibernate.Hibernate;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.navalplanner.business.calendars.entities.BaseCalendar;
import org.navalplanner.business.calendars.entities.SameWorkHoursEveryDay;
import org.navalplanner.business.common.IAdHocTransactionService;
import org.navalplanner.business.common.IOnTransaction;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.orders.daos.IOrderDAO;
import org.navalplanner.business.orders.entities.Order;
import org.navalplanner.business.orders.entities.OrderElement;
import org.navalplanner.business.planner.daos.ITaskElementDAO;
import org.navalplanner.business.planner.entities.DayAssignment;
import org.navalplanner.business.planner.entities.DerivedAllocation;
import org.navalplanner.business.planner.entities.GenericResourceAllocation;
import org.navalplanner.business.planner.entities.ICostCalculator;
import org.navalplanner.business.planner.entities.ResourceAllocation;
import org.navalplanner.business.planner.entities.Task;
import org.navalplanner.business.planner.entities.TaskElement;
import org.navalplanner.business.planner.entities.TaskGroup;
import org.navalplanner.business.planner.entities.TaskMilestone;
import org.navalplanner.business.resources.daos.ICriterionDAO;
import org.navalplanner.business.resources.daos.IResourceDAO;
import org.navalplanner.business.resources.entities.Criterion;
import org.navalplanner.business.resources.entities.Resource;
import org.navalplanner.business.users.daos.IOrderAuthorizationDAO;
import org.navalplanner.business.users.daos.IUserDAO;
import org.navalplanner.business.users.entities.OrderAuthorization;
import org.navalplanner.business.users.entities.OrderAuthorizationType;
import org.navalplanner.business.users.entities.User;
import org.navalplanner.business.users.entities.UserRole;
import org.navalplanner.business.workreports.daos.IWorkReportLineDAO;
import org.navalplanner.business.workreports.entities.WorkReportLine;
import org.navalplanner.web.common.ViewSwitcher;
import org.navalplanner.web.planner.ITaskElementAdapter;
import org.navalplanner.web.planner.ITaskElementAdapter.IOnMoveListener;
import org.navalplanner.web.planner.allocation.IResourceAllocationCommand;
import org.navalplanner.web.planner.calendar.CalendarAllocationController;
import org.navalplanner.web.planner.calendar.ICalendarAllocationCommand;
import org.navalplanner.web.planner.chart.Chart;
import org.navalplanner.web.planner.chart.ChartFiller;
import org.navalplanner.web.planner.chart.EarnedValueChartFiller;
import org.navalplanner.web.planner.chart.IChartFiller;
import org.navalplanner.web.planner.chart.EarnedValueChartFiller.EarnedValueType;
import org.navalplanner.web.planner.milestone.IAddMilestoneCommand;
import org.navalplanner.web.planner.milestone.IDeleteMilestoneCommand;
import org.navalplanner.web.planner.order.ISaveCommand.IAfterSaveListener;
import org.navalplanner.web.planner.taskedition.EditTaskController;
import org.navalplanner.web.planner.taskedition.ITaskPropertiesCommand;
import org.navalplanner.web.print.CutyPrint;
import org.navalplanner.web.security.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.zkforge.timeplot.Plotinfo;
import org.zkforge.timeplot.Timeplot;
import org.zkforge.timeplot.geometry.TimeGeometry;
import org.zkforge.timeplot.geometry.ValueGeometry;
import org.zkoss.ganttz.Planner;
import org.zkoss.ganttz.adapters.IStructureNavigator;
import org.zkoss.ganttz.adapters.PlannerConfiguration;
import org.zkoss.ganttz.adapters.PlannerConfiguration.IPrintAction;
import org.zkoss.ganttz.adapters.PlannerConfiguration.IReloadChartListener;
import org.zkoss.ganttz.extensions.ICommand;
import org.zkoss.ganttz.timetracker.TimeTracker;
import org.zkoss.ganttz.timetracker.zoom.DetailItem;
import org.zkoss.ganttz.timetracker.zoom.IDetailItemModificator;
import org.zkoss.ganttz.timetracker.zoom.IZoomLevelChangedListener;
import org.zkoss.ganttz.timetracker.zoom.ZoomLevel;
import org.zkoss.ganttz.util.Interval;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Div;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Tabbox;
import org.zkoss.zul.Tabpanel;
import org.zkoss.zul.Tabpanels;
import org.zkoss.zul.Tabs;
import org.zkoss.zul.Vbox;
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public abstract class OrderPlanningModel implements IOrderPlanningModel {
public static final String COLOR_CAPABILITY_LINE = "#000000"; // Black
public static final String COLOR_ASSIGNED_LOAD_GLOBAL = "#98D471"; // Green
public static final String COLOR_OVERLOAD_GLOBAL = "#FDBE13"; // Orange
public static final String COLOR_ASSIGNED_LOAD_SPECIFIC = "#AA80d5"; // Violet
public static final String COLOR_OVERLOAD_SPECIFIC = "#FF5A11"; // Red
@Autowired
private IOrderDAO orderDAO;
private PlanningState planningState;
@Autowired
private IResourceDAO resourceDAO;
@Autowired
private ICriterionDAO criterionDAO;
@Autowired
private IWorkReportLineDAO workReportLineDAO;
@Autowired
private ITaskElementDAO taskDAO;
@Autowired
private IUserDAO userDAO;
@Autowired
private IOrderAuthorizationDAO orderAuthorizationDAO;
@Autowired
private IAdHocTransactionService transactionService;
private List<IZoomLevelChangedListener> keepAliveZoomListeners = new ArrayList<IZoomLevelChangedListener>();
private ITaskElementAdapter taskElementAdapter;
@Autowired
private ICostCalculator hoursCostCalculator;
private List<Checkbox> earnedValueChartConfigurationCheckboxes = new ArrayList<Checkbox>();
private final class TaskElementNavigator implements
IStructureNavigator<TaskElement> {
@Override
public List<TaskElement> getChildren(TaskElement object) {
return object.getChildren();
}
@Override
public boolean isLeaf(TaskElement object) {
return object.isLeaf();
}
@Override
public boolean isMilestone(TaskElement object) {
if (object != null) {
return object instanceof TaskMilestone;
}
return false;
}
}
@Override
@Transactional(readOnly = true)
public void setConfigurationToPlanner(Planner planner, Order order,
ViewSwitcher switcher,
EditTaskController editTaskController,
CalendarAllocationController calendarAllocationController,
List<ICommand<TaskElement>> additional) {
Order orderReloaded = reload(order);
if (!orderReloaded.isSomeTaskElementScheduled()) {
throw new IllegalArgumentException(_(
"The order {0} must be scheduled", orderReloaded));
}
PlannerConfiguration<TaskElement> configuration = createConfiguration(orderReloaded);
addAdditional(additional, configuration);
ISaveCommand saveCommand = null;
if(SecurityUtils.isUserInRole(UserRole.ROLE_EDIT_ALL_ORDERS)) {
saveCommand = buildSaveCommand();
configuration.addGlobalCommand(saveCommand);
}
else {
try {
User user = userDAO.findByLoginName(SecurityUtils.getSessionUserLoginName());
for(OrderAuthorization authorization :
orderAuthorizationDAO.listByOrderUserAndItsProfiles(order, user)) {
if(authorization.getAuthorizationType() ==
OrderAuthorizationType.WRITE_AUTHORIZATION) {
saveCommand = buildSaveCommand();
configuration.addGlobalCommand(saveCommand);
break;
}
}
}
catch(InstanceNotFoundException e) {
//this case shouldn't happen, because it would mean that there isn't a logged user
//anyway, if it happenned we continue, disabling the save button
}
}
final IResourceAllocationCommand resourceAllocationCommand = buildResourceAllocationCommand(editTaskController);
configuration.addCommandOnTask(resourceAllocationCommand);
configuration.addCommandOnTask(buildMilestoneCommand());
configuration.addCommandOnTask(buildDeleteMilestoneCommand());
configuration
.addCommandOnTask(buildCalendarAllocationCommand(calendarAllocationController));
configuration
.addCommandOnTask(buildTaskPropertiesCommand(editTaskController));
configuration
.addCommandOnTask(buildSubcontractCommand(editTaskController));
configuration.setDoubleClickCommand(resourceAllocationCommand);
addPrintSupport(configuration, order);
Tabbox chartComponent = new Tabbox();
chartComponent.setOrient("vertical");
chartComponent.setHeight("200px");
appendTabs(chartComponent);
configuration.setChartComponent(chartComponent);
showDeadlineIfExists(orderReloaded, configuration);
planner.setConfiguration(configuration);
Timeplot chartLoadTimeplot = new Timeplot();
Timeplot chartEarnedValueTimeplot = new Timeplot();
OrderEarnedValueChartFiller earnedValueChartFiller = new OrderEarnedValueChartFiller(
orderReloaded);
earnedValueChartFiller.calculateValues(planner.getTimeTracker()
.getRealInterval());
appendTabpanels(chartComponent, chartLoadTimeplot,
chartEarnedValueTimeplot, earnedValueChartFiller);
Chart loadChart = setupChart(orderReloaded,
new OrderLoadChartFiller(orderReloaded), chartLoadTimeplot,
planner.getTimeTracker());
refillLoadChartWhenNeeded(configuration, planner, saveCommand,
loadChart);
Chart earnedValueChart = setupChart(orderReloaded,
earnedValueChartFiller,
chartEarnedValueTimeplot, planner.getTimeTracker());
refillLoadChartWhenNeeded(configuration, planner, saveCommand,
earnedValueChart);
setEventListenerConfigurationCheckboxes(earnedValueChart);
}
private void addPrintSupport(
PlannerConfiguration<TaskElement> configuration, final Order order) {
configuration.setPrintAction(new IPrintAction() {
@Override
public void doPrint() {
CutyPrint.print(order);
}
@Override
public void doPrint(Map<String, String> parameters) {
CutyPrint.print(order, parameters);
}
@Override
public void doPrint(HashMap<String, String> parameters,
Planner planner) {
CutyPrint.print(order, parameters, planner);
}
});
}
private IDeleteMilestoneCommand buildDeleteMilestoneCommand() {
IDeleteMilestoneCommand result = getDeleteMilestoneCommand();
result.setState(planningState);
return result;
}
private void showDeadlineIfExists(Order orderReloaded,
PlannerConfiguration<TaskElement> configuration) {
if (orderReloaded.getDeadline() != null) {
configuration
.setSecondLevelModificators(createDeadlineShower(orderReloaded
.getDeadline()));
}
}
private IDetailItemModificator createDeadlineShower(Date orderDeadline) {
final DateTime deadline = new DateTime(orderDeadline);
return new IDetailItemModificator() {
@Override
public DetailItem applyModificationsTo(DetailItem item) {
item.markDeadlineDay(deadline);
return item;
}
};
}
private void appendTabs(Tabbox chartComponent) {
Tabs chartTabs = new Tabs();
chartTabs.appendChild(new Tab(_("Load")));
chartTabs.appendChild(new Tab(_("Earned value")));
chartComponent.appendChild(chartTabs);
chartTabs.setSclass("charts-tabbox");
}
private void appendTabpanels(Tabbox chartComponent, Timeplot loadChart,
Timeplot chartEarnedValueTimeplot,
OrderEarnedValueChartFiller earnedValueChartFiller) {
Tabpanels chartTabpanels = new Tabpanels();
Tabpanel loadChartPannel = new Tabpanel();
appendLoadChartAndLegend(loadChartPannel, loadChart);
chartTabpanels.appendChild(loadChartPannel);
Tabpanel earnedValueChartPannel = new Tabpanel();
appendEarnedValueChartAndLegend(earnedValueChartPannel,
chartEarnedValueTimeplot, earnedValueChartFiller);
chartTabpanels.appendChild(earnedValueChartPannel);
chartComponent.appendChild(chartTabpanels);
}
private void appendLoadChartAndLegend(Tabpanel loadChartPannel,
Timeplot loadChart) {
Hbox hbox = new Hbox();
hbox.appendChild(getLoadChartLegend());
hbox.setSclass("load-chart");
Div div = new Div();
div.appendChild(loadChart);
div.setSclass("plannergraph");
hbox.appendChild(div);
loadChartPannel.appendChild(hbox);
}
private org.zkoss.zk.ui.Component getLoadChartLegend() {
Hbox hbox = new Hbox();
hbox.setClass("legend-container");
hbox.setAlign("center");
hbox.setPack("center");
Executions.createComponents("/planner/_legendLoadChartOrder.zul", hbox,
null);
return hbox;
}
private void appendEarnedValueChartAndLegend(
Tabpanel earnedValueChartPannel, Timeplot chartEarnedValueTimeplot,
OrderEarnedValueChartFiller earnedValueChartFiller) {
Vbox vbox = new Vbox();
vbox.setClass("legend-container");
vbox.setAlign("center");
vbox.setPack("center");
Hbox dateHbox = new Hbox();
dateHbox.appendChild(new Label(_("Select date:")));
LocalDate date = new LocalDate();
Datebox datebox = new Datebox(date.toDateTimeAtStartOfDay().toDate());
dateHbox.appendChild(datebox);
appendEventListenerToDateboxIndicators(earnedValueChartFiller, vbox,
datebox);
vbox.appendChild(dateHbox);
vbox.appendChild(getEarnedValueChartConfigurableLegend(
earnedValueChartFiller, date));
Hbox hbox = new Hbox();
hbox.setSclass("earned-value-chart");
hbox.appendChild(vbox);
Div div = new Div();
div.appendChild(chartEarnedValueTimeplot);
div.setSclass("plannergraph");
hbox.appendChild(div);
earnedValueChartPannel.appendChild(hbox);
}
private void appendEventListenerToDateboxIndicators(
final OrderEarnedValueChartFiller earnedValueChartFiller,
final Vbox vbox, final Datebox datebox) {
datebox.addEventListener(Events.ON_CHANGE, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
LocalDate date = new LocalDate(datebox.getValue());
org.zkoss.zk.ui.Component child = vbox
.getFellow("indicatorsTable");
vbox.removeChild(child);
vbox.appendChild(getEarnedValueChartConfigurableLegend(
earnedValueChartFiller, date));
}
});
}
private org.zkoss.zk.ui.Component getEarnedValueChartConfigurableLegend(
OrderEarnedValueChartFiller earnedValueChartFiller, LocalDate date) {
Hbox mainhbox = new Hbox();
mainhbox.setId("indicatorsTable");
Vbox vbox = new Vbox();
vbox.setId("earnedValueChartConfiguration");
vbox.setClass("legend");
Vbox column1 = new Vbox();
Vbox column2 = new Vbox();
column1.setSclass("earned-parameter-column");
column2.setSclass("earned-parameter-column");
int columnNumber = 0;
for (EarnedValueType type : EarnedValueType.values()) {
Checkbox checkbox = new Checkbox(type.getAcronym());
checkbox.setTooltiptext(type.getName());
checkbox.setAttribute("indicator", type);
checkbox.setStyle("color: " + type.getColor());
BigDecimal value = earnedValueChartFiller.getIndicator(type, date);
String units = _("h");
if (type.equals(EarnedValueType.CPI)
|| type.equals(EarnedValueType.SPI)) {
value = value.multiply(new BigDecimal(100));
units = "%";
}
Label valueLabel = new Label(value.intValue() + " " + units);
Hbox hbox = new Hbox();
hbox.appendChild(checkbox);
hbox.appendChild(valueLabel);
columnNumber = columnNumber + 1;
switch (columnNumber) {
case 1:
column1.appendChild(hbox);
break;
case 2:
column2.appendChild(hbox);
columnNumber = 0;
}
earnedValueChartConfigurationCheckboxes.add(checkbox);
}
Hbox hbox = new Hbox();
hbox.appendChild(column1);
hbox.appendChild(column2);
vbox.appendChild(hbox);
mainhbox.appendChild(vbox);
markAsSelectedDefaultIndicators();
return mainhbox;
}
private void markAsSelectedDefaultIndicators() {
for (Checkbox checkbox : earnedValueChartConfigurationCheckboxes) {
EarnedValueType type = (EarnedValueType) checkbox
.getAttribute("indicator");
switch (type) {
case BCWS:
case ACWP:
case BCWP:
checkbox.setChecked(true);
break;
default:
checkbox.setChecked(false);
break;
}
}
}
private Set<EarnedValueType> getEarnedValueSelectedIndicators() {
Set<EarnedValueType> result = new HashSet<EarnedValueType>();
for (Checkbox checkbox : earnedValueChartConfigurationCheckboxes) {
if (checkbox.isChecked()) {
EarnedValueType type = (EarnedValueType) checkbox
.getAttribute("indicator");
result.add(type);
}
}
return result;
}
private void setEventListenerConfigurationCheckboxes(
final Chart earnedValueChart) {
for (Checkbox checkbox : earnedValueChartConfigurationCheckboxes) {
checkbox.addEventListener(Events.ON_CHECK, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
transactionService
.runOnReadOnlyTransaction(new IOnTransaction<Void>() {
@Override
public Void execute() {
earnedValueChart.fillChart();
return null;
}
});
}
});
}
}
private void refillLoadChartWhenNeeded(
PlannerConfiguration<?> configuration, Planner planner,
ISaveCommand saveCommand, final Chart loadChart) {
planner.getTimeTracker().addZoomListener(fillOnZoomChange(loadChart));
if(saveCommand != null) {
saveCommand.addListener(fillChartOnSave(loadChart));
}
taskElementAdapter.addListener(readOnlyProxy(transactionService,
IOnMoveListener.class, new IOnMoveListener() {
@Override
public void moved(TaskElement taskElement) {
loadChart.fillChart();
}
}));
configuration.addReloadChartListener(readOnlyProxy(transactionService,
IReloadChartListener.class, new IReloadChartListener() {
@Override
public void reloadChart() {
loadChart.fillChart();
}
}));
}
private void addAdditional(List<ICommand<TaskElement>> additional,
PlannerConfiguration<TaskElement> configuration) {
for (ICommand<TaskElement> c : additional) {
configuration.addGlobalCommand(c);
}
}
private ICalendarAllocationCommand buildCalendarAllocationCommand(
CalendarAllocationController calendarAllocationController) {
ICalendarAllocationCommand calendarAllocationCommand = getCalendarAllocationCommand();
calendarAllocationCommand
.setCalendarAllocationController(calendarAllocationController);
return calendarAllocationCommand;
}
private ITaskPropertiesCommand buildTaskPropertiesCommand(
EditTaskController editTaskController) {
ITaskPropertiesCommand taskPropertiesCommand = getTaskPropertiesCommand();
taskPropertiesCommand.initialize(editTaskController,
planningState);
return taskPropertiesCommand;
}
private IAddMilestoneCommand buildMilestoneCommand() {
IAddMilestoneCommand addMilestoneCommand = getAddMilestoneCommand();
addMilestoneCommand.setState(planningState);
return addMilestoneCommand;
}
private IResourceAllocationCommand buildResourceAllocationCommand(
EditTaskController editTaskController) {
IResourceAllocationCommand resourceAllocationCommand = getResourceAllocationCommand();
resourceAllocationCommand.initialize(editTaskController,
planningState);
return resourceAllocationCommand;
}
private ISaveCommand buildSaveCommand() {
ISaveCommand saveCommand = getSaveCommand();
saveCommand.setState(planningState);
return saveCommand;
}
private Chart setupChart(Order orderReloaded,
IChartFiller loadChartFiller, Timeplot chartComponent,
TimeTracker timeTracker) {
Chart result = new Chart(chartComponent, loadChartFiller,
timeTracker);
result.fillChart();
return result;
}
private IZoomLevelChangedListener fillOnZoomChange(final Chart loadChart) {
IZoomLevelChangedListener zoomListener = new IZoomLevelChangedListener() {
@Override
public void zoomLevelChanged(ZoomLevel detailLevel) {
loadChart.setZoomLevel(detailLevel);
transactionService
.runOnReadOnlyTransaction(new IOnTransaction<Void>() {
@Override
public Void execute() {
loadChart.fillChart();
return null;
}
});
}
};
keepAliveZoomListeners.add(zoomListener);
return zoomListener;
}
private IAfterSaveListener fillChartOnSave(final Chart loadChart) {
IAfterSaveListener result = new IAfterSaveListener() {
@Override
public void onAfterSave() {
transactionService
.runOnReadOnlyTransaction(new IOnTransaction<Void>() {
@Override
public Void execute() {
loadChart.fillChart();
return null;
}
});
}
};
return result;
}
private PlannerConfiguration<TaskElement> createConfiguration(
Order orderReloaded) {
taskElementAdapter = getTaskElementAdapter();
taskElementAdapter.setOrder(orderReloaded);
TaskGroup taskElement = orderReloaded
.getAssociatedTaskElement();
final List<Resource> allResources = resourceDAO.list(Resource.class);
criterionDAO.list(Criterion.class);
forceLoadOfChildren(Arrays.asList(taskElement));
planningState = new PlanningState(taskElement, orderReloaded
.getAssociatedTasks(), allResources);
forceLoadOfDependenciesCollections(planningState.getInitial());
forceLoadOfWorkingHours(planningState.getInitial());
forceLoadOfLabels(planningState.getInitial());
PlannerConfiguration<TaskElement> result = new PlannerConfiguration<TaskElement>(
taskElementAdapter,
new TaskElementNavigator(), planningState.getInitial());
result.setNotBeforeThan(orderReloaded.getInitDate());
result.setDependenciesConstraintsHavePriority(orderReloaded
.getDependenciesConstraintsHavePriority());
return result;
}
private void forceLoadOfChildren(Collection<? extends TaskElement> initial) {
for (TaskElement each : initial) {
forceLoadOfResourceAllocationsResources(each);
forceLoadOfCriterions(each);
if (each instanceof TaskGroup) {
findChildrenWithQueryToAvoidProxies((TaskGroup) each);
List<TaskElement> children = each.getChildren();
forceLoadOfChildren(children);
}
}
}
/**
* Forcing the load of all criterions so there are no different criterion
* instances for the same criteiron at database
*/
private void forceLoadOfCriterions(TaskElement taskElement) {
List<GenericResourceAllocation> generic = ResourceAllocation.getOfType(
GenericResourceAllocation.class, taskElement
.getResourceAllocations());
for (GenericResourceAllocation each : generic) {
for (Criterion eachCriterion : each.getCriterions()) {
eachCriterion.getName();
}
}
}
/**
* Forcing the load of all resources so the resources at planning state and
* at allocations are the same
*/
private void forceLoadOfResourceAllocationsResources(TaskElement taskElement) {
Set<ResourceAllocation<?>> resourceAllocations = taskElement
.getResourceAllocations();
for (ResourceAllocation<?> each : resourceAllocations) {
each.getAssociatedResources();
for (DerivedAllocation eachDerived : each.getDerivedAllocations()) {
eachDerived.getResources();
}
}
}
private void findChildrenWithQueryToAvoidProxies(TaskGroup group) {
for (TaskElement eachTask : taskDAO.findChildrenOf(group)) {
Hibernate.initialize(eachTask);
}
}
private void forceLoadOfWorkingHours(List<TaskElement> initial) {
for (TaskElement taskElement : initial) {
taskElement.getTaskSource().getTotalHours();
OrderElement orderElement = taskElement.getOrderElement();
if (orderElement != null) {
orderElement.getWorkHours();
}
if (!taskElement.isLeaf()) {
forceLoadOfWorkingHours(taskElement.getChildren());
}
}
}
private void forceLoadOfDependenciesCollections(
Collection<? extends TaskElement> elements) {
for (TaskElement task : elements) {
forceLoadOfDepedenciesCollections(task);
if (!task.isLeaf()) {
forceLoadOfDependenciesCollections(task.getChildren());
}
}
}
private void forceLoadOfDepedenciesCollections(TaskElement task) {
task.getDependenciesWithThisOrigin().size();
task.getDependenciesWithThisDestination().size();
}
private void forceLoadOfLabels(List<TaskElement> initial) {
for (TaskElement taskElement : initial) {
if (taskElement.isLeaf()) {
OrderElement orderElement = taskElement.getOrderElement();
if (orderElement != null) {
orderElement.getLabels().size();
}
} else {
forceLoadOfLabels(taskElement.getChildren());
}
}
}
// spring method injection
protected abstract ITaskElementAdapter getTaskElementAdapter();
protected abstract ISaveCommand getSaveCommand();
protected abstract IResourceAllocationCommand getResourceAllocationCommand();
protected abstract IAddMilestoneCommand getAddMilestoneCommand();
protected abstract IDeleteMilestoneCommand getDeleteMilestoneCommand();
protected abstract ITaskPropertiesCommand getTaskPropertiesCommand();
protected abstract ICalendarAllocationCommand getCalendarAllocationCommand();
private Order reload(Order order) {
try {
return orderDAO.find(order.getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
}
private class OrderLoadChartFiller extends ChartFiller {
private final Order order;
private SortedMap<LocalDate, BigDecimal> mapOrderLoad = new TreeMap<LocalDate, BigDecimal>();
private SortedMap<LocalDate, BigDecimal> mapOrderOverload = new TreeMap<LocalDate, BigDecimal>();
private SortedMap<LocalDate, BigDecimal> mapMaxCapacity = new TreeMap<LocalDate, BigDecimal>();
private SortedMap<LocalDate, BigDecimal> mapOtherLoad = new TreeMap<LocalDate, BigDecimal>();
private SortedMap<LocalDate, BigDecimal> mapOtherOverload = new TreeMap<LocalDate, BigDecimal>();
public OrderLoadChartFiller(Order orderReloaded) {
this.order = orderReloaded;
}
@Override
public void fillChart(Timeplot chart, Interval interval, Integer size) {
chart.getChildren().clear();
chart.invalidate();
String javascript = "zkTasklist.timeplotcontainer_rescroll();";
Clients.evalJavaScript(javascript);
resetMinimumAndMaximumValueForChart();
resetMaps();
List<DayAssignment> orderDayAssignments = order.getDayAssignments();
SortedMap<LocalDate, Map<Resource, Integer>> orderDayAssignmentsGrouped = groupDayAssignmentsByDayAndResource(orderDayAssignments);
List<DayAssignment> resourcesDayAssignments = new ArrayList<DayAssignment>();
for (Resource resource : order.getResources()) {
resourcesDayAssignments.addAll(resource.getAssignments());
}
SortedMap<LocalDate, Map<Resource, Integer>> resourceDayAssignmentsGrouped = groupDayAssignmentsByDayAndResource(resourcesDayAssignments);
fillMaps(orderDayAssignmentsGrouped, resourceDayAssignmentsGrouped);
convertAsNeededByZoomMaps();
Plotinfo plotOrderLoad = createPlotinfo(
mapOrderLoad, interval);
Plotinfo plotOrderOverload = createPlotinfo(
mapOrderOverload,
interval);
Plotinfo plotMaxCapacity = createPlotinfo(
mapMaxCapacity, interval);
Plotinfo plotOtherLoad = createPlotinfo(
mapOtherLoad, interval);
Plotinfo plotOtherOverload = createPlotinfo(
mapOtherOverload,
interval);
plotOrderLoad.setFillColor(COLOR_ASSIGNED_LOAD_SPECIFIC);
plotOrderLoad.setLineWidth(0);
plotOtherLoad.setFillColor(COLOR_ASSIGNED_LOAD_GLOBAL);
plotOtherLoad.setLineWidth(0);
plotMaxCapacity.setLineColor(COLOR_CAPABILITY_LINE);
plotMaxCapacity.setFillColor("#FFFFFF");
plotMaxCapacity.setLineWidth(2);
plotOrderOverload.setFillColor(COLOR_OVERLOAD_SPECIFIC);
plotOrderOverload.setLineWidth(0);
plotOtherOverload.setFillColor(COLOR_OVERLOAD_GLOBAL);
plotOtherOverload.setLineWidth(0);
ValueGeometry valueGeometry = getValueGeometry();
TimeGeometry timeGeometry = getTimeGeometry(interval);
// Stacked area: load - otherLoad - max - overload - otherOverload
appendPlotinfo(chart, plotOrderLoad, valueGeometry, timeGeometry);
appendPlotinfo(chart, plotOtherLoad, valueGeometry, timeGeometry);
appendPlotinfo(chart, plotMaxCapacity, valueGeometry, timeGeometry);
appendPlotinfo(chart, plotOrderOverload, valueGeometry,
timeGeometry);
appendPlotinfo(chart, plotOtherOverload, valueGeometry,
timeGeometry);
chart.setWidth(size + "px");
chart.setHeight("150px");
}
private void resetMaps() {
mapOrderLoad.clear();
mapOrderOverload.clear();
mapMaxCapacity.clear();
mapOtherLoad.clear();
mapOtherOverload.clear();
}
private void convertAsNeededByZoomMaps() {
mapOrderLoad = convertAsNeededByZoom(mapOrderLoad);
mapOrderOverload = convertAsNeededByZoom(mapOrderOverload);
mapMaxCapacity = convertAsNeededByZoom(mapMaxCapacity);
mapOtherLoad = convertAsNeededByZoom(mapOtherLoad);
mapOtherOverload = convertAsNeededByZoom(mapOtherOverload);
}
private void fillMaps(
SortedMap<LocalDate, Map<Resource, Integer>> orderDayAssignmentsGrouped,
SortedMap<LocalDate, Map<Resource, Integer>> resourceDayAssignmentsGrouped) {
for (LocalDate day : orderDayAssignmentsGrouped.keySet()) {
Integer maxCapacity = getMaxCapcity(orderDayAssignmentsGrouped,
day);
mapMaxCapacity.put(day, new BigDecimal(maxCapacity));
Integer orderLoad = 0;
Integer orderOverload = 0;
Integer otherLoad = 0;
Integer otherOverload = 0;
for (Resource resource : orderDayAssignmentsGrouped.get(day)
.keySet()) {
int workableHours = getWorkableHours(resource, day);
Integer hoursOrder = orderDayAssignmentsGrouped.get(day).get(
resource);
Integer hoursOther = resourceDayAssignmentsGrouped.get(day)
.get(resource)
- hoursOrder;
if (hoursOrder <= workableHours) {
orderLoad += hoursOrder;
orderOverload += 0;
} else {
orderLoad += workableHours;
orderOverload += hoursOrder - workableHours;
}
if ((hoursOrder + hoursOther) <= workableHours) {
otherLoad += hoursOther;
otherOverload += 0;
} else {
if (hoursOrder <= workableHours) {
otherLoad += (workableHours - hoursOrder);
otherOverload += hoursOrder + hoursOther
- workableHours;
} else {
otherLoad += 0;
otherOverload += hoursOther;
}
}
}
mapOrderLoad.put(day, new BigDecimal(orderLoad));
mapOrderOverload.put(day, new BigDecimal(orderOverload
+ maxCapacity));
mapOtherLoad.put(day, new BigDecimal(otherLoad + orderLoad));
mapOtherOverload.put(day, new BigDecimal(otherOverload
+ orderOverload + maxCapacity));
}
}
private int getMaxCapcity(
SortedMap<LocalDate, Map<Resource, Integer>> orderDayAssignmentsGrouped,
LocalDate day) {
int maxCapacity = 0;
for (Resource resource : orderDayAssignmentsGrouped.get(day)
.keySet()) {
maxCapacity += getWorkableHours(resource, day);
}
return maxCapacity;
}
private int getWorkableHours(Resource resource, LocalDate day) {
BaseCalendar calendar = resource.getCalendar();
int workableHours = SameWorkHoursEveryDay.getDefaultWorkingDay()
.getCapacityAt(day);
if (calendar != null) {
workableHours = calendar.getCapacityAt(day);
}
return workableHours;
}
}
private class OrderEarnedValueChartFiller extends EarnedValueChartFiller {
private Order order;
public OrderEarnedValueChartFiller(Order orderReloaded) {
this.order = orderReloaded;
}
protected void calculateBudgetedCostWorkScheduled(Interval interval) {
List<TaskElement> list = order
.getAllChildrenAssociatedTaskElements();
list.add(order.getAssociatedTaskElement());
SortedMap<LocalDate, BigDecimal> estimatedCost = new TreeMap<LocalDate, BigDecimal>();
for (TaskElement taskElement : list) {
if (taskElement instanceof Task) {
addCost(estimatedCost, hoursCostCalculator
.getEstimatedCost((Task) taskElement));
}
}
estimatedCost = accumulateResult(estimatedCost);
addZeroBeforeTheFirstValue(estimatedCost);
indicators.put(EarnedValueType.BCWS, calculatedValueForEveryDay(
estimatedCost, interval.getStart(), interval.getFinish()));
}
protected void calculateActualCostWorkPerformed(Interval interval) {
SortedMap<LocalDate, BigDecimal> workReportCost = getWorkReportCost();
workReportCost = accumulateResult(workReportCost);
addZeroBeforeTheFirstValue(workReportCost);
indicators.put(EarnedValueType.ACWP, calculatedValueForEveryDay(
workReportCost, interval.getStart(), interval.getFinish()));
}
public SortedMap<LocalDate, BigDecimal> getWorkReportCost() {
SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
List<WorkReportLine> workReportLines = workReportLineDAO
.findByOrderElementAndChildren(order);
if (workReportLines.isEmpty()) {
return result;
}
for (WorkReportLine workReportLine : workReportLines) {
LocalDate day = new LocalDate(workReportLine.getWorkReport()
.getDate());
BigDecimal cost = new BigDecimal(workReportLine.getNumHours());
if (!result.containsKey(day)) {
result.put(day, BigDecimal.ZERO);
}
result.put(day, result.get(day).add(cost));
}
return result;
}
protected void calculateBudgetedCostWorkPerformed(Interval interval) {
List<TaskElement> list = order
.getAllChildrenAssociatedTaskElements();
list.add(order.getAssociatedTaskElement());
SortedMap<LocalDate, BigDecimal> advanceCost = new TreeMap<LocalDate, BigDecimal>();
for (TaskElement taskElement : list) {
if (taskElement instanceof Task) {
addCost(advanceCost, hoursCostCalculator
.getAdvanceCost((Task) taskElement));
}
}
advanceCost = accumulateResult(advanceCost);
addZeroBeforeTheFirstValue(advanceCost);
indicators.put(EarnedValueType.BCWP, calculatedValueForEveryDay(
advanceCost, interval.getStart(), interval.getFinish()));
}
@Override
protected Set<EarnedValueType> getSelectedIndicators() {
return getEarnedValueSelectedIndicators();
}
}
private ISubcontractCommand buildSubcontractCommand(
EditTaskController editTaskController) {
ISubcontractCommand subcontractCommand = getSubcontractCommand();
subcontractCommand.initialize(editTaskController,
planningState);
return subcontractCommand;
}
protected abstract ISubcontractCommand getSubcontractCommand();
} |
package org.openrdf.repository.object.composition;
import static javassist.bytecode.AnnotationsAttribute.visibleTag;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.ParameterAnnotationsAttribute;
import javassist.bytecode.SignatureAttribute;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.ArrayMemberValue;
import javassist.bytecode.annotation.ClassMemberValue;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.MethodCall;
import org.openrdf.repository.object.annotations.parameterTypes;
import org.openrdf.repository.object.exceptions.ObjectCompositionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class builder.
*
* @author James Leigh
*
*/
public class ClassTemplate {
private Logger logger = LoggerFactory.getLogger(ClassTemplate.class);
private CodeBuilder cb;
private CtClass cc;
private ClassFactory cp;
protected ClassTemplate(final CtClass cc, final ClassFactory cp) {
this.cc = cc;
this.cp = cp;
this.cb = new CodeBuilder(this) {
@Override
public CodeBuilder end() {
try {
semi();
cc.makeClassInitializer().insertAfter(toString());
} catch (CannotCompileException e) {
throw new ObjectCompositionException(e.getMessage()
+ " for " + toString(), e);
}
clear();
return this;
}
};
}
public void addConstructor(Class<?>[] types, String string)
throws ObjectCompositionException {
try {
CtConstructor con = new CtConstructor(asCtClassArray(types), cc);
con.setBody("{" + string + "}");
cc.addConstructor(con);
} catch (CannotCompileException e) {
throw new ObjectCompositionException(e);
} catch (NotFoundException e) {
throw new ObjectCompositionException(e);
}
}
@Override
public String toString() {
return cc.getName();
}
public void addInterface(Class<?> face) throws ObjectCompositionException {
cc.addInterface(get(face));
}
public CodeBuilder assignStaticField(Class<?> type, final String fieldName)
throws ObjectCompositionException {
try {
CtField field = new CtField(get(type), fieldName, cc);
field.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
cc.addField(field);
} catch (CannotCompileException e) {
throw new ObjectCompositionException(e);
}
CodeBuilder code = new CodeBuilder(this) {
@Override
public CodeBuilder end() {
semi();
return cb.code(toString()).end();
}
};
return code.assign(fieldName);
}
public void createField(Class<?> type, String fieldName)
throws ObjectCompositionException {
try {
CtField field = new CtField(get(type), fieldName, cc);
field.setModifiers(Modifier.PRIVATE);
cc.addField(field);
} catch (CannotCompileException e) {
throw new ObjectCompositionException(e);
}
}
public MethodBuilder createMethod(Class<?> type, String name,
Class<?>... parameters) throws ObjectCompositionException {
CtClass[] exces = new CtClass[] { get(Throwable.class) };
try {
CtMethod cm = CtNewMethod.make(get(type), name,
asCtClassArray(parameters), exces, null, cc);
return begin(cm, parameters);
} catch (CannotCompileException e) {
throw new ObjectCompositionException(e);
} catch (NotFoundException e) {
throw new ObjectCompositionException(e);
}
}
public MethodBuilder createPrivateMethod(Class<?> type, String name,
Class<?>... parameters) throws ObjectCompositionException {
CtClass[] exces = new CtClass[] { get(Throwable.class) };
try {
CtMethod cm = CtNewMethod.make(Modifier.PRIVATE, get(type), name,
asCtClassArray(parameters), exces, null, cc);
return begin(cm, parameters);
} catch (CannotCompileException e) {
throw new ObjectCompositionException(e);
} catch (NotFoundException e) {
throw new ObjectCompositionException(e);
}
}
public void copyAnnotationsFrom(Class<?> c) {
ClassFile cf = get(c).getClassFile();
AnnotationsAttribute ai = (AnnotationsAttribute) cf
.getAttribute(visibleTag);
if (ai != null && ai.getAnnotations().length > 0) {
ClassFile info = cc.getClassFile();
info.addAttribute(ai.copy(info.getConstPool(),
Collections.EMPTY_MAP));
}
}
public void addAnnotation(Class<?> type, Class<?>... values) {
ClassFile cf = cc.getClassFile();
ConstPool cp = cf.getConstPool();
ClassMemberValue[] elements = new ClassMemberValue[values.length];
for (int i = 0; i < values.length; i++) {
elements[i] = cb.createClassMemberValue(values[i], cp);
}
ArrayMemberValue value = new ArrayMemberValue(cp);
value.setValue(elements);
AnnotationsAttribute ai = (AnnotationsAttribute) cf
.getAttribute(visibleTag);
if (ai == null) {
ai = new AnnotationsAttribute(cp, visibleTag);
cf.addAttribute(ai);
}
try {
Annotation annotation = new Annotation(cp, get(type));
annotation.addMemberValue("value", value);
ai.addAnnotation(annotation);
} catch (NotFoundException e) {
throw new AssertionError(e);
}
}
public MethodBuilder copyMethod(Method method, String name, boolean bridge)
throws ObjectCompositionException {
try {
CtClass[] parameters = asCtClassArray(getParameterTypes(method));
CtClass[] exces = new CtClass[] { get(Throwable.class) };
CtMethod cm = CtNewMethod.make(get(method.getReturnType()), name,
parameters, exces, null, cc);
MethodInfo info = cm.getMethodInfo();
copyAttributes(method, info);
if (bridge) {
info.setAccessFlags(info.getAccessFlags() | AccessFlag.BRIDGE);
}
return begin(cm, getParameterTypes(method));
} catch (CannotCompileException e) {
throw new ObjectCompositionException(e);
} catch (NotFoundException e) {
throw new ObjectCompositionException(e);
}
}
public MethodBuilder createTransientMethod(Method method)
throws ObjectCompositionException {
String name = method.getName();
Class<?> type = method.getReturnType();
Class<?>[] parameters = getParameterTypes(method);
CtClass[] exces = new CtClass[] { get(Throwable.class) };
try {
CtMethod cm = CtNewMethod.make(get(type), name,
asCtClassArray(parameters), exces, null, cc);
cm.setModifiers(cm.getModifiers() | Modifier.TRANSIENT);
MethodInfo info = cm.getMethodInfo();
copyAttributes(method, info);
info.setAccessFlags(info.getAccessFlags() | AccessFlag.BRIDGE);
return begin(cm, parameters);
} catch (CannotCompileException e) {
throw new ObjectCompositionException(e);
} catch (NotFoundException e) {
throw new ObjectCompositionException(e);
}
}
public CodeBuilder getCodeBuilder() {
return cb;
}
public CtClass getCtClass() {
return cc;
}
public Set<String> getDeclaredFieldNames() {
CtField[] fields = cc.getDeclaredFields();
Set<String> result = new HashSet<String>(fields.length);
for (CtField field : fields) {
result.add(field.getName());
}
return result;
}
public Class<?> getSuperclass() {
try {
return cp.getJavaClass(cc.getSuperclass());
} catch (NotFoundException e) {
throw new ObjectCompositionException(e);
} catch (ClassNotFoundException e) {
throw new ObjectCompositionException(e);
}
}
public Class<?>[] getInterfaces() throws ObjectCompositionException {
try {
CtClass[] cc1 = cc.getInterfaces();
Class<?>[] result = new Class<?>[cc1.length];
for (int i = 0; i < cc1.length; i++) {
result[i] = cp.getJavaClass(cc1[i]);
}
return result;
} catch (NotFoundException e) {
throw new ObjectCompositionException(e);
} catch (ClassNotFoundException e) {
throw new ObjectCompositionException(e);
}
}
public MethodBuilder overrideMethod(Method method, boolean bridge)
throws ObjectCompositionException {
return copyMethod(method, method.getName(), bridge);
}
public Set<Field> getFieldsRead(Method method) throws NotFoundException {
String name = method.getName();
CtClass[] parameters = asCtClassArray(getParameterTypes(method));
final Set<CtMethod> methods = new HashSet<CtMethod>();
final Set<Field> accessed = new HashSet<Field>();
for (CtMethod cm : cc.getMethods()) {
if (equals(cm, name, parameters)) {
findMethodCalls(cm, methods);
}
}
for (CtMethod cm : methods) {
try {
cm.instrument(new ExprEditor() {
@Override
public void edit(FieldAccess f) {
try {
if (f.isReader()) {
CtField field = f.getField();
String name = field.getName();
String dname = field.getDeclaringClass()
.getName();
Class<?> declared = cp.loadClass(dname);
accessed.add(declared.getDeclaredField(name));
}
} catch (RuntimeException exc) {
throw exc;
} catch (Exception exc) {
logger.warn(exc.toString(), exc);
}
}
});
} catch (CannotCompileException e) {
throw new AssertionError(e);
}
}
return accessed;
}
public Set<Field> getFieldsWritten(Method method) throws NotFoundException {
String name = method.getName();
CtClass[] parameters = asCtClassArray(getParameterTypes(method));
final Set<CtMethod> methods = new HashSet<CtMethod>();
final Set<Field> accessed = new HashSet<Field>();
for (CtMethod cm : cc.getMethods()) {
if (equals(cm, name, parameters)) {
findMethodCalls(cm, methods);
}
}
for (CtMethod cm : methods) {
try {
cm.instrument(new ExprEditor() {
@Override
public void edit(FieldAccess f) {
try {
if (f.isWriter()) {
CtField field = f.getField();
String name = field.getName();
String dname = field.getDeclaringClass()
.getName();
Class<?> declared = cp.loadClass(dname);
accessed.add(declared.getDeclaredField(name));
}
} catch (RuntimeException exc) {
throw exc;
} catch (Exception exc) {
logger.warn(exc.toString(), exc);
}
}
});
} catch (CannotCompileException e) {
throw new AssertionError(e);
}
}
return accessed;
}
CtClass get(Class<?> type) throws ObjectCompositionException {
return cp.get(type);
}
private Set<CtMethod> getAll(Method method) throws NotFoundException {
Set<CtMethod> result = new HashSet<CtMethod>();
String name = method.getName();
CtClass[] parameters = asCtClassArray(getParameterTypes(method));
for (CtMethod cm : get(method.getDeclaringClass()).getDeclaredMethods()) {
if (!equals(cm, name, parameters))
continue;
result.add(cm);
}
return result;
}
private Class<?>[] getParameterTypes(Method method) {
if (method.isAnnotationPresent(parameterTypes.class))
return method.getAnnotation(parameterTypes.class).value();
return method.getParameterTypes();
}
private boolean equals(CtMethod cm, String name, CtClass[] parameters)
throws NotFoundException {
if (!cm.getName().equals(name))
return false;
if (Arrays.equals(cm.getParameterTypes(), parameters))
return true;
if (cm.getParameterTypes().length != 1)
return false;
try {
parameterTypes types;
types = (parameterTypes) cm.getAnnotation(parameterTypes.class);
if (types == null)
return false;
return Arrays.equals(asCtClassArray(types.value()), parameters);
} catch (ClassNotFoundException e) {
throw new AssertionError("@parameterTypes not in classpath");
}
}
private void findMethodCalls(CtMethod cm, final Set<CtMethod> methods) {
if (methods.add(cm)) {
try {
cm.instrument(new ExprEditor() {
@Override
public void edit(MethodCall m) {
try {
CtClass enclosing = m.getEnclosingClass();
String className = m.getClassName();
if (isAssignableFrom(className, enclosing)) {
findMethodCalls(m.getMethod(), methods);
}
} catch (NotFoundException e) {
logger.warn(e.toString(), e);
}
}
private boolean isAssignableFrom(String className,
CtClass enclosing) throws NotFoundException {
if (enclosing == null)
return false;
if (className.equals(enclosing.getName()))
return true;
return isAssignableFrom(className, enclosing
.getSuperclass());
}
});
} catch (CannotCompileException e) {
throw new AssertionError(e);
}
}
}
private void copyAttributes(Method method, MethodInfo info)
throws NotFoundException {
copyMethodAnnotations(method, info);
copyParameterAnnotations(method, info);
copyMethodSignature(method, info);
}
private void copyMethodAnnotations(Method method, MethodInfo info)
throws NotFoundException {
for (CtMethod e : getAll(method)) {
MethodInfo em = e.getMethodInfo();
AnnotationsAttribute ai = (AnnotationsAttribute) em
.getAttribute(AnnotationsAttribute.visibleTag);
if (ai == null)
continue;
if (ai.getAnnotations().length > 0) {
info.addAttribute(ai.copy(info.getConstPool(),
Collections.EMPTY_MAP));
break;
}
}
}
private void copyParameterAnnotations(Method method, MethodInfo info)
throws NotFoundException {
for (CtMethod e : getAll(method)) {
MethodInfo em = e.getMethodInfo();
ParameterAnnotationsAttribute ai = (ParameterAnnotationsAttribute) em
.getAttribute(ParameterAnnotationsAttribute.visibleTag);
if (ai == null)
continue;
Annotation[][] anns = ai.getAnnotations();
for (int i = 0, n = anns.length; i < n; i++) {
if (anns[i].length > 0) {
info.addAttribute(ai.copy(info.getConstPool(),
Collections.EMPTY_MAP));
return;
}
}
}
}
private void copyMethodSignature(Method method, MethodInfo info)
throws NotFoundException {
for (CtMethod e : getAll(method)) {
MethodInfo em = e.getMethodInfo();
SignatureAttribute sa = (SignatureAttribute) em
.getAttribute(SignatureAttribute.tag);
if (sa == null)
continue;
if (sa.getSignature() != null) {
info.addAttribute(sa.copy(info.getConstPool(),
Collections.EMPTY_MAP));
break;
}
}
}
private CtClass[] asCtClassArray(Class<?>[] cc) throws NotFoundException {
CtClass[] result = new CtClass[cc.length];
for (int i = 0; i < cc.length; i++) {
result[i] = get(cc[i]);
}
return result;
}
private MethodBuilder begin(CtMethod cm, Class<?>... parameters) {
return new MethodBuilder(this, cm);
}
} |
package org.peerbox.presenter.settings.synchronization;
import java.io.IOException;
import java.nio.file.Path;
import org.controlsfx.control.action.Action;
import org.controlsfx.dialog.Dialogs;
import org.controlsfx.dialog.Dialog;
import org.peerbox.app.manager.file.IFileManager;
import org.peerbox.app.manager.user.IUserManager;
import org.peerbox.interfaces.IFxmlLoaderProvider;
import org.peerbox.presenter.settings.Properties;
import org.peerbox.share.IShareFolderHandler;
import org.peerbox.share.ShareFolderController;
import org.peerbox.share.ShareFolderHandler;
import org.peerbox.view.ViewNames;
import org.peerbox.watchservice.IFileEventManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.MenuItem;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Callback;
/**
* This class is used as a template to produce the context menu of
* the {@link javafx.scene.control.CheckBoxTreeItem CheckBoxTreeItem}s
* for the {@link org.peerbox.presenter.settings.synchronization.
* Synchronization Synchronization} class.
* @author Claudio
*
*/
public class CustomizedTreeCell extends CheckBoxTreeCell<PathItem> {
private static final Logger logger = LoggerFactory.getLogger(CustomizedTreeCell.class);
private ContextMenu menu = new ContextMenu();
private Provider<IShareFolderHandler> shareFolderHandlerProvider;
private Stage stage;
public CustomizedTreeCell(IFileEventManager fileEventManager,
Provider<IShareFolderHandler> shareFolderHandlerProvider){
this.shareFolderHandlerProvider = shareFolderHandlerProvider;
CustomMenuItem deleteItem = new CustomMenuItem(new Label("Delete from network"));
Label shareLabel = new Label("Share");
CustomMenuItem shareItem = new CustomMenuItem(shareLabel);
MenuItem propertiesItem = new MenuItem("Properties");
shareItem.setOnAction(new ShareFolderAction());
menu.getItems().add(deleteItem);
menu.getItems().add(shareItem);
menu.getItems().add(propertiesItem);
menu.setOnShowing(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent arg0) {
if(getItem().isFile()){
shareItem.setVisible(false);
propertiesItem.setVisible(false);
} else if(!getItem().getPath().toFile().exists()){
shareItem.setDisable(true);
Label label = (Label)shareItem.getContent();
label.setTooltip(new Tooltip("You cannot share this folder as it is not synchronized."));
} else {
shareItem.setDisable(false);
shareItem.setVisible(true);
Rectangle rect = new Rectangle();
rect.setWidth(200);
rect.setHeight(100);
Label label = (Label)shareItem.getContent();
label.setTooltip(new Tooltip("Right-click to share this folder with a friend."));
}
}
});
propertiesItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
showProperties(getItem());
}
private void showProperties(PathItem item) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource(
ViewNames.PROPERTIES_VIEW));
loader.setController(new Properties(getItem()));
Parent root = loader.load();
// load UI on Application thread and show window
Runnable showStage = new Runnable() {
@Override
public void run() {
Scene scene = new Scene(root);
stage = new Stage();
stage.setTitle("Properties of "
+ getItem().getPath().getFileName());
stage.setScene(scene);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
stage = null;
}
});
stage.show();
}
};
if (Platform.isFxApplicationThread()) {
showStage.run();
} else {
Platform.runLater(showStage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
deleteItem.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
Action response = Dialogs.create()
.title("You're about to irreversibly hard-delete this file from the network!")
.masthead(null)
.message("Do you really want to hard-delete" + getItem().getPath() + "?" +
" The file is automatically deleted from all devices and cannot be "
+ "reconstructed.")
.actions(Dialog.ACTION_OK, Dialog.ACTION_CANCEL)
.showConfirm();
if(response == Dialog.ACTION_OK){
fileEventManager.onLocalFileHardDelete(getItem().getPath());
Dialogs.create()
.title("PeerWasp Information")
.masthead(null)
.message(getItem().getPath() + " has been hard-deleted.")
.showInformation();
}
}
});
setContextMenu(menu);
}
private class ShareFolderAction implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
IShareFolderHandler handler = shareFolderHandlerProvider.get();
Path toShare = getItem().getPath();
handler.shareFolder(toShare);
}
}
} |
package com.dtstack.jlogstash.inputs;
import com.alibaba.otter.canal.parse.exception.CanalParseException;
import com.alibaba.otter.canal.parse.index.AbstractLogPositionManager;
import com.alibaba.otter.canal.protocol.position.LogPosition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BinlogPositionManager extends AbstractLogPositionManager {
private static final Logger logger = LoggerFactory.getLogger(BinlogPositionManager.class);
private final Binlog binlog;
public BinlogPositionManager(Binlog binlog) {
this.binlog = binlog;
}
@Override
public LogPosition getLatestIndexBy(String destination) {
return null;
}
@Override
public void persistLogPosition(String destination, LogPosition logPosition) throws CanalParseException {
if(logger.isDebugEnabled()){
logger.debug("persistLogPosition: " + logPosition.toString());
}
binlog.updateLastPos(logPosition.getPostion());
}
} |
package gov.nih.nci.cabig.caaers.web.participant;
import gov.nih.nci.cabig.caaers.dao.StudySiteDao;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroupMap;
import gov.nih.nci.cabig.caaers.web.fields.TabWithFields;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
*
* @author Biju Joseph
*
*/
public class ReviewAssignmentTab extends TabWithFields<AssignParticipantStudyCommand> {
private StudySiteDao studySiteDao;
public ReviewAssignmentTab() {
super("Review", "Review", "par/reg_review_submit");
// super("Review and Submit", "Review and Submit", "par/par_confirmation");
}
public Map<String, InputFieldGroup> createFieldGroups(AssignParticipantStudyCommand command) {
InputFieldGroupMap map = new InputFieldGroupMap();
return map;
}
@Override
public void onDisplay(HttpServletRequest request,AssignParticipantStudyCommand command) {
super.onDisplay(request, command);
studySiteDao.lock(command.getStudySite());
}
public StudySiteDao getStudySiteDao() {
return studySiteDao;
}
public void setStudySiteDao(StudySiteDao studySiteDao) {
this.studySiteDao = studySiteDao;
}
} |
package org.ow2.proactive.resourcemanager.selection;
import java.io.File;
import java.security.Permission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.utils.NamedThreadFactory;
import org.ow2.proactive.authentication.principals.TokenPrincipal;
import org.ow2.proactive.permissions.PrincipalPermission;
import org.ow2.proactive.resourcemanager.authentication.Client;
import org.ow2.proactive.resourcemanager.core.RMCore;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.exception.NotConnectedException;
import org.ow2.proactive.resourcemanager.rmnode.RMNode;
import org.ow2.proactive.resourcemanager.selection.policies.ShufflePolicy;
import org.ow2.proactive.resourcemanager.selection.topology.TopologyHandler;
import org.ow2.proactive.scripting.Script;
import org.ow2.proactive.scripting.ScriptException;
import org.ow2.proactive.scripting.ScriptResult;
import org.ow2.proactive.scripting.SelectionScript;
import org.ow2.proactive.utils.Criteria;
import org.ow2.proactive.utils.NodeSet;
import org.ow2.proactive.utils.appenders.MultipleFileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
/**
* An interface of selection manager which is responsible for
* nodes selection from a pool of free nodes for further scripts execution.
*
*/
public abstract class SelectionManager {
private final static Logger logger = Logger.getLogger(SelectionManager.class);
private RMCore rmcore;
private static final int SELECTION_THEADS_NUMBER = PAResourceManagerProperties.RM_SELECTION_MAX_THREAD_NUMBER
.getValueAsInt();
private ExecutorService scriptExecutorThreadPool;
private Set<String> inProgress;
protected HashSet<String> authorizedSelectionScripts = null;
// the policy for arranging nodes
private SelectionPolicy selectionPolicy;
public SelectionManager() {
}
public SelectionManager(RMCore rmcore) {
this.rmcore = rmcore;
this.scriptExecutorThreadPool = Executors.newFixedThreadPool(SELECTION_THEADS_NUMBER,
new NamedThreadFactory("Selection manager threadpool"));
this.inProgress = Collections.synchronizedSet(new HashSet<String>());
String policyClassName = PAResourceManagerProperties.RM_SELECTION_POLICY.getValueAsString();
try {
Class<?> policyClass = Class.forName(policyClassName);
selectionPolicy = (SelectionPolicy) policyClass.newInstance();
} catch (Exception e) {
logger.error("Cannot use the specified policy class: " + policyClassName, e);
logger.warn("Using the default class: " + ShufflePolicy.class.getName());
selectionPolicy = new ShufflePolicy();
}
loadAuthorizedScriptsSignatures();
}
/**
* Loads authorized selection scripts.
*/
public void loadAuthorizedScriptsSignatures() {
String dirName = PAResourceManagerProperties.RM_EXECUTE_SCRIPT_AUTHORIZED_DIR.getValueAsString();
if (dirName != null && dirName.length() > 0) {
dirName = PAResourceManagerProperties.getAbsolutePath(dirName);
logger.info("The resource manager will accept only selection scripts from " + dirName);
File folder = new File(dirName);
if (folder.exists() && folder.isDirectory()) {
authorizedSelectionScripts = new HashSet<>();
for (File file : folder.listFiles()) {
if (file.isFile()) {
try {
String script = SelectionScript.readFile(file);
logger.debug("Adding authorized selection script " + file.getAbsolutePath());
authorizedSelectionScripts.add(SelectionScript.digest(script));
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
} else {
logger.error("Invalid dir name for authorized scripts " + dirName);
}
}
}
/**
* Arranges nodes for script execution based on some criteria
* for example previous execution statistics.
*
* @param nodes - nodes list for script execution
* @param scripts - set of selection scripts
* @return collection of arranged nodes
*/
public abstract List<RMNode> arrangeNodesForScriptExecution(final List<RMNode> nodes,
List<SelectionScript> scripts);
/**
* Predicts script execution result. Allows to avoid duplicate script execution
* on the same node.
*
* @param script - script to execute
* @param rmnode - target node
* @return true if script will pass on the node
*/
public abstract boolean isPassed(SelectionScript script, RMNode rmnode);
/**
* Processes script result and updates knowledge base of
* selection manager at the same time.
*
* @param script - executed script
* @param scriptResult - obtained script result
* @param rmnode - node on which script has been executed
* @return whether node is selected
*/
public abstract boolean processScriptResult(SelectionScript script, ScriptResult<Boolean> scriptResult,
RMNode rmnode);
public NodeSet selectNodes(Criteria criteria, Client client) {
maybeSetLoggingContext(criteria);
try {
return doSelectNodes(criteria, client);
} finally {
unsetLoggingContext();
}
}
static void maybeSetLoggingContext(Criteria criteria) {
if (criteria.getComputationDescriptors() != null) {
// logging selection script execution into tasks logs
MDC.put(MultipleFileAppender.FILE_NAMES, criteria.getComputationDescriptors());
}
}
static void unsetLoggingContext() {
MDC.remove(MultipleFileAppender.FILE_NAMES);
}
private NodeSet doSelectNodes(Criteria criteria, Client client) {
boolean hasScripts = criteria.getScripts() != null && criteria.getScripts().size() > 0;
logger.info(client + " requested " + criteria.getSize() + " nodes with " + criteria.getTopology());
if (logger.isDebugEnabled()) {
if (hasScripts) {
logger.debug("Selection scripts:");
for (SelectionScript s : criteria.getScripts()) {
logger.debug(s);
}
}
if (criteria.getBlackList() != null && criteria.getBlackList().size() > 0) {
logger.debug("Black list nodes:");
for (Node n : criteria.getBlackList()) {
logger.debug(n);
}
}
}
// can throw Exception if topology is disabled
TopologyHandler handler = RMCore.topologyManager.getHandler(criteria.getTopology());
List<RMNode> freeNodes = rmcore.getFreeNodes();
// filtering out the "free node list"
List<RMNode> filteredNodes = filterOut(freeNodes, criteria, client);
if (filteredNodes.size() == 0) {
logger.debug(client + " will get 0 nodes");
return new NodeSet();
}
// arranging nodes according to the selection policy
// if could be shuffling or node source priorities
List<RMNode> afterPolicyNodes = selectionPolicy.arrangeNodes(criteria.getSize(), filteredNodes,
client);
List<Node> matchedNodes;
if (hasScripts) {
// checking if all scripts are authorized
checkAuthorizedScripts(criteria.getScripts());
// arranging nodes for script execution
List<RMNode> arrangedNodes = arrangeNodesForScriptExecution(afterPolicyNodes,
criteria.getScripts());
if (criteria.getTopology().isTopologyBased()) {
// run scripts on all available nodes
matchedNodes = runScripts(arrangedNodes, criteria);
} else {
// run scripts not on all nodes, but always on missing number of nodes
// until required node set is found
matchedNodes = new LinkedList<>();
while (matchedNodes.size() < criteria.getSize()) {
int numberOfNodesForScriptExecution = criteria.getSize() - matchedNodes.size();
if (numberOfNodesForScriptExecution < SELECTION_THEADS_NUMBER) {
// we can run "SELECTION_THEADS_NUMBER" scripts in parallel
// in case when we need less nodes it still useful to
// the full capacity of the thread pool to find nodes quicker
// it is not important if we find more nodes than needed
// subset will be selected later (topology handlers)
numberOfNodesForScriptExecution = SELECTION_THEADS_NUMBER;
}
List<RMNode> subset = arrangedNodes.subList(0,
Math.min(numberOfNodesForScriptExecution, arrangedNodes.size()));
matchedNodes.addAll(runScripts(subset, criteria));
// removing subset of arrangedNodes
subset.clear();
if (arrangedNodes.size() == 0) {
break;
}
}
}
logger.debug(matchedNodes.size() + " nodes found after scripts execution for " + client);
} else {
matchedNodes = new LinkedList<>();
for (RMNode node : afterPolicyNodes) {
matchedNodes.add(node.getNode());
}
}
// now we have a list of nodes which match to selection scripts
// selecting subset according to topology requirements
// TopologyHandler handler = RMCore.topologyManager.getHandler(topologyDescriptor);
if (criteria.getTopology().isTopologyBased()) {
logger.debug("Filtering nodes with topology " + criteria.getTopology());
}
NodeSet selectedNodes = handler.select(criteria.getSize(), matchedNodes);
if (selectedNodes.size() < criteria.getSize() && !criteria.isBestEffort()) {
selectedNodes.clear();
if (selectedNodes.getExtraNodes() != null) {
selectedNodes.getExtraNodes().clear();
}
}
// the nodes are selected, now mark them as busy.
for (Node node : selectedNodes) {
try {
// Synchronous call
rmcore.setBusyNode(node.getNodeInformation().getURL(), client);
} catch (NotConnectedException e) {
// client has disconnected during getNodes request
logger.warn(e.getMessage(), e);
return null;
}
}
// marking extra selected nodes as busy
if (selectedNodes.size() > 0 && selectedNodes.getExtraNodes() != null) {
for (Node node : new LinkedList<>(selectedNodes.getExtraNodes())) {
try {
// synchronous call
rmcore.setBusyNode(node.getNodeInformation().getURL(), client);
} catch (NotConnectedException e) {
// client has disconnected during getNodes request
logger.warn(e.getMessage(), e);
return null;
}
}
}
String extraNodes = selectedNodes.getExtraNodes() != null && selectedNodes.getExtraNodes().size() > 0 ? "and " +
selectedNodes.getExtraNodes().size() + " extra nodes"
: "";
logger.info(client + " will get " + selectedNodes.size() + " nodes " + extraNodes);
if (logger.isDebugEnabled()) {
for (Node n : selectedNodes) {
logger.debug(n.getNodeInformation().getURL());
}
}
return selectedNodes;
}
/**
* Checks is all scripts are authorized. If not throws an exception.
*/
private void checkAuthorizedScripts(List<SelectionScript> scripts) {
if (authorizedSelectionScripts == null || scripts == null)
return;
for (SelectionScript script : scripts) {
if (!authorizedSelectionScripts.contains(SelectionScript.digest(script.getScript()))) {
// unauthorized selection script
throw new SecurityException("Cannot execute unauthorized script " + script.getScript());
}
}
}
/**
* Runs scripts on given set of nodes and returns matched nodes.
* It blocks until all results are obtained.
*
* @param candidates nodes to execute scripts on
* @param criteria contains a set of scripts to execute on each node
* @return nodes matched to all scripts
*/
private List<Node> runScripts(List<RMNode> candidates, Criteria criteria) {
List<Node> matched = new LinkedList<>();
if (candidates.size() == 0) {
return matched;
}
// creating script executors object to be run in dedicated thread pool
List<Callable<Node>> scriptExecutors = new LinkedList<>();
synchronized (inProgress) {
if (inProgress.size() > 0) {
logger.warn(inProgress.size() + " nodes are in process of script execution");
for (String nodeName : inProgress) {
logger.warn(nodeName);
}
logger.warn("Something is wrong on these nodes");
}
for (RMNode node : candidates) {
if (!inProgress.contains(node.getNodeURL())) {
inProgress.add(node.getNodeURL());
scriptExecutors.add(new ScriptExecutor(node, criteria, this));
}
}
}
try {
// launching
Collection<Future<Node>> matchedNodes = scriptExecutorThreadPool.invokeAll(scriptExecutors,
PAResourceManagerProperties.RM_SELECT_SCRIPT_TIMEOUT.getValueAsInt(),
TimeUnit.MILLISECONDS);
int index = 0;
// waiting for the results
for (Future<Node> futureNode : matchedNodes) {
if (!futureNode.isCancelled()) {
Node node;
try {
node = futureNode.get();
if (node != null) {
matched.add(node);
}
} catch (InterruptedException e) {
logger.warn("Interrupting the selection manager");
return matched;
} catch (ExecutionException e) {
logger.warn("Ignoring exception in selection script: " + e.getMessage());
}
} else {
// no script result was obtained
logger.warn("Timeout on " + scriptExecutors.get(index));
// in this case scriptExecutionFinished may not be called
scriptExecutionFinished(((ScriptExecutor) scriptExecutors.get(index)).getRMNode()
.getNodeURL());
}
index++;
}
} catch (InterruptedException e1) {
logger.warn("Interrupting the selection manager");
}
return matched;
}
/**
* Removes exclusion nodes and nodes not accessible for the client
*/
private List<RMNode> filterOut(List<RMNode> freeNodes, Criteria criteria, Client client) {
NodeSet exclusion = criteria.getBlackList();
boolean nodeWithTokenRequested = criteria.getNodeAccessToken() != null &&
criteria.getNodeAccessToken().length() > 0;
TokenPrincipal tokenPrincipal = null;
if (nodeWithTokenRequested) {
logger.debug("Node access token specified " + criteria.getNodeAccessToken());
tokenPrincipal = new TokenPrincipal(criteria.getNodeAccessToken());
client.getSubject().getPrincipals().add(tokenPrincipal);
}
List<RMNode> filteredList = new ArrayList<>();
HashSet<Permission> clientPermissions = new HashSet<>();
for (RMNode node : freeNodes) {
try {
if (!clientPermissions.contains(node.getUserPermission())) {
client.checkPermission(node.getUserPermission(), client +
" is not authorized to get the node " + node.getNodeURL() + " from " +
node.getNodeSource().getName());
clientPermissions.add(node.getUserPermission());
}
} catch (SecurityException e) {
// client does not have an access to this node
logger.debug(e.getMessage());
continue;
}
// if the node access token is specified we filtered out all nodes
// with other tokens but must also filter out nodes without tokens
if (nodeWithTokenRequested && !node.isProtectedByToken()) {
continue;
}
// we will avoid it here
if (nodeWithTokenRequested) {
PrincipalPermission perm = (PrincipalPermission) node.getUserPermission();
// checking explicitly that node has this token identity
if (!perm.hasPrincipal(tokenPrincipal)) {
logger.debug(client + " does not have required token to get the node " +
node.getNodeURL() + " from " + node.getNodeSource().getName());
continue;
}
}
if (!contains(exclusion, node)) {
filteredList.add(node);
}
}
return filteredList;
}
public <T> List<ScriptResult<T>> executeScript(final Script<T> script, final Collection<RMNode> nodes) {
// TODO: add a specific timeout for script execution
final int timeout = PAResourceManagerProperties.RM_EXECUTE_SCRIPT_TIMEOUT.getValueAsInt();
final ArrayList<Callable<ScriptResult<T>>> scriptExecutors = new ArrayList<>(
nodes.size());
// Execute the script on each selected node
for (final RMNode node : nodes) {
scriptExecutors.add(new Callable<ScriptResult<T>>() {
@Override
public ScriptResult<T> call() throws Exception {
// Execute with a timeout the script by the remote handler
// and always async-unlock the node, exceptions will be treated as ExecutionException
try {
ScriptResult<T> res = node.executeScript(script);
PAFuture.waitFor(res, timeout);
return res;
//return PAFuture.getFutureValue(res, timeout);
} finally {
// cleaning the node
try {
node.clean();
} catch (Throwable ex) {
logger.error("Cannot clean the node " + node.getNodeURL(), ex);
}
SelectionManager.this.rmcore.unlockNodes(Collections.singleton(node.getNodeURL()));
}
}
@Override
public String toString() {
return "executing script on " + node.getNodeURL();
}
});
}
// Invoke all Callables and get the list of futures
List<Future<ScriptResult<T>>> futures = null;
try {
futures = this.scriptExecutorThreadPool
.invokeAll(scriptExecutors, timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.warn("Interrupted while waiting, unable to execute all scripts", e);
Thread.currentThread().interrupt();
}
final List<ScriptResult<T>> results = new LinkedList<>();
int index = 0;
// waiting for the results
for (final Future<ScriptResult<T>> future : futures) {
final String description = scriptExecutors.get(index++).toString();
ScriptResult<T> result = null;
try {
result = future.get();
} catch (CancellationException e) {
result = new ScriptResult<>(new ScriptException("Cancelled due to timeout expiration when " +
description, e));
} catch (InterruptedException e) {
result = new ScriptResult<>(new ScriptException("Cancelled due to interruption when " +
description));
} catch (ExecutionException e) {
// Unwrap the root exception
Throwable rex = e.getCause();
result = new ScriptResult<>(new ScriptException("Exception occured in script call when " +
description, rex));
}
results.add(result);
}
return results;
}
/**
* Indicates that script execution is finished for the node with specified url.
*/
public void scriptExecutionFinished(String nodeUrl) {
synchronized (inProgress) {
inProgress.remove(nodeUrl);
}
}
/**
* Handles shut down of the selection manager
*/
public void shutdown() {
// shutdown the thread pool without waiting for script execution completions
scriptExecutorThreadPool.shutdownNow();
PAActiveObject.terminateActiveObject(false);
}
/**
* Return true if node contains the node set.
*
* @param nodeset - a list of nodes to inspect
* @param node - a node to find
* @return true if node contains the node set.
*/
private boolean contains(NodeSet nodeset, RMNode node) {
if (nodeset == null)
return false;
for (Node n : nodeset) {
try {
if (n.getNodeInformation().getURL().equals(node.getNodeURL())) {
return true;
}
} catch (Exception e) {
continue;
}
}
return false;
}
} |
package com.planetmayo.debrief.satc.model.contributions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.ListIterator;
import com.planetmayo.debrief.satc.model.VehicleType;
import com.planetmayo.debrief.satc.model.states.BaseRange;
import com.planetmayo.debrief.satc.model.states.BaseRange.IncompatibleStateException;
import com.planetmayo.debrief.satc.model.states.BoundedState;
import com.planetmayo.debrief.satc.model.states.ProblemSpace;
public abstract class BaseAnalysisContribution<R extends BaseRange<?>> extends
BaseContribution
{
private static final long serialVersionUID = 1L;
/**
* apply this bounded constraint to all to all of the states in the list
*
* @param commonRange
* @param statesInThisLeg
* @throws IncompatibleStateException
*/
protected void assignCommonState(R commonRange,
ArrayList<BoundedState> statesInThisLeg)
throws IncompatibleStateException
{
// ok - apply the common bounded range to all the states in the leg
// have we produced a constrained range?
if (commonRange != null)
{
// yes. we need to apply the min constraints to all the points in
// that leg
Iterator<BoundedState> iter = statesInThisLeg.iterator();
while (iter.hasNext())
{
BoundedState boundedState = (BoundedState) iter.next();
applyThis(boundedState, commonRange);
}
}
// now we need to clear the remembered states, so we're ready for the
// next leg
statesInThisLeg.clear();
}
protected abstract void applyThis(BoundedState state, R thisState)
throws IncompatibleStateException;
@Override
public void actUpon(final ProblemSpace space)
throws IncompatibleStateException
{
// do a forward pass through the list
analyseConstraints(space, new SwitchableIterator(true));
// and now a reverse pass
analyseConstraints(space, new SwitchableIterator(false));
}
/** support class that lets use move either forwards or backwards through a list
*
* @author Ian
*
*/
private static class SwitchableIterator
{
private final boolean _fwd;
protected SwitchableIterator(boolean fwd)
{
_fwd = fwd;
}
protected ListIterator<BoundedState> getIterator(ArrayList<BoundedState> states )
{
if(_fwd)
return states.listIterator();
else
return states.listIterator(states.size());
}
protected BoundedState next(ListIterator<BoundedState> iter)
{
if (_fwd)
return iter.next();
else
return iter.previous();
}
protected boolean canStep(ListIterator<BoundedState> iter)
{
if (_fwd)
return iter.hasNext();
else
return iter.hasPrevious();
}
}
private void analyseConstraints(final ProblemSpace space,
SwitchableIterator switcher) throws IncompatibleStateException
{
// remember the previous state
BoundedState lastStateWithState = null;
// remember the current bounded range
R currentLegRange = null;
// keep track of the states in this leg - so we can apply the common range
// bounds to them
final ArrayList<BoundedState> statesInThisLeg = new ArrayList<BoundedState>();
// get the vehicle type
final VehicleType vType = space.getVehicleType();
// ok, loop through the states, setting range limits for any unbounded
// ranges
Collection<BoundedState> theStates = space.states();
ArrayList<BoundedState> al = new ArrayList<BoundedState>(theStates);
ListIterator<BoundedState> iter = switcher.getIterator(al);
while(switcher.canStep(iter))
{
BoundedState currentState = switcher.next(iter);
// ok - what leg is this?
String thisLeg = currentState.getMemberOf();
// is it even in a leg?
if (thisLeg == null)
{
// ok, have we just finished a leg?
if (!statesInThisLeg.isEmpty())
{
assignCommonState(currentLegRange, statesInThisLeg);
currentLegRange = null;
}
// ok, we're not in a leg. relax it.
lastStateWithState = applyRelaxedRangeBounds(lastStateWithState,
currentState, vType);
}
else
{
// ok, we're in a leg - see if this is the first point (in which case we
// allow relaxation),
// or a successive point (in which case we just constrain)
// is this the first item in this leg
if (statesInThisLeg.isEmpty())
{
// yes. this is the first leg. We do need to allow some relaxation
// on range from the previous one
lastStateWithState = applyRelaxedRangeBounds(lastStateWithState,
currentState, vType);
// now we can probably store this state
if (lastStateWithState != null)
currentLegRange = getRangeFor(lastStateWithState);
}
else
{
// ok, we won't be relaxing this leg - we're just going to further
// constrain the range
// does this have a range consraint?
R thisRange = getRangeFor(currentState);
if (thisRange != null)
{
if (currentLegRange == null)
{
// ok, store it
currentLegRange = duplicateThis(thisRange);
}
else
{
// ok, constrain it.
furtherConstrain(currentLegRange, thisRange);
}
}
// but, we do need to know the DTG and range of the last
// state that had both. If we've ever had a range constraint,
// then we know we're able to use this state for the DTG.
if (lastStateWithState != null)
lastStateWithState = currentState;
}
// ok, remmber this leg
statesInThisLeg.add(currentState);
}
}
// ok, do we have a dangling set of states to be assigned?
if (!statesInThisLeg.isEmpty())
{
assignCommonState(currentLegRange, statesInThisLeg);
currentLegRange = null;
}
}
protected BoundedState applyRelaxedRangeBounds(
BoundedState lastStateWithRange, BoundedState currentState,
VehicleType vehicleType) throws IncompatibleStateException
{
R newRange = null;
// do we have vehicle reference data?
if (vehicleType != null)
{
// do we have a previous state?
if (lastStateWithRange != null)
{
// ok, how long since that last observation?
long millis = currentState.getTime().getTime()
- lastStateWithRange.getTime().getTime();
// just in case we're doing a reverse pass, use the abs millis
millis = Math.abs(millis);
// ok, what does that state relax to
newRange = calcRelaxedRange(lastStateWithRange, vehicleType, millis);
// ok, apply this new constraint, or further constrain any existing one
applyThis(currentState, newRange);
}
}
final BoundedState newLastState;
// ok, now a tricky bit. We have to find out if we have a new state object that
// has a constraint in our range type.
// retrieve our range
R thisRange = getRangeFor(currentState);
// is there a range for our type?
if (thisRange != null)
{
// yes - we can use this state
newLastState = currentState;
}
else
{
// have we calculated a relaxed range?
if(newRange != null)
// yes, use it
newLastState = currentState;
else
// now, lose the constraint
newLastState= null;
}
return newLastState;
}
abstract protected void relaxConstraint(BoundedState currentState, R newRange);
/**
* apply our range to this existing one
*
* @param currentLegRange
* @param thisRange
* @throws IncompatibleStateException
*/
abstract protected void furtherConstrain(R currentLegRange, R thisRange)
throws IncompatibleStateException;
/**
* run the copy constructor for this range
*
* @param thisRange
* @return
*/
protected abstract R duplicateThis(R thisRange);
/**
* extract my range type from this state
*
* @param lastStateWithRange
* @return
*/
abstract protected R getRangeFor(BoundedState lastStateWithRange);
/** ok, how far does the range relax after the specified period
*
* @param lastStateWithRange the last known state with contraints for our range
* @param vType the vehicle type data
* @param millis how long has elapsed
* @return the new bounded state
*/
abstract protected R calcRelaxedRange(BoundedState lastStateWithRange,
VehicleType vType, long millis);
} |
package org.apache.mesos.elasticsearch.scheduler;
import org.apache.log4j.Logger;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.elasticsearch.common.Discovery;
import org.apache.mesos.elasticsearch.scheduler.cluster.ClusterMonitor;
import org.apache.mesos.elasticsearch.scheduler.state.ClusterState;
import org.apache.mesos.elasticsearch.scheduler.state.FrameworkState;
import java.net.InetSocketAddress;
import java.util.*;
/**
* Scheduler for Elasticsearch.
*/
@SuppressWarnings({"PMD.TooManyMethods"})
public class ElasticsearchScheduler implements Scheduler {
private static final Logger LOGGER = Logger.getLogger(ElasticsearchScheduler.class.toString());
private final Configuration configuration;
private final TaskInfoFactory taskInfoFactory;
private ClusterMonitor clusterMonitor = null;
Clock clock = new Clock();
Map<String, Task> tasks = new HashMap<>();
private Observable statusUpdateWatchers = new StatusUpdateObservable();
private Boolean registered = false;
public ElasticsearchScheduler(Configuration configuration, TaskInfoFactory taskInfoFactory) {
this.configuration = configuration;
this.taskInfoFactory = taskInfoFactory;
}
public Map<String, Task> getTasks() {
return tasks;
}
public void run() {
LOGGER.info("Starting ElasticSearch on Mesos - [numHwNodes: " + configuration.getNumberOfHwNodes() + ", zk: " + configuration.getZookeeperUrl() + ", ram:" + configuration.getMem() + "]");
final Protos.FrameworkInfo.Builder frameworkBuilder = Protos.FrameworkInfo.newBuilder();
frameworkBuilder.setUser("");
frameworkBuilder.setName(configuration.getFrameworkName());
frameworkBuilder.setFailoverTimeout(configuration.getFailoverTimeout());
frameworkBuilder.setCheckpoint(true); // DCOS certification 04 - Checkpointing is enabled.
Protos.FrameworkID frameworkID = configuration.getFrameworkId(); // DCOS certification 02
if (frameworkID != null && !frameworkID.getValue().isEmpty()) {
LOGGER.info("Found previous frameworkID: " + frameworkID);
frameworkBuilder.setId(frameworkID);
}
final MesosSchedulerDriver driver = new MesosSchedulerDriver(this, frameworkBuilder.build(), configuration.getZookeeperUrl());
driver.run();
}
@Override
public void registered(SchedulerDriver driver, Protos.FrameworkID frameworkId, Protos.MasterInfo masterInfo) {
FrameworkState frameworkState = new FrameworkState(configuration.getState());
frameworkState.setFrameworkId(frameworkId);
configuration.setFrameworkState(frameworkState); // DCOS certification 02
LOGGER.info("Framework registered as " + frameworkId.getValue());
ClusterState clusterState = new ClusterState(configuration.getState(), frameworkState); // Must use new framework state. This is when we are allocated our FrameworkID.
clusterMonitor = new ClusterMonitor(configuration, this, driver, clusterState);
statusUpdateWatchers.addObserver(clusterMonitor);
List<Protos.Resource> resources = Resources.buildFrameworkResources(configuration);
Protos.Request request = Protos.Request.newBuilder()
.addAllResources(resources)
.build();
List<Protos.Request> requests = Collections.singletonList(request);
driver.requestResources(requests);
registered = true;
}
@Override
public void reregistered(SchedulerDriver driver, Protos.MasterInfo masterInfo) {
LOGGER.info("Framework re-registered");
}
// Todo, this massive if statement needs to be performed better.
@Override
public void resourceOffers(SchedulerDriver driver, List<Protos.Offer> offers) {
if (!registered) {
LOGGER.debug("Not registered, can't accept resource offers.");
return;
}
for (Protos.Offer offer : offers) {
if (isHostAlreadyRunningTask(offer)) {
driver.declineOffer(offer.getId()); // DCOS certification 05
LOGGER.info("Declined offer: Host " + offer.getHostname() + " is already running an Elastisearch task");
} else if (clusterMonitor.getClusterState().getTaskList().size() == configuration.getNumberOfHwNodes()) {
driver.declineOffer(offer.getId()); // DCOS certification 05
LOGGER.info("Declined offer: Mesos runs already runs " + configuration.getNumberOfHwNodes() + " Elasticsearch tasks");
} else if (!containsTwoPorts(offer.getResourcesList())) {
LOGGER.info("Declined offer: Offer did not contain 2 ports for Elasticsearch client and transport connection");
driver.declineOffer(offer.getId());
} else if (!isEnoughCPU(offer.getResourcesList())) {
LOGGER.info("Declined offer: Not enough CPU resources");
driver.declineOffer(offer.getId());
} else if (!isEnoughRAM(offer.getResourcesList())) {
LOGGER.info("Declined offer: Not enough RAM resources");
driver.declineOffer(offer.getId());
} else if (!isEnoughDisk(offer.getResourcesList())) {
LOGGER.info("Not enough Disk resources");
driver.declineOffer(offer.getId());
} else {
LOGGER.info("Accepted offer: " + offer.getHostname());
Protos.TaskInfo taskInfo = taskInfoFactory.createTask(configuration, offer);
LOGGER.debug(taskInfo.toString());
driver.launchTasks(Collections.singleton(offer.getId()), Collections.singleton(taskInfo));
Task task = new Task(
offer.getHostname(),
taskInfo.getTaskId().getValue(),
Protos.TaskState.TASK_STAGING,
clock.zonedNow(),
new InetSocketAddress(offer.getHostname(), taskInfo.getDiscovery().getPorts().getPorts(Discovery.CLIENT_PORT_INDEX).getNumber()),
new InetSocketAddress(offer.getHostname(), taskInfo.getDiscovery().getPorts().getPorts(Discovery.TRANSPORT_PORT_INDEX).getNumber())
);
tasks.put(taskInfo.getTaskId().getValue(), task);
clusterMonitor.monitorTask(taskInfo); // Add task to cluster monitor
}
}
}
private boolean isEnoughDisk(List<Protos.Resource> resourcesList) {
ResourceCheck resourceCheck = new ResourceCheck(Resources.disk(0).getName());
return resourceCheck.isEnough(resourcesList, configuration.getDisk());
}
private boolean isEnoughCPU(List<Protos.Resource> resourcesList) {
ResourceCheck resourceCheck = new ResourceCheck(Resources.cpus(0).getName());
return resourceCheck.isEnough(resourcesList, configuration.getCpus());
}
private boolean isEnoughRAM(List<Protos.Resource> resourcesList) {
ResourceCheck resourceCheck = new ResourceCheck(Resources.mem(0).getName());
return resourceCheck.isEnough(resourcesList, configuration.getMem());
}
private boolean containsTwoPorts(List<Protos.Resource> resources) {
int count = Resources.selectTwoPortsFromRange(resources).size();
return count == 2;
}
@Override
public void offerRescinded(SchedulerDriver driver, Protos.OfferID offerId) {
LOGGER.info("Offer " + offerId.getValue() + " rescinded");
}
@Override
public void statusUpdate(SchedulerDriver driver, Protos.TaskStatus status) {
LOGGER.info("Status update - Task with ID '" + status.getTaskId().getValue() + "' is now in state '" + status.getState() + "'. Message: " + status.getMessage());
statusUpdateWatchers.notifyObservers(status);
}
@Override
public void frameworkMessage(SchedulerDriver driver, Protos.ExecutorID executorId, Protos.SlaveID slaveId, byte[] data) {
LOGGER.info("Framework Message - Executor: " + executorId.getValue() + ", SlaveID: " + slaveId.getValue());
}
@Override
public void disconnected(SchedulerDriver driver) {
LOGGER.warn("Disconnected");
}
@Override
public void slaveLost(SchedulerDriver driver, Protos.SlaveID slaveId) {
LOGGER.info("Slave lost: " + slaveId.getValue());
}
// Todo, we still don't perform reconciliation
@Override
public void executorLost(SchedulerDriver driver, Protos.ExecutorID executorId, Protos.SlaveID slaveId, int status) {
// This is never called by Mesos, so we have to call it ourselves via a healthcheck
LOGGER.info("Executor lost: " + executorId.getValue() +
"on slave " + slaveId.getValue() +
"with status " + status);
}
@Override
public void error(SchedulerDriver driver, String message) {
LOGGER.error("Error: " + message);
}
private boolean isHostAlreadyRunningTask(Protos.Offer offer) {
Boolean result = false;
List<Protos.TaskInfo> stateList = clusterMonitor.getClusterState().getTaskList();
for (Protos.TaskInfo t : stateList) {
if (t.getSlaveId().equals(offer.getSlaveId())) {
result = true;
}
}
return result;
}
/**
* Implementation of Observable to fix the setChanged problem.
*/
private static class StatusUpdateObservable extends Observable {
@Override
public void notifyObservers(Object arg) {
this.setChanged(); // This is ridiculous.
super.notifyObservers(arg);
}
}
} |
package com.github.shiraji.permissionsdispatcherplugin.views;
import javax.swing.*;
import java.util.List;
public class GeneratePMCodeDialog extends JDialog {
JPanel contentPane;
JButton buttonOK;
JButton buttonCancel;
JCheckBox readCalendar;
JCheckBox writeCalendar;
JCheckBox camera;
JCheckBox readContacts;
JCheckBox writeContacts;
JCheckBox getAccounts;
JCheckBox accessFineLocation;
JCheckBox accessCoarseLocation;
JCheckBox recordAudio;
JCheckBox readPhoneState;
JCheckBox callPhone;
JCheckBox readCallLog;
JCheckBox writeCallLog;
JCheckBox addVoicemail;
JCheckBox useSip;
JCheckBox processOutgoingCall;
JCheckBox bodySensors;
JCheckBox sendSms;
JCheckBox receiveSms;
JCheckBox readSms;
JCheckBox receiveWapPush;
JCheckBox receiveMms;
JCheckBox readExternalStorage;
JCheckBox writeExternalStorage;
JCheckBox systemAlertWindow;
JCheckBox writeSettings;
public JTextField needsPermissionTextField;
public JCheckBox needsPermissionCheckBox;
public JTextField onShowRationaleTextField;
public JCheckBox onShowRationaleCheckBox;
public JTextField onPermissionDeniedTextField;
public JCheckBox onPermissionDeniedCheckBox;
public JTextField onNeverAskAgainTextField;
public JCheckBox onNeverAskAgainCheckBox;
public boolean isOk = false;
private GeneratePMCodeDialogDelegate generatePMCodeDialogDelegate;
public GeneratePMCodeDialog() {
generatePMCodeDialogDelegate = new GeneratePMCodeDialogDelegate(this);
generatePMCodeDialogDelegate.initDialog();
}
public List<String> getSelectedPermissions() {
return generatePMCodeDialogDelegate.getSelectedPermissions();
}
public static void main(String[] args) {
GeneratePMCodeDialog dialog = new GeneratePMCodeDialog();
dialog.pack();
dialog.setVisible(true);
if (dialog.isOk) {
System.out.println("ok!");
}
System.exit(0);
}
} |
package net.imglib2.interpolation.randomaccess;
import net.imglib2.RandomAccessible;
import net.imglib2.RealInterval;
import net.imglib2.RealRandomAccess;
import net.imglib2.Volatile;
import net.imglib2.interpolation.InterpolatorFactory;
import net.imglib2.type.numeric.ARGBType;
import net.imglib2.type.numeric.NumericType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.volatiles.VolatileARGBType;
/**
* Provides clamping n-linear interpolators for volatile and non-volatile types.
*
* @param <T>
*
* @author Tobias Pietzsch <tobias.pietzsch@gmail.com>
*/
public class ClampingNLinearInterpolatorFactory< T extends NumericType< T > > implements InterpolatorFactory< T, RandomAccessible< T > >
{
@SuppressWarnings( { "unchecked", "rawtypes" } )
@Override
public RealRandomAccess< T > create( final RandomAccessible< T > randomAccessible )
{
final T type = randomAccessible.randomAccess().get();
if ( type instanceof RealType )
{
if ( type instanceof Volatile )
return new ClampingNLinearInterpolatorVolatileRealType( randomAccessible );
else
return new ClampingNLinearInterpolatorRealType( randomAccessible );
}
else if ( ARGBType.class.isInstance( type ) )
{
return ( RealRandomAccess ) new NLinearInterpolatorARGB( ( RandomAccessible ) randomAccessible );
}
else if ( VolatileARGBType.class.isInstance( type ) )
{
return ( RealRandomAccess ) new ClampingNLinearInterpolatorVolatileARGB< VolatileARGBType >( ( RandomAccessible ) randomAccessible );
}
else
// fall back to (non-clamping) NLinearInterpolator
return new NLinearInterpolator< T >( randomAccessible );
}
/**
* For now, ignore the {@link RealInterval} and return
* {@link #create(RandomAccessible)}.
*/
@Override
public RealRandomAccess< T > create( final RandomAccessible< T > randomAccessible, final RealInterval interval )
{
return create( randomAccessible );
}
} |
package nl.opengeogroep.safetymaps.server.security;
import java.io.IOException;
import javax.servlet.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.security.Principal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.naming.NamingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import nl.opengeogroep.safetymaps.server.db.DB;
import static nl.opengeogroep.safetymaps.server.db.DB.USERNAME_LDAP;
import static nl.opengeogroep.safetymaps.server.db.DB.USER_TABLE;
import static nl.opengeogroep.safetymaps.server.db.DB.qr;
import static nl.opengeogroep.safetymaps.server.security.PersistentSessionManager.LDAP_GROUP;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
*
* @author matthijsln
*/
public class PersistentAuthenticationFilter implements Filter {
private static final Log log = LogFactory.getLog(PersistentAuthenticationFilter.class);
private FilterConfig filterConfig = null;
/**
* Prefix for context global parameters which can be set to override filter
* init params for easier deployments without overwriting web.xml.
*/
private static final String CONTEXT_PARAM_PREFIX = "persistentAuth";
private static final String COOKIE_NAME = "sm-plogin";
private static final String SESSION_USERNAME = PersistentAuthenticationFilter.class.getName() + ".USERNAME";
private static final String SESSION_PRINCIPAL = PersistentAuthenticationFilter.class.getName() + ".PRINCIPAL";
private static final String SESSION_ADDITIONAL_ROLES = PersistentAuthenticationFilter.class.getName() + ".ADDITIONAL_ROLES";
private static final int EXPIRY_DEFAULT_UNIT = Calendar.YEAR;
private static final int EXPIRY_DEFAULT = 10;
private static final String PARAM_ENABLED = "enabled";
private static final String PARAM_PERSISTENT_LOGIN_PATH_PREFIX = "persistentLoginPathPrefix";
private static final String PARAM_ALLOWED_ROLES = "allowedRoles";
private static final String PARAM_LOGIN_URL = "loginUrl";
private static final String PARAM_LOGOUT_URL = "logoutUrl";
private String persistentLoginPrefix;
private boolean enabled;
private String loginUrl;
private String logoutUrl;
private List<String> allowedRoles;
private static final ConcurrentMap<String,HttpSession> containerSessions = new ConcurrentHashMap();
/**
* Get a filter init-parameter which can be overriden by a context parameter
* when prefixed with "persistentAuth".
*/
private String getInitParameter(String paramName) {
String contextParamName = CONTEXT_PARAM_PREFIX + StringUtils.capitalize(paramName);
String value = filterConfig.getServletContext().getInitParameter(contextParamName);
if(value == null) {
value = filterConfig.getInitParameter(paramName);
log.debug("Using filter init parameter " + paramName + ": " + value);
} else {
log.debug("Using context parameter " + contextParamName + ": " + value);
}
return value;
}
@Override
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
this.enabled = "true".equals(ObjectUtils.firstNonNull(getInitParameter(PARAM_ENABLED), "true"));
this.persistentLoginPrefix = ObjectUtils.firstNonNull(getInitParameter(PARAM_PERSISTENT_LOGIN_PATH_PREFIX), "/");
this.loginUrl = ObjectUtils.firstNonNull(getInitParameter(PARAM_LOGIN_URL), "/viewer/api/login");
this.logoutUrl = ObjectUtils.firstNonNull(getInitParameter(PARAM_LOGOUT_URL), "/logout.jsp");
this.allowedRoles = Arrays.asList(ObjectUtils.firstNonNull(getInitParameter(PARAM_ALLOWED_ROLES), "").split(","));
log.info("Initialized - " + toString());
}
@Override
public void destroy() {
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
private void chainWithPrincipal(final HttpServletRequest request, HttpServletResponse response, FilterChain chain, final AuthenticatedPrincipal principal) throws IOException, ServletException {
chain.doFilter(new HttpServletRequestWrapper(request) {
@Override
public String getRemoteUser() {
return principal.getName();
}
@Override
public Principal getUserPrincipal() {
return principal;
}
@Override
public boolean isUserInRole(String role) {
return request.isUserInRole(role) || principal.isUserInRole(role);
}
}, response);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
HttpSession session = request.getSession();
containerSessions.putIfAbsent(session.getId(), session);
if(!enabled) {
chain.doFilter(request, response);
return;
}
Cookie authCookie = null;
Map<String,Object> persistentSession = null;
if(request.getCookies() != null) {
for(Cookie cookie: request.getCookies()) {
if(COOKIE_NAME.equals(cookie.getName())) {
authCookie = cookie;
}
}
}
if(request.getRequestURI().startsWith(request.getContextPath() + logoutUrl)) {
if(authCookie != null) {
String sessionId = authCookie.getValue();
log.info("Clearing persistent login cookie for persistent session ID " + sessionId + " on logout");
Cookie cookie = new Cookie(COOKIE_NAME, sessionId);
cookie.setMaxAge(0);
response.addCookie(cookie);
PersistentSessionManager.deleteSession(sessionId);
}
session.invalidate();
chain.doFilter(request, response);
return;
}
if(!request.getRequestURI().startsWith(request.getContextPath() + persistentLoginPrefix)) {
// No authentication required
chain.doFilter(request, response);
return;
}
if(authCookie != null) {
String sessionId = authCookie.getValue();
persistentSession = PersistentSessionManager.getValidPersistentSession(request, sessionId);
}
Principal principal = request.getUserPrincipal();
if(principal != null) {
session.setAttribute(SESSION_USERNAME, principal.getName());
boolean allowed = false;
for(String role: allowedRoles) {
if(request.isUserInRole(role)) {
allowed = true;
break;
}
}
if(!allowed) {
log.warn("User " + request.getRemoteUser() + " has no access to voertuigviewer (authenticated by user database)");
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Toegang tot voertuigviewer geweigerd");
return;
}
// If valid persistent session already set, do nothing
if(persistentSession != null) {
log.trace("Request external authenticated for user " + principal.getName() + ", persistent session verified, path: " + request.getRequestURI());
// If LDAP user, apply additional roles from DB user set in session
// in other branch of this if statement
AuthenticatedPrincipal ldapPrincipal = (AuthenticatedPrincipal)session.getAttribute(SESSION_PRINCIPAL);
if(ldapPrincipal != null) {
chainWithPrincipal(request, response, chain, ldapPrincipal);
} else {
chain.doFilter(servletRequest, servletResponse);
}
return;
} else {
// Create new persistent session
String dbUsername = request.getRemoteUser();
if(request.isUserInRole(LDAP_GROUP)) {
dbUsername = USERNAME_LDAP;
}
Map<String,Object> data;
try {
data = qr().query("select * from " + USER_TABLE + " where username = ?", new MapHandler(), dbUsername);
} catch(SQLException | NamingException e) {
throw new IOException(e);
}
// If user is deleted...
if(data == null) {
session.invalidate();
chain.doFilter(request, response);
}
Integer expiry = data.containsKey("session_expiry_number") ? (Integer)data.get("session_expiry_number") : null;
String expiryTimeUnit = (String)data.get("session_expiry_timeunit");
Calendar c = Calendar.getInstance();
if(expiry != null) {
if(expiryTimeUnit.equals("days")) {
c.add(Calendar.DAY_OF_YEAR, expiry);
} else if(expiryTimeUnit.equals("weeks")) {
c.add(Calendar.WEEK_OF_YEAR, expiry);
} else if(expiryTimeUnit.equals("months")) {
c.add(Calendar.MONTH, expiry);
} else if(expiryTimeUnit.equals("years")) {
c.add(Calendar.YEAR, expiry);
} else {
c.add(EXPIRY_DEFAULT_UNIT, EXPIRY_DEFAULT);
}
} else {
c.add(EXPIRY_DEFAULT_UNIT, EXPIRY_DEFAULT);
}
String id = PersistentSessionManager.createPersistentSession(request, c.getTime());
Cookie cookie = new Cookie(COOKIE_NAME, id);
String path = request.getServletContext().getContextPath();
if("".equals(path)) {
// for ROOT webapp the context path is "", make sure cookie path is
// set to "/", otherwise cookie will not be set on /logout.jsp,
// making logging out impossible
path = "/";
}
cookie.setPath(path); // Set path so we can clear cookie on logout
cookie.setHttpOnly(true);
cookie.setSecure(request.getScheme().equals("https"));
cookie.setMaxAge((int)((c.getTimeInMillis() - System.currentTimeMillis()) / 1000));
log.info("Request externally authenticated for user " + principal.getName() + ", setting persistent login cookie " + obfuscateSessionId(id));
response.addCookie(cookie);
// Apply additional roles if LDAP user
if(request.isUserInRole(LDAP_GROUP)) {
try {
List<String> roles = qr().query("select role from " + DB.USER_ROLE_TABLE + " where username = ?", new ColumnListHandler<String>(), dbUsername);
AuthenticatedPrincipal ldapPrincipal = new AuthenticatedPrincipal(principal.getName(), new HashSet<>(roles));
log.info("Apply additional roles for this LDAP user in this session: " + roles);
session.setAttribute(SESSION_PRINCIPAL, ldapPrincipal);
chainWithPrincipal(request, response, chain, ldapPrincipal);
return;
} catch(SQLException | NamingException e) {
throw new IOException(e);
}
}
}
}
AuthenticatedPrincipal persistentPrincipal = (AuthenticatedPrincipal)session.getAttribute(SESSION_PRINCIPAL);
if(persistentPrincipal != null) {
log.trace("Request authenticated by cookie for user " + persistentPrincipal.getName() + ", using principal from session: " + request.getRequestURI());
} else if(authCookie == null) {
log.info("User not authenticated externally and no persistent session cookie, redirect tologin page");
response.sendRedirect(request.getServletContext().getContextPath() + this.loginUrl);
return;
} else {
if(persistentSession != null) {
// persistentSession was found and not expired
String obfuscatedSession = obfuscateSessionId((String)persistentSession.get("id"));
log.info("Using authentication from cookie session for user " + persistentSession.get("username") + " from session id " + obfuscatedSession + ", saving principal in session: " + request.getRequestURI());
try {
// Changes in authorizations
List<String> roles;
if("LDAP".equals(persistentSession.get("login_source"))) {
roles = qr().query("select role from " + DB.USER_ROLE_TABLE + " where username = ?", new ColumnListHandler<String>(), USERNAME_LDAP);
// XXX original LDAP roles lost. Maybe
// - Save to database (needs reflection to get list (see authinfo.jsp), role changes in LDAP never propagated)
// - Recheck using JNDI.. (double LDAP config, extra code)
// For now only grant roles special user has
roles.add("LDAPUser");
log.warn("Returning LDAP user " + persistentSession.get("username") + " using persistent session cookie, only granting LDAPUser role and roles granted to special user '" + USERNAME_LDAP + "', roles: " + roles.toString());
} else {
roles = qr().query("select role from " + DB.USER_ROLE_TABLE + " where username = ?", new ColumnListHandler<String>(), persistentSession.get("username"));
}
boolean allowed = false;
for(String role: allowedRoles) {
if(roles.contains(role)) {
allowed = true;
break;
}
}
if(!allowed) {
log.warn("User " + persistentSession.get("username") + " has no access to voertuigviewer (authenticated from persistent session cookie)");
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Toegang tot voertuigviewer geweigerd");
return;
}
persistentPrincipal = new AuthenticatedPrincipal((String)persistentSession.get("username"), new HashSet(roles));
request.getSession().setAttribute(SESSION_PRINCIPAL, persistentPrincipal);
} catch(javax.naming.NamingException | java.sql.SQLException e) {
throw new IOException(e);
}
} else {
log.info("User not authenticated externally, persistent cookie is not valid, redirect tologin page");
response.sendRedirect(request.getServletContext().getContextPath() + this.loginUrl);
return;
}
}
session.setAttribute(SESSION_USERNAME, persistentPrincipal.getName());
final AuthenticatedPrincipal thePrincipal = persistentPrincipal;
chainWithPrincipal(request, response, chain, thePrincipal);
}
public static void invalidateUserSessions(String name) throws IOException {
List<String> invalidSessionIds = new ArrayList<>();
for(HttpSession session: containerSessions.values()) {
try {
String sessionUser = (String)session.getAttribute(SESSION_USERNAME);
log.debug("Checking container session " + session.getId() + " to delete, session user = " + sessionUser);
if(name.equals(sessionUser)) {
log.info("Invalidating container session for user " + name + ": " + session.getId());
session.invalidate();
invalidSessionIds.add(session.getId());
}
} catch(IllegalStateException e) {
log.info("Session already invalid: " + session.getId());
invalidSessionIds.add(session.getId());
}
}
for(String id: invalidSessionIds) {
containerSessions.remove(id);
}
PersistentSessionManager.deleteUserSessions(name);
}
private static String obfuscateSessionId(String id) {
return StringUtils.repeat("x", id.length() / 2) + id.substring(id.length() / 2);
}
private class AuthenticatedPrincipal implements Principal {
private final String name;
private final Set<String> roles;
public AuthenticatedPrincipal(String name, Set<String> roles) {
this.name = name;
this.roles = roles;
}
@Override
public String getName() {
return name;
}
public boolean isUserInRole(String r) {
return roles.contains(r);
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
throw new UnsupportedOperationException();
}
}
} |
package org.liveontologies.protege.explanation.justification;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JPanel;
import org.liveontologies.protege.explanation.justification.service.JustificationComputation;
import org.liveontologies.protege.explanation.justification.service.JustificationComputation.InterruptMonitor;
import org.liveontologies.protege.explanation.justification.service.JustificationComputationManager;
import org.liveontologies.protege.explanation.justification.service.JustificationComputationService;
import org.liveontologies.protege.explanation.justification.service.JustificationListener;
import org.liveontologies.protege.explanation.justification.service.JustificationPriorityComparator;
import org.protege.editor.core.log.LogBanner;
import org.protege.editor.owl.OWLEditorKit;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Used to keep track of the computed justifications for a particular entailed
* {@link OWLAxiom}
*
* @author Yevgeny Kazakov
*
*/
public class JustificationManager implements
JustificationComputationManager.ChangeListener, JustificationListener {
// logger for this class
private static final Logger LOGGER_ = LoggerFactory
.getLogger(JustificationManager.class);
/**
* the manager for the registered justification computation services
*/
private final JustificationComputationServiceManager serviceMan_;
/**
* the entailement for which the computations are managed
*/
private final OWLAxiom entailment_;
private final JustificationComputationListener computationListener_;
private final InterruptMonitor interruptMonitor_;
private final ExecutorService executorService_;
private final Queue<Justification> justifications_ = new PriorityQueue<>();
/**
* the size of #justifications_
*/
private int justificationCount_ = 0;
/**
* counts how many times each axiom occurs in a justification
*/
private final Map<OWLAxiom, Integer> axiomsPopularity_ = new HashMap<>();
private JustificationComputationService selectedComputationService_;
private JustificationComputationManager computationManager_;
private JPanel computationSettingsPanel_;
/**
* the listeners to be notified when {@link #justifications_} have changed
*/
private final List<ChangeListener> listeners_ = new ArrayList<ChangeListener>();
JustificationManager(JustificationComputationServiceManager serviceManager,
OWLAxiom entailment,
JustificationComputationListener computationListener,
InterruptMonitor interruptMonitor) {
this.serviceMan_ = serviceManager;
this.entailment_ = entailment;
this.computationListener_ = computationListener;
this.interruptMonitor_ = interruptMonitor;
this.executorService_ = Executors.newSingleThreadExecutor();
}
JustificationManager(OWLEditorKit kit, OWLAxiom entailment,
JustificationComputationListener computationListener,
InterruptMonitor interruptMonitor) throws Exception {
this(JustificationComputationServiceManager.get(kit), entailment,
computationListener, interruptMonitor);
}
/**
* @return the axiom for which the proofs are managed
*/
public OWLAxiom getEntailment() {
return entailment_;
}
public OWLEditorKit getOwlEditorKit() {
return serviceMan_.getOwlEditorKit();
}
/**
* @return the {@link JustificationComputationService} that can be used for
* computing justifications for the {@link #getEntailment()}, i.e.,
* those for which
* {@link JustificationComputationService#canJustify(OWLAxiom)} is
* {@code true}
*
* @see #getEntailment()
*/
public Collection<JustificationComputationService> getServices() {
List<JustificationComputationService> result = new ArrayList<>();
for (JustificationComputationService service : serviceMan_
.getServices()) {
if (service.canJustify(entailment_)) {
result.add(service);
}
}
return result;
}
private void resetJustifications() {
justifications_.clear();
justificationCount_ = 0;
axiomsPopularity_.clear();
}
private void addJustification(Set<OWLAxiom> justification) {
justifications_.add(new Justification(justification));
justificationCount_++;
for (OWLAxiom axiom : justification) {
Integer popularity = axiomsPopularity_.get(axiom);
if (popularity == null) {
popularity = 0;
}
popularity++;
axiomsPopularity_.put(axiom, popularity);
}
}
public JPanel getSettingsPanel() {
return computationSettingsPanel_;
}
/**
* Sets the {@link JustificationComputationService} that should be used for
* computing justifications for {@link #getEntailment()}; the computed
* justifications are updated if necessary. The
* {@link JustificationComputationService} must be from
* {@link #getServices()}.
*
* @param service
* @see #getEntailment()
* @see #getServices()
*/
public synchronized void selectJusificationService(
JustificationComputationService service) {
if (selectedComputationService_ == service) {
return;
}
selectedComputationService_ = service;
if (computationManager_ != null) {
computationManager_.removeListener(this);
}
computationManager_ = service.createComputationManager(entailment_,
this, interruptMonitor_);
computationSettingsPanel_ = computationManager_.getSettingsPanel();
notifySettingsPanelChanged();
recomputeJustifications();
computationManager_.addListener(this);
}
@Override
public void computationChanged() {
recomputeJustifications();
}
@Override
public void settingsPanelChanged() {
notifySettingsPanelChanged();
}
@Override
public void justificationFound(Set<OWLAxiom> justification) {
addJustification(justification);
computationListener_.justificationFound(justification);
}
void recomputeJustifications() {
resetJustifications();
try {
computationListener_.computationStarted();
executorService_.submit(new ExplanationComputationTask());
} catch (OWLRuntimeException e) {
LOGGER_.info("Justification computation terminated early by user");
}
}
public synchronized void addListener(ChangeListener listener) {
listeners_.add(listener);
}
public synchronized void removeListener(ChangeListener listener) {
listeners_.remove(listener);
}
public Justification pollJustification() {
if (justificationCount_ == 0) {
return null;
}
// else
justificationCount_
return justifications_.poll();
}
public int getRemainingJustificationCount() {
return justificationCount_;
}
public int getPopularity(OWLAxiom axiom) {
return axiomsPopularity_.get(axiom);
}
private void notifyJustificationsRecomputed() {
int i = 0;
try {
for (; i < listeners_.size(); i++) {
listeners_.get(i).justificationsRecomputed();
}
} catch (Throwable e) {
LOGGER_.warn("Remove the listener due to an exception", e);
removeListener(listeners_.get(i));
}
}
private void notifySettingsPanelChanged() {
int i = 0;
try {
for (; i < listeners_.size(); i++) {
listeners_.get(i).settingsPanelChanged();
}
} catch (Throwable e) {
LOGGER_.warn("Remove the listener due to an exception", e);
removeListener(listeners_.get(i));
}
}
public interface ChangeListener {
/**
* fired when the justifications supported by a
* {@link JustificationManager} have been recomputed
*/
void justificationsRecomputed();
/**
* fired when {@link JustificationManager#getSettingsPanel()} may return
* a different value
*/
void settingsPanelChanged();
}
// TODO: use SwingWorker
private class ExplanationComputationTask implements Runnable,
JustificationPriorityComparator<Justification> {
private final JustificationComputation computation_;
private ExplanationComputationTask() {
this.computation_ = computationManager_.getComputation();
computation_.setPrefferredPriority(this);
}
@Override
public void run() {
try {
LOGGER_.info(LogBanner.start("Computing Justifications"));
LOGGER_.info("Computing justifications for {}", entailment_);
computationListener_.computationStarted();
computation_.startComputation();
} catch (Throwable e) {
LOGGER_.info("Exception while computing justifications", e);
} finally {
computationListener_.computationFinished();
LOGGER_.info("A total of {} justifications have been computed",
justificationCount_);
LOGGER_.info(LogBanner.end());
notifyJustificationsRecomputed();
}
}
@Override
public int compare(Justification j1, Justification j2) {
return j1.compareTo(j2);
}
@Override
public Justification getPriority(Set<OWLAxiom> justification) {
return new Justification(justification);
}
}
} |
package org.helioviewer.jhv.plugins.eveplugin.draw;
import java.awt.Rectangle;
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 org.helioviewer.jhv.base.Range;
import org.helioviewer.jhv.base.interval.Interval;
import org.helioviewer.jhv.base.logging.Log;
import org.helioviewer.jhv.base.time.JHVDate;
import org.helioviewer.jhv.base.time.TimeUtils;
import org.helioviewer.jhv.data.datatype.event.JHVEventHighlightListener;
import org.helioviewer.jhv.data.datatype.event.JHVRelatedEvents;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.layers.LayersListener;
import org.helioviewer.jhv.layers.TimeListener;
import org.helioviewer.jhv.plugins.eveplugin.DrawConstants;
import org.helioviewer.jhv.plugins.eveplugin.draw.YAxisElement.YAxisLocation;
import org.helioviewer.jhv.plugins.eveplugin.lines.data.DownloadController;
import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorElement;
import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorModel;
import org.helioviewer.jhv.plugins.eveplugin.view.linedataselector.LineDataSelectorModelListener;
import org.helioviewer.jhv.viewmodel.view.View;
public class DrawController implements LineDataSelectorModelListener, JHVEventHighlightListener, LayersListener, TimeListener {
private static DrawController instance;
private Interval selectedInterval;
private Interval availableInterval;
private final List<TimingListener> tListeners;
private Rectangle graphSize;
private final List<GraphDimensionListener> gdListeners;
private List<YAxisElement> yAxisSet;
private final Map<DrawableType, Set<DrawableElement>> drawableElements;
private final List<DrawControllerListener> listeners;
private double scaledMinTime;
private double scaledMaxTime;
private double scaledSelectedMinTime;
private double scaledSelectedMaxTime;
private double minSelectedTimeDiff;
private final Set<ValueSpace> valueSpaces;
private DrawController() {
drawableElements = new HashMap<DrawableType, Set<DrawableElement>>();
listeners = new ArrayList<DrawControllerListener>();
yAxisSet = new ArrayList<YAxisElement>();
tListeners = new ArrayList<TimingListener>();
gdListeners = new ArrayList<GraphDimensionListener>();
graphSize = new Rectangle();
long d = System.currentTimeMillis();
availableInterval = new Interval(d - TimeUtils.DAY_IN_MILLIS, d);
selectedInterval = availableInterval;
LineDataSelectorModel.getSingletonInstance().addLineDataSelectorModelListener(this);
scaledMinTime = 0.0;
scaledMaxTime = 1.0;
scaledSelectedMinTime = 0.0;
scaledSelectedMaxTime = 1.0;
minSelectedTimeDiff = 0;
valueSpaces = new HashSet<ValueSpace>();
isLocked = false;
latestMovieTime = Long.MIN_VALUE;
}
public int calculateXLocation(long timestamp) {
return (int) ((timestamp - selectedInterval.start) * getRatioX()) + getPlotArea().x;
}
public double getRatioX() {
return getPlotArea().width / (double) (selectedInterval.end - selectedInterval.start);
}
public void moveTime(double scaledDistance) {
long diffTime = selectedInterval.end - selectedInterval.start;
long newStart = (long) Math.floor(selectedInterval.start + scaledDistance * diffTime);
long newEnd = (long) Math.floor(selectedInterval.end + scaledDistance * diffTime);
setSelectedInterval(new Interval(newStart, newEnd), false, false);
}
public void zoomTime(double factor, double ratioLeft) {
long diffTime = selectedInterval.end - selectedInterval.start;
long newStart = (long) Math.floor(selectedInterval.start - factor * diffTime * ratioLeft);
long newEnd = (long) Math.floor(selectedInterval.end + factor * diffTime * (1. - ratioLeft));
setSelectedInterval(new Interval(newStart, newEnd), false, false);
}
public static DrawController getSingletonInstance() {
if (instance == null) {
instance = new DrawController();
JHVRelatedEvents.addHighlightListener(instance);
JHVRelatedEvents.addHighlightListener(Displayer.getSingletonInstance());
}
return instance;
}
public void addDrawControllerListener(DrawControllerListener listener) {
listeners.add(listener);
}
public void removeDrawControllerListener(DrawControllerListener listener) {
listeners.remove(listener);
}
public void addGraphDimensionListener(GraphDimensionListener l) {
gdListeners.add(l);
}
public void addTimingListener(TimingListener listener) {
tListeners.add(listener);
}
public void updateDrawableElement(DrawableElement drawableElement, boolean needsFire) {
addDrawableElement(drawableElement, false);
if (needsFire && drawableElement.hasElementsToDraw()) {
fireRedrawRequest();
}
}
private void addDrawableElement(DrawableElement element, boolean redraw) {
Set<DrawableElement> elements = drawableElements.get(element.getDrawableElementType().getLevel());
if (elements == null) {
elements = new HashSet<DrawableElement>();
drawableElements.put(element.getDrawableElementType().getLevel(), elements);
}
elements.add(element);
if (element.getYAxisElement() != null) {
if (!yAxisSet.contains(element.getYAxisElement())) {
yAxisSet.add(element.getYAxisElement());
}
}
if (redraw) {
fireRedrawRequest();
}
}
private void removeDrawableElement(DrawableElement element, boolean redraw, boolean keepYAxisElement) {
Set<DrawableElement> elements = drawableElements.get(element.getDrawableElementType().getLevel());
if (elements != null && !keepYAxisElement) {
elements.remove(element);
if (elements.isEmpty()) {
drawableElements.remove(element.getDrawableElementType().getLevel());
}
createYAxisSet();
}
if (redraw) {
fireRedrawRequest();
}
}
public void removeDrawableElement(DrawableElement element) {
removeDrawableElement(element, true, false);
}
public List<YAxisElement> getYAxisElements() {
return yAxisSet;
}
public Map<DrawableType, Set<DrawableElement>> getDrawableElements() {
return drawableElements;
}
public void setSelectedRange(Range selectedRange) {
fireRedrawRequest();
}
public void fireRedrawRequest() {
for (DrawControllerListener l : listeners) {
l.drawRequest();
}
}
public void setAvailableInterval(final Interval interval) {
availableInterval = makeCompleteDay(interval.start, interval.end);
fireAvailableIntervalChanged();
final Interval downloadInterval = new Interval(availableInterval.start, availableInterval.end - TimeUtils.DAY_IN_MILLIS);
DownloadController.getSingletonInstance().updateBands(downloadInterval, selectedInterval);
setSelectedInterval(selectedInterval, false, false);
}
public final Interval getAvailableInterval() {
return availableInterval;
}
@Override
public void downloadStartded(LineDataSelectorElement element) {
}
@Override
public void downloadFinished(LineDataSelectorElement element) {
}
@Override
public void lineDataAdded(LineDataSelectorElement element) {
}
@Override
public void lineDataRemoved(LineDataSelectorElement element) {
fireRedrawRequest();
}
@Override
public void lineDataUpdated(LineDataSelectorElement element) {
fireRedrawRequest();
}
private void fireRedrawRequestMovieFrameChanged(final long time) {
for (DrawControllerListener l : listeners) {
l.drawMovieLineRequest(time);
}
}
private void centraliseSelected(long time) {
if (time != Long.MIN_VALUE && latestMovieTime != time && isLocked && availableInterval.containsPointInclusive(time)) {
latestMovieTime = time;
long selectedIntervalDiff = selectedInterval.end - selectedInterval.start;
setSelectedInterval(new Interval(time - ((long) (0.5 * selectedIntervalDiff)), time + ((long) (0.5 * selectedIntervalDiff))), false, false);
}
}
@Override
public void timeChanged(JHVDate date) {
centraliseSelected(date.milli);
fireRedrawRequestMovieFrameChanged(date.milli);
}
public long getLastDateWithData() {
long lastDate = Long.MAX_VALUE;
for (Set<DrawableElement> des : drawableElements.values()) {
for (DrawableElement de : des) {
long temp = de.getLastDateWithData();
if (temp != -1 && temp < lastDate) {
lastDate = temp;
}
}
}
return lastDate;
}
@Override
public void eventHightChanged(JHVRelatedEvents event) {
fireRedrawRequest();
}
@Override
public void layerAdded(View view) {
Interval interval = new Interval(Layers.getStartDate().milli, Layers.getEndDate().milli);
if (availableInterval == null) {
availableInterval = interval;
} else {
long start = availableInterval.start;
if (interval.start < start) {
start = interval.start;
}
long end = availableInterval.end;
if (interval.end > end) {
end = interval.end;
}
setAvailableInterval(new Interval(start, end));
}
if (isLocked()) {
setSelectedInterval(interval, true, false);
setLocked(true);
}
}
@Override
public void activeLayerChanged(View view) {
if (view == null) {
fireRedrawRequestMovieFrameChanged(Long.MIN_VALUE);
}
}
private Interval makeCompleteDay(final long start, final long end) {
long endDate = end;
long now = System.currentTimeMillis();
if (end > now) {
endDate = now;
}
long new_start = start - start % TimeUtils.DAY_IN_MILLIS;
long new_end = endDate - endDate % TimeUtils.DAY_IN_MILLIS + TimeUtils.DAY_IN_MILLIS;
return new Interval(new_start, new_end);
}
public void setSelectedInterval(final Interval newSelectedInterval, boolean useFullValueSpace, boolean resetAvailable) {
if (newSelectedInterval.start <= newSelectedInterval.end) {
if (availableInterval.containsInclusive(newSelectedInterval)) {
selectedInterval = newSelectedInterval;
if (resetAvailable) {
setAvailableInterval(newSelectedInterval);
}
} else {
long start = newSelectedInterval.start;
long end = newSelectedInterval.end;
long availableStart = availableInterval.start;
long availableEnd = availableInterval.end;
boolean changeAvailableInterval = false;
if (!availableInterval.containsPointInclusive(start) && !availableInterval.containsPointInclusive(end)) {
changeAvailableInterval = true;
availableStart = start;
availableEnd = end;
}
if (start == end) {
selectedInterval = new Interval(availableStart, availableEnd);
} else {
selectedInterval = new Interval(start, end);
}
if (changeAvailableInterval) {
setAvailableInterval(new Interval(availableStart, availableEnd));
}
}
fireSelectedIntervalChanged(useFullValueSpace);
fireRedrawRequest();
} else {
Log.debug("Start was after end. Set by: ");
Thread.dumpStack();
}
}
public Interval getSelectedInterval() {
return selectedInterval;
}
private void fireSelectedIntervalChanged(boolean keepFullValueRange) {
for (TimingListener listener : tListeners) {
listener.selectedIntervalChanged(keepFullValueRange);
}
}
private void fireAvailableIntervalChanged() {
centraliseSelected(latestMovieTime);
for (TimingListener listener : tListeners) {
listener.availableIntervalChanged();
}
}
/*
* public PlotAreaSpace getPlotAreaSpace() { return pas; }
*/
public void setGraphInformation(Rectangle graphSize) {
this.graphSize = graphSize;
fireGraphDimensionsChanged();
fireRedrawRequest();
}
private void fireGraphDimensionsChanged() {
for (GraphDimensionListener l : gdListeners) {
l.graphDimensionChanged();
}
}
public Rectangle getPlotArea() {
return new Rectangle(0, 0, getGraphWidth(), getGraphHeight());
}
public Rectangle getGraphArea() {
return new Rectangle(DrawConstants.GRAPH_LEFT_SPACE, DrawConstants.GRAPH_TOP_SPACE, getGraphWidth(), getGraphHeight());
}
public Rectangle getLeftAxisArea() {
return new Rectangle(0, DrawConstants.GRAPH_TOP_SPACE, DrawConstants.GRAPH_LEFT_SPACE, getGraphHeight() - (DrawConstants.GRAPH_TOP_SPACE + DrawConstants.GRAPH_BOTTOM_SPACE));
}
private int getGraphHeight() {
return graphSize.height - (DrawConstants.GRAPH_TOP_SPACE + DrawConstants.GRAPH_BOTTOM_SPACE);
}
private int getGraphWidth() {
int twoYAxis = 0;
if (getYAxisElements().size() >= 2) {
twoYAxis = 1;
}
return graphSize.width - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + twoYAxis * DrawConstants.TWO_AXIS_GRAPH_RIGHT);
}
private void createYAxisSet() {
YAxisElement[] tempArray = new YAxisElement[2];
for (Set<DrawableElement> elementsSet : drawableElements.values()) {
for (DrawableElement de : elementsSet) {
if (de.getYAxisElement() != null) {
if (yAxisSet.contains(de.getYAxisElement())) {
tempArray[yAxisSet.indexOf(de.getYAxisElement())] = de.getYAxisElement();
}
}
}
}
List<YAxisElement> newYAxisList = new ArrayList<YAxisElement>();
for (int i = 0; i < 2; i++) {
if (tempArray[i] != null) {
newYAxisList.add(tempArray[i]);
}
}
yAxisSet = newYAxisList;
}
public boolean hasAxisAvailable() {
return yAxisSet.size() < 2;
}
public boolean canBePutOnAxis(String unit) {
for (YAxisElement el : yAxisSet) {
if (el.getLabel().toLowerCase().equals(unit.toLowerCase())) {
return true;
}
}
return false;
}
public YAxisElement getYAxisElementForUnit(String unit) {
for (YAxisElement el : yAxisSet) {
if (el.getOriginalLabel().toLowerCase().equals(unit.toLowerCase())) {
return el;
}
}
return null;
}
private List<YAxisElement> getAllYAxisElementsForUnit(String unit) {
List<YAxisElement> all = new ArrayList<YAxisElement>();
for (YAxisElement el : yAxisSet) {
if (el.getOriginalLabel().toLowerCase().equals(unit.toLowerCase())) {
all.add(el);
}
}
return all;
}
public boolean canChangeAxis(String unitLabel) {
return getAllYAxisElementsForUnit(unitLabel).size() == 2 || yAxisSet.size() < 2;
}
public YAxisElement.YAxisLocation getYAxisLocation(YAxisElement yAxisElement) {
switch (yAxisSet.indexOf(yAxisElement)) {
case 0:
return YAxisElement.YAxisLocation.LEFT;
case 1:
return YAxisElement.YAxisLocation.RIGHT;
}
return YAxisLocation.LEFT;
}
public double getScaledMinTime() {
return scaledMinTime;
}
public double getScaledMaxTime() {
return scaledMaxTime;
}
public double getScaledSelectedMinTime() {
return scaledSelectedMinTime;
}
public double getScaledSelectedMaxTime() {
return scaledSelectedMaxTime;
}
public void setScaledSelectedTime(double scaledSelectedMinTime, double scaledSelectedMaxTime, boolean forced) {
if ((forced || !(this.scaledSelectedMinTime == scaledSelectedMinTime && this.scaledSelectedMaxTime == scaledSelectedMaxTime)) && (scaledSelectedMaxTime - scaledSelectedMinTime) > minSelectedTimeDiff) {
this.scaledSelectedMinTime = scaledSelectedMinTime;
this.scaledSelectedMaxTime = scaledSelectedMaxTime;
if (this.scaledSelectedMinTime < scaledMinTime || this.scaledSelectedMaxTime > scaledMaxTime) {
double oldScaledMinTime = scaledMinTime;
double oldScaledMaxTime = scaledMaxTime;
scaledMinTime = Math.min(this.scaledSelectedMinTime, scaledMinTime);
scaledMaxTime = Math.max(this.scaledSelectedMaxTime, scaledMaxTime);
fireAvailableAreaSpaceChanged(oldScaledMinTime, oldScaledMaxTime, scaledMinTime, scaledMaxTime);
}
firePlotAreaSpaceChanged(forced);
}
}
private void fireAvailableAreaSpaceChanged(double oldScaledMinTime, double oldScaledMaxTime, double newMinTime, double newMaxTime) {
if (oldScaledMinTime > newMinTime || oldScaledMaxTime < newMaxTime) {
double timeRatio = (availableInterval.end - availableInterval.start) / (oldScaledMaxTime - oldScaledMinTime);
double startDifference = oldScaledMinTime - newMinTime;
double endDifference = newMaxTime - oldScaledMaxTime;
long tempStartDate = availableInterval.start - Math.round(startDifference * timeRatio);
long tempEndDate = availableInterval.end + Math.round(endDifference * timeRatio);
setAvailableInterval(new Interval(tempStartDate, tempEndDate));
}
}
public Set<ValueSpace> getValueSpaces() {
return valueSpaces;
}
public boolean minMaxTimeIntervalContainsTime(double value) {
return value >= scaledMinTime && value <= scaledMaxTime;
}
public void resetSelectedValueAndTimeInterval() {
scaledSelectedMinTime = scaledMinTime;
scaledSelectedMaxTime = scaledMaxTime;
for (ValueSpace vs : valueSpaces) {
vs.resetScaledSelectedRange();
}
}
@Override
public String toString() {
return "Scaled min time : " + scaledMinTime + "\n" + "Scaled max time : " + scaledMaxTime + "\n" + "\n" + "Selected scaled min time : " + scaledSelectedMinTime + "\n" + "Selected scaled max time : " + scaledSelectedMaxTime + "\n";
}
private void firePlotAreaSpaceChanged(boolean forced) {
long diffTime = availableInterval.end - availableInterval.start;
double scaleDiff = scaledMaxTime - scaledMinTime;
double selectedMin = (scaledSelectedMinTime - scaledMinTime) / scaleDiff;
double selectedMax = (scaledSelectedMaxTime - scaledMinTime) / scaleDiff;
long newSelectedStartTime = availableInterval.start + Math.round(diffTime * selectedMin);
long newSelectedEndTime = availableInterval.start + Math.round(diffTime * selectedMax);
if (forced || !(newSelectedEndTime == selectedInterval.end) && newSelectedStartTime == selectedInterval.start) {
setSelectedInterval(new Interval(newSelectedStartTime, newSelectedEndTime), false, false);
}
}
public void addValueSpace(ValueSpace valueSpace) {
valueSpaces.add(valueSpace);
}
public void removeValueSpace(ValueSpace valueSpace) {
valueSpaces.remove(valueSpace);
}
public void setMinSelectedTimeDiff(double minSelectedTimeDiff) {
this.minSelectedTimeDiff = minSelectedTimeDiff;
}
/** Is the time interval locked */
private boolean isLocked;
/** Holds the previous movie time */
private long latestMovieTime;
// private final PlotAreaSpace plotAreaSpace;
/**
* Is the time interval locked
*
* @return true if the interval is locked, false if the interval is not
* locked
*/
public boolean isLocked() {
return isLocked;
}
/**
* Sets the locked state of the time interval.
*
* @param isLocked
* true if the interval is locked, false if the interval is not
* locked
*/
public void setLocked(boolean isLocked) {
this.isLocked = isLocked;
if (isLocked) {
if (latestMovieTime != Long.MIN_VALUE) {
centraliseSelected(latestMovieTime);
}
}
}
} |
package hr.fer.zemris.vhdllab.applets.schema2.model.commands;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import hr.fer.zemris.vhdllab.applets.schema2.enums.EErrorTypes;
import hr.fer.zemris.vhdllab.applets.schema2.enums.EPropertyChange;
import hr.fer.zemris.vhdllab.applets.schema2.exceptions.DuplicateKeyException;
import hr.fer.zemris.vhdllab.applets.schema2.exceptions.InvalidCommandOperationException;
import hr.fer.zemris.vhdllab.applets.schema2.exceptions.OverlapException;
import hr.fer.zemris.vhdllab.applets.schema2.exceptions.UnknownKeyException;
import hr.fer.zemris.vhdllab.applets.schema2.interfaces.ICommand;
import hr.fer.zemris.vhdllab.applets.schema2.interfaces.ICommandResponse;
import hr.fer.zemris.vhdllab.applets.schema2.interfaces.ISchemaComponent;
import hr.fer.zemris.vhdllab.applets.schema2.interfaces.ISchemaComponentCollection;
import hr.fer.zemris.vhdllab.applets.schema2.interfaces.ISchemaInfo;
import hr.fer.zemris.vhdllab.applets.schema2.interfaces.ISchemaWire;
import hr.fer.zemris.vhdllab.applets.schema2.misc.Caseless;
import hr.fer.zemris.vhdllab.applets.schema2.misc.ChangeTuple;
import hr.fer.zemris.vhdllab.applets.schema2.misc.PlacedComponent;
import hr.fer.zemris.vhdllab.applets.schema2.misc.SchemaError;
import hr.fer.zemris.vhdllab.applets.schema2.misc.SchemaPort;
import hr.fer.zemris.vhdllab.applets.schema2.model.CommandResponse;
public class DeleteWireCommand implements ICommand {
private static class ConnectionInfo {
public Caseless cmpname, portname;
public ConnectionInfo(Caseless componentName, Caseless schemaPortName) {
cmpname = componentName;
portname = schemaPortName;
}
}
/* static fields */
public static final String COMMAND_NAME = "DeleteWireCommand";
/* private fields */
private Caseless name;
private ISchemaWire deleted;
private List<ConnectionInfo> cachedconnections;
/* ctors */
public DeleteWireCommand(Caseless wireName) {
name = wireName;
deleted = null;
cachedconnections = new ArrayList<ConnectionInfo>();
}
/* methods */
public String getCommandName() {
return COMMAND_NAME;
}
public boolean isUndoable() {
return true;
}
public ICommandResponse performCommand(ISchemaInfo info) {
deleted = info.getWires().fetchWire(name);
if (deleted == null) {
return new CommandResponse(new SchemaError(EErrorTypes.NONEXISTING_WIRE_NAME,
"Wire with name '" + name.toString() + "' could not be found."));
}
try {
info.getWires().removeWire(name);
} catch (UnknownKeyException e) {
throw new IllegalStateException("Wire was found once, but not twice!");
}
unplugAndCacheConnections(info);
return new CommandResponse(new ChangeTuple(EPropertyChange.ANY_CHANGE));
}
public ICommandResponse undoCommand(ISchemaInfo info) throws InvalidCommandOperationException {
if (deleted == null)
throw new InvalidCommandOperationException("Cannot call undo before command has been performed.");
try {
info.getWires().addWire(deleted);
} catch (DuplicateKeyException e) {
return new CommandResponse(new SchemaError(EErrorTypes.DUPLICATE_WIRE_NAME,
"Wire with name '" + name.toString() + "' already exists."));
} catch (OverlapException e) {
return new CommandResponse(new SchemaError(EErrorTypes.WIRE_OVERLAP,
"Wire with name '" + name.toString() + "' would overlap something else."));
}
plugCachedConnections(info);
deleted = null;
return new CommandResponse(new ChangeTuple(EPropertyChange.CANVAS_CHANGE));
}
private void unplugAndCacheConnections(ISchemaInfo info) {
SchemaPort sp = null;
Iterator<SchemaPort> spit = null;
for (PlacedComponent placed : info.getComponents()) {
spit = placed.comp.schemaPortIterator();
while (spit.hasNext()) {
sp = spit.next();
if (name.equals(sp.getMapping())) {
cachedconnections.add(new ConnectionInfo(placed.comp.getName(), sp.getName()));
sp.setMapping(null);
}
}
}
}
private void plugCachedConnections(ISchemaInfo info) {
ISchemaComponentCollection components = info.getComponents();
for (ConnectionInfo ci : cachedconnections) {
ISchemaComponent cmp = components.fetchComponent(ci.cmpname);
SchemaPort sp = cmp.getSchemaPort(ci.portname);
sp.setMapping(name);
}
cachedconnections.clear();
}
} |
package de.danielnaber.languagetool.rules.patterns;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import junit.framework.TestCase;
import org.xml.sax.SAXException;
import de.danielnaber.languagetool.AnalyzedSentence;
import de.danielnaber.languagetool.JLanguageTool;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.rules.Rule;
import de.danielnaber.languagetool.rules.RuleMatch;
/**
* @author Daniel Naber
*/
public class PatternRuleTest extends TestCase {
private static JLanguageTool langTool = null;
public void setUp() throws IOException {
if (langTool == null)
langTool = new JLanguageTool(Language.ENGLISH);
}
public void testEnglishGrammarRulesFromXML() throws IOException, ParserConfigurationException, SAXException {
PatternRuleLoader ruleLoader = new PatternRuleLoader();
List rules = ruleLoader.getRules("rules/en/grammar.xml");
for (Iterator iter = rules.iterator(); iter.hasNext();) {
Rule rule = (Rule) iter.next();
String goodSentence = rule.getCorrectExample();
String badSentence = rule.getIncorrectExample();
assertTrue(goodSentence.trim().length() > 0);
assertTrue(badSentence.trim().length() > 0);
assertFalse("Did not expect error in: " + goodSentence, match(rule, goodSentence));
assertTrue("Did expect error in: " + badSentence, match(rule, badSentence));
}
}
private boolean match(Rule rule, String sentence) throws IOException {
AnalyzedSentence text = langTool.getAnalyzedSentence(sentence);
//System.err.println(text);
RuleMatch[] matches = rule.match(text);
/*for (int i = 0; i < matches.length; i++) {
System.err.println(matches[i]);
}*/
return matches.length > 0;
}
public void testRule() throws IOException {
PatternRule pr;
RuleMatch[] matches;
pr = makePatternRule("\"one\"");
matches = pr.match(langTool.getAnalyzedSentence("A non-matching sentence."));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("A matching sentence with one match."));
assertEquals(1, matches.length);
assertEquals(25, matches[0].getFromPos());
assertEquals(28, matches[0].getToPos());
// these two are not set if the rule is called standalone (not via JLanguageTool):
assertEquals(-1, matches[0].getColumn());
assertEquals(-1, matches[0].getLine());
assertEquals("ID1", matches[0].getRule().getId());
assertTrue(matches[0].getMessage().equals("user visible message"));
matches = pr.match(langTool.getAnalyzedSentence("one one and one: three matches"));
assertEquals(3, matches.length);
pr = makePatternRule("\"one\" \"two\"");
matches = pr.match(langTool.getAnalyzedSentence("this is one not two"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("this is two one"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("this is one two three"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one two"));
assertEquals(1, matches.length);
pr = makePatternRule("\"one|foo|xxxx\" \"two\"");
matches = pr.match(langTool.getAnalyzedSentence("one foo three"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("foo two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one foo two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("y x z one two blah foo"));
assertEquals(1, matches.length);
pr = makePatternRule("\"one|foo|xxxx\" \"two|yyy\"");
matches = pr.match(langTool.getAnalyzedSentence("one, yyy"));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("one yyy"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("xxxx two"));
assertEquals(1, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("xxxx yyy"));
assertEquals(1, matches.length);
}
private PatternRule makePatternRule(String s) {
return new PatternRule("ID1", Language.ENGLISH, s, "test rule", "user visible message");
}
public void testSentenceStart() throws IOException {
PatternRule pr;
RuleMatch[] matches;
pr = makePatternRule("SENT_START \"One\"");
matches = pr.match(langTool.getAnalyzedSentence("Not One word."));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("One word."));
assertEquals(1, matches.length);
}
public void testNegation() throws IOException {
PatternRule pr;
RuleMatch[] matches;
pr = makePatternRule("\"one\" ^\"two\"");
matches = pr.match(langTool.getAnalyzedSentence("Here's one two."));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("Here's one four."));
assertEquals(1, matches.length);
pr = makePatternRule("\"one\" ^\"two|three\"");
matches = pr.match(langTool.getAnalyzedSentence("Here's one two."));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("Here's one three."));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("Here's one four."));
assertEquals(1, matches.length);
pr = makePatternRule("SENT_START ^\"One\"");
matches = pr.match(langTool.getAnalyzedSentence("One two."));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("Two three."));
assertEquals(1, matches.length);
pr = makePatternRule("\"One\" ^CD");
matches = pr.match(langTool.getAnalyzedSentence("One two."));
assertEquals(0, matches.length);
matches = pr.match(langTool.getAnalyzedSentence("One walk."));
assertEquals(1, matches.length);
}
} |
package dbws.testing.visit;
//javase imports
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.w3c.dom.Document;
//JUnit4 imports
//import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
//EclipseLink imports
import org.eclipse.persistence.internal.helper.NonSynchronizedVector;
import org.eclipse.persistence.internal.oxm.schema.SchemaModelGenerator;
import org.eclipse.persistence.internal.oxm.schema.SchemaModelGeneratorProperties;
import org.eclipse.persistence.internal.oxm.schema.SchemaModelProject;
import org.eclipse.persistence.internal.oxm.schema.model.Schema;
import org.eclipse.persistence.internal.xr.ProjectHelper;
import org.eclipse.persistence.internal.xr.XRDynamicEntity;
import org.eclipse.persistence.internal.xr.XRDynamicClassLoader;
import org.eclipse.persistence.mappings.structures.ObjectRelationalDataTypeDescriptor;
import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.XMLMarshaller;
import org.eclipse.persistence.platform.database.oracle.publisher.PublisherException;
import org.eclipse.persistence.platform.database.oracle.publisher.visit.PublisherListenerChainAdapter;
import org.eclipse.persistence.platform.database.oracle.publisher.visit.PublisherWalker;
import org.eclipse.persistence.queries.DatabaseQuery;
import org.eclipse.persistence.queries.ValueReadQuery;
import org.eclipse.persistence.sessions.DatabaseLogin;
import org.eclipse.persistence.sessions.DatabaseSession;
import org.eclipse.persistence.sessions.Project;
import org.eclipse.persistence.tools.dbws.DBWSBuilder;
import org.eclipse.persistence.tools.dbws.OperationModel;
import org.eclipse.persistence.tools.dbws.ProcedureOperationModel;
import org.eclipse.persistence.tools.dbws.TypeSuffixTransformer;
import org.eclipse.persistence.tools.dbws.DBWSBuilder.DbStoredProcedureNameAndModel;
import org.eclipse.persistence.tools.dbws.jdbc.DbStoredProcedure;
import org.eclipse.persistence.tools.dbws.oracle.AdvancedJDBCORDescriptorBuilder;
import org.eclipse.persistence.tools.dbws.oracle.AdvancedJDBCOXDescriptorBuilder;
import org.eclipse.persistence.tools.dbws.oracle.AdvancedJDBCQueryBuilder;
import org.eclipse.persistence.tools.dbws.oracle.OracleHelper;
import static org.eclipse.persistence.internal.oxm.schema.SchemaModelGeneratorProperties.ELEMENT_FORM_QUALIFIED_KEY;
//domain (testing) imports
import static dbws.testing.visit.WebServiceTestSuite.DEFAULT_DATABASE_DRIVER;
public class AdvancedJDBCTestSuite extends BuilderTestSuite {
static final String REGION_OR_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>region</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>advanced_object_demo.region</class>" +
"<alias>region</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>reg_id</attribute-name>" +
"<field name=\"REG_ID\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>reg_name</attribute-name>" +
"<field name=\"REG_NAME\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>REGION</structure>" +
"<field-order>" +
"<field name=\"REG_ID\" xsi:type=\"column\"/>" +
"<field name=\"REG_NAME\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"<queries>" +
"<query name=\"echoRegion\" xsi:type=\"value-read-query\">" +
"<arguments>" +
"<argument name=\"AREGION\">" +
"<type>java.lang.Object</type>" +
"</argument>" +
"</arguments>" +
"<maintain-cache>false</maintain-cache>" +
"<bind-all-parameters>true</bind-all-parameters>" +
"<call xsi:type=\"stored-function-call\">" +
"<procedure-name>ADVANCED_OBJECT_DEMO.ECHOREGION</procedure-name>" +
"<cursor-output-procedure>false</cursor-output-procedure>" +
"<arguments>" +
"<argument>" +
"<procedure-argument-name>AREGION</procedure-argument-name>" +
"<argument-name>AREGION</argument-name>" +
"<procedure-argument-type>advanced_object_demo.region</procedure-argument-type>" +
"<procedure-argument-sqltype>2002</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>REGION</procedure-argument-sqltype-name>" +
"</argument>" +
"</arguments>" +
"<stored-function-result>" +
"<procedure-argument-type>advanced_object_demo.region</procedure-argument-type>" +
"<procedure-argument-sqltype>2002</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>REGION</procedure-argument-sqltype-name>" +
"</stored-function-result>" +
"</call>" +
"</query>" +
"</queries>" +
"</object-persistence>";
@SuppressWarnings("unchecked")
@Test
public void struct1LevelDeep_OrPart()
throws SQLException, PublisherException, InstantiationException, IllegalAccessException {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("echoRegion");
pModel.setCatalogPattern("ADVANCED_OBJECT_DEMO");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("ECHOREGION");
pModel.setReturnType("regionType");
testOrProject(pModel, "region", REGION_OR_PROJECT);
// test query
DatabaseSession ds = fixUp(REGION_OR_PROJECT);
ValueReadQuery vrq = (ValueReadQuery)ds.getQuery("echoRegion");
XRDynamicEntity regionEntity = (XRDynamicEntity)ds.getProject().getDescriptorForAlias(
"region").getObjectBuilder().buildNewInstance();
regionEntity.set("reg_id", BigDecimal.valueOf(5));
regionEntity.set("reg_name", "this is a test");
@SuppressWarnings("rawtypes") Vector v = new NonSynchronizedVector();
v.add(regionEntity);
Object o = ds.executeQuery(vrq, v);
assertTrue("incorrect return type from StoredFunctionCall",
o instanceof XRDynamicEntity);
XRDynamicEntity regionEntityEchoed = (XRDynamicEntity)o;
assertTrue("incorrect first field for type returned from StoredFunctionCall",
regionEntityEchoed.get("reg_id").equals(BigDecimal.valueOf(5)));
assertTrue("incorrect second field for type returned from StoredFunctionCall",
regionEntityEchoed.get("reg_name").equals("this is a test"));
}
@Test
public void struct1LevelDeep_OxPart() throws SQLException, PublisherException {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setCatalogPattern("advanced_object_demo");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("echoRegion");
testOxProject(pModel, "region", "urn:struct1", REGION_OX_PROJECT, REGION_SCHEMA);
}
static final String REGION_OX_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>region</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>advanced_object_demo.region</class>" +
"<alias>region</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>reg_id</attribute-name>" +
"<field is-required=\"true\" name=\"reg_id/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.math.BigDecimal</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>reg_name</attribute-name>" +
"<field is-required=\"true\" name=\"reg_name/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.lang.String</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<default-root-element>regionType</default-root-element>" +
"<default-root-element-field name=\"regionType\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:struct1</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/regionType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"</object-persistence>";
static final String REGION_SCHEMA =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsd:schema targetNamespace=\"urn:struct1\" xmlns=\"urn:struct1\" elementFormDefault=\"qualified\" xmlns:xsd=\"http:
"<xsd:complexType name=\"regionType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"reg_id\" type=\"xsd:decimal\" nillable=\"true\"/>" +
"<xsd:element name=\"reg_name\" type=\"xsd:string\" nillable=\"true\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"regionType\" type=\"regionType\"/>" +
"</xsd:schema>";
static final String EMPADDRESS_OR_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
"<object-persistence xmlns=\"http:
"<name>empAddress</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>advanced_object_demo.region</class>" +
"<alias>region</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>reg_id</attribute-name>" +
"<field name=\"REG_ID\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>reg_name</attribute-name>" +
"<field name=\"REG_NAME\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>REGION</structure>" +
"<field-order>" +
"<field name=\"REG_ID\" xsi:type=\"column\"/>" +
"<field name=\"REG_NAME\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>advanced_object_demo.emp_address</class>" +
"<alias>emp_address</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>street</attribute-name>" +
"<field name=\"STREET\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>suburb</attribute-name>" +
"<field name=\"SUBURB\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"structure-mapping\">" +
"<attribute-name>addr_region</attribute-name>" +
"<reference-class>advanced_object_demo.region</reference-class>" +
"<field name=\"ADDR_REGION\" xsi:type=\"object-relational-field\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>postcode</attribute-name>" +
"<field name=\"POSTCODE\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>EMP_ADDRESS</structure>" +
"<field-order>" +
"<field name=\"STREET\" xsi:type=\"column\"/>" +
"<field name=\"SUBURB\" xsi:type=\"column\"/>" +
"<field name=\"ADDR_REGION\" xsi:type=\"column\"/>" +
"<field name=\"POSTCODE\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"<queries>" +
"<query name=\"echoEmpAddress\" xsi:type=\"value-read-query\">" +
"<arguments>" +
"<argument name=\"ANEMPADDRESS\">" +
"<type>java.lang.Object</type>" +
"</argument>" +
"</arguments>" +
"<maintain-cache>false</maintain-cache>" +
"<bind-all-parameters>true</bind-all-parameters>" +
"<call xsi:type=\"stored-function-call\">" +
"<procedure-name>advanced_object_demo.ECHOEMPADDRESS</procedure-name>" +
"<cursor-output-procedure>false</cursor-output-procedure>" +
"<arguments>" +
"<argument>" +
"<procedure-argument-name>ANEMPADDRESS</procedure-argument-name>" +
"<argument-name>ANEMPADDRESS</argument-name>" +
"<procedure-argument-type>advanced_object_demo.emp_address</procedure-argument-type>" +
"<procedure-argument-sqltype>2002</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>EMP_ADDRESS</procedure-argument-sqltype-name>" +
"</argument>" +
"</arguments>" +
"<stored-function-result>" +
"<procedure-argument-type>advanced_object_demo.emp_address</procedure-argument-type>" +
"<procedure-argument-sqltype>2002</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>EMP_ADDRESS</procedure-argument-sqltype-name>" +
"</stored-function-result>" +
"</call>" +
"</query>" +
"</queries>" +
"</object-persistence>";
@SuppressWarnings("unchecked")
@Test
public void struct2LevelDeep_OrPart()
throws SQLException, PublisherException, InstantiationException, IllegalAccessException {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("echoEmpAddress");
pModel.setCatalogPattern("advanced_object_demo"); // test case-insensitivity
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("echoEmpAddress");
pModel.setReturnType("empAddressType");
testOrProject(pModel, "empAddress", EMPADDRESS_OR_PROJECT);
// test query
DatabaseSession ds = fixUp(EMPADDRESS_OR_PROJECT);
ObjectRelationalDataTypeDescriptor regionDesc =
(ObjectRelationalDataTypeDescriptor)ds.getProject().getDescriptorForAlias("region");
ObjectRelationalDataTypeDescriptor empAddressDesc =
(ObjectRelationalDataTypeDescriptor)ds.getProject().getDescriptorForAlias("emp_address");
ValueReadQuery vrq = (ValueReadQuery)ds.getQuery("echoEmpAddress");
XRDynamicEntity regionEntity = (XRDynamicEntity)regionDesc.getObjectBuilder().buildNewInstance();
regionEntity.set("reg_id", BigDecimal.valueOf(5));
regionEntity.set("reg_name", "this is a test");
XRDynamicEntity empAddressEntity = (XRDynamicEntity)empAddressDesc.getObjectBuilder().buildNewInstance();
empAddressEntity.set("street", "20 Pinetrail Cres.");
empAddressEntity.set("suburb", "Centrepointe");
empAddressEntity.set("addr_region", regionEntity);
empAddressEntity.set("postcode", BigDecimal.valueOf(12));
@SuppressWarnings("rawtypes") Vector v = new NonSynchronizedVector();
v.add(empAddressEntity);
Object o = ds.executeQuery(vrq, v);
assertTrue("incorect return type from StoredFunctionCall", o instanceof XRDynamicEntity);
XRDynamicEntity addressEntityEchoed = (XRDynamicEntity)o;
assertTrue("incorrect first field for type returned from StoredFunctionCall",
addressEntityEchoed.get("street").equals("20 Pinetrail Cres."));
assertTrue("incorrect second field for type returned from StoredFunctionCall",
addressEntityEchoed.get("suburb").equals("Centrepointe"));
XRDynamicEntity regionEntityEchoed = (XRDynamicEntity)addressEntityEchoed.get("addr_region");
assertTrue("incorrect nested-third-first field for type returned from StoredFunctionCall",
regionEntityEchoed.get("reg_id").equals(BigDecimal.valueOf(5)));
assertTrue("incorrect nested-third-second field for type returned from StoredFunctionCall",
regionEntityEchoed.get("reg_name").equals("this is a test"));
assertTrue("incorrect fourth field for type returned from StoredFunctionCall",
addressEntityEchoed.get("postcode").equals(BigDecimal.valueOf(12)));
}
@Test
public void struct2LevelDeep_OxPart() throws SQLException, PublisherException {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setCatalogPattern("advanced_object_demo");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("echoEmpAddress");
testOxProject(pModel, "empAddress", "urn:struct2", EMPADDRESS_OX_PROJECT, EMPADDRESS_SCHEMA);
}
static final String EMPADDRESS_OX_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>empAddress</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>advanced_object_demo.region</class>" +
"<alias>region</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>reg_id</attribute-name>" +
"<field is-required=\"true\" name=\"reg_id/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.math.BigDecimal</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>reg_name</attribute-name>" +
"<field is-required=\"true\" name=\"reg_name/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.lang.String</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:struct2</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/regionType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>advanced_object_demo.emp_address</class>" +
"<alias>emp_address</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>street</attribute-name>" +
"<field is-required=\"true\" name=\"street/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.lang.String</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>suburb</attribute-name>" +
"<field is-required=\"true\" name=\"suburb/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.lang.String</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-composite-object-mapping\">" +
"<attribute-name>addr_region</attribute-name>" +
"<reference-class>advanced_object_demo.region</reference-class>" +
"<field is-required=\"true\" name=\"addr_region\" xsi:type=\"node\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>postcode</attribute-name>" +
"<field is-required=\"true\" name=\"postcode/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.math.BigInteger</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<default-root-element>emp_addressType</default-root-element>" +
"<default-root-element-field name=\"emp_addressType\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:struct2</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/emp_addressType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"</object-persistence>";
static final String EMPADDRESS_SCHEMA =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsd:schema targetNamespace=\"urn:struct2\" xmlns=\"urn:struct2\" elementFormDefault=\"qualified\" xmlns:xsd=\"http:
"<xsd:complexType name=\"emp_addressType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"street\" type=\"xsd:string\" nillable=\"true\"/>" +
"<xsd:element name=\"suburb\" type=\"xsd:string\" nillable=\"true\"/>" +
"<xsd:element name=\"addr_region\" type=\"regionType\"/>" +
"<xsd:element name=\"postcode\" type=\"xsd:integer\" nillable=\"true\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"regionType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"reg_id\" type=\"xsd:decimal\" nillable=\"true\"/>" +
"<xsd:element name=\"reg_name\" type=\"xsd:string\" nillable=\"true\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"emp_addressType\" type=\"emp_addressType\"/>" +
"</xsd:schema>";
static final String EMPOBJECT_OR_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>empObject</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>advanced_object_demo.region</class>" +
"<alias>region</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>reg_id</attribute-name>" +
"<field name=\"REG_ID\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>reg_name</attribute-name>" +
"<field name=\"REG_NAME\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>REGION</structure>" +
"<field-order>" +
"<field name=\"REG_ID\" xsi:type=\"column\"/>" +
"<field name=\"REG_NAME\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>advanced_object_demo.emp_object</class>" +
"<alias>emp_object</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>employee_id</attribute-name>" +
"<field name=\"EMPLOYEE_ID\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"structure-mapping\">" +
"<attribute-name>address</attribute-name>" +
"<reference-class>advanced_object_demo.emp_address</reference-class>" +
"<field name=\"ADDRESS\" xsi:type=\"object-relational-field\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>employee_name</attribute-name>" +
"<field name=\"EMPLOYEE_NAME\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>date_of_hire</attribute-name>" +
"<field name=\"DATE_OF_HIRE\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>EMP_OBJECT</structure>" +
"<field-order>" +
"<field name=\"EMPLOYEE_ID\" xsi:type=\"column\"/>" +
"<field name=\"ADDRESS\" xsi:type=\"column\"/>" +
"<field name=\"EMPLOYEE_NAME\" xsi:type=\"column\"/>" +
"<field name=\"DATE_OF_HIRE\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>advanced_object_demo.emp_address</class>" +
"<alias>emp_address</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>street</attribute-name>" +
"<field name=\"STREET\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>suburb</attribute-name>" +
"<field name=\"SUBURB\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"structure-mapping\">" +
"<attribute-name>addr_region</attribute-name>" +
"<reference-class>advanced_object_demo.region</reference-class>" +
"<field name=\"ADDR_REGION\" xsi:type=\"object-relational-field\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>postcode</attribute-name>" +
"<field name=\"POSTCODE\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>EMP_ADDRESS</structure>" +
"<field-order>" +
"<field name=\"STREET\" xsi:type=\"column\"/>" +
"<field name=\"SUBURB\" xsi:type=\"column\"/>" +
"<field name=\"ADDR_REGION\" xsi:type=\"column\"/>" +
"<field name=\"POSTCODE\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"<queries>" +
"<query name=\"echoEmpObject\" xsi:type=\"value-read-query\">" +
"<arguments>" +
"<argument name=\"ANEMPOBJECT\">" +
"<type>java.lang.Object</type>" +
"</argument>" +
"</arguments>" +
"<maintain-cache>false</maintain-cache>" +
"<bind-all-parameters>true</bind-all-parameters>" +
"<call xsi:type=\"stored-function-call\">" +
"<procedure-name>advanced_object_demo.ECHOEMPOBJECT</procedure-name>" +
"<cursor-output-procedure>false</cursor-output-procedure>" +
"<arguments>" +
"<argument>" +
"<procedure-argument-name>ANEMPOBJECT</procedure-argument-name>" +
"<argument-name>ANEMPOBJECT</argument-name>" +
"<procedure-argument-type>advanced_object_demo.emp_object</procedure-argument-type>" +
"<procedure-argument-sqltype>2002</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>EMP_OBJECT</procedure-argument-sqltype-name>" +
"</argument>" +
"</arguments>" +
"<stored-function-result>" +
"<procedure-argument-type>advanced_object_demo.emp_object</procedure-argument-type>" +
"<procedure-argument-sqltype>2002</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>EMP_OBJECT</procedure-argument-sqltype-name>" +
"</stored-function-result>" +
"</call>" +
"</query>" +
"</queries>" +
"</object-persistence>";
@SuppressWarnings("unchecked")
@Test
public void struct3LevelDeep_OrPart()
throws SQLException, PublisherException, InstantiationException, IllegalAccessException {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("echoEmpObject");
pModel.setCatalogPattern("advanced_object_demo"); // test case-insensitivity
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("echoEmpObject");
pModel.setReturnType("empObject");
testOrProject(pModel, "empObject", EMPOBJECT_OR_PROJECT);
// test query
DatabaseSession ds = fixUp(EMPOBJECT_OR_PROJECT);
ObjectRelationalDataTypeDescriptor regionDesc =
(ObjectRelationalDataTypeDescriptor)ds.getProject().getDescriptorForAlias("region");
ObjectRelationalDataTypeDescriptor empAddressDesc =
(ObjectRelationalDataTypeDescriptor)ds.getProject().getDescriptorForAlias("emp_address");
ObjectRelationalDataTypeDescriptor empObjectDesc =
(ObjectRelationalDataTypeDescriptor)ds.getProject().getDescriptorForAlias("emp_object");
ValueReadQuery vrq = (ValueReadQuery)ds.getQuery("echoEmpObject");
XRDynamicEntity regionEntity = (XRDynamicEntity)regionDesc.getObjectBuilder().buildNewInstance();
regionEntity.set("reg_id", BigDecimal.valueOf(5));
regionEntity.set("reg_name", "this is a test");
XRDynamicEntity empAddressEntity = (XRDynamicEntity)empAddressDesc.getJavaClass().newInstance();
empAddressEntity.set("street", "20 Pinetrail Cres.");
empAddressEntity.set("suburb", "Centrepointe");
empAddressEntity.set("addr_region", regionEntity);
empAddressEntity.set("postcode", BigDecimal.valueOf(12));
XRDynamicEntity empObjectEntity = (XRDynamicEntity)empObjectDesc.getObjectBuilder().buildNewInstance();
empObjectEntity.set("employee_id", BigDecimal.valueOf(55));
empObjectEntity.set("address", empAddressEntity);
empObjectEntity.set("employee_name", "Mike Norman");
empObjectEntity.set("date_of_hire", new java.sql.Date(System.currentTimeMillis()));
@SuppressWarnings("rawtypes") Vector v = new NonSynchronizedVector();
v.add(empObjectEntity);
Object o = ds.executeQuery(vrq, v);
assertTrue("incorect return type from StoredFunctionCall", o instanceof XRDynamicEntity);
XRDynamicEntity empObjectEntityEchoed = (XRDynamicEntity)o;
assertTrue("incorrect first field for type returned from StoredFunctionCall",
empObjectEntityEchoed.get("employee_id").equals(BigDecimal.valueOf(55)));
XRDynamicEntity addressEntityEchoed = (XRDynamicEntity)empObjectEntityEchoed.get("address");
assertTrue("incorrect nested-second-first field for type returned from StoredFunctionCall",
addressEntityEchoed.get("street").equals("20 Pinetrail Cres."));
assertTrue("incorrect nested-second-second field for type returned from StoredFunctionCall",
addressEntityEchoed.get("suburb").equals("Centrepointe"));
XRDynamicEntity regionEntityEchoed = (XRDynamicEntity)addressEntityEchoed.get("addr_region");
assertTrue("incorrect nested-second-third-first field for type returned from StoredFunctionCall",
regionEntityEchoed.get("reg_id").equals(BigDecimal.valueOf(5)));
assertTrue("incorrect nested-second-third-second field for type returned from StoredFunctionCall",
regionEntityEchoed.get("reg_name").equals("this is a test"));
assertTrue("incorrect nested-second-fourth field for type returned from StoredFunctionCall",
addressEntityEchoed.get("postcode").equals(BigDecimal.valueOf(12)));
assertTrue("incorrect third field for type returned from StoredFunctionCall",
empObjectEntityEchoed.get("employee_name").equals("Mike Norman"));
// assume date works out
}
@Test
public void struct3LevelDeep_OxPart() throws SQLException, PublisherException,
InstantiationException, IllegalAccessException {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setCatalogPattern("advanced_object_demo");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("echoEmpObject");
testOxProject(pModel, "empObject", "urn:struct3", EMPOBJECT_OX_PROJECT, EMPOBJECT_SCHEMA);
// test marshalling
XRDynamicClassLoader xrdecl = new XRDynamicClassLoader(this.getClass().getClassLoader());
XMLContext xmlContext = new XMLContext(readObjectPersistenceProject, xrdecl);
Project p2 = (Project)xmlContext.createUnmarshaller().unmarshal(
new StringReader(EMPOBJECT_OX_PROJECT));
ProjectHelper.fixOROXAccessors(p2, null);
XMLDescriptor regionDesc = (XMLDescriptor)p2.getDescriptorForAlias("region");
XMLDescriptor empAddressDesc = (XMLDescriptor)p2.getDescriptorForAlias("emp_address");
XMLDescriptor empObjectDesc = (XMLDescriptor)p2.getDescriptorForAlias("emp_object");
XRDynamicEntity regionEntity = (XRDynamicEntity)regionDesc.getObjectBuilder().buildNewInstance();
regionEntity.set("reg_id", BigDecimal.valueOf(5));
regionEntity.set("reg_name", "this is a test");
XRDynamicEntity empAddressEntity = (XRDynamicEntity)empAddressDesc.getObjectBuilder().buildNewInstance();
empAddressEntity.set("street", "20 Pinetrail Cres.");
empAddressEntity.set("suburb", "Centrepointe");
empAddressEntity.set("addr_region", regionEntity);
empAddressEntity.set("postcode", BigInteger.valueOf(12));
XRDynamicEntity empObjectEntity = (XRDynamicEntity)empObjectDesc.getObjectBuilder().buildNewInstance();
empObjectEntity.set("employee_id", BigDecimal.valueOf(55));
empObjectEntity.set("address", empAddressEntity);
empObjectEntity.set("employee_name", "Mike Norman");
java.sql.Date today = new java.sql.Date(System.currentTimeMillis());
empObjectEntity.set("date_of_hire", today);
XMLContext xmlContext2 = new XMLContext(p2, xrdecl);
Document empObjectEntityDoc = xmlPlatform.createDocument();
xmlContext2.createMarshaller().marshal(empObjectEntity, empObjectEntityDoc);
String empObjectEntityString =
DBWSTestHelper.documentToString(empObjectEntityDoc).replaceAll("[\r\n]", "");
empObjectEntityString = empObjectEntityString.replaceAll(">( *)<", "><");
if (empObjectEntityString.startsWith(STANDALONE_XML_HEADER)) {
empObjectEntityString =
empObjectEntityString.replace(STANDALONE_XML_HEADER, REGULAR_XML_HEADER);
}
String anEmpObject = ANEMPOBJECT + today.toString() + ANEMPOBJECT_SUFFIX;
assertTrue("instance empObject not same as control empObject",
anEmpObject.equals(empObjectEntityString));
// test un-marshalling
XRDynamicEntity echoedEmpObjectEntity = (XRDynamicEntity)xmlContext2.createUnmarshaller().unmarshal(
new StringReader(anEmpObject), empObjectDesc.getJavaClass());
assertTrue("incorrect first field for type returned from StoredFunctionCall",
echoedEmpObjectEntity.get("employee_id").equals(BigDecimal.valueOf(55)));
XRDynamicEntity addressEntityEchoed = (XRDynamicEntity)echoedEmpObjectEntity.get("address");
assertTrue("incorrect nested-second-first field for type returned from StoredFunctionCall",
addressEntityEchoed.get("street").equals("20 Pinetrail Cres."));
assertTrue("incorrect nested-second-second field for type returned from StoredFunctionCall",
addressEntityEchoed.get("suburb").equals("Centrepointe"));
XRDynamicEntity regionEntityEchoed = (XRDynamicEntity)addressEntityEchoed.get("addr_region");
assertTrue("incorrect nested-second-third-first field for type returned from StoredFunctionCall",
regionEntityEchoed.get("reg_id").equals(BigDecimal.valueOf(5)));
assertTrue("incorrect nested-second-third-second field for type returned from StoredFunctionCall",
regionEntityEchoed.get("reg_name").equals("this is a test"));
assertTrue("incorrect nested-second-fourth field for type returned from StoredFunctionCall",
addressEntityEchoed.get("postcode").equals(BigInteger.valueOf(12)));
assertTrue("incorrect third field for type returned from StoredFunctionCall",
echoedEmpObjectEntity.get("employee_name").equals("Mike Norman"));
Object date = echoedEmpObjectEntity.get("date_of_hire");
assertTrue("incorrect fourth field (type) for type returned from StoredFunctionCall",
date instanceof java.sql.Date);
}
static final String EMPOBJECT_OX_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>empObject</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>advanced_object_demo.region</class>" +
"<alias>region</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>reg_id</attribute-name>" +
"<field is-required=\"true\" name=\"reg_id/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.math.BigDecimal</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>reg_name</attribute-name>" +
"<field is-required=\"true\" name=\"reg_name/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.lang.String</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:struct3</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/regionType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>advanced_object_demo.emp_object</class>" +
"<alias>emp_object</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>employee_id</attribute-name>" +
"<field is-required=\"true\" name=\"employee_id/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.math.BigDecimal</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-composite-object-mapping\">" +
"<attribute-name>address</attribute-name>" +
"<reference-class>advanced_object_demo.emp_address</reference-class>" +
"<field is-required=\"true\" name=\"address\" xsi:type=\"node\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>employee_name</attribute-name>" +
"<field is-required=\"true\" name=\"employee_name/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.lang.String</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>date_of_hire</attribute-name>" +
"<field is-required=\"true\" name=\"date_of_hire/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"<xml-to-java-conversion-pair>" +
"<qname>{http:
"<class-name>java.sql.Date</class-name>" +
"</xml-to-java-conversion-pair>" +
"<java-to-xml-conversion-pair>" +
"<qname>{http:
"<class-name>java.sql.Date</class-name>" +
"</java-to-xml-conversion-pair>" +
"</field>" +
"<attribute-classification>java.sql.Date</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<default-root-element>emp_objectType</default-root-element>" +
"<default-root-element-field name=\"emp_objectType\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsd</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:struct3</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/emp_objectType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>advanced_object_demo.emp_address</class>" +
"<alias>emp_address</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>street</attribute-name>" +
"<field is-required=\"true\" name=\"street/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.lang.String</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>suburb</attribute-name>" +
"<field is-required=\"true\" name=\"suburb/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.lang.String</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-composite-object-mapping\">" +
"<attribute-name>addr_region</attribute-name>" +
"<reference-class>advanced_object_demo.region</reference-class>" +
"<field is-required=\"true\" name=\"addr_region\" xsi:type=\"node\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>postcode</attribute-name>" +
"<field is-required=\"true\" name=\"postcode/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.math.BigInteger</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:struct3</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/emp_addressType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"</object-persistence>";
static final String EMPOBJECT_SCHEMA =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsd:schema targetNamespace=\"urn:struct3\" xmlns=\"urn:struct3\" elementFormDefault=\"qualified\" xmlns:xsd=\"http:
"<xsd:complexType name=\"emp_addressType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"street\" type=\"xsd:string\" nillable=\"true\"/>" +
"<xsd:element name=\"suburb\" type=\"xsd:string\" nillable=\"true\"/>" +
"<xsd:element name=\"addr_region\" type=\"regionType\"/>" +
"<xsd:element name=\"postcode\" type=\"xsd:integer\" nillable=\"true\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"emp_objectType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"employee_id\" type=\"xsd:decimal\" nillable=\"true\"/>" +
"<xsd:element name=\"address\" type=\"emp_addressType\"/>" +
"<xsd:element name=\"employee_name\" type=\"xsd:string\" nillable=\"true\"/>" +
"<xsd:element name=\"date_of_hire\" type=\"xsd:date\" nillable=\"true\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"regionType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"reg_id\" type=\"xsd:decimal\" nillable=\"true\"/>" +
"<xsd:element name=\"reg_name\" type=\"xsd:string\" nillable=\"true\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"emp_objectType\" type=\"emp_objectType\"/>" +
"</xsd:schema>";
public static final String EMP_ARRAY_OR_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>empArray</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>another_advanced_demo.emp_info</class>" +
"<alias>emp_info</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>id</attribute-name>" +
"<field name=\"ID\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>name</attribute-name>" +
"<field name=\"NAME\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>EMP_INFO</structure>" +
"<field-order>" +
"<field name=\"ID\" xsi:type=\"column\"/>" +
"<field name=\"NAME\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>another_advanced_demo.emp_info_array_CollectionWrapper</class>" +
"<alias>emp_info_array</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"object-array-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<reference-class>another_advanced_demo.emp_info</reference-class>" +
"<field name=\"items\" xsi:type=\"object-relational-field\"/>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>EMP_INFO_ARRAY</structure>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"<queries>" +
"<query name=\"buildEmpArray\" xsi:type=\"value-read-query\">" +
"<arguments>" +
"<argument name=\"NUM\">" +
"<type>java.lang.Object</type>" +
"</argument>" +
"</arguments>" +
"<maintain-cache>false</maintain-cache>" +
"<bind-all-parameters>true</bind-all-parameters>" +
"<call xsi:type=\"stored-function-call\">" +
"<procedure-name>another_advanced_demo.BUILDEMPARRAY</procedure-name>" +
"<cursor-output-procedure>false</cursor-output-procedure>" +
"<arguments>" +
"<argument>" +
"<procedure-argument-name>NUM</procedure-argument-name>" +
"<argument-name>NUM</argument-name>" +
"</argument>" +
"</arguments>" +
"<stored-function-result>" +
"<procedure-argument-type>another_advanced_demo.emp_info_array_CollectionWrapper</procedure-argument-type>" +
"<procedure-argument-sqltype>2003</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>EMP_INFO_ARRAY</procedure-argument-sqltype-name>" +
"<nested-type-field>" +
"<procedure-argument-type>another_advanced_demo.emp_info</procedure-argument-type>" +
"<procedure-argument-sqltype>2002</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>EMP_INFO</procedure-argument-sqltype-name>" +
"</nested-type-field>" +
"</stored-function-result>" +
"</call>" +
"</query>" +
"</queries>" +
"</object-persistence>";
static final String STANDALONE_XML_HEADER =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>";
static final String REGULAR_XML_HEADER =
"<?xml version = '1.0' encoding = 'UTF-8'?>";
static final String ANEMPOBJECT =
REGULAR_XML_HEADER +
"<emp_objectType xmlns=\"urn:struct3\" xmlns:xsd=\"http:
"<employee_id>55</employee_id>" +
"<address>" +
"<street>20 Pinetrail Cres.</street>" +
"<suburb>Centrepointe</suburb>" +
"<addr_region>" +
"<reg_id>5</reg_id>" +
"<reg_name>this is a test</reg_name>" +
"</addr_region>" +
"<postcode>12</postcode>" +
"</address>" +
"<employee_name>Mike Norman</employee_name>" +
"<date_of_hire>";
static final String ANEMPOBJECT_SUFFIX =
"</date_of_hire>" +
"</emp_objectType>";
@SuppressWarnings("unchecked")
@Test
public void buildEmpArray_OrPart() throws SQLException, PublisherException {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("buildEmpArray");
pModel.setCatalogPattern("another_advanced_demo");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("buildEmpArray");
pModel.setReturnType("emp_info_arrayType");
testOrProject(pModel, "empArray", EMP_ARRAY_OR_PROJECT);
// test query
DatabaseSession ds = fixUp(EMP_ARRAY_OR_PROJECT);
DatabaseQuery vrq = ds.getQuery("buildEmpArray");
@SuppressWarnings("rawtypes") Vector args = new NonSynchronizedVector();
args.add(Integer.valueOf(3));
Object o = ds.executeQuery(vrq, args);
assertTrue("return value not correct type", o instanceof XRDynamicEntity);
XRDynamicEntity returnValue = (XRDynamicEntity)o;
Object o2 = returnValue.get("items");
assertTrue("return value array not correct type", o2 instanceof ArrayList);
ArrayList<XRDynamicEntity> empInfo = (ArrayList<XRDynamicEntity>)o2;
assertTrue("return value array wrong size", empInfo.size() == 3);
XRDynamicEntity emp1 = empInfo.get(0);
assertTrue("return value array first element id wrong value",
emp1.get("id").equals(BigDecimal.valueOf(1)));
assertTrue("return value array first element name wrong value",
emp1.get("name").equals("entry 1"));
XRDynamicEntity emp2 = empInfo.get(1);
assertTrue("return value array second element id wrong value",
emp2.get("id").equals(BigDecimal.valueOf(2)));
assertTrue("return value array second element name wrong value",
emp2.get("name").equals("entry 2"));
XRDynamicEntity emp3 = empInfo.get(2);
assertTrue("return value array third element id wrong value",
emp3.get("id").equals(BigDecimal.valueOf(3)));
assertTrue("return value array second element name wrong value",
emp3.get("name").equals("entry 3"));
}
@Test
public void buildEmpArray_OxPart() throws SQLException, PublisherException,
InstantiationException, IllegalAccessException {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("buildEmpArray");
pModel.setCatalogPattern("another_advanced_demo");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("buildEmpArray");
pModel.setReturnType("emp_info_arrayType");
testOxProject(pModel, "empArray", "urn:empArray", EMPARRAY_OX_PROJECT, EMPARRAY_SCHEMA);
}
static final String EMPARRAY_OX_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>empArray</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>another_advanced_demo.emp_info</class>" +
"<alias>emp_info</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>id</attribute-name>" +
"<field is-required=\"true\" name=\"id/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.math.BigDecimal</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>name</attribute-name>" +
"<field is-required=\"true\" name=\"name/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.lang.String</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:empArray</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/emp_infoType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>another_advanced_demo.emp_info_array_CollectionWrapper</class>" +
"<alias>emp_info_array</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-collection-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<reference-class>another_advanced_demo.emp_info</reference-class>" +
"<field name=\"item\" xsi:type=\"node\"/>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<default-root-element>emp_info_arrayType</default-root-element>" +
"<default-root-element-field name=\"emp_info_arrayType\"/>" +
"<namespace-resolver>" +
"<default-namespace-uri>urn:empArray</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/emp_info_arrayType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"</object-persistence>";
static final String EMPARRAY_SCHEMA =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsd:schema targetNamespace=\"urn:empArray\" xmlns=\"urn:empArray\" elementFormDefault=\"qualified\" xmlns:xsd=\"http:
"<xsd:complexType name=\"emp_infoType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"id\" type=\"xsd:decimal\" nillable=\"true\"/>" +
"<xsd:element name=\"name\" type=\"xsd:string\" nillable=\"true\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"emp_info_arrayType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"item\" type=\"emp_infoType\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"emp_info_arrayType\" type=\"emp_info_arrayType\"/>" +
"</xsd:schema>";
public static final String SF_TBL1_OR_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>sfTbl1</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl1_CollectionWrapper</class>" +
"<alias>somepackage_tbl1</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field name=\"items\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"12\" column-definition=\"VARCHAR2\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL1</structure>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"<queries>" +
"<query name=\"sfTbl1\" xsi:type=\"value-read-query\">" +
"<arguments>" +
"<argument name=\"NUM\">" +
"<type>java.lang.Object</type>" +
"</argument>" +
"</arguments>" +
"<maintain-cache>false</maintain-cache>" +
"<bind-all-parameters>true</bind-all-parameters>" +
"<call xsi:type=\"stored-function-call\">" +
"<procedure-name>SF_TBL1</procedure-name>" +
"<cursor-output-procedure>false</cursor-output-procedure>" +
"<arguments>" +
"<argument>" +
"<procedure-argument-name>NUM</procedure-argument-name>" +
"<argument-name>NUM</argument-name>" +
"</argument>" +
"</arguments>" +
"<stored-function-result>" +
"<procedure-argument-type>toplevel.somepackage_tbl1_CollectionWrapper</procedure-argument-type>" +
"<procedure-argument-sqltype>2003</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>SOMEPACKAGE_TBL1</procedure-argument-sqltype-name>" +
"</stored-function-result>" +
"</call>" +
"</query>" +
"</queries>" +
"</object-persistence>";
@SuppressWarnings("unchecked")
@Test
public void sfTbl1_OrPart() {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("sfTbl1");
pModel.setCatalogPattern("toplevel");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("SF_TBL1");
pModel.setReturnType("somepackage_tbl1Type");
testOrProject(pModel, "sfTbl1", SF_TBL1_OR_PROJECT);
// test query
DatabaseSession ds = fixUp(SF_TBL1_OR_PROJECT);
DatabaseQuery vrq = ds.getQuery("sfTbl1");
@SuppressWarnings("rawtypes") Vector args = new NonSynchronizedVector();
args.add(Integer.valueOf(3));
Object o = ds.executeQuery(vrq, args);
assertTrue("return value not correct type", o instanceof XRDynamicEntity);
XRDynamicEntity returnValue = (XRDynamicEntity)o;
ArrayList<String> strings = (ArrayList<String>)returnValue.get("items");
assertTrue("wrong number of returned strings", 3 == strings.size());
for (int i = 0, len = strings.size(); i < len; i++) {
assertTrue("wrong array element value", ("entry " + (i + 1)).equals(strings.get(i)));
}
}
@Test
public void sfTbl1_OxPart() {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("sfTbl1");
pModel.setCatalogPattern("toplevel");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("SF_TBL1");
pModel.setReturnType("somepackage_tbl1Type");
testOxProject(pModel, "sfTbl1", "urn:tbl1", SF_TBL1_OX_PROJECT, SF_TBL1_SCHEMA);
}
public static final String SF_TBL1_OX_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>sfTbl1</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl1_CollectionWrapper</class>" +
"<alias>somepackage_tbl1</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field is-required=\"true\" name=\"item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.lang.String</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<default-root-element>somepackage_tbl1Type</default-root-element>" +
"<default-root-element-field name=\"somepackage_tbl1Type\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:tbl1</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/somepackage_tbl1Type</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"</object-persistence>";
public static final String SF_TBL1_SCHEMA =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
"<xsd:schema xmlns:xsd=\"http:
"<xsd:complexType name=\"somepackage_tbl1Type\">" +
"<xsd:sequence>" +
"<xsd:element maxOccurs=\"unbounded\" name=\"item\" nillable=\"true\" type=\"xsd:string\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"somepackage_tbl1Type\" type=\"somepackage_tbl1Type\"/>" +
"</xsd:schema>";
public static final String TBL5_OR_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>tbl5</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl5_CollectionWrapper</class>" +
"<alias>somepackage_tbl5</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field name=\"items\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"91\" column-definition=\"DATE\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL5</structure>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"<queries>" +
"<query name=\"tbl5\" xsi:type=\"value-read-query\">" +
"<arguments>" +
"<argument name=\"NUM\">" +
"<type>java.lang.Object</type>" +
"</argument>" +
"</arguments>" +
"<maintain-cache>false</maintain-cache>" +
"<bind-all-parameters>true</bind-all-parameters>" +
"<call xsi:type=\"stored-function-call\">" +
"<procedure-name>BUILDTBL5</procedure-name>" +
"<cursor-output-procedure>false</cursor-output-procedure>" +
"<arguments>" +
"<argument>" +
"<procedure-argument-name>NUM</procedure-argument-name>" +
"<argument-name>NUM</argument-name>" +
"</argument>" +
"</arguments>" +
"<stored-function-result>" +
"<procedure-argument-type>toplevel.somepackage_tbl5_CollectionWrapper</procedure-argument-type>" +
"<procedure-argument-sqltype>2003</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>SOMEPACKAGE_TBL5</procedure-argument-sqltype-name>" +
"</stored-function-result>" +
"</call>" +
"</query>" +
"</queries>" +
"</object-persistence>";
@SuppressWarnings("unchecked")
@Test
public void tbl5_OrPart() {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("tbl5");
pModel.setCatalogPattern("toplevel");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("BuildTbl5");
pModel.setReturnType("somepackage_tbl5Type");
testOrProject(pModel, "tbl5", TBL5_OR_PROJECT);
// test query
DatabaseSession ds = fixUp(TBL5_OR_PROJECT);
DatabaseQuery vrq = ds.getQuery("tbl5");
@SuppressWarnings("rawtypes") Vector args = new NonSynchronizedVector();
args.add(Integer.valueOf(3));
Object o = ds.executeQuery(vrq, args);
assertTrue("return value not correct type", o instanceof XRDynamicEntity);
XRDynamicEntity returnValue = (XRDynamicEntity)o;
ArrayList<java.sql.Date> dates = (ArrayList<java.sql.Date>)returnValue.get("items");
assertTrue("wrong number of returned dates", 3 == dates.size());
}
@Test
public void tbl5_OxPart() {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("tbl5");
pModel.setCatalogPattern("toplevel");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("BuildTbl5");
pModel.setReturnType("somepackage_tbl5Type");
testOxProject(pModel, "BuildTbl5", "urn:tbl5", TBL5_OX_PROJECT, TBL5_SCHEMA);
}
public static final String TBL5_OX_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>BuildTbl5</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl5_CollectionWrapper</class>" +
"<alias>somepackage_tbl5</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field is-required=\"true\" name=\"item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.sql.Date</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<default-root-element>somepackage_tbl5Type</default-root-element>" +
"<default-root-element-field name=\"somepackage_tbl5Type\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:tbl5</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/somepackage_tbl5Type</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"</object-persistence>";
public static final String TBL5_SCHEMA =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsd:schema targetNamespace=\"urn:tbl5\" xmlns=\"urn:tbl5\" elementFormDefault=\"qualified\" xmlns:xsd=\"http:
"<xsd:complexType name=\"somepackage_tbl5Type\">" +
"<xsd:sequence>" +
"<xsd:element name=\"item\" type=\"xsd:date\" nillable=\"true\" maxOccurs=\"unbounded\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"somepackage_tbl5Type\" type=\"somepackage_tbl5Type\"/>" +
"</xsd:schema>";
public static final String ARECORD_OR_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>aRecord</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_arecord</class>" +
"<alias>somepackage_arecord</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>t1</attribute-name>" +
"<field name=\"T1\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"12\" column-definition=\"VARCHAR2\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL1</structure>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>t2</attribute-name>" +
"<field name=\"T2\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"2\" column-definition=\"NUMBER\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL2</structure>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>t3</attribute-name>" +
"<field name=\"T3\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>SOMEPACKAGE_ARECORD</structure>" +
"<field-order>" +
"<field name=\"T1\" xsi:type=\"column\"/>" +
"<field name=\"T2\" xsi:type=\"column\"/>" +
"<field name=\"T3\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl1_CollectionWrapper</class>" +
"<alias>somepackage_tbl1</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field name=\"items\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"12\" column-definition=\"VARCHAR2\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL1</structure>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl2_CollectionWrapper</class>" +
"<alias>somepackage_tbl2</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field name=\"items\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"2\" column-definition=\"NUMBER\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL2</structure>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"<queries>" +
"<query name=\"buildARecord\" xsi:type=\"value-read-query\">" +
"<arguments>" +
"<argument name=\"NUM\">" +
"<type>java.lang.Object</type>" +
"</argument>" +
"</arguments>" +
"<maintain-cache>false</maintain-cache>" +
"<bind-all-parameters>true</bind-all-parameters>" +
"<call xsi:type=\"stored-function-call\">" +
"<procedure-name>BUILDARECORD</procedure-name>" +
"<cursor-output-procedure>false</cursor-output-procedure>" +
"<arguments>" +
"<argument>" +
"<procedure-argument-name>NUM</procedure-argument-name>" +
"<argument-name>NUM</argument-name>" +
"</argument>" +
"</arguments>" +
"<stored-function-result>" +
"<procedure-argument-type>toplevel.somepackage_arecord</procedure-argument-type>" +
"<procedure-argument-sqltype>2002</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>SOMEPACKAGE_ARECORD</procedure-argument-sqltype-name>" +
"</stored-function-result>" +
"</call>" +
"</query>" +
"</queries>" +
"</object-persistence>";
@SuppressWarnings("unchecked")
@Test
public void BuildARecord_OrPart() {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("buildARecord");
pModel.setCatalogPattern("toplevel");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("BuildARecord");
pModel.setReturnType("somepackage_arecordType");
testOrProject(pModel, "aRecord", ARECORD_OR_PROJECT);
// test query
DatabaseSession ds = fixUp(ARECORD_OR_PROJECT);
DatabaseQuery vrq = ds.getQuery("buildARecord");
@SuppressWarnings("rawtypes") Vector args = new NonSynchronizedVector();
int num = 3;
args.add(Integer.valueOf(num));
Object o = ds.executeQuery(vrq, args);
assertTrue("return value not correct type", o instanceof XRDynamicEntity);
XRDynamicEntity returnValue = (XRDynamicEntity)o;
ArrayList<String> tbl1 = (ArrayList<String>)returnValue.get("t1");
assertTrue("wrong number of returned strings", num == tbl1.size());
for (int i = 0, len = tbl1.size(); i < len; i++) {
assertTrue("wrong array element value", ("entry " + (i + 1)).equals(tbl1.get(i)));
}
ArrayList<BigDecimal> tbl2 = (ArrayList<BigDecimal>)returnValue.get("t2");
assertTrue("wrong number of returned strings", num == tbl2.size());
for (int i = 0, len = tbl2.size(); i < len; i++) {
assertTrue("wrong array element value", BigDecimal.valueOf(i+1).equals(tbl2.get(i)));
}
BigDecimal t3 = (BigDecimal)returnValue.get("t3");
assertTrue("wrong array element value", BigDecimal.valueOf(num).equals(t3));
}
@Test
public void BuildARecord_OxPart() {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("buildARecord");
pModel.setCatalogPattern("toplevel");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("BuildARecord");
pModel.setReturnType("somepackage_arecordType");
testOxProject(pModel, "buildARecord", "urn:aRecord", ARECORD_OX_PROJECT, ARECORD_SCHEMA);
}
public static final String ARECORD_OX_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>buildARecord</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_arecord</class>" +
"<alias>somepackage_arecord</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>t1</attribute-name>" +
"<field is-required=\"true\" name=\"t1/item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.lang.String</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>t2</attribute-name>" +
"<field is-required=\"true\" name=\"t2/item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.math.BigDecimal</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>t3</attribute-name>" +
"<field is-required=\"true\" name=\"t3/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.math.BigInteger</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<default-root-element>somepackage_arecordType</default-root-element>" +
"<default-root-element-field name=\"somepackage_arecordType\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:aRecord</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/somepackage_arecordType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl1_CollectionWrapper</class>" +
"<alias>somepackage_tbl1</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field is-required=\"true\" name=\"item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.lang.String</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:aRecord</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/somepackage_tbl1Type</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl2_CollectionWrapper</class>" +
"<alias>somepackage_tbl2</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field is-required=\"true\" name=\"item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.math.BigDecimal</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:aRecord</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/somepackage_tbl2Type</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"</object-persistence>";
public static final String ARECORD_SCHEMA =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsd:schema targetNamespace=\"urn:aRecord\" xmlns=\"urn:aRecord\" elementFormDefault=\"qualified\" xmlns:xsd=\"http:
"<xsd:complexType name=\"somepackage_tbl2Type\">" +
"<xsd:sequence>" +
"<xsd:element name=\"item\" type=\"xsd:decimal\" nillable=\"true\" maxOccurs=\"unbounded\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"somepackage_arecordType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"t1\">" +
"<xsd:complexType>" +
"<xsd:sequence>" +
"<xsd:element name=\"item\" type=\"xsd:string\" nillable=\"true\" maxOccurs=\"unbounded\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:element>" +
"<xsd:element name=\"t2\">" +
"<xsd:complexType>" +
"<xsd:sequence>" +
"<xsd:element name=\"item\" type=\"xsd:decimal\" nillable=\"true\" maxOccurs=\"unbounded\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:element>" +
"<xsd:element name=\"t3\" type=\"xsd:integer\" nillable=\"true\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"somepackage_tbl1Type\">" +
"<xsd:sequence>" +
"<xsd:element name=\"item\" type=\"xsd:string\" nillable=\"true\" maxOccurs=\"unbounded\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"somepackage_arecordType\" type=\"somepackage_arecordType\"/>" +
"</xsd:schema>";
public static final String CRECORD_OR_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>cRecord</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_crecord</class>" +
"<alias>somepackage_crecord</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"structure-mapping\">" +
"<attribute-name>c1</attribute-name>" +
"<reference-class>toplevel.somepackage_arecord</reference-class>" +
"<field name=\"C1\" xsi:type=\"object-relational-field\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>c2</attribute-name>" +
"<field name=\"C2\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"2\" column-definition=\"NUMBER\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL2</structure>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>SOMEPACKAGE_CRECORD</structure>" +
"<field-order>" +
"<field name=\"C1\" xsi:type=\"column\"/>" +
"<field name=\"C2\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_arecord</class>" +
"<alias>somepackage_arecord</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>t1</attribute-name>" +
"<field name=\"T1\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"12\" column-definition=\"VARCHAR2\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL1</structure>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>t2</attribute-name>" +
"<field name=\"T2\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"2\" column-definition=\"NUMBER\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL2</structure>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"direct-mapping\">" +
"<attribute-name>t3</attribute-name>" +
"<field name=\"T3\" xsi:type=\"column\"/>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<structure>SOMEPACKAGE_ARECORD</structure>" +
"<field-order>" +
"<field name=\"T1\" xsi:type=\"column\"/>" +
"<field name=\"T2\" xsi:type=\"column\"/>" +
"<field name=\"T3\" xsi:type=\"column\"/>" +
"</field-order>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl1_CollectionWrapper</class>" +
"<alias>somepackage_tbl1</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field name=\"items\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"12\" column-definition=\"VARCHAR2\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL1</structure>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"object-relational-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl2_CollectionWrapper</class>" +
"<alias>somepackage_tbl2</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"array-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field name=\"items\" xsi:type=\"object-relational-field\">" +
"<nested-type-field name=\"\" sql-typecode=\"2\" column-definition=\"NUMBER\"/>" +
"</field>" +
"<container xsi:type=\"list-container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<structure>SOMEPACKAGE_TBL2</structure>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<caching>" +
"<cache-size>-1</cache-size>" +
"</caching>" +
"<remote-caching>" +
"<cache-size>-1</cache-size>" +
"</remote-caching>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"<queries>" +
"<query name=\"buildCRecord\" xsi:type=\"value-read-query\">" +
"<arguments>" +
"<argument name=\"NUM\">" +
"<type>java.lang.Object</type>" +
"</argument>" +
"</arguments>" +
"<maintain-cache>false</maintain-cache>" +
"<bind-all-parameters>true</bind-all-parameters>" +
"<call xsi:type=\"stored-function-call\">" +
"<procedure-name>BUILDCRECORD</procedure-name>" +
"<cursor-output-procedure>false</cursor-output-procedure>" +
"<arguments>" +
"<argument>" +
"<procedure-argument-name>NUM</procedure-argument-name>" +
"<argument-name>NUM</argument-name>" +
"</argument>" +
"</arguments>" +
"<stored-function-result>" +
"<procedure-argument-type>toplevel.somepackage_crecord</procedure-argument-type>" +
"<procedure-argument-sqltype>2002</procedure-argument-sqltype>" +
"<procedure-argument-sqltype-name>SOMEPACKAGE_CRECORD</procedure-argument-sqltype-name>" +
"</stored-function-result>" +
"</call>" +
"</query>" +
"</queries>" +
"</object-persistence>";
@SuppressWarnings("unchecked")
@Test
public void BuildCRecord_OrPart() {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("buildCRecord");
pModel.setCatalogPattern("toplevel");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("BuildCRecord");
pModel.setReturnType("somepackage_crecordType");
testOrProject(pModel, "cRecord", CRECORD_OR_PROJECT);
// test query
DatabaseSession ds = fixUp(CRECORD_OR_PROJECT);
DatabaseQuery vrq = ds.getQuery("buildCRecord");
@SuppressWarnings("rawtypes") Vector args = new NonSynchronizedVector();
int num = 3;
args.add(Integer.valueOf(num));
Object o = ds.executeQuery(vrq, args);
assertTrue("return value not correct type", o instanceof XRDynamicEntity);
}
@Test
public void BuildCRecord_OxPart() {
ProcedureOperationModel pModel = new ProcedureOperationModel();
pModel.setName("buildCRecord");
pModel.setCatalogPattern("toplevel");
pModel.setSchemaPattern(username.toUpperCase());
pModel.setProcedurePattern("BuildCRecord");
pModel.setReturnType("somepackage_crecordType");
testOxProject(pModel, "cRecord", "urn:cRecord", CRECORD_OX_PROJECT, CRECORD_SCHEMA);
}
public static final String CRECORD_OX_PROJECT =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<object-persistence version=\"Eclipse Persistence Services - some version (some build date)\" xmlns=\"http:
"<name>cRecord</name>" +
"<class-mapping-descriptors>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_crecord</class>" +
"<alias>somepackage_crecord</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-object-mapping\">" +
"<attribute-name>c1</attribute-name>" +
"<reference-class>toplevel.somepackage_arecord</reference-class>" +
"<field is-required=\"true\" name=\"c1\" xsi:type=\"node\"/>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>c2</attribute-name>" +
"<field is-required=\"true\" name=\"c2/item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.math.BigDecimal</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<default-root-element>somepackage_crecordType</default-root-element>" +
"<default-root-element-field name=\"somepackage_crecordType\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:cRecord</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/somepackage_crecordType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_arecord</class>" +
"<alias>somepackage_arecord</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>t1</attribute-name>" +
"<field is-required=\"true\" name=\"t1/item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.lang.String</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>t2</attribute-name>" +
"<field is-required=\"true\" name=\"t2/item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.math.BigDecimal</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"<attribute-mapping xsi:type=\"xml-direct-mapping\">" +
"<attribute-name>t3</attribute-name>" +
"<field is-required=\"true\" name=\"t3/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<attribute-classification>java.math.BigInteger</attribute-classification>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:cRecord</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/somepackage_arecordType</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl1_CollectionWrapper</class>" +
"<alias>somepackage_tbl1</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field is-required=\"true\" name=\"item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.lang.String</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:cRecord</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/somepackage_tbl1Type</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"<class-mapping-descriptor xsi:type=\"xml-class-mapping-descriptor\">" +
"<class>toplevel.somepackage_tbl2_CollectionWrapper</class>" +
"<alias>somepackage_tbl2</alias>" +
"<events/>" +
"<querying/>" +
"<attribute-mappings>" +
"<attribute-mapping xsi:type=\"xml-composite-direct-collection-mapping\">" +
"<attribute-name>items</attribute-name>" +
"<field is-required=\"true\" name=\"item/text()\" xsi:type=\"node\">" +
"<schema-type>{http:
"</field>" +
"<value-converter xsi:type=\"type-conversion-converter\">" +
"<object-class>java.math.BigDecimal</object-class>" +
"</value-converter>" +
"<container xsi:type=\"container-policy\">" +
"<collection-type>java.util.ArrayList</collection-type>" +
"</container>" +
"<null-policy xsi:type=\"null-policy\">" +
"<xsi-nil-represents-null>true</xsi-nil-represents-null>" +
"<null-representation-for-xml>XSI_NIL</null-representation-for-xml>" +
"</null-policy>" +
"</attribute-mapping>" +
"</attribute-mappings>" +
"<descriptor-type>aggregate</descriptor-type>" +
"<instantiation/>" +
"<copying xsi:type=\"instantiation-copy-policy\"/>" +
"<namespace-resolver>" +
"<namespaces>" +
"<namespace>" +
"<prefix>xsi</prefix>" +
"<namespace-uri>http:
"</namespace>" +
"</namespaces>" +
"<default-namespace-uri>urn:cRecord</default-namespace-uri>" +
"</namespace-resolver>" +
"<schema xsi:type=\"schema-url-reference\">" +
"<schema-context>/somepackage_tbl2Type</schema-context>" +
"<node-type>complex-type</node-type>" +
"</schema>" +
"</class-mapping-descriptor>" +
"</class-mapping-descriptors>" +
"</object-persistence>";
public static final String CRECORD_SCHEMA =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsd:schema xmlns:xsd=\"http:
"<xsd:complexType name=\"somepackage_crecordType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"c1\" type=\"somepackage_arecordType\"/>" +
"<xsd:element name=\"c2\">" +
"<xsd:complexType>" +
"<xsd:sequence>" +
"<xsd:element maxOccurs=\"unbounded\" name=\"item\" nillable=\"true\" type=\"xsd:decimal\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:element>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"somepackage_tbl2Type\">" +
"<xsd:sequence>" +
"<xsd:element maxOccurs=\"unbounded\" name=\"item\" nillable=\"true\" type=\"xsd:decimal\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"somepackage_arecordType\">" +
"<xsd:sequence>" +
"<xsd:element name=\"t1\">" +
"<xsd:complexType>" +
"<xsd:sequence>" +
"<xsd:element maxOccurs=\"unbounded\" name=\"item\" nillable=\"true\" type=\"xsd:string\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:element>" +
"<xsd:element name=\"t2\">" +
"<xsd:complexType>" +
"<xsd:sequence>" +
"<xsd:element maxOccurs=\"unbounded\" name=\"item\" nillable=\"true\" type=\"xsd:decimal\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"</xsd:element>" +
"<xsd:element name=\"t3\" nillable=\"true\" type=\"xsd:integer\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:complexType name=\"somepackage_tbl1Type\">" +
"<xsd:sequence>" +
"<xsd:element maxOccurs=\"unbounded\" name=\"item\" nillable=\"true\" type=\"xsd:string\"/>" +
"</xsd:sequence>" +
"</xsd:complexType>" +
"<xsd:element name=\"somepackage_crecordType\" type=\"somepackage_crecordType\"/>" +
"</xsd:schema>";
protected void testOrProject(ProcedureOperationModel pModel, String projectName, String orProject) {
List<DbStoredProcedure> storedProcedures =
OracleHelper.buildStoredProcedure(conn, username, ora11Platform, pModel);
Map<DbStoredProcedure, DbStoredProcedureNameAndModel> dbStoredProcedure2QueryName =
new HashMap<DbStoredProcedure, DbStoredProcedureNameAndModel>();
ArrayList<OperationModel> operations = new ArrayList<OperationModel>();
operations.add(pModel);
DBWSBuilder.buildDbStoredProcedure2QueryNameMap(dbStoredProcedure2QueryName,
storedProcedures, operations, true);
AdvancedJDBCORDescriptorBuilder advJOrDescriptorBuilder =
new AdvancedJDBCORDescriptorBuilder();
AdvancedJDBCQueryBuilder queryBuilder =
new AdvancedJDBCQueryBuilder(storedProcedures, dbStoredProcedure2QueryName);
PublisherListenerChainAdapter listenerChainAdapter = new PublisherListenerChainAdapter();
listenerChainAdapter.addListener(advJOrDescriptorBuilder);
listenerChainAdapter.addListener(queryBuilder);
PublisherWalker walker = new PublisherWalker(listenerChainAdapter);
pModel.getJPubType().accept(walker);
List<ObjectRelationalDataTypeDescriptor> descriptors =
advJOrDescriptorBuilder.getDescriptors();
Project p = new Project();
p.setName(projectName);
for (ObjectRelationalDataTypeDescriptor ordt : descriptors) {
p.addDescriptor(ordt);
}
List<DatabaseQuery> queries = queryBuilder.getQueries();
if (queries != null && queries.size() > 0) {
p.getQueries().addAll(queries);
}
Document resultDoc = xmlPlatform.createDocument();
XMLMarshaller marshaller = new XMLContext(writeObjectPersistenceProject).createMarshaller();
marshaller.marshal(p, resultDoc);
Document controlDoc = xmlParser.parse(new StringReader(orProject));
boolean nodeEqual = comparer.isNodeEqual(controlDoc, resultDoc);
assertTrue("control document not same as instance document", nodeEqual);
}
protected void testOxProject(ProcedureOperationModel pModel, String projectName,
String nameSpace, String oxProject, String oxSchema) {
OracleHelper.buildStoredProcedure(conn, username, ora11Platform, pModel);
AdvancedJDBCOXDescriptorBuilder advJOxDescriptorBuilder =
new AdvancedJDBCOXDescriptorBuilder(nameSpace, new TypeSuffixTransformer());
PublisherWalker walker = new PublisherWalker(advJOxDescriptorBuilder);
pModel.getJPubType().accept(walker);
List<XMLDescriptor> descriptors =
((AdvancedJDBCOXDescriptorBuilder)walker.getListener()).getDescriptors();
Project p = new Project();
p.setName(projectName);
for (XMLDescriptor xDesc : descriptors) {
p.addDescriptor(xDesc);
}
Document resultDoc = xmlPlatform.createDocument();
XMLMarshaller marshaller = new XMLContext(writeObjectPersistenceProject).createMarshaller();
marshaller.marshal(p, resultDoc);
Document controlDoc = xmlParser.parse(new StringReader(oxProject));
assertTrue("control document not same as instance document",
comparer.isNodeEqual(controlDoc, resultDoc));
SchemaModelGenerator schemaGenerator = new SchemaModelGenerator();
SchemaModelGeneratorProperties sgProperties = new SchemaModelGeneratorProperties();
// set element form default to qualified for target namespace
sgProperties.addProperty(nameSpace, ELEMENT_FORM_QUALIFIED_KEY, true);
Map<String, Schema> schemaMap = schemaGenerator.generateSchemas(descriptors, sgProperties);
Schema s = schemaMap.get(nameSpace);
Document schema = xmlPlatform.createDocument();
new XMLContext(new SchemaModelProject()).createMarshaller().marshal(s, schema);
Document controlSchema = xmlParser.parse(new StringReader(oxSchema));
assertTrue("control schema not same as instance schema",
comparer.isNodeEqual(controlSchema, schema));
}
public DatabaseSession fixUp(String projectString) {
XRDynamicClassLoader xrdecl = new XRDynamicClassLoader(this.getClass().getClassLoader());
XMLContext xmlContext = new XMLContext(readObjectPersistenceProject, xrdecl);
Project project = (Project)xmlContext.createUnmarshaller().unmarshal(
new StringReader(projectString));
DatabaseLogin login = new DatabaseLogin();
login.setUserName(username);
login.setPassword(password);
login.setConnectionString(url);
login.setDriverClassName(DEFAULT_DATABASE_DRIVER);
login.setDatasourcePlatform(ora11Platform);
login.bindAllParameters();
project.setDatasourceLogin(login);
ProjectHelper.fixOROXAccessors(project, null);
DatabaseSession ds = project.createDatabaseSession();
ds.dontLogMessages();
ds.login();
return ds;
}
} |
package com.github.binarywang.wxpay.bean.ecommerce;
import com.google.gson.annotations.SerializedName;
import lombok.*;
import java.io.Serializable;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RefundsRequest implements Serializable {
private static final long serialVersionUID = -3186851559004865784L;
/**
* <pre>
*
* sub_mchid
*
* string32
*
*
* 1900000109
* </pre>
*/
@SerializedName(value = "sub_mchid")
private String subMchid;
/**
* <pre>
* APPID
* sp_appid
*
* string32
*
* APPID
* wx8888888888888888
* </pre>
*/
@SerializedName(value = "sp_appid")
private String spAppid;
/**
* <pre>
* APPID
* sub_appid
*
* string32
*
* ID
* wxd678efh567hg6999
* </pre>
*/
@SerializedName(value = "sub_appid")
private String subAppid;
/**
* <pre>
*
* transaction_id
* out_order_no
* string32
*
*
* 4208450740201411110007820472
* </pre>
*/
@SerializedName(value = "transaction_id")
private String transactionId;
/**
* <pre>
*
* out_trade_no
* transaction_id
* string64
*
*
* P20150806125346
* </pre>
*/
@SerializedName(value = "out_trade_no")
private String outTradeNo;
/**
* <pre>
*
* out_refund_no
*
* string64
*
* _-|*@
* 1217752501201407033233368018
* </pre>
*/
@SerializedName(value = "out_refund_no")
private String outRefundNo;
@SerializedName(value = "reason")
private String reason;
/**
* <pre>
*
* amount
*
* object
*
*
* </pre>
*/
@SerializedName(value = "amount")
private Amount amount;
@SerializedName(value = "notify_url")
private String notifyUrl;
@Data
@Builder
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public static class Amount implements Serializable {
private static final long serialVersionUID = 7383027142329410399L;
/**
* <pre>
*
* refund
*
* int
*
*
* 888
* </pre>
*/
@SerializedName(value = "refund")
private Integer refund;
/**
* <pre>
*
* total
*
* int64
*
*
* 888
* </pre>
*/
@SerializedName(value = "total")
private Integer total;
/**
* <pre>
*
* currency
*
* string(18)
*
* ISO 4217CNY
* CNY
* </pre>
*/
@SerializedName(value = "currency")
private String currency;
}
} |
package alma.acs.alarmsystem.test.alarmsource;
import java.util.concurrent.TimeUnit;
import alma.acs.alarmsystem.source.AlarmSource;
import alma.acs.alarmsystem.source.AlarmSourceImpl;
import alma.acs.component.client.ComponentClientTestCase;
/**
* The test for the {@link AlarmSourceImpl}.
* <P>
* The test is done by junit and tat. tat is used for checking
* if the alarms are published as expected.
* <P>
* <EM>Note</em>: in this module the only availabale alarm system
* is the ACS implementation so the published alarms
* are identified by logs.
*
* @author acaproni
*
*/
public class AlarmSourceTest extends ComponentClientTestCase {
/**
* The source to test.
*/
private AlarmSource alarmSource;
/**
* Constructor
*
* @throws Exception
*/
public AlarmSourceTest() throws Exception {
super(AlarmSourceTest.class.getName());
}
@Override
protected void setUp() throws Exception {
super.setUp();
alarmSource= new AlarmSourceImpl(this.getContainerServices());
assertNotNull(alarmSource);
alarmSource.start();
}
@Override
protected void tearDown() throws Exception {
alarmSource.tearDown();
super.tearDown();
}
/**
* Check the multiple activation of the same alarm
*
* @throws Exception
*/
public void testMultipleRaise() throws Exception {
// Raise several times the same alarm to
// check if it is sent only once
for (int t=0; t<5; t++) {
alarmSource.raiseAlarm("RaiseMultipleSend", "RaiseMultipleSendMember", 1);
}
}
/**
* Check the multiple clearing of the same alarm
*
* @throws Exception
*/
public void testMultipleClear() throws Exception {
// Clear several times the same alarm to
// check if it is sent only once
for (int t=0; t<5; t++) {
alarmSource.clearAlarm("ClearMultipleSend", "ClearMultipleSendMember", 1);
}
// Give the oscillation thread enough time to clear the alarm
Thread.sleep(TimeUnit.SECONDS.toMillis(AlarmSourceImpl.ALARM_OSCILLATION_TIME*2));
}
/**
* Test if the source is limiting the oscillation of alarms
* <P>
* The test is done by activating and clearing the alarm several time inside
* the {@link AlarmSourceImpl#ALARM_OSCILLATION_TIME} time interval.
* In this case, the activation of an alarm should inhibit its termination.
* <P>
* If this test is working well, there are only 2 alarms: activation
* at the beginning and the final clearing.
*
* @throws Exception
*/
public void testOscillation() throws Exception {
// Activate the alarm
alarmSource.raiseAlarm("OscillationFF", "OscillationFM", 1);
// now a series of activation and deactivation that must not
// produce any alarm to be sent to the alarm service
for (int t=0; t<10; t++) {
alarmSource.clearAlarm("OscillationFF", "OscillationFM", 1);
Thread.sleep(250);
alarmSource.raiseAlarm("OscillationFF", "OscillationFM", 1);
}
// As the last operation clear the alarm
alarmSource.clearAlarm("OscillationFF", "OscillationFM", 1);
// Give the oscillation thread enough time to clear the alarm
Thread.sleep(TimeUnit.SECONDS.toMillis(AlarmSourceImpl.ALARM_OSCILLATION_TIME*2));
}
/**
* Check that no alarms are published when the source is disabled
*/
public void testDisable() throws Exception {
// An alarm sent before, it must be published
alarmSource.raiseAlarm("DisableFF", "DisableFM", 15);
alarmSource.disableAlarms();
for (int t=0; t<10; t++) {
alarmSource.clearAlarm("DisableFF", "DisableFM", t);
Thread.sleep(250);
alarmSource.raiseAlarm("DisableFF", "DisableFM"+t, 20);
}
alarmSource.enableAlarms();
// An alarm sent after, it must be published
alarmSource.clearAlarm("DisableFF", "DisableFM", 15);
// Give the oscillation thread enough time to clear the alarm
Thread.sleep(TimeUnit.SECONDS.toMillis(AlarmSourceImpl.ALARM_OSCILLATION_TIME*2));
}
/**
* The alarm are queued and sent all together when queuing is disbaled
*
* @throws Exception
*/
public void testQueueing() throws Exception {
// An alarm sent before, it must be published
alarmSource.raiseAlarm("QueueFF", "QueueFM", 15);
System.out.println("Queueing alarms");
alarmSource.queueAlarms();
// The following alarms will be published after queueing
for (int t=0; t<10; t++) {
alarmSource.clearAlarm("QueueFF", "QueueFM", t);
Thread.sleep(250);
alarmSource.raiseAlarm("QueueFF", "QueueFM"+t, 20);
}
Thread.sleep(10000);
System.out.println("Flushing alarms");
alarmSource.flushAlarms();
// An alarm sent after, it must be published
alarmSource.clearAlarm("QueueFF", "QueueFM", 15);
// Give the oscillation thread enough time to clear the alarm
Thread.sleep(TimeUnit.SECONDS.toMillis(AlarmSourceImpl.ALARM_OSCILLATION_TIME*2));
}
/**
* The alarm are queued for 30 seconds
* and sent all together when queuing is disbaled
*
* @throws Exception
*/
public void testQueueingTimer() throws Exception {
// An alarm sent before, it must be published
alarmSource.raiseAlarm("QueueTimerFF", "QueueTimerFM", 15);
System.out.println("Queueing alarms with timer");
alarmSource.queueAlarms(30,TimeUnit.SECONDS);
// The following alarms will be published after queueing
for (int t=0; t<10; t++) {
alarmSource.clearAlarm("QueueTimerFF", "QueueTimerFM", t);
Thread.sleep(250);
alarmSource.raiseAlarm("QueueTimerFF", "QueueTimerFM"+t, 20);
}
// An alarm sent after, it must be published
alarmSource.clearAlarm("QueueTimerFF", "QueueTimerFM", 15);
// Give the oscillation thread enough time to clear the alarm
Thread.sleep(TimeUnit.SECONDS.toMillis(AlarmSourceImpl.ALARM_OSCILLATION_TIME*2));
// Wait 30 seconds until the flush terminates
System.out.println("Waiting for the flush to happen");
Thread.sleep(TimeUnit.SECONDS.toMillis(30));
}
/**
* When queuing is activated we expect that an alarm that has been
* raised and cleared is not published at all
*/
public void testQueuingSingleAlarm() throws Exception {
// An alarm sent before queuing: it must be published
alarmSource.raiseAlarm("QueueFFSA", "QueueFMSA", 15);
System.out.println("Queueing alarms");
alarmSource.queueAlarms();
// The following alarms will be published after queueing
for (int t=0; t<10; t++) {
alarmSource.raiseAlarm("QueueFFSA", "QueueFMSA", t);
Thread.sleep(250);
}
for (int t=0; t<10; t++) {
alarmSource.clearAlarm("QueueFFSA", "QueueFMSA", t);
Thread.sleep(250);
}
Thread.sleep(10000);
System.out.println("Flushing alarms");
alarmSource.flushAlarms();
// An alarm sent after, it must be published
alarmSource.clearAlarm("QueueFFSA", "QueueFMSA", 15);
// Give the oscillation thread enough time to clear the alarm
Thread.sleep(TimeUnit.SECONDS.toMillis(AlarmSourceImpl.ALARM_OSCILLATION_TIME*2));
}
} |
package org.springframework.roo.addon.jsf.converter;
import static java.lang.reflect.Modifier.PUBLIC;
import static org.springframework.roo.addon.jsf.model.JsfJavaType.CONVERTER;
import static org.springframework.roo.addon.jsf.model.JsfJavaType.FACES_CONTEXT;
import static org.springframework.roo.addon.jsf.model.JsfJavaType.FACES_CONVERTER;
import static org.springframework.roo.addon.jsf.model.JsfJavaType.UI_COMPONENT;
import static org.springframework.roo.model.JavaType.OBJECT;
import static org.springframework.roo.model.JavaType.STRING;
import java.util.Arrays;
import java.util.List;
import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.details.MethodMetadataBuilder;
import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder;
import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder;
import org.springframework.roo.classpath.layers.MemberTypeAdditions;
import org.springframework.roo.metadata.MetadataIdentificationUtils;
import org.springframework.roo.model.ImportRegistrationResolver;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.model.JdkJavaType;
import org.springframework.roo.project.LogicalPath;
import org.springframework.roo.support.style.ToStringCreator;
import org.springframework.roo.support.util.Assert;
/**
* Metadata for {@link RooJsfConverter}.
*
* @author Alan Stewart
* @since 1.2.0
*/
public class JsfConverterMetadata extends AbstractItdTypeDetailsProvidingMetadataItem {
// Constants
static final String ID_FIELD_NAME = "id";
private static final String PROVIDES_TYPE_STRING = JsfConverterMetadata.class.getName();
private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING);
public JsfConverterMetadata(final String identifier, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final JsfConverterAnnotationValues annotationValues, final MethodMetadata identifierAccessor, final MemberTypeAdditions findMethod) {
super(identifier, aspectName, governorPhysicalTypeMetadata);
Assert.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' is invalid");
Assert.notNull(annotationValues, "Annotation values required");
if (!isValid()) {
return;
}
if (findMethod == null || identifierAccessor == null) {
valid = false;
return;
}
if (!isConverterInterfaceIntroduced()) {
final ImportRegistrationResolver imports = builder.getImportRegistrationResolver();
imports.addImport(CONVERTER);
builder.addImplementsType(CONVERTER);
}
builder.addAnnotation(getFacesConverterAnnotation());
builder.addMethod(getGetAsObjectMethod(findMethod, identifierAccessor));
builder.addMethod(getGetAsStringMethod(annotationValues.getEntity(), identifierAccessor));
// Create a representation of the desired output ITD
itdTypeDetails = builder.build();
}
private AnnotationMetadata getFacesConverterAnnotation() {
AnnotationMetadata annotation = getTypeAnnotation(FACES_CONVERTER);
if (annotation == null) {
return null;
}
AnnotationMetadataBuilder annotationBuulder = new AnnotationMetadataBuilder(annotation);
// annotationBuulder.addClassAttribute("forClass", entity); // TODO The forClass attribute causes issues
annotationBuulder.addStringAttribute("value", destination.getFullyQualifiedTypeName());
return annotationBuulder.build();
}
private boolean isConverterInterfaceIntroduced() {
return isImplementing(governorTypeDetails, CONVERTER);
}
private MethodMetadata getGetAsObjectMethod(final MemberTypeAdditions findMethod, final MethodMetadata identifierAccessor) {
final JavaSymbolName methodName = new JavaSymbolName("getAsObject");
final JavaType[] parameterTypes = { FACES_CONTEXT, UI_COMPONENT, STRING };
if (governorHasMethod(methodName, parameterTypes)) {
return null;
}
findMethod.copyAdditionsTo(builder, governorTypeDetails);
final JavaType returnType = identifierAccessor.getReturnType();
final ImportRegistrationResolver imports = builder.getImportRegistrationResolver();
imports.addImport(returnType);
imports.addImport(FACES_CONTEXT);
imports.addImport(UI_COMPONENT);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (value == null || value.length() == 0) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("return null;");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine(returnType.getSimpleTypeName() + " " + ID_FIELD_NAME + " = " + getJavaTypeConversionString(returnType) + ";");
bodyBuilder.appendFormalLine("return " + findMethod.getMethodCall() + ";");
// Create getAsObject method
final List<JavaSymbolName> parameterNames = Arrays.asList(new JavaSymbolName("context"), new JavaSymbolName("component"), new JavaSymbolName("value"));
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), PUBLIC, methodName, OBJECT, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder);
return methodBuilder.build();
}
private MethodMetadata getGetAsStringMethod(final JavaType entity, final MethodMetadata identifierAccessor) {
final JavaSymbolName methodName = new JavaSymbolName("getAsString");
final JavaType[] parameterTypes = { FACES_CONTEXT, UI_COMPONENT, OBJECT };
if (governorHasMethod(methodName, parameterTypes)) {
return null;
}
final ImportRegistrationResolver imports = builder.getImportRegistrationResolver();
imports.addImport(entity);
imports.addImport(FACES_CONTEXT);
imports.addImport(UI_COMPONENT);
String simpleTypeName = entity.getSimpleTypeName();
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("return value instanceof " + simpleTypeName + " ? ((" + simpleTypeName + ") value)." + identifierAccessor.getMethodName().getSymbolName() + "().toString() : \"\";");
// Create getAsString method
final List<JavaSymbolName> parameterNames = Arrays.asList(new JavaSymbolName("context"), new JavaSymbolName("component"), new JavaSymbolName("value"));
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), PUBLIC, methodName, JavaType.STRING, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder);
return methodBuilder.build();
}
private String getJavaTypeConversionString(JavaType javaType) {
if (javaType.equals(JavaType.LONG_OBJECT) || javaType.equals(JavaType.LONG_PRIMITIVE)) {
return "Long.parseLong(value)";
} else if (javaType.equals(JavaType.INT_OBJECT) || javaType.equals(JavaType.INT_PRIMITIVE)) {
return "Integer.parseInt(value)";
} else if (javaType.equals(JavaType.DOUBLE_OBJECT) || javaType.equals(JavaType.DOUBLE_PRIMITIVE)) {
return "Double.parseDouble(value)";
} else if (javaType.equals(JavaType.FLOAT_OBJECT) || javaType.equals(JavaType.FLOAT_PRIMITIVE)) {
return "Float.parseFloat(value)";
} else if (javaType.equals(JavaType.SHORT_OBJECT) || javaType.equals(JavaType.SHORT_PRIMITIVE)) {
return "Short.parseShort(value)";
} else if (javaType.equals(JavaType.BYTE_OBJECT) || javaType.equals(JavaType.BYTE_PRIMITIVE)) {
return "Byte.parseByte(value)";
} else if (javaType.equals(JdkJavaType.BIG_DECIMAL)) {
return "new BigDecimal(value)";
} else if (javaType.equals(JdkJavaType.BIG_INTEGER)) {
return "new BigInteger(value)";
} else if (javaType.equals(STRING)) {
return "value";
} else {
return "value.toString()";
}
}
@Override
public String toString() {
final ToStringCreator tsc = new ToStringCreator(this);
tsc.append("identifier", getId());
tsc.append("valid", valid);
tsc.append("aspectName", aspectName);
tsc.append("destinationType", destination);
tsc.append("governor", governorPhysicalTypeMetadata.getId());
tsc.append("itdTypeDetails", itdTypeDetails);
return tsc.toString();
}
public static String getMetadataIdentiferType() {
return PROVIDES_TYPE;
}
public static String createIdentifier(final JavaType javaType, final LogicalPath path) {
return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path);
}
public static JavaType getJavaType(final String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static LogicalPath getPath(final String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static boolean isValid(final String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
} |
package org.jetbrains.idea.maven.aether;
import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.collection.CollectResult;
import org.eclipse.aether.collection.DependencyCollectionException;
import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.graph.DependencyFilter;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.graph.DependencyVisitor;
import org.eclipse.aether.impl.DefaultServiceLocator;
import org.eclipse.aether.repository.LocalRepository;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.repository.RepositoryPolicy;
import org.eclipse.aether.resolution.*;
import org.eclipse.aether.spi.connector.RepositoryConnectorFactory;
import org.eclipse.aether.spi.connector.transport.TransporterFactory;
import org.eclipse.aether.transfer.TransferCancelledException;
import org.eclipse.aether.transfer.TransferEvent;
import org.eclipse.aether.transfer.TransferListener;
import org.eclipse.aether.transport.file.FileTransporterFactory;
import org.eclipse.aether.transport.http.HttpTransporterFactory;
import org.eclipse.aether.util.artifact.DelegatingArtifact;
import org.eclipse.aether.util.artifact.JavaScopes;
import org.eclipse.aether.util.filter.DependencyFilterUtils;
import org.eclipse.aether.util.graph.visitor.FilteringDependencyVisitor;
import org.eclipse.aether.util.graph.visitor.TreeDependencyVisitor;
import org.eclipse.aether.util.version.GenericVersionScheme;
import org.eclipse.aether.version.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
/**
* @author Eugene Zhuravlev
*
* Aether-based repository manager and dependency resolver using maven implementation of this functionality.
*
* instance of this component should be managed by the code which requires dependency resolution functionality
* all necessary params like path to local repo should be passed in constructor
*/
public class ArtifactRepositoryManager {
private static final VersionScheme ourVersioning = new GenericVersionScheme();
private static final JreProxySelector ourProxySelector = new JreProxySelector();
private static final Logger LOG = LoggerFactory.getLogger(ArtifactRepositoryManager.class);
private final DefaultRepositorySystemSession mySession;
private static final RemoteRepository MAVEN_CENTRAL_REPOSITORY = createRemoteRepository(
"central", "https://repo1.maven.org/maven2/"
);
private static final RemoteRepository JBOSS_COMMUNITY_REPOSITORY = createRemoteRepository(
"jboss.community", "https://repository.jboss.org/nexus/content/repositories/public/"
);
private static final RepositorySystem ourSystem;
static {
final DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
locator.addService(TransporterFactory.class, FileTransporterFactory.class);
locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
locator.setErrorHandler(new DefaultServiceLocator.ErrorHandler() {
@Override
public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable exception) {
if (exception != null) {
throw new RuntimeException(exception);
}
}
});
ourSystem = locator.getService(RepositorySystem.class);
}
private final List<RemoteRepository> myRemoteRepositories = new ArrayList<>();
public ArtifactRepositoryManager(@NotNull File localRepositoryPath) {
this(localRepositoryPath, ProgressConsumer.DEAF);
}
public ArtifactRepositoryManager(@NotNull File localRepositoryPath, @NotNull final ProgressConsumer progressConsumer) {
// recreate remote repository objects to ensure the latest proxy settings are used
this(localRepositoryPath, Arrays.asList(createRemoteRepository(MAVEN_CENTRAL_REPOSITORY), createRemoteRepository(JBOSS_COMMUNITY_REPOSITORY)), progressConsumer);
}
public ArtifactRepositoryManager(@NotNull File localRepositoryPath, List<RemoteRepository> remoteRepositories, @NotNull final ProgressConsumer progressConsumer) {
myRemoteRepositories.addAll(remoteRepositories);
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
if (progressConsumer != ProgressConsumer.DEAF) {
session.setTransferListener(new TransferListener() {
@Override
public void transferInitiated(TransferEvent event) throws TransferCancelledException {
handle(event);
}
@Override
public void transferStarted(TransferEvent event) throws TransferCancelledException {
handle(event);
}
@Override
public void transferProgressed(TransferEvent event) throws TransferCancelledException {
handle(event);
}
@Override
public void transferCorrupted(TransferEvent event) throws TransferCancelledException {
}
@Override
public void transferSucceeded(TransferEvent event) {
}
@Override
public void transferFailed(TransferEvent event) {
}
private void handle(TransferEvent event) throws TransferCancelledException {
if (progressConsumer.isCanceled()) {
throw new TransferCancelledException();
}
progressConsumer.consume(event.toString());
}
});
}
// setup session here
session.setLocalRepositoryManager(ourSystem.newLocalRepositoryManager(session, new LocalRepository(localRepositoryPath)));
session.setProxySelector(ourProxySelector);
session.setReadOnly();
mySession = session;
}
/**
* Returns list of classes corresponding to classpath entries for this this module.
*/
@SuppressWarnings("UnnecessaryFullyQualifiedName")
public static List<Class<?>> getClassesFromDependencies() {
return Arrays.asList(
org.jetbrains.idea.maven.aether.ArtifactRepositoryManager.class, //this module
org.apache.maven.repository.internal.VersionsMetadataGeneratorFactory.class, //maven-aether-provider
org.apache.maven.artifact.Artifact.class, //maven-artifact
org.apache.commons.lang3.StringUtils.class, //commons-lang3
org.codehaus.plexus.util.Base64.class, //plexus-utils
org.apache.maven.building.Problem.class, //maven-builder-support
org.apache.maven.model.Model.class, //maven-model
org.apache.maven.model.building.ModelBuilder.class, //maven-model-builder
org.apache.maven.artifact.repository.metadata.Metadata.class, //maven-repository-metadata
org.codehaus.plexus.component.annotations.Component.class, //plexus-component-annotations
org.codehaus.plexus.interpolation.Interpolator.class, //plexus-interpolation
org.eclipse.aether.RepositorySystem.class, //aether-api
org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory.class, //aether-connector-basic
org.eclipse.aether.spi.connector.RepositoryConnector.class, //aether-spi
org.eclipse.aether.util.StringUtils.class, //aether-util
org.eclipse.aether.impl.ArtifactResolver.class, //aether-impl
org.eclipse.aether.transport.file.FileTransporterFactory.class, //aether-transport-file
org.eclipse.aether.transport.http.HttpTransporterFactory.class, //aether-transport-http
com.google.common.base.Predicate.class, //guava
org.apache.http.HttpConnection.class, //httpcore
org.apache.http.client.HttpClient.class, //httpclient
org.apache.commons.logging.LogFactory.class, // commons-logging
org.slf4j.Marker.class // slf4j
);
}
public Collection<File> resolveDependency(String groupId, String artifactId, String version, boolean includeTransitiveDependencies,
List<String> excludedDependencies) throws Exception {
final List<File> files = new ArrayList<>();
for (Artifact artifact : resolveDependencyAsArtifact(groupId, artifactId, version, EnumSet.of(ArtifactKind.ARTIFACT), includeTransitiveDependencies,
excludedDependencies)) {
files.add(artifact.getFile());
}
return files;
}
@Nullable
public ArtifactDependencyNode collectDependencies(String groupId, String artifactId, String versionConstraint) throws Exception {
Set<VersionConstraint> constraints = Collections.singleton(asVersionConstraint(versionConstraint));
CollectRequest collectRequest = createCollectRequest(groupId, artifactId, constraints, EnumSet.of(ArtifactKind.ARTIFACT));
ArtifactDependencyTreeBuilder builder = new ArtifactDependencyTreeBuilder();
DependencyNode root = ourSystem.collectDependencies(mySession, collectRequest).getRoot();
if (root.getArtifact() == null && root.getChildren().size() == 1) {
root = root.getChildren().get(0);
}
root.accept(new TreeDependencyVisitor(new FilteringDependencyVisitor(builder, createScopeFilter())));
return builder.getRoot();
}
@NotNull
public Collection<Artifact> resolveDependencyAsArtifact(String groupId, String artifactId, String versionConstraint,
Set<ArtifactKind> artifactKinds, boolean includeTransitiveDependencies,
List<String> excludedDependencies) throws Exception {
final List<Artifact> artifacts = new ArrayList<>();
final VersionConstraint originalConstraints = asVersionConstraint(versionConstraint);
for (ArtifactKind kind : artifactKinds) {
// RepositorySystem.resolveDependencies() ignores classifiers, so we need to set classifiers explicitly for discovered dependencies.
// Because of that we have to first discover deps and then resolve corresponding artifacts
try {
final List<ArtifactRequest> requests;
final Set<VersionConstraint> constraints;
if (kind == ArtifactKind.ANNOTATIONS) {
constraints = relaxForAnnotations(originalConstraints);
} else {
constraints = Collections.singleton(originalConstraints);
}
if (includeTransitiveDependencies) {
final CollectResult collectResult = ourSystem.collectDependencies(
mySession, createCollectRequest(groupId, artifactId, constraints, EnumSet.of(kind))
);
final ArtifactRequestBuilder builder = new ArtifactRequestBuilder(kind);
DependencyFilter filter = createScopeFilter();
if (!excludedDependencies.isEmpty()) {
filter = DependencyFilterUtils.andFilter(filter, new ExcludeDependenciesFilter(excludedDependencies));
}
collectResult.getRoot().accept(new TreeDependencyVisitor(new FilteringDependencyVisitor(builder, filter)));
requests = builder.getRequests();
}
else {
requests = new ArrayList<>();
for (Artifact artifact : toArtifacts(groupId, artifactId, constraints, Collections.singleton(kind))) {
if (ourVersioning.parseVersionConstraint(artifact.getVersion()).getRange() != null) {
final VersionRangeRequest versionRangeRequest = new VersionRangeRequest(artifact, Collections.unmodifiableList(myRemoteRepositories), null);
final VersionRangeResult result = ourSystem.resolveVersionRange(mySession, versionRangeRequest);
if (!result.getVersions().isEmpty()) {
Artifact newArtifact = artifact.setVersion(result.getHighestVersion().toString());
requests.add(new ArtifactRequest(newArtifact, Collections.unmodifiableList(myRemoteRepositories), null));
}
}
else {
requests.add(new ArtifactRequest(artifact, Collections.unmodifiableList(myRemoteRepositories), null));
}
}
}
if (!requests.isEmpty()) {
try {
for (ArtifactResult result : ourSystem.resolveArtifacts(mySession, requests)) {
artifacts.add(result.getArtifact());
}
}
catch (ArtifactResolutionException e) {
if (kind != ArtifactKind.ARTIFACT) {
// for sources and javadocs try to process requests one-by-one and fetch at least something
if (requests.size() > 1) {
for (ArtifactRequest request : requests) {
try {
final ArtifactResult result = ourSystem.resolveArtifact(mySession, request);
artifacts.add(result.getArtifact());
}
catch (ArtifactResolutionException ignored) {
}
}
}
}
else {
// for ArtifactKind.ARTIFACT should fail if at least one request in this group fails
throw e;
}
}
}
}
catch (DependencyCollectionException e) {
if (kind == ArtifactKind.ARTIFACT) {
throw e;
}
}
}
return artifacts;
}
/**
* Modify version constraint to look for applicable annotations artifact.
*
* Annotations artifact for a given library is matched by Group Id, Artifact Id
* and classifier "annotations". Annotations version is selected using following rules:
* <ul>
* <li>it is larger or equal to major component of library version (or lower constraint bound).
* E.g., annotations artifact ver 3.1 is applicable to library ver 3.6.5 (3.1 > 3.0)</li>
* <li>it is smaller or equal to library version with suffix (-an10000).
* E.g., annotations artifact ver 3.2-an3 is applicable to library ver 3.2</li>
* </ul>
* This allows to re-use existing annotations artifacts across different library versions
* @param constraint - version or range constraint of original library
* @return resulting relaxed constraint to select annotations artifact.
*/
private static Set<VersionConstraint> relaxForAnnotations(VersionConstraint constraint) {
String annotationsConstraint = constraint.toString();
final Version version = constraint.getVersion();
if (version != null) {
final String major = version.toString().split("[.\\-_]")[0];
annotationsConstraint = "[" + major + ", " + version.toString() + "-an10000]";
}
final VersionRange range = constraint.getRange();
if (range != null) {
final String majorLower = range.getLowerBound().getVersion().toString().split("[.\\-_]")[0];
String upper = range.getUpperBound().isInclusive()
? range.getUpperBound().toString() + "-an10000]"
: range.getUpperBound().toString() + ")";
annotationsConstraint = "[" + majorLower + ", " + upper;
}
try {
return Collections.singleton(ourVersioning.parseVersionConstraint(annotationsConstraint));
} catch (InvalidVersionSpecificationException e) {
LOG.info("Failed to parse version constraint " + annotationsConstraint, e);
}
return Collections.singleton(constraint);
}
@NotNull
private static DependencyFilter createScopeFilter() {
return DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE, JavaScopes.RUNTIME);
}
/**
* Gets the versions (in ascending order) that matched the requested range.
*/
@NotNull
public List<Version> getAvailableVersions(String groupId, String artifactId, String versionConstraint, final ArtifactKind artifactKind) throws Exception {
final VersionRangeResult result = ourSystem.resolveVersionRange(
mySession, createVersionRangeRequest(groupId, artifactId, asVersionConstraint(versionConstraint), artifactKind)
);
return result.getVersions();
}
public static RemoteRepository createRemoteRepository(final String id,
final String url) {
return createRemoteRepository(id, url, true);
}
public static RemoteRepository createRemoteRepository(final String id,
final String url,
boolean allowSnapshots) {
// for maven repos repository type should be 'default'
RemoteRepository.Builder builder = new RemoteRepository.Builder(id, "default", url);
if (!allowSnapshots) {
builder.setSnapshotPolicy(new RepositoryPolicy(false, null, null));
}
return builder.setProxy(ourProxySelector.getProxy(url)).build();
}
public static RemoteRepository createRemoteRepository(RemoteRepository prototype) {
final String url = prototype.getUrl();
return new RemoteRepository.Builder(prototype.getId(), prototype.getContentType(), url).setProxy(ourProxySelector.getProxy(url)).build();
}
private CollectRequest createCollectRequest(String groupId, String artifactId, Collection<VersionConstraint> versions, final Set<ArtifactKind> kinds) {
final CollectRequest request = new CollectRequest();
for (Artifact artifact : toArtifacts(groupId, artifactId, versions, kinds)) {
request.addDependency(new Dependency(artifact, JavaScopes.COMPILE));
}
return request.setRepositories(Collections.unmodifiableList(myRemoteRepositories));
}
private VersionRangeRequest createVersionRangeRequest(String groupId, String artifactId, VersionConstraint versioning, final ArtifactKind artifactKind) {
final VersionRangeRequest request = new VersionRangeRequest();
for (Artifact artifact : toArtifacts(groupId, artifactId, Collections.singleton(versioning), EnumSet.of(artifactKind))) {
request.setArtifact(artifact); // will be at most 1 artifact
}
List<RemoteRepository> repositories = new ArrayList<>(myRemoteRepositories.size());
for (RemoteRepository repository : myRemoteRepositories) {
RepositoryPolicy policy = new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_ALWAYS, RepositoryPolicy.CHECKSUM_POLICY_WARN);
repositories.add(new RemoteRepository.Builder(repository).setPolicy(policy).build());
}
return request.setRepositories(repositories);
}
public static Version asVersion(@Nullable String str) throws InvalidVersionSpecificationException {
return ourVersioning.parseVersion(str == null? "" : str);
}
public static VersionConstraint asVersionConstraint(@Nullable String str) throws InvalidVersionSpecificationException {
return ourVersioning.parseVersionConstraint(str == null? "" : str);
}
private static List<Artifact> toArtifacts(String groupId, String artifactId, Collection<VersionConstraint> constraints, Set<ArtifactKind> kinds) {
if (constraints.isEmpty() || kinds.isEmpty()) {
return Collections.emptyList();
}
final List<Artifact> result = new ArrayList<>(kinds.size() * constraints.size());
for (ArtifactKind kind : kinds) {
for (VersionConstraint constraint : constraints) {
result.add(new DefaultArtifact(groupId, artifactId, kind.getClassifier(), kind.getExtension(), constraint.toString()));
}
}
return result;
}
private static class ArtifactWithChangedClassifier extends DelegatingArtifact {
private final String myClassifier;
ArtifactWithChangedClassifier(Artifact artifact, String classifier) {
super(artifact);
myClassifier = classifier;
}
@Override
protected DelegatingArtifact newInstance(Artifact artifact) {
return new ArtifactWithChangedClassifier(artifact, myClassifier);
}
@Override
public String getClassifier() {
return myClassifier;
}
}
/**
* Simplified copy of package-local org.eclipse.aether.internal.impl.ArtifactRequestBuilder
*/
private static class ArtifactRequestBuilder implements DependencyVisitor {
private final ArtifactKind myKind;
private final List<ArtifactRequest> myRequests = new ArrayList<>();
ArtifactRequestBuilder(ArtifactKind kind) {
myKind = kind;
}
@Override
public boolean visitEnter(DependencyNode node) {
final Dependency dep = node.getDependency();
if (dep != null) {
Artifact artifact = dep.getArtifact();
String classifier = myKind.getClassifier();
if (classifier.isEmpty()) {
myRequests.add(new ArtifactRequest(node));
}
else {
myRequests.add(new ArtifactRequest(new ArtifactWithChangedClassifier(artifact, classifier),
node.getRepositories(),
node.getRequestContext()
));
}
}
return true;
}
@Override
public boolean visitLeave(DependencyNode node) {
return true;
}
@NotNull
public List<ArtifactRequest> getRequests() {
return myRequests;
}
}
private static class ExcludeDependenciesFilter implements DependencyFilter {
private final HashSet<String> myExcludedDependencies;
ExcludeDependenciesFilter(List<String> excludedDependencies) {
myExcludedDependencies = new HashSet<>(excludedDependencies);
}
@Override
public boolean accept(DependencyNode node, List<DependencyNode> parents) {
Artifact artifact = node.getArtifact();
if (artifact != null && myExcludedDependencies.contains(artifact.getGroupId() + ":" + artifact.getArtifactId())) {
return false;
}
for (DependencyNode parent : parents) {
Artifact parentArtifact = parent.getArtifact();
if (parentArtifact != null && myExcludedDependencies.contains(parentArtifact.getGroupId() + ":" + parentArtifact.getArtifactId())) {
return false;
}
}
return true;
}
}
private static class ArtifactDependencyTreeBuilder implements DependencyVisitor {
private final List<List<ArtifactDependencyNode>> myCurrentChildren = new ArrayList<>();
ArtifactDependencyTreeBuilder() {
myCurrentChildren.add(new ArrayList<>());
}
@Override
public boolean visitEnter(DependencyNode node) {
Artifact artifact = node.getArtifact();
if (artifact == null) return false;
myCurrentChildren.add(new ArrayList<>());
return true;
}
@Override
public boolean visitLeave(DependencyNode node) {
Artifact artifact = node.getArtifact();
if (artifact != null) {
List<ArtifactDependencyNode> last = myCurrentChildren.get(myCurrentChildren.size() - 1);
myCurrentChildren.remove(myCurrentChildren.size() - 1);
myCurrentChildren.get(myCurrentChildren.size() - 1).add(new ArtifactDependencyNode(artifact, last));
}
return true;
}
public ArtifactDependencyNode getRoot() {
List<ArtifactDependencyNode> rootNodes = myCurrentChildren.get(0);
return rootNodes.isEmpty() ? null : rootNodes.get(0);
}
}
} |
package nodomain.freeyourgadget.gadgetbridge.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.content.LocalBroadcastManager;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.adapter.ItemWithDetailsAdapter;
import nodomain.freeyourgadget.gadgetbridge.devices.DeviceCoordinator;
import nodomain.freeyourgadget.gadgetbridge.devices.DeviceManager;
import nodomain.freeyourgadget.gadgetbridge.devices.InstallHandler;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.model.GenericItem;
import nodomain.freeyourgadget.gadgetbridge.model.ItemWithDetails;
import nodomain.freeyourgadget.gadgetbridge.util.DeviceHelper;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
public class FwAppInstallerActivity extends AbstractGBActivity implements InstallActivity {
private static final Logger LOG = LoggerFactory.getLogger(FwAppInstallerActivity.class);
private static final String ITEM_DETAILS = "details";
private TextView fwAppInstallTextView;
private Button installButton;
private Uri uri;
private GBDevice device;
private InstallHandler installHandler;
private boolean mayConnect;
private ProgressBar mProgressBar;
private ListView itemListView;
private final List<ItemWithDetails> mItems = new ArrayList<>();
private ItemWithDetailsAdapter mItemAdapter;
private ListView detailsListView;
private ItemWithDetailsAdapter mDetailsItemAdapter;
private ArrayList<ItemWithDetails> mDetails = new ArrayList<>();
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (GBDevice.ACTION_DEVICE_CHANGED.equals(action)) {
device = intent.getParcelableExtra(GBDevice.EXTRA_DEVICE);
if (device != null) {
refreshBusyState(device);
if (!device.isInitialized()) {
setInstallEnabled(false);
if (mayConnect) {
GB.toast(FwAppInstallerActivity.this, getString(R.string.connecting), Toast.LENGTH_SHORT, GB.INFO);
connect();
} else {
setInfoText(getString(R.string.fwappinstaller_connection_state, device.getStateString()));
}
} else {
validateInstallation();
}
}
} else if (GB.ACTION_DISPLAY_MESSAGE.equals(action)) {
String message = intent.getStringExtra(GB.DISPLAY_MESSAGE_MESSAGE);
int severity = intent.getIntExtra(GB.DISPLAY_MESSAGE_SEVERITY, GB.INFO);
addMessage(message, severity);
}
}
};
private void refreshBusyState(GBDevice dev) {
if (dev.isConnecting() || dev.isBusy()) {
mProgressBar.setVisibility(View.VISIBLE);
} else {
boolean wasBusy = mProgressBar.getVisibility() != View.GONE;
if (wasBusy) {
mProgressBar.setVisibility(View.GONE);
// done!
}
}
}
private void connect() {
mayConnect = false; // only do that once per #onCreate
GBApplication.deviceService().connect(device);
}
private void validateInstallation() {
if (installHandler != null) {
installHandler.validateInstallation(this, device);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appinstaller);
GBDevice dev = getIntent().getParcelableExtra(GBDevice.EXTRA_DEVICE);
if (dev != null) {
device = dev;
}
if (savedInstanceState != null) {
mDetails = savedInstanceState.getParcelableArrayList(ITEM_DETAILS);
if (mDetails == null) {
mDetails = new ArrayList<>();
}
}
mayConnect = true;
itemListView = (ListView) findViewById(R.id.itemListView);
mItemAdapter = new ItemWithDetailsAdapter(this, mItems);
itemListView.setAdapter(mItemAdapter);
fwAppInstallTextView = (TextView) findViewById(R.id.infoTextView);
installButton = (Button) findViewById(R.id.installButton);
mProgressBar = (ProgressBar) findViewById(R.id.installProgressBar);
detailsListView = (ListView) findViewById(R.id.detailsListView);
mDetailsItemAdapter = new ItemWithDetailsAdapter(this, mDetails);
mDetailsItemAdapter.setSize(ItemWithDetailsAdapter.SIZE_SMALL);
detailsListView.setAdapter(mDetailsItemAdapter);
setInstallEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(GBDevice.ACTION_DEVICE_CHANGED);
filter.addAction(GB.ACTION_DISPLAY_MESSAGE);
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
installButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setInstallEnabled(false);
installHandler.onStartInstall(device);
GBApplication.deviceService().onInstallApp(uri);
}
});
uri = getIntent().getData();
if (uri == null) { //for "share" intent
uri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
}
installHandler = findInstallHandlerFor(uri);
if (installHandler == null) {
setInfoText(getString(R.string.installer_activity_unable_to_find_handler));
} else {
setInfoText(getString(R.string.installer_activity_wait_while_determining_status));
// needed to get the device
if (device == null || !device.isConnected()) {
connect();
} else {
GBApplication.deviceService().requestDeviceInfo();
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(ITEM_DETAILS, mDetails);
}
private InstallHandler findInstallHandlerFor(Uri uri) {
for (DeviceCoordinator coordinator : getAllCoordinatorsConnectedFirst()) {
InstallHandler handler = coordinator.findInstallHandler(uri, this);
if (handler != null) {
return handler;
}
}
return null;
}
private List<DeviceCoordinator> getAllCoordinatorsConnectedFirst() {
DeviceManager deviceManager = ((GBApplication) getApplicationContext()).getDeviceManager();
List<DeviceCoordinator> connectedCoordinators = new ArrayList<>();
List<DeviceCoordinator> allCoordinators = DeviceHelper.getInstance().getAllCoordinators();
List<DeviceCoordinator> sortedCoordinators = new ArrayList<>(allCoordinators.size());
GBDevice connectedDevice = deviceManager.getSelectedDevice();
if (connectedDevice != null && connectedDevice.isConnected()) {
DeviceCoordinator coordinator = DeviceHelper.getInstance().getCoordinator(connectedDevice);
if (coordinator != null) {
connectedCoordinators.add(coordinator);
}
}
sortedCoordinators.addAll(connectedCoordinators);
for (DeviceCoordinator coordinator : allCoordinators) {
if (!connectedCoordinators.contains(coordinator)) {
sortedCoordinators.add(coordinator);
}
}
return sortedCoordinators;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
super.onDestroy();
}
@Override
public void setInfoText(String text) {
fwAppInstallTextView.setText(text);
}
@Override
public CharSequence getInfoText() {
return fwAppInstallTextView.getText();
}
@Override
public void setInstallEnabled(boolean enable) {
boolean enabled = device != null && device.isConnected() && enable;
installButton.setEnabled(enabled);
installButton.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
@Override
public void clearInstallItems() {
mItems.clear();
mItemAdapter.notifyDataSetChanged();
}
@Override
public void setInstallItem(ItemWithDetails item) {
mItems.clear();
mItems.add(item);
mItemAdapter.notifyDataSetChanged();
}
private void addMessage(String message, int severity) {
mDetails.add(new GenericItem(message));
mDetailsItemAdapter.notifyDataSetChanged();
}
} |
package org.fossasia.susi.ai.adapters.recycleradapters;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.util.Log;
import android.util.Patterns;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.leocardz.link.preview.library.LinkPreviewCallback;
import com.leocardz.link.preview.library.SourceContent;
import com.leocardz.link.preview.library.TextCrawler;
import org.fossasia.susi.ai.R;
import org.fossasia.susi.ai.adapters.viewholders.ChatViewHolder;
import org.fossasia.susi.ai.adapters.viewholders.LinkPreviewViewHolder;
import org.fossasia.susi.ai.adapters.viewholders.MapViewHolder;
import org.fossasia.susi.ai.adapters.viewholders.MessageViewHolder;
import org.fossasia.susi.ai.adapters.viewholders.PieChartViewHolder;
import org.fossasia.susi.ai.adapters.viewholders.SearchResultsHolder;
import org.fossasia.susi.ai.adapters.viewholders.TypingDotsHolder;
import org.fossasia.susi.ai.adapters.viewholders.ZeroHeightHolder;
import org.fossasia.susi.ai.helper.AndroidHelper;
import org.fossasia.susi.ai.helper.MapHelper;
import org.fossasia.susi.ai.model.ChatMessage;
import org.fossasia.susi.ai.rest.model.Datum;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.realm.OrderedRealmCollection;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmList;
import io.realm.RealmResults;
import pl.tajchert.sample.DotsTextView;
public class ChatFeedRecyclerAdapter extends SelectableAdapter implements MessageViewHolder.ClickListener {
public static final int USER_MESSAGE = 0;
public static final int SUSI_MESSAGE = 1;
public static final int USER_IMAGE = 2;
public static final int SUSI_IMAGE = 3;
public static final int MAP = 4;
public static final int PIECHART = 7;
private static final int USER_WITHLINK = 5;
private static final int SUSI_WITHLINK = 6;
private static final int DOTS = 8;
private static final int NULL_HOLDER = 9;
private static final int SEARCH_RESULT = 10;
private final RequestManager glide;
public int highlightMessagePosition = -1;
public String query = "";
private Context currContext;
private Realm realm;
private int lastMsgCount;
private RealmResults<ChatMessage> itemList;
private String TAG = ChatFeedRecyclerAdapter.class.getSimpleName();
private RecyclerView recyclerView;
private MessageViewHolder.ClickListener clickListener;
private ActionModeCallback actionModeCallback = new ActionModeCallback();
private ActionMode actionMode;
private SparseBooleanArray selectedItems;
private AppCompatActivity currActivity;
// For typing dots from Susi
private TypingDotsHolder dotsHolder;
private ZeroHeightHolder nullHolder;
private boolean isSusiTyping = false;
public ChatFeedRecyclerAdapter(RequestManager glide, @NonNull Context context, @Nullable OrderedRealmCollection<ChatMessage> data, boolean autoUpdate) {
super(context, data, autoUpdate);
this.glide = glide;
this.clickListener = this;
currContext = context;
currActivity = (AppCompatActivity) context;
lastMsgCount = getItemCount();
selectedItems = new SparseBooleanArray();
RealmChangeListener<RealmResults> listener = new RealmChangeListener<RealmResults>() {
@Override
public void onChange(RealmResults elements) {
//only scroll if new is added.
if (lastMsgCount < getItemCount()) {
scrollToBottom();
}
lastMsgCount = getItemCount();
}
};
if (data instanceof RealmResults) {
RealmResults realmResults = (RealmResults) data;
realmResults.addChangeListener(listener);
}
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_waiting_dots, null);
dotsHolder = new TypingDotsHolder(view);
DotsTextView dots = dotsHolder.dotsTextView;
dots.start();
View view1 = inflater.inflate(R.layout.item_without_height, null);
nullHolder = new ZeroHeightHolder(view1);
}
private static List<String> extractLinks(String text) {
List<String> links = new ArrayList<String>();
Matcher m = Patterns.WEB_URL.matcher(text);
while (m.find()) {
String url = m.group();
links.add(url);
}
return links;
}
public void showDots() {
isSusiTyping = true;
}
public void hideDots() {
isSusiTyping = false;
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
this.recyclerView = recyclerView;
realm = Realm.getDefaultInstance();
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
this.recyclerView = null;
realm.close();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view;
switch (viewType) {
case USER_MESSAGE:
view = inflater.inflate(R.layout.item_user_message, viewGroup, false);
return new ChatViewHolder(view, clickListener, USER_MESSAGE);
case SUSI_MESSAGE:
view = inflater.inflate(R.layout.item_susi_message, viewGroup, false);
return new ChatViewHolder(view, clickListener, SUSI_MESSAGE);
case USER_IMAGE:
view = inflater.inflate(R.layout.item_user_image, viewGroup, false);
return new ChatViewHolder(view, clickListener, USER_IMAGE);
case SUSI_IMAGE:
view = inflater.inflate(R.layout.item_susi_image, viewGroup, false);
return new ChatViewHolder(view, clickListener, SUSI_IMAGE);
case MAP:
view = inflater.inflate(R.layout.item_susi_map, viewGroup, false);
return new MapViewHolder(view, clickListener);
case USER_WITHLINK:
view = inflater.inflate(R.layout.item_user_link_preview, viewGroup, false);
return new LinkPreviewViewHolder(view, clickListener);
case SUSI_WITHLINK:
view = inflater.inflate(R.layout.item_susi_link_preview, viewGroup, false);
return new LinkPreviewViewHolder(view, clickListener);
case PIECHART:
view = inflater.inflate(R.layout.item_susi_piechart, viewGroup, false);
return new PieChartViewHolder(view, clickListener);
case SEARCH_RESULT:
view = inflater.inflate(R.layout.search_list, viewGroup, false);
return new SearchResultsHolder(view);
case DOTS:
return dotsHolder;
case NULL_HOLDER:
return nullHolder;
default:
view = inflater.inflate(R.layout.item_user_message, viewGroup, false);
return new ChatViewHolder(view, clickListener, USER_MESSAGE);
}
}
@Override
public int getItemViewType(int position) {
ChatMessage item = getItem(position);
if (item.getId() == -404) return DOTS;
else if (item.getId() == -405) return NULL_HOLDER;
else if (item.isMap()) return MAP;
else if (item.isSearchResult()) return SEARCH_RESULT;
else if (item.isPieChart()) return PIECHART;
else if (item.isMine() && item.isHavingLink()) return USER_WITHLINK;
else if (!item.isMine() && item.isHavingLink()) return SUSI_WITHLINK;
else if (item.isMine() && !item.isImage()) return USER_MESSAGE;
else if (!item.isMine() && !item.isImage()) return SUSI_MESSAGE;
else if (item.isMine() && item.isImage()) return USER_IMAGE;
else return SUSI_IMAGE;
}
@Override
public int getItemCount() {
if (getData() != null && getData().isValid()) {
return getData().size() + 1;
}
return 0;
}
@Nullable
@Override
public ChatMessage getItem(int index) {
if (getData() != null && getData().isValid()) {
if (index == getData().size()) {
if (isSusiTyping) {
return new ChatMessage(-404, "", false, false, false, false, false, false,
"", null);
}
return new ChatMessage(-405, "", false, false, false, false, false, false,
"", null);
}
return getData().get(index);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ChatViewHolder) {
ChatViewHolder chatViewHolder = (ChatViewHolder) holder;
handleItemEvents(chatViewHolder, position);
} else if (holder instanceof MapViewHolder) {
MapViewHolder mapViewHolder = (MapViewHolder) holder;
handleItemEvents(mapViewHolder, position);
} else if (holder instanceof PieChartViewHolder) {
PieChartViewHolder pieChartViewHolder = (PieChartViewHolder) holder;
handleItemEvents(pieChartViewHolder, position);
} else if (holder instanceof LinkPreviewViewHolder) {
LinkPreviewViewHolder linkPreviewViewHolder = (LinkPreviewViewHolder) holder;
handleItemEvents(linkPreviewViewHolder, position);
} else if (holder instanceof SearchResultsHolder) {
SearchResultsHolder searchResultsHolder = (SearchResultsHolder) holder;
handleItemEvents(searchResultsHolder, position);
}
/* if (highlightMessagePosition == position) {
holder.itemView.setBackgroundColor(Color.parseColor("#3e6182"));
} else {
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
}*/
}
private void handleItemEvents(SearchResultsHolder searchResultsHolder, int position) {
final ChatMessage model = getData().get(position);
if (model != null) {
searchResultsHolder.message.setText(model.getContent());
LinearLayoutManager layoutManager = new LinearLayoutManager(currContext,
LinearLayoutManager.HORIZONTAL, false);
searchResultsHolder.recyclerView.setLayoutManager(layoutManager);
SearchResultsAdapter resultsAdapter = new SearchResultsAdapter(currContext, model.getDatumRealmList());
searchResultsHolder.recyclerView.setAdapter(resultsAdapter);
searchResultsHolder.timeStamp.setText(model.getTimeStamp());
} else {
searchResultsHolder.recyclerView.setAdapter(null);
searchResultsHolder.recyclerView.setLayoutManager(null);
searchResultsHolder.message.setText(null);
searchResultsHolder.timeStamp.setText(null);
}
}
private void handleItemEvents(final ChatViewHolder chatViewHolder, final int position) {
final ChatMessage model = getData().get(position);
chatViewHolder.chatMessageView.setBackgroundColor(ContextCompat.getColor(currContext, isSelected(position) ? R.color.translucent_blue : android.R.color.transparent));
if (model != null) {
try {
switch (getItemViewType(position)) {
case USER_MESSAGE:
chatViewHolder.chatTextView.setText(model.getContent());
chatViewHolder.timeStamp.setText(model.getTimeStamp());
if(model.getIsDelivered())
chatViewHolder.receivedTick.setImageResource(R.drawable.check);
else
chatViewHolder.receivedTick.setImageResource(R.drawable.clock);
chatViewHolder.chatTextView.setTag(chatViewHolder);
if (highlightMessagePosition == position) {
String text = chatViewHolder.chatTextView.getText().toString();
SpannableString modify = new SpannableString(text);
Pattern pattern = Pattern.compile(query, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(modify);
while (matcher.find()) {
int startIndex = matcher.start();
int endIndex = matcher.end();
modify.setSpan(new BackgroundColorSpan(Color.parseColor("#2b3c4e")), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
chatViewHolder.chatTextView.setText(modify);
}
chatViewHolder.timeStamp.setTag(chatViewHolder);
chatViewHolder.receivedTick.setTag(chatViewHolder);
break;
case SUSI_MESSAGE:
chatViewHolder.chatTextView.setText(model.getContent());
chatViewHolder.timeStamp.setText(model.getTimeStamp());
chatViewHolder.chatTextView.setTag(chatViewHolder);
if (highlightMessagePosition == position) {
String text = chatViewHolder.chatTextView.getText().toString();
SpannableString modify = new SpannableString(text);
Pattern pattern = Pattern.compile(query, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(modify);
while (matcher.find()) {
int startIndex = matcher.start();
int endIndex = matcher.end();
modify.setSpan(new BackgroundColorSpan(Color.parseColor("#2b3c4e")), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
chatViewHolder.chatTextView.setText(modify);
}
chatViewHolder.timeStamp.setTag(chatViewHolder);
break;
case USER_IMAGE:
case SUSI_IMAGE:
default:
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void handleItemEvents(final MapViewHolder mapViewHolder, final int position) {
final ChatMessage model = getData().get(position);
mapViewHolder.chatMessageView.setBackgroundColor(ContextCompat.getColor(currContext, isSelected(position) ? R.color.translucent_blue : android.R.color.transparent));
if (model != null) {
try {
final MapHelper mapHelper = new MapHelper(model.getContent());
mapViewHolder.text.setText(mapHelper.getDisplayText());
mapViewHolder.timestampTextView.setText(model.getTimeStamp());
Glide.with(currContext).load(mapHelper.getMapURL()).into(mapViewHolder.mapImage);
mapViewHolder.mapImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mapViewHolder.onClick(v);
/*
Open in Google Maps if installed, otherwise open browser.
*/
if (AndroidHelper.isGoogleMapsInstalled(currContext) && mapHelper.isParseSuccessful()) {
Uri gmmIntentUri = Uri.parse(String.format("geo:%s,%s?z=%s", mapHelper.getLattitude(), mapHelper.getLongitude(), mapHelper.getZoom()));
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage(AndroidHelper.GOOGLE_MAPS_PKG);
currContext.startActivity(mapIntent);
} else {
Intent mapIntent = new Intent(Intent.ACTION_VIEW);
mapIntent.setData(Uri.parse(mapHelper.getWebLink()));
currContext.startActivity(mapIntent);
}
}
});
if (highlightMessagePosition == position) {
String text = mapViewHolder.text.getText().toString();
SpannableString modify = new SpannableString(text);
Pattern pattern = Pattern.compile(query, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(modify);
while (matcher.find()) {
int startIndex = matcher.start();
int endIndex = matcher.end();
modify.setSpan(new BackgroundColorSpan(Color.parseColor("#2b3c4e")), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
mapViewHolder.text.setText(modify);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void handleItemEvents(final LinkPreviewViewHolder linkPreviewViewHolder, final int position) {
final ChatMessage model = getData().get(position);
linkPreviewViewHolder.text.setText(model.getContent());
linkPreviewViewHolder.timestampTextView.setText(model.getTimeStamp());
if(model.getIsDelivered())
linkPreviewViewHolder.receivedTick.setImageResource(R.drawable.check);
else
linkPreviewViewHolder.receivedTick.setImageResource(R.drawable.clock);
linkPreviewViewHolder.chatMessageView.setBackgroundColor(ContextCompat.getColor(currContext, isSelected(position) ? R.color.translucent_blue : android.R.color.transparent));
LinkPreviewCallback linkPreviewCallback = new LinkPreviewCallback() {
@Override
public void onPre() {
linkPreviewViewHolder.previewImageView.setVisibility(View.GONE);
linkPreviewViewHolder.descriptionTextView.setVisibility(View.GONE);
linkPreviewViewHolder.titleTextView.setVisibility(View.GONE);
linkPreviewViewHolder.previewLayout.setVisibility(View.GONE);
}
@Override
public void onPos(final SourceContent sourceContent, boolean b) {
linkPreviewViewHolder.previewLayout.setVisibility(View.VISIBLE);
linkPreviewViewHolder.previewImageView.setVisibility(View.VISIBLE);
linkPreviewViewHolder.descriptionTextView.setVisibility(View.VISIBLE);
linkPreviewViewHolder.titleTextView.setVisibility(View.VISIBLE);
linkPreviewViewHolder.titleTextView.setText(sourceContent.getTitle());
linkPreviewViewHolder.descriptionTextView.setText(sourceContent.getDescription());
final List<String> imageList = sourceContent.getImages();
if (imageList == null || imageList.size() == 0) {
linkPreviewViewHolder.previewImageView.setVisibility(View.GONE);
} else {
glide.load(imageList.get(0))
.centerCrop()
.into(linkPreviewViewHolder.previewImageView);
}
linkPreviewViewHolder.previewLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
linkPreviewViewHolder.onClick(view);
Uri webpage = Uri.parse(sourceContent.getFinalUrl());
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(currContext.getPackageManager()) != null) {
currContext.startActivity(intent);
}
}
});
}
};
if (highlightMessagePosition == position) {
String text = linkPreviewViewHolder.text.getText().toString();
SpannableString modify = new SpannableString(text);
Pattern pattern = Pattern.compile(query, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(modify);
while (matcher.find()) {
int startIndex = matcher.start();
int endIndex = matcher.end();
modify.setSpan(new BackgroundColorSpan(Color.parseColor("#2b3c4e")), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
linkPreviewViewHolder.text.setText(modify);
}
if (model != null) {
List<String> urlList = extractLinks(model.getContent());
String url = urlList.get(0);
if (!(url.startsWith("http:
url = "http://" + url;
}
TextCrawler textCrawler = new TextCrawler();
textCrawler.makePreview(linkPreviewCallback, url);
}
}
private void handleItemEvents(final PieChartViewHolder pieChartViewHolder, final int position) {
final ChatMessage model = getData().get(position);
if (model != null) {
try {
pieChartViewHolder.chatTextView.setText(model.getContent());
pieChartViewHolder.chatMessageView.setBackgroundColor(ContextCompat.getColor(currContext, isSelected(position) ? R.color.translucent_blue : android.R.color.transparent));
pieChartViewHolder.timeStamp.setText(model.getTimeStamp());
pieChartViewHolder.pieChart.setUsePercentValues(true);
pieChartViewHolder.pieChart.setDrawHoleEnabled(true);
pieChartViewHolder.pieChart.setHoleRadius(7);
pieChartViewHolder.pieChart.setTransparentCircleRadius(10);
pieChartViewHolder.pieChart.setRotationEnabled(true);
pieChartViewHolder.pieChart.setRotationAngle(0);
pieChartViewHolder.pieChart.setDragDecelerationFrictionCoef(0.001f);
pieChartViewHolder.pieChart.getLegend().setEnabled(false);
pieChartViewHolder.pieChart.setDescription("");
RealmList<Datum> datumList = model.getDatumRealmList();
final ArrayList<Entry> yVals = new ArrayList<>();
final ArrayList<String> xVals = new ArrayList<>();
for (int i = 0; i < datumList.size(); i++) {
yVals.add(new Entry(datumList.get(i).getPercent(), i));
xVals.add(datumList.get(i).getPresident());
}
pieChartViewHolder.pieChart.setClickable(false);
pieChartViewHolder.pieChart.setHighlightPerTapEnabled(false);
PieDataSet dataSet = new PieDataSet(yVals, "");
dataSet.setSliceSpace(3);
dataSet.setSelectionShift(5);
ArrayList<Integer> colors = new ArrayList<>();
for (int c : ColorTemplate.VORDIPLOM_COLORS)
colors.add(c);
for (int c : ColorTemplate.JOYFUL_COLORS)
colors.add(c);
for (int c : ColorTemplate.COLORFUL_COLORS)
colors.add(c);
for (int c : ColorTemplate.LIBERTY_COLORS)
colors.add(c);
for (int c : ColorTemplate.PASTEL_COLORS)
colors.add(c);
dataSet.setColors(colors);
PieData data = new PieData(xVals, dataSet);
data.setValueFormatter(new PercentFormatter());
data.setValueTextSize(11f);
data.setValueTextColor(Color.GRAY);
pieChartViewHolder.pieChart.setData(data);
pieChartViewHolder.pieChart.highlightValues(null);
pieChartViewHolder.pieChart.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void setClipboard(String text) {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) currContext.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
clipboard.setPrimaryClip(clip);
}
private void deleteMessage(final int position) {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
getData().deleteFromRealm(position);
}
});
}
private void scrollToBottom() {
if (getData() != null && !getData().isEmpty() && recyclerView != null) {
recyclerView.smoothScrollToPosition(getItemCount() - 1);
}
}
private void toggleSelectedItem(int position) {
toggleSelection(position);
int count = getSelectedItemCount();
Log.d(TAG, position + " " + isSelected(position));
selectedItems.put(position, isSelected(position));
if (count == 0) {
actionMode.finish();
} else {
actionMode.setTitle(String.valueOf(count));
actionMode.invalidate();
}
}
@Override
public void onItemClicked(int position) {
if (actionMode != null) {
toggleSelectedItem(position);
}
}
@Override
public boolean onItemLongClicked(int position) {
if (actionMode == null) {
actionMode = ((AppCompatActivity) currContext).startSupportActionMode(actionModeCallback);
}
toggleSelectedItem(position);
return true;
}
private class ActionModeCallback implements ActionMode.Callback {
@SuppressWarnings("unused")
private final String TAG = ChatFeedRecyclerAdapter.ActionModeCallback.class.getSimpleName();
private int statusBarColor;
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.menu_selection_mode, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
statusBarColor = currActivity.getWindow().getStatusBarColor();
currActivity.getWindow().setStatusBarColor(ContextCompat.getColor(currContext, R.color.md_teal_500));
}
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int nSelected;
switch (item.getItemId()) {
case R.id.menu_item_delete:
AlertDialog.Builder d = new AlertDialog.Builder(context);
d.setMessage("Are you sure ?").
setCancelable(false).
setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
for (int i = getSelectedItems().size() - 1; i >= 0; i
deleteMessage(getSelectedItems().get(i));
}
if (getSelectedItems().size() == 1)
Snackbar.make(recyclerView, " Message Deleted !!", Snackbar.LENGTH_LONG).show();
else
Snackbar.make(recyclerView, getSelectedItems().size() + " Messages Deleted !!", Snackbar.LENGTH_LONG).show();
actionMode.finish();
}
}).
setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = d.create();
alert.setTitle("Delete");
alert.show();
Button cancel = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
cancel.setTextColor(Color.BLUE);
Button delete = alert.getButton(DialogInterface.BUTTON_POSITIVE);
delete.setTextColor(Color.RED);
return true;
case R.id.menu_item_copy:
nSelected = getSelectedItems().size();
if (nSelected == 1) {
String copyText;
int selected = getSelectedItems().get(0);
copyText = getItem(selected).getContent();
if (getItem(selected).isMap()) {
copyText = copyText.substring(0, copyText.indexOf("http"));
}
setClipboard(copyText);
} else {
String copyText = "";
for (Integer i : getSelectedItems()) {
ChatMessage message = getData().get(i);
Log.d(TAG, message.toString());
copyText += "[" + message.getTimeStamp() + "]";
copyText += " ";
copyText += message.isMine() ? "Me: " : "Susi: ";
if (message.isMap()) {
String CopiedText = getData().get(i).getContent();
copyText += CopiedText.substring(0, CopiedText.indexOf("http"));
} else
copyText += message.getContent();
copyText += "\n";
Log.d("copyText", " " + i + " " + copyText);
}
copyText = copyText.substring(0, copyText.length() - 1);
setClipboard(copyText);
}
Snackbar.make(recyclerView, "Copied to Clipboard!!", Snackbar.LENGTH_LONG).show();
actionMode.finish();
return true;
case R.id.menu_item_share:
nSelected = getSelectedItems().size();
if (nSelected == 1) {
int selected = getSelectedItems().get(0);
shareMessage(getItem(selected).getContent());
} else {
String shareText = "";
for (Integer i : getSelectedItems()) {
ChatMessage message = getData().get(i);
Log.d(TAG, message.toString());
shareText += "[" + message.getTimeStamp() + "]";
shareText += " ";
shareText += message.isMine() ? "Me: " : "Susi: ";
shareText += message.getContent();
shareText += "\n";
}
shareText = shareText.substring(0, shareText.length() - 1);
shareMessage(shareText);
}
actionMode.finish();
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
clearSelection();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
currActivity.getWindow().setStatusBarColor(statusBarColor);
}
actionMode = null;
}
public void shareMessage(String message) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setType("text/plain");
currContext.startActivity(sendIntent);
}
}
} |
package org.csstudio.swt.xygraph.figures;
import java.util.ArrayList;
import java.util.List;
import org.csstudio.swt.xygraph.Preferences;
import org.csstudio.swt.xygraph.dataprovider.IDataProvider;
import org.csstudio.swt.xygraph.dataprovider.IDataProviderListener;
import org.csstudio.swt.xygraph.dataprovider.ISample;
import org.csstudio.swt.xygraph.dataprovider.Sample;
import org.csstudio.swt.xygraph.linearscale.Range;
import org.csstudio.swt.xygraph.linearscale.AbstractScale.LabelSide;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
/**
* The trace figure.
* @author Xihui Chen
* @author Kay Kasemir (synchronization, STEP_HORIZONTALLY tweaks)
*/
public class Trace extends Figure implements IDataProviderListener, IAxisListener{
/** Size of 'markers' used on X axis to indicate non-plottable samples */
final private static int MARKER_SIZE = 6;
/** Use advanced graphics?
* Might not make a real performance difference, but since this it called a lot,
* keep it in variable
*/
final private static boolean use_advanced_graphics = Preferences.useAdvancedGraphics();
/** The way how the trace will be drawn.
* @author Xihui Chen
*/
public enum TraceType {
/** Solid Line */
SOLID_LINE("Solid Line"),
/** Dash Line */
DASH_LINE("Dash Line"),
/** Only draw point whose style is defined by pointStyle.
* Its size is defined by pointSize. */
POINT("Point"),
/** Draw each data point as a bar whose width is defined by lineWidth.
* The data point is in the middle of the bar on X direction.
* The bottom of the bar depends on the baseline.
* The alpha of the bar is defined by areaAlpha. */
BAR("Bar"),
/** Fill the area under the trace.
* The bottom of the filled area depends on the baseline.
* The alpha of the filled area is defined by areaAlpha. */
AREA("Area"),
/**
* Solid line in step. It looks like the y value(on vertical direction) changed firstly.
*/
STEP_VERTICALLY("Step Vertically"),
/**
* Solid line in step. It looks like the x value(on horizontal direction) changed firstly.
*/
STEP_HORIZONTALLY("Step Horizontally");
/** Draw a single point. Only the last data point will be drawn.*/
//SINGLE_POINT("Single Point");
private TraceType(String description) {
this.description = description;
}
private String description;
@Override
public String toString() {
return description;
}
public static String[] stringValues(){
String[] sv = new String[values().length];
int i=0;
for(TraceType p : values())
sv[i++] = p.toString();
return sv;
}
}
public enum BaseLine {
NEGATIVE_INFINITY,
ZERO,
POSITIVE_INFINITY;
public static String[] stringValues(){
String[] sv = new String[values().length];
int i=0;
for(BaseLine p : values())
sv[i++] = p.toString();
return sv;
}
}
public enum PointStyle{
NONE("None"),
POINT("point(" + (char)7 + ")"),
CIRCLE("Circle(o)"),
TRIANGLE("Triangle"),
FILLED_TRIANGLE("Filled Triangle"),
SQUARE("Square"),
FILLED_SQUARE("Filled Square"),
DIAMOND("Diamond"),
FILLED_DIAMOND("Filled Diamond"),
XCROSS("XCross(x)"),
CROSS("Cross(+)"),
BAR("Bar(|)");
private PointStyle(String description) {
this.description = description;
}
private String description;
@Override
public String toString() {
return description;
}
public static String[] stringValues(){
String[] sv = new String[values().length];
int i=0;
for(PointStyle p : values())
sv[i++] = p.toString();
return sv;
}
}
public enum ErrorBarType{
NONE,
PLUS,
MINUS,
BOTH;
public static String[] stringValues(){
String[] sv = new String[values().length];
int i=0;
for(ErrorBarType p : values())
sv[i++] = p.toString();
return sv;
}
}
private String name;
private IDataProvider traceDataProvider;
private Axis xAxis;
private Axis yAxis;
private Color traceColor;
private TraceType traceType = TraceType.SOLID_LINE;
private BaseLine baseLine = BaseLine.ZERO;
private PointStyle pointStyle = PointStyle.NONE;
/**
* If traceType is bar, this is the width of the bar.
*/
private int lineWidth = 1;
private int pointSize = 4;
private int areaAlpha = 100;
private boolean antiAliasing = true;
private boolean errorBarEnabled = false;
private ErrorBarType yErrorBarType = ErrorBarType.BOTH;
private ErrorBarType xErrorBarType = ErrorBarType.BOTH;
private int errorBarCapWidth = 4;
private Color errorBarColor;
private boolean drawYErrorInArea = false;
private XYGraph xyGraph;
private List<ISample> hotSampleist;
public Trace(String name, Axis xAxis, Axis yAxis, IDataProvider dataProvider) {
this.setName(name);
this.xAxis = xAxis;
this.yAxis = yAxis;
xAxis.addTrace(this);
yAxis.addTrace(this);
xAxis.addListener(this);
yAxis.addListener(this);
setDataProvider(dataProvider);
hotSampleist = new ArrayList<ISample>();
}
private void drawErrorBar(Graphics graphics, Point dpPos, ISample dp){
graphics.pushState();
if(errorBarColor == null)
errorBarColor = traceColor;
graphics.setForegroundColor(errorBarColor);
graphics.setLineStyle(SWT.LINE_SOLID);
graphics.setLineWidth(1);
Point ep;
switch (yErrorBarType) {
case BOTH:
case MINUS:
ep = new Point(xAxis.getValuePosition(dp.getXValue(), false),
yAxis.getValuePosition(dp.getYValue() - dp.getYMinusError(), false));
graphics.drawLine(dpPos, ep);
graphics.drawLine(ep.x - errorBarCapWidth/2, ep.y, ep.x + errorBarCapWidth/2, ep.y);
if(yErrorBarType != ErrorBarType.BOTH)
break;
case PLUS:
ep = new Point(xAxis.getValuePosition(dp.getXValue(), false),
yAxis.getValuePosition(dp.getYValue() + dp.getYPlusError(), false));
graphics.drawLine(dpPos, ep);
graphics.drawLine(ep.x - errorBarCapWidth/2, ep.y, ep.x + errorBarCapWidth/2, ep.y);
break;
default:
break;
}
switch (xErrorBarType) {
case BOTH:
case MINUS:
ep = new Point(xAxis.getValuePosition(dp.getXValue() - dp.getXMinusError(), false),
yAxis.getValuePosition(dp.getYValue(), false));
graphics.drawLine(dpPos, ep);
graphics.drawLine(ep.x, ep.y - errorBarCapWidth/2, ep.x, ep.y + errorBarCapWidth/2);
if(xErrorBarType != ErrorBarType.BOTH)
break;
case PLUS:
ep = new Point(xAxis.getValuePosition(dp.getXValue() + dp.getXPlusError(), false),
yAxis.getValuePosition(dp.getYValue(), false));
graphics.drawLine(dpPos, ep);
graphics.drawLine(ep.x , ep.y - errorBarCapWidth/2, ep.x, ep.y + errorBarCapWidth/2);
break;
default:
break;
}
graphics.popState();
}
private void drawYErrorArea(Graphics graphics, ISample predp, ISample dp, Point predpPos, Point dpPos){
graphics.pushState();
if(errorBarColor == null)
errorBarColor = traceColor;
Color lighter = null;
if (use_advanced_graphics)
{
graphics.setBackgroundColor(errorBarColor);
graphics.setAlpha(areaAlpha);
}
else
{
final float[] hsb = errorBarColor.getRGB().getHSB();
lighter = new Color(Display.getCurrent(),
new RGB(hsb[0], hsb[1]*areaAlpha/255, 1.0f));
graphics.setBackgroundColor(lighter);
}
Point preEp, ep;
switch (yErrorBarType) {
case BOTH:
case PLUS:
preEp = new Point(xAxis.getValuePosition(predp.getXValue(), false),
yAxis.getValuePosition(predp.getYValue() + predp.getYPlusError(), false));
ep = new Point(xAxis.getValuePosition(dp.getXValue(), false),
yAxis.getValuePosition(dp.getYValue() + dp.getYPlusError(), false));
graphics.fillPolygon(new int[]{predpPos.x, predpPos.y,
preEp.x, preEp.y, ep.x, ep.y, dpPos.x, dpPos.y});
if(yErrorBarType != ErrorBarType.BOTH)
break;
case MINUS:
preEp = new Point(xAxis.getValuePosition(predp.getXValue(), false),
yAxis.getValuePosition(predp.getYValue() - predp.getYMinusError(), false));
ep = new Point(xAxis.getValuePosition(dp.getXValue(), false),
yAxis.getValuePosition(dp.getYValue() - dp.getYMinusError(), false));
graphics.fillPolygon(new int[]{predpPos.x, predpPos.y,
preEp.x, preEp.y, ep.x, ep.y, dpPos.x, dpPos.y});
break;
default:
break;
}
graphics.popState();
if (lighter != null)
lighter.dispose();
}
/**Draw point with the pointStyle and size of the trace;
* @param graphics
* @param pos
*/
public void drawPoint(Graphics graphics, Point pos){
// Shortcut when no point requested
if (pointStyle == PointStyle.NONE)
return;
graphics.pushState();
graphics.setBackgroundColor(traceColor);
//graphics.setForegroundColor(traceColor);
graphics.setLineWidth(1);
graphics.setLineStyle(SWT.LINE_SOLID);
switch (pointStyle) {
case POINT:
graphics.fillOval(new Rectangle(
pos.x - pointSize/2, pos.y - pointSize/2,
pointSize, pointSize));
break;
case CIRCLE:
graphics.drawOval(new Rectangle(
pos.x - pointSize/2, pos.y - pointSize/2,
pointSize, pointSize));
break;
case TRIANGLE:
graphics.drawPolygon(new int[]{pos.x-pointSize/2, pos.y + pointSize/2,
pos.x, pos.y - pointSize/2, pos.x + pointSize/2, pos.y + pointSize/2});
break;
case FILLED_TRIANGLE:
graphics.fillPolygon(new int[]{pos.x-pointSize/2, pos.y + pointSize/2,
pos.x, pos.y - pointSize/2, pos.x + pointSize/2, pos.y + pointSize/2});
break;
case SQUARE:
graphics.drawRectangle(new Rectangle(
pos.x - pointSize/2, pos.y - pointSize/2,
pointSize, pointSize));
break;
case FILLED_SQUARE:
graphics.fillRectangle(new Rectangle(
pos.x - pointSize/2, pos.y - pointSize/2,
pointSize, pointSize));
break;
case BAR:
graphics.drawLine(pos.x, pos.y - pointSize/2,
pos.x, pos.y + pointSize/2);
break;
case CROSS:
graphics.drawLine(pos.x, pos.y - pointSize/2,
pos.x, pos.y + pointSize/2);
graphics.drawLine(pos.x - pointSize/2, pos.y,
pos.x + pointSize/2, pos.y);
break;
case XCROSS:
graphics.drawLine(pos.x - pointSize/2, pos.y - pointSize/2,
pos.x + pointSize/2, pos.y + pointSize/2);
graphics.drawLine(pos.x + pointSize/2 , pos.y - pointSize/2,
pos.x - pointSize/2, pos.y + pointSize/2);
break;
case DIAMOND:
graphics.drawPolyline(new int[]{
pos.x, pos.y - pointSize/2,
pos.x - pointSize/2, pos.y,
pos.x, pos.y + pointSize/2,
pos.x + pointSize/2, pos.y,
pos.x, pos.y - pointSize/2});
break;
case FILLED_DIAMOND:
graphics.fillPolygon(new int[]{
pos.x, pos.y - pointSize/2,
pos.x - pointSize/2, pos.y,
pos.x, pos.y + pointSize/2,
pos.x + pointSize/2, pos.y});
break;
default:
break;
}
graphics.popState();
}
/**Draw line with the line style and line width of the trace.
* @param graphics
* @param p1
* @param p2
*/
public void drawLine(Graphics graphics, Point p1, Point p2){
graphics.pushState();
switch (traceType) {
case SOLID_LINE:
graphics.setLineStyle(SWT.LINE_SOLID);
graphics.drawLine(p1, p2);
break;
case BAR:
if (use_advanced_graphics)
graphics.setAlpha(areaAlpha);
graphics.setLineStyle(SWT.LINE_SOLID);
graphics.drawLine(p1, p2);
break;
case DASH_LINE:
graphics.setLineStyle(SWT.LINE_DASH);
graphics.drawLine(p1, p2);
break;
case AREA:
int basey;
switch (baseLine) {
case NEGATIVE_INFINITY:
basey = yAxis.getValuePosition(yAxis.getRange().getLower(), false);
break;
case POSITIVE_INFINITY:
basey = yAxis.getValuePosition(yAxis.getRange().getUpper(), false);
break;
default:
basey = yAxis.getValuePosition(0, false);
break;
}
if (use_advanced_graphics)
graphics.setAlpha(areaAlpha);
graphics.setBackgroundColor(traceColor);
graphics.fillPolygon(new int[]{
p1.x, p1.y,
p1.x, basey,
p2.x, basey,
p2.x, p2.y
});
break;
case STEP_HORIZONTALLY:
graphics.setLineStyle(SWT.LINE_SOLID);
Point ph = new Point(p2.x, p1.y);
graphics.drawLine(p1, ph);
graphics.drawLine(ph, p2);
break;
case STEP_VERTICALLY:
graphics.setLineStyle(SWT.LINE_SOLID);
Point pv = new Point(p1.x, p2.y);
graphics.drawLine(p1, pv);
graphics.drawLine(pv, p2);
break;
default:
break;
}
graphics.popState();
}
@Override
protected void paintFigure(Graphics graphics) {
super.paintFigure(graphics);
graphics.pushState();
if (use_advanced_graphics)
graphics.setAntialias(antiAliasing? SWT.ON : SWT.OFF);
graphics.setForegroundColor(traceColor);
graphics.setLineWidth(lineWidth);
ISample predp = null;
boolean predpInRange = false;
Point dpPos = null;
hotSampleist.clear();
if(traceDataProvider == null)
throw new RuntimeException("No DataProvider defined for trace: " + name); //$NON-NLS-1$
// Lock data provider to prevent changes while painting
synchronized (traceDataProvider)
{
if(traceDataProvider.getSize()>0){
// Is only a sub-set of the trace data visible?
final int startIndex, endIndex;
if(traceDataProvider.isChronological()){
final Range indexRange = getIndexRangeOnXAxis();
if(indexRange == null){
startIndex = 0;
endIndex = -1;
}else{
startIndex = (int) indexRange.getLower();
endIndex = (int) indexRange.getUpper();
}
}
else
{ // Cannot optimize range, use all data points
startIndex = 0;
endIndex = traceDataProvider.getSize()-1;
}
for (int i=startIndex; i<=endIndex; i++)
{
ISample dp = traceDataProvider.getSample(i);
final boolean dpInXRange = xAxis.getRange().inRange(dp.getXValue());
// Mark 'NaN' samples on X axis
final boolean valueIsNaN = Double.isNaN(dp.getYValue());
if (dpInXRange && valueIsNaN)
{
Point markPos = new Point(xAxis.getValuePosition(dp.getXValue(), false),
yAxis.getValuePosition(xAxis.getTickLablesSide() == LabelSide.Primary?
yAxis.getRange().getLower() : yAxis.getRange().getUpper(), false));
graphics.setBackgroundColor(traceColor);
graphics.fillRectangle(markPos.x -MARKER_SIZE/2, markPos.y - MARKER_SIZE/2, MARKER_SIZE, MARKER_SIZE);
Sample nanSample = new Sample(dp.getXValue(),xAxis.getTickLablesSide() == LabelSide.Primary?
yAxis.getRange().getLower() : yAxis.getRange().getUpper(),
dp.getYPlusError(), dp.getYMinusError(),
Double.NaN, dp.getXMinusError(), dp.getInfo());
hotSampleist.add(nanSample);
}
// Is data point in the plot area?
boolean dpInRange = dpInXRange &&
yAxis.getRange().inRange(dp.getYValue());
//draw point
if(dpInRange){
dpPos = new Point(xAxis.getValuePosition(dp.getXValue(), false),
yAxis.getValuePosition(dp.getYValue(), false));
hotSampleist.add(dp);
drawPoint(graphics, dpPos);
if(errorBarEnabled && !drawYErrorInArea)
drawErrorBar(graphics, dpPos, dp);
}
if(traceType == TraceType.POINT && !drawYErrorInArea)
continue; // no need to draw line
//draw line
if(traceType == TraceType.BAR){
switch (baseLine) {
case NEGATIVE_INFINITY:
predp = new Sample(dp.getXValue(), yAxis.getRange().getLower());
break;
case POSITIVE_INFINITY:
predp = new Sample(dp.getXValue(), yAxis.getRange().getUpper());
break;
default:
predp = new Sample(dp.getXValue(), 0);
break;
}
predpInRange = xAxis.getRange().inRange(predp.getXValue()) && yAxis.getRange().inRange(predp.getYValue());
}
if(predp == null)
{ // No previous data point from which to draw a line
predp = dp;
predpInRange = dpInRange;
continue;
}
// Save original dp info because handling of NaN or
// axis intersections might patch it
final ISample origin_dp = dp;
final boolean origin_dpInRange = dpInRange;
// In 'STEP' modes, if there was a value, now there is none,
// continue that last value until the NaN location
if (valueIsNaN && !Double.isNaN(predp.getYValue()) &&
(traceType == TraceType.STEP_HORIZONTALLY ||
traceType == TraceType.STEP_VERTICALLY))
{ // Patch 'y' of dp, re-compute dpInRange for new 'y'
dp = new Sample(dp.getXValue(), predp.getYValue());
dpInRange = yAxis.getRange().inRange(dp.getYValue());
}
if(traceType != TraceType.AREA)
{
if(!predpInRange && !dpInRange){ //both are out of plot area
ISample[] dpTuple = getIntersection(predp, dp);
if(dpTuple[0] == null || dpTuple[1] == null){ // no intersection with plot area
predp = origin_dp;
predpInRange = origin_dpInRange;
continue;
}else{
predp = dpTuple[0];
dp = dpTuple[1];
}
}else if(!predpInRange || !dpInRange){ // one in and one out
//calculate the intersection point with the boundary of plot area.
if(!predpInRange){
predp = getIntersection(predp, dp)[0];
if(predp == null){ // no intersection
predp = origin_dp;
predpInRange = origin_dpInRange;
continue;
}
}else{
dp = getIntersection(predp, dp)[0];
if(dp == null){ // no intersection
predp = origin_dp;
predpInRange = origin_dpInRange;
continue;
}
}
}
}
final Point predpPos = new Point(xAxis.getValuePosition(predp.getXValue(), false),
yAxis.getValuePosition(predp.getYValue(), false));
dpPos = new Point(xAxis.getValuePosition(dp.getXValue(), false),
yAxis.getValuePosition(dp.getYValue(), false));
if(!dpPos.equals(predpPos)){
if(errorBarEnabled && drawYErrorInArea && traceType!=TraceType.BAR)
drawYErrorArea(graphics, predp, dp, predpPos, dpPos);
drawLine(graphics, predpPos, dpPos);
}
predp = origin_dp;
predpInRange = origin_dpInRange;
}
}
}
graphics.popState();
}
/** Compute axes intersection considering the 'TraceType'
* @param dp1 'Start' point of line
* @param dp2 'End' point of line
* @return The intersection points with the axes when draw the line between the two
* data points. The index 0 of the result is the first intersection point. index 1 is the second one.
*/
private ISample[] getIntersection(final ISample dp1, final ISample dp2)
{
if (traceType == TraceType.STEP_HORIZONTALLY)
{
final ISample[] result = new Sample[2];
int count = 0;
// Data point between dp1 and dp2 using horizontal steps:
// dp2
final ISample dp = new Sample(dp2.getXValue(), dp1.getYValue());
final ISample iy[] = getStraightLineIntersection(dp1, dp);
// Intersects both y axes?
if (iy[1] != null)
return iy;
// Intersects one y axis?
if(iy[0] != null)
result[count++] = iy[0];
// Check intersections of vertical dp/dp2 section with x axes
final ISample ix[] = getStraightLineIntersection(dp, dp2);
// Intersects both x axes?
if (ix[1] != null)
return ix;
// Intersects one x axis?
if (ix[0] != null)
result[count++] = ix[0];
return result;
}
if (traceType == TraceType.STEP_VERTICALLY)
{
final ISample[] result = new Sample[2];
int count = 0;
// Data point between dp1 and dp2 using vertical steps:
// dp1
final ISample dp = new Sample(dp1.getXValue(), dp2.getYValue());
// Check intersections of vertical dp1/dp section
final ISample ix[] = getStraightLineIntersection(dp1, dp);
// Intersects both X axes?
if (ix[1] != null)
return ix;
// Intersects one X axis?
if (ix[0] != null)
result[count++] = ix[0];
final ISample iy[] = getStraightLineIntersection(dp, dp2);
// Intersects both y axes?
if (iy[1] != null)
return iy;
// Intersects one y axis?
if (iy[0] != null)
result[count++] = iy[0];
return result;
}
return getStraightLineIntersection(dp1, dp2);
}
/** Compute intersection of straight line with axes,
* no correction for 'TraceType'.
* @param dp1 'Start' point of line
* @param dp2 'End' point of line
* @return The intersection points between the line,
* which is the straight line between the two data points, and the axes.
* Result could be { null, null }, { point1, null } or { point1, point2 }.
*/
private ISample[] getStraightLineIntersection(final ISample dp1, final ISample dp2){
final double x1 = dp1.getXValue();
final double y1 = dp1.getYValue();
final double x2 = dp2.getXValue();
final double y2 = dp2.getYValue();
final double dx = x2 - x1;
final double dy = y2 - y1;
final ISample[] dpTuple = new Sample[2];
int count = 0; // number of valid dbTuple entries
double x, y;
if (dy != 0.0)
{ // Intersection with lower xAxis
final double ymin = yAxis.getRange().getLower();
x = (ymin-y1)*dx/dy + x1;
y = ymin;
if(evalDP(x, y, dp1, dp2))
dpTuple[count++] = new Sample(x, y);
// Intersection with upper xAxis
final double ymax = yAxis.getRange().getUpper();
x = (ymax-y1)*dx/dy+x1;
y = ymax;
if(evalDP(x, y, dp1, dp2))
dpTuple[count++] = new Sample(x, y);
}
// A line that runs diagonally through the plot,
// hitting for example the lower left as well as upper right corners
// would cut both X as well as both Y axes.
// Return only the X axes hits, since Y axes hits are actually the
// same points.
if (count == 2)
return dpTuple;
if (dx != 0.0)
{ // Intersection with left yAxis
final double xmin = xAxis.getRange().getLower();
x = xmin;
y = (xmin-x1)*dy/dx+y1;
if(evalDP(x, y, dp1, dp2))
dpTuple[count++] = new Sample(x, y);
// Intersection with right yAxis
final double xmax = xAxis.getRange().getUpper();
x = xmax;
y = (xmax-x1)*dy/dx + y1;
if(dx != 0 && evalDP(x, y, dp1, dp2))
dpTuple[count++] = new Sample(x, y);
}
return dpTuple;
}
/** Sanity check:
* Point x/y was computed to be an axis intersection, but that can fail
* because of rounding errors or for samples with NaN, Infinity.
* Is it in the plot area?
* Is it between the start/end points.
* @param x
* @param y
* @param dp1
* @param dp2
* @return true if the point (x,y) is between dp1 and dp2
* BUT not equal to either
* AND within the x/y axes. false otherwise
*/
private boolean evalDP(final double x, final double y, final ISample dp1, final ISample dp2){
// First check axis limits
if (!xAxis.getRange().inRange(x) || !yAxis.getRange().inRange(y))
return false;
// Check if dp is between dp1 and dp2.
// Could this be done without constructing 2 new Ranges?
if (! new Range(dp1.getXValue(), dp2.getXValue()).inRange(x) ||
! new Range(dp1.getYValue(), dp2.getYValue()).inRange(y))
return false;
// TODO why the ==dp1,2 test?
final ISample dp = new Sample(x, y);
if(dp.equals(dp1) || dp.equals(dp2))
return false;
return true;
}
/**
* @param axis the xAxis to set
*/
public void setXAxis(Axis axis) {
if(xAxis == axis)
return;
if(xAxis != null){
xAxis.removeListenr(this);
xAxis.removeTrace(this);
}
/*if(traceDataProvider != null){
traceDataProvider.removeDataProviderListener(xAxis);
traceDataProvider.addDataProviderListener(axis);
} */
xAxis = axis;
xAxis.addTrace(this);
xAxis.addListener(this);
revalidate();
}
/**
* @return the xAxis
*/
public Axis getXAxis() {
return xAxis;
}
/**
* @param axis the yAxis to set
*/
public void setYAxis(Axis axis) {
if(yAxis == axis)
return;
xyGraph.getLegendMap().get(yAxis).removeTrace(this);
if(xyGraph.getLegendMap().get(yAxis).getTraceList().size() <=0){
xyGraph.remove(xyGraph.getLegendMap().get(yAxis));
xyGraph.getLegendMap().remove(yAxis);
}
if(xyGraph.getLegendMap().containsKey(axis))
xyGraph.getLegendMap().get(axis).addTrace(this);
else{
xyGraph.getLegendMap().put(axis, new Legend());
xyGraph.getLegendMap().get(axis).addTrace(this);
xyGraph.add(xyGraph.getLegendMap().get(axis));
}
if(yAxis != null){
yAxis.removeListenr(this);
yAxis.removeTrace(this);
}
/*if(traceDataProvider != null){
traceDataProvider.removeDataProviderListener(yAxis);
traceDataProvider.addDataProviderListener(axis);
} */
yAxis = axis;
yAxis.addTrace(this);
yAxis.addListener(this);
xyGraph.repaint();
}
/**
* @param traceDataProvider the traceDataProvider to set
*/
public void setDataProvider(
IDataProvider traceDataProvider) {
traceDataProvider.addDataProviderListener(this);
// traceDataProvider.addDataProviderListener(xAxis);
// traceDataProvider.addDataProviderListener(yAxis);
this.traceDataProvider = traceDataProvider;
}
/**
* @return the traceType
*/
public TraceType getTraceType() {
return traceType;
}
/**
* @param traceColor the traceColor to set
*/
public void setTraceColor(Color traceColor) {
this.traceColor = traceColor;
}
/**
* @return the traceColor
*/
public Color getTraceColor() {
return traceColor;
}
/**
* @param traceType the traceType to set
*/
public void setTraceType(TraceType traceType) {
this.traceType = traceType;
}
/**
* @param baseLine the baseLine to set
*/
public void setBaseLine(BaseLine baseLine) {
this.baseLine = baseLine;
}
/**
* @param pointStyle the pointStyle to set
*/
public void setPointStyle(PointStyle pointStyle) {
this.pointStyle = pointStyle;
}
/**
* @param lineWidth the lineWidth to set
*/
public void setLineWidth(int lineWidth) {
this.lineWidth = lineWidth;
}
/**
* @param pointSize the pointSize to set
*/
public void setPointSize(int pointSize) {
this.pointSize = pointSize;
}
/**
* @param areaAlpha the areaAlpha to set
*/
public void setAreaAlpha(int areaAlpha) {
this.areaAlpha = areaAlpha;
}
/**
* @param antiAliasing the antiAliasing to set
*/
public void setAntiAliasing(boolean antiAliasing) {
this.antiAliasing = antiAliasing;
}
/**
* @param name the name of the trace to set
*/
public void setName(String name) {
this.name = name;
revalidate();
}
/**
* @return the name of the trace
*/
public String getName() {
return name;
}
/**
* @return the pointSize
*/
public int getPointSize() {
return pointSize;
}
/**
* @return the areaAlpha
*/
public int getAreaAlpha() {
return areaAlpha;
}
/**
* @return the yAxis
*/
public Axis getYAxis() {
return yAxis;
}
@Override
public String toString() {
return name;
}
public void dataChanged(IDataProvider dataProvider) {
//if the axis has been repainted, it will cause the trace to be repainted autoly,
//the trace doesn't have to be repainted again.
boolean xRepainted = xAxis.performAutoScale(false);
boolean yRepainted = yAxis.performAutoScale(false);
if( !xRepainted && !yRepainted )
repaint();
}
/**Get the corresponding sample index range based on the range of xAxis.
* This will help trace to draw only the part of data confined in xAxis.
* So it may also provides the first data out of the range to make the line could be drawn
* between inside data and outside data.
* <b>This method only works for chronological data,
* which means the data is naturally sorted on xAxis.</b>
* @return the Range of the index.
*/
private Range getIndexRangeOnXAxis() {
Range axisRange = xAxis.getRange();
if(traceDataProvider.getSize() <=0)
return null;
if(axisRange.getLower()> traceDataProvider.getSample(traceDataProvider.getSize()-1).getXValue()
|| axisRange.getUpper()<traceDataProvider.getSample(0).getXValue())
return null;
int lowIndex = 0;
int highIndex = traceDataProvider.getSize()-1;
if(axisRange.getLower()>traceDataProvider.getSample(0).getXValue())
lowIndex = nearBinarySearchX(axisRange.getLower(), true);
if(axisRange.getUpper()<traceDataProvider.getSample(highIndex).getXValue())
highIndex = nearBinarySearchX(axisRange.getUpper(), false);
return new Range(lowIndex, highIndex);
}
// It will return the index on the closest left(if left is true) or right of the data
// Like public version, but without range checks.
private int nearBinarySearchX(double key, boolean left) {
int low = 0;
int high = traceDataProvider.getSize() - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
double midVal = traceDataProvider.getSample(mid).getXValue();
int cmp;
if (midVal < key) {
cmp = -1; // Neither val is NaN, thisVal is smaller
} else if (midVal > key) {
cmp = 1; // Neither val is NaN, thisVal is larger
} else {
long midBits = Double.doubleToLongBits(midVal);
long keyBits = Double.doubleToLongBits(key);
cmp = (midBits == keyBits ? 0 : // Values are equal
(midBits < keyBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}
if (cmp < 0){
if(mid < traceDataProvider.getSize()-1 && key < traceDataProvider.getSample(mid+1).getXValue() ){
if(left)
return mid;
else
return mid+1;
}
low = mid + 1;
}
else if (cmp > 0){
if(mid>0 && key > traceDataProvider.getSample(mid-1).getXValue())
if(left)
return mid-1;
else
return mid;
high = mid - 1;
}
else
return mid; // key found
}
return -(low + 1); // key not found.
}
public void axisRevalidated(Axis axis) {
repaint();
}
public void axisRangeChanged(Axis axis, Range old_range, Range new_range) {
//do nothing
}
/**
* @return the traceDataProvider
*/
public IDataProvider getDataProvider() {
return traceDataProvider;
}
/**
* @param errorBarEnabled the errorBarEnabled to set
*/
public void setErrorBarEnabled(boolean errorBarEnabled) {
this.errorBarEnabled = errorBarEnabled;
}
/**
* @param errorBarType the yErrorBarType to set
*/
public void setYErrorBarType(ErrorBarType errorBarType) {
yErrorBarType = errorBarType;
}
/**
* @param errorBarType the xErrorBarType to set
*/
public void setXErrorBarType(ErrorBarType errorBarType) {
xErrorBarType = errorBarType;
}
/**
* @param drawYErrorInArea the drawYErrorArea to set
*/
public void setDrawYErrorInArea(boolean drawYErrorInArea) {
this.drawYErrorInArea = drawYErrorInArea;
}
/**
* @param errorBarCapWidth the errorBarCapWidth to set
*/
public void setErrorBarCapWidth(int errorBarCapWidth) {
this.errorBarCapWidth = errorBarCapWidth;
}
/**
* @param errorBarColor the errorBarColor to set
*/
public void setErrorBarColor(Color errorBarColor) {
this.errorBarColor = errorBarColor;
}
/**Hot Sample is the sample on the trace which has been drawn in plot area.
* @return the hotPointList
*/
public List<ISample> getHotSampleList() {
return hotSampleist;
}
/**
* @return the baseLine
*/
public BaseLine getBaseLine() {
return baseLine;
}
/**
* @return the pointStyle
*/
public PointStyle getPointStyle() {
return pointStyle;
}
/**
* @return the lineWidth
*/
public int getLineWidth() {
return lineWidth;
}
/**
* @return the antiAliasing
*/
public boolean isAntiAliasing() {
return antiAliasing;
}
/**
* @return the errorBarEnabled
*/
public boolean isErrorBarEnabled() {
return errorBarEnabled;
}
/**
* @return the yErrorBarType
*/
public ErrorBarType getYErrorBarType() {
return yErrorBarType;
}
/**
* @return the xErrorBarType
*/
public ErrorBarType getXErrorBarType() {
return xErrorBarType;
}
/**
* @return the errorBarCapWidth
*/
public int getErrorBarCapWidth() {
return errorBarCapWidth;
}
/**
* @return the errorBarColor
*/
public Color getErrorBarColor() {
if(errorBarColor == null)
errorBarColor = traceColor;
return errorBarColor;
}
/**
* @return the drawYErrorInArea
*/
public boolean isDrawYErrorInArea() {
return drawYErrorInArea;
}
/**
* @param xyGraph the xyGraph to set
*/
public void setXYGraph(XYGraph xyGraph) {
this.xyGraph = xyGraph;
}
/**
* @return the xyGraph
*/
public XYGraph getXYGraph() {
return xyGraph;
}
} |
package com.axelor.apps.production.service;
import com.axelor.app.production.db.IManufOrder;
import com.axelor.apps.base.db.Company;
import com.axelor.apps.base.db.IAdministration;
import com.axelor.apps.base.db.Product;
import com.axelor.apps.base.db.Unit;
import com.axelor.apps.base.service.ProductVariantService;
import com.axelor.apps.base.service.UnitConversionService;
import com.axelor.apps.base.service.administration.SequenceService;
import com.axelor.apps.base.service.app.AppBaseService;
import com.axelor.apps.production.db.BillOfMaterial;
import com.axelor.apps.production.db.ManufOrder;
import com.axelor.apps.production.db.ProdProcess;
import com.axelor.apps.production.db.ProdProcessLine;
import com.axelor.apps.production.db.ProdProduct;
import com.axelor.apps.production.db.ProdResidualProduct;
import com.axelor.apps.production.db.repo.ManufOrderRepository;
import com.axelor.apps.production.exceptions.IExceptionMessage;
import com.axelor.apps.production.service.app.AppProductionService;
import com.axelor.apps.production.service.config.StockConfigProductionService;
import com.axelor.apps.stock.db.StockConfig;
import com.axelor.apps.stock.db.StockLocation;
import com.axelor.apps.stock.db.StockMove;
import com.axelor.apps.stock.db.StockMoveLine;
import com.axelor.apps.stock.service.StockMoveLineService;
import com.axelor.apps.stock.service.StockMoveService;
import com.axelor.exception.AxelorException;
import com.axelor.exception.db.IException;
import com.axelor.i18n.I18n;
import com.axelor.inject.Beans;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class ManufOrderServiceImpl implements ManufOrderService {
private final Logger logger = LoggerFactory.getLogger( MethodHandles.lookup().lookupClass() );
protected SequenceService sequenceService;
protected OperationOrderService operationOrderService;
protected ManufOrderWorkflowService manufOrderWorkflowService;
protected ProductVariantService productVariantService;
protected AppProductionService appProductionService;
protected ManufOrderRepository manufOrderRepo;
@Inject
public ManufOrderServiceImpl(SequenceService sequenceService, OperationOrderService operationOrderService,
ManufOrderWorkflowService manufOrderWorkflowService, ProductVariantService productVariantService,
AppProductionService appProductionService, ManufOrderRepository manufOrderRepo) {
this.sequenceService = sequenceService;
this.operationOrderService = operationOrderService;
this.manufOrderWorkflowService = manufOrderWorkflowService;
this.productVariantService = productVariantService;
this.appProductionService = appProductionService;
this.manufOrderRepo = manufOrderRepo;
}
@Override
@Transactional(rollbackOn = {AxelorException.class, Exception.class})
public ManufOrder generateManufOrder(Product product, BigDecimal qtyRequested, int priority, boolean isToInvoice,
BillOfMaterial billOfMaterial, LocalDateTime plannedStartDateT) throws AxelorException {
if(billOfMaterial == null) { billOfMaterial = this.getBillOfMaterial(product); }
Company company = billOfMaterial.getCompany();
BigDecimal qty = qtyRequested.divide(billOfMaterial.getQty());
ManufOrder manufOrder = this.createManufOrder(product, qty, priority, IS_TO_INVOICE, company, billOfMaterial, plannedStartDateT);
manufOrder = manufOrderWorkflowService.plan(manufOrder);
return manufOrderRepo.save(manufOrder);
}
@Override
public void createToConsumeProdProductList(ManufOrder manufOrder) {
BigDecimal manufOrderQty = manufOrder.getQty();
BillOfMaterial billOfMaterial = manufOrder.getBillOfMaterial();
if(billOfMaterial.getBillOfMaterialSet() != null) {
for(BillOfMaterial billOfMaterialLine : billOfMaterial.getBillOfMaterialSet()) {
if(!billOfMaterialLine.getHasNoManageStock()) {
Product product = productVariantService.getProductVariant(manufOrder.getProduct(), billOfMaterialLine.getProduct());
BigDecimal qty = billOfMaterialLine.getQty().multiply(manufOrderQty).setScale(appProductionService.getNbDecimalDigitForBomQty(), RoundingMode.HALF_EVEN);
manufOrder.addToConsumeProdProductListItem(
new ProdProduct(product, qty, billOfMaterialLine.getUnit()));
}
}
}
}
@Override
public void createToProduceProdProductList(ManufOrder manufOrder) {
BigDecimal manufOrderQty = manufOrder.getQty();
BillOfMaterial billOfMaterial = manufOrder.getBillOfMaterial();
BigDecimal qty = billOfMaterial.getQty().multiply(manufOrderQty).setScale(appProductionService.getNbDecimalDigitForBomQty(), RoundingMode.HALF_EVEN);
// add the produced product
manufOrder.addToProduceProdProductListItem(
new ProdProduct(manufOrder.getProduct(), billOfMaterial.getQty().multiply(manufOrderQty), billOfMaterial.getUnit()));
// Add the residual products
if(appProductionService.getAppProduction().getManageResidualProductOnBom() && billOfMaterial.getProdResidualProductList() != null) {
for(ProdResidualProduct prodResidualProduct : billOfMaterial.getProdResidualProductList()) {
Product product = productVariantService.getProductVariant(manufOrder.getProduct(), prodResidualProduct.getProduct());
qty = prodResidualProduct.getQty().multiply(manufOrderQty).setScale(appProductionService.getNbDecimalDigitForBomQty(), RoundingMode.HALF_EVEN);
manufOrder.addToProduceProdProductListItem(
new ProdProduct(product, qty, prodResidualProduct.getUnit()));
}
}
}
@Override
public ManufOrder createManufOrder(Product product, BigDecimal qty, int priority, boolean isToInvoice, Company company,
BillOfMaterial billOfMaterial, LocalDateTime plannedStartDateT) throws AxelorException {
logger.debug("Création d'un OF {}", priority);
ProdProcess prodProcess = billOfMaterial.getProdProcess();
ManufOrder manufOrder = new ManufOrder(
qty,
company,
null,
priority,
this.isManagedConsumedProduct(billOfMaterial),
billOfMaterial,
product,
prodProcess,
plannedStartDateT,
IManufOrder.STATUS_DRAFT);
if(prodProcess != null && prodProcess.getProdProcessLineList() != null) {
for(ProdProcessLine prodProcessLine : this._sortProdProcessLineByPriority(prodProcess.getProdProcessLineList())) {
manufOrder.addOperationOrderListItem(
operationOrderService.createOperationOrder(manufOrder, prodProcessLine));
}
}
if(!manufOrder.getIsConsProOnOperation()) {
this.createToConsumeProdProductList(manufOrder);
}
this.createToProduceProdProductList(manufOrder);
return manufOrder;
}
@Override
@Transactional
public void preFillOperations(ManufOrder manufOrder) throws AxelorException{
BillOfMaterial billOfMaterial = manufOrder.getBillOfMaterial();
manufOrder.setIsConsProOnOperation(this.isManagedConsumedProduct(billOfMaterial));
if(manufOrder.getProdProcess() == null){
manufOrder.setProdProcess(billOfMaterial.getProdProcess());
}
ProdProcess prodProcess = manufOrder.getProdProcess();
if(manufOrder.getPlannedStartDateT() == null){
manufOrder.setPlannedStartDateT(appProductionService.getTodayDateTime().toLocalDateTime());
}
if(prodProcess != null && prodProcess.getProdProcessLineList() != null) {
for(ProdProcessLine prodProcessLine : this._sortProdProcessLineByPriority(prodProcess.getProdProcessLineList())) {
manufOrder.addOperationOrderListItem(operationOrderService.createOperationOrder(manufOrder, prodProcessLine));
}
}
manufOrderRepo.save(manufOrder);
manufOrder.setPlannedEndDateT(manufOrderWorkflowService.computePlannedEndDateT(manufOrder));
if(!manufOrder.getIsConsProOnOperation()) {
this.createToConsumeProdProductList(manufOrder);
}
this.createToProduceProdProductList(manufOrder);
manufOrderRepo.save(manufOrder);
}
public List<ProdProcessLine> _sortProdProcessLineByPriority(List<ProdProcessLine> prodProcessLineList){
Collections.sort(prodProcessLineList, new Comparator<ProdProcessLine>() {
@Override
public int compare(ProdProcessLine ppl1, ProdProcessLine ppl2) {
return ppl1.getPriority().compareTo(ppl2.getPriority());
}
});
return prodProcessLineList;
}
@Override
public String getManufOrderSeq() throws AxelorException {
String seq = sequenceService.getSequenceNumber(IAdministration.MANUF_ORDER);
if (seq == null) {
throw new AxelorException(IException.CONFIGURATION_ERROR, I18n.get(IExceptionMessage.MANUF_ORDER_SEQ));
}
return seq;
}
@Override
public boolean isManagedConsumedProduct(BillOfMaterial billOfMaterial) {
if(billOfMaterial != null && billOfMaterial.getProdProcess() != null && billOfMaterial.getProdProcess().getProdProcessLineList() != null) {
for(ProdProcessLine prodProcessLine : billOfMaterial.getProdProcess().getProdProcessLineList()) {
if((prodProcessLine.getToConsumeProdProductList() != null && !prodProcessLine.getToConsumeProdProductList().isEmpty())) {
return true;
}
}
}
return false;
}
public BillOfMaterial getBillOfMaterial(Product product) throws AxelorException {
BillOfMaterial billOfMaterial = product.getDefaultBillOfMaterial();
if (billOfMaterial == null && product.getParentProduct() != null) {
billOfMaterial = product.getParentProduct().getDefaultBillOfMaterial();
}
if (billOfMaterial == null) {
throw new AxelorException(product, IException.CONFIGURATION_ERROR, I18n.get(IExceptionMessage.PRODUCTION_ORDER_SALES_ORDER_NO_BOM), product.getName(), product.getCode());
}
return billOfMaterial;
}
@Override
public BigDecimal getProducedQuantity(ManufOrder manufOrder) {
for (StockMoveLine stockMoveLine : manufOrder.getProducedStockMoveLineList()) {
if(stockMoveLine.getProduct().equals(manufOrder.getProduct())) {
return stockMoveLine.getRealQty();
}
}
return BigDecimal.ZERO;
}
@Override
@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public StockMove generateWasteStockMove(ManufOrder manufOrder) throws AxelorException {
StockMove wasteStockMove = null;
Company company = manufOrder.getCompany();
if (manufOrder.getWasteProdProductList() == null || company == null || manufOrder.getWasteProdProductList().isEmpty()) {
return wasteStockMove;
}
StockConfigProductionService stockConfigService = Beans.get(StockConfigProductionService.class);
StockMoveService stockMoveService = Beans.get(StockMoveService.class);
StockMoveLineService stockMoveLineService = Beans.get(StockMoveLineService.class);
AppBaseService appBaseService = Beans.get(AppBaseService.class);
StockConfig stockConfig = stockConfigService.getStockConfig(company);
StockLocation virtualStockLocation = stockConfigService.getProductionVirtualStockLocation(stockConfig);
StockLocation wasteStockLocation = stockConfigService.getWasteStockLocation(stockConfig);
wasteStockMove = stockMoveService.createStockMove(virtualStockLocation.getAddress(), wasteStockLocation.getAddress(),
company, company.getPartner(), virtualStockLocation, wasteStockLocation, null, appBaseService.getTodayDate(),
manufOrder.getWasteProdDescription(), null, null);
for (ProdProduct prodProduct : manufOrder.getWasteProdProductList()) {
StockMoveLine stockMoveLine = stockMoveLineService.createStockMoveLine(
prodProduct.getProduct(),
prodProduct.getProduct().getName(),
prodProduct.getProduct().getDescription(),
prodProduct.getQty(),
prodProduct.getProduct().getCostPrice(),
prodProduct.getUnit(),
wasteStockMove,
StockMoveLineService.TYPE_WASTE_PRODUCTIONS,
false,
BigDecimal.ZERO);
wasteStockMove.addStockMoveLineListItem(stockMoveLine);
}
stockMoveService.validate(wasteStockMove);
manufOrder.setWasteStockMove(wasteStockMove);
return wasteStockMove;
}
@Transactional
public ManufOrder updateQty(ManufOrder manufOrder) {
manufOrder.clearToConsumeProdProductList();
manufOrder.clearToProduceProdProductList();
this.createToConsumeProdProductList(manufOrder);
this.createToProduceProdProductList(manufOrder);
manufOrderRepo.save(manufOrder);
return manufOrder;
}
public ManufOrder updateDiffProdProductList(ManufOrder manufOrder) throws AxelorException {
List<ProdProduct> toConsumeList = manufOrder.getToConsumeProdProductList();
List<StockMoveLine> consumedList = manufOrder.getConsumedStockMoveLineList();
if (toConsumeList == null || consumedList == null) {
return manufOrder;
}
List<ProdProduct> diffConsumeList = createDiffProdProductList(manufOrder, toConsumeList, consumedList);
manufOrder.setDiffConsumeProdProductList(diffConsumeList);
return manufOrder;
}
public List<ProdProduct> createDiffProdProductList(ManufOrder manufOrder, List<ProdProduct> prodProductList, List<StockMoveLine> stockMoveLineList) throws AxelorException {
List<ProdProduct> diffConsumeList = new ArrayList<>();
for (ProdProduct prodProduct : prodProductList) {
Product product = prodProduct.getProduct();
Unit newUnit = prodProduct.getUnit();
List<StockMoveLine> stockMoveLineProductList = stockMoveLineList.stream()
.filter(stockMoveLine1 -> stockMoveLine1.getProduct() != null)
.filter(stockMoveLine1 -> stockMoveLine1.getProduct().equals(product))
.collect(Collectors.toList());
if (stockMoveLineProductList.isEmpty()) {
continue;
}
BigDecimal diffQty = computeDiffQty(prodProduct, stockMoveLineProductList, product);
if (diffQty.compareTo(BigDecimal.ZERO) != 0) {
ProdProduct diffProdProduct = new ProdProduct();
diffProdProduct.setQty(diffQty);
diffProdProduct.setProduct(product);
diffProdProduct.setUnit(newUnit);
diffProdProduct.setDiffConsumeManufOrder(manufOrder);
diffConsumeList.add(diffProdProduct);
}
}
return diffConsumeList;
}
/**
* Compute the difference in qty between a prodProduct and the qty in a list
* of stock move lines.
* @param prodProduct
* @param stockMoveLineList
* @param product
* @return
* @throws AxelorException
*/
protected BigDecimal computeDiffQty(ProdProduct prodProduct, List<StockMoveLine> stockMoveLineList, Product product) throws AxelorException {
BigDecimal consumedQty = BigDecimal.ZERO;
for (StockMoveLine stockMoveLine : stockMoveLineList) {
if (stockMoveLine.getUnit() != null && prodProduct.getUnit() != null) {
consumedQty = consumedQty.add(Beans.get(UnitConversionService.class)
.convertWithProduct(stockMoveLine.getUnit(), prodProduct.getUnit(), stockMoveLine.getQty(), product)
);
} else {
consumedQty = consumedQty.add(stockMoveLine.getQty());
}
}
return consumedQty.subtract(prodProduct.getQty());
}
} |
package com.shc.silenceengine.backend.android;
import android.content.pm.ActivityInfo;
import android.graphics.Point;
import android.opengl.GLSurfaceView;
import android.os.SystemClock;
import com.shc.silenceengine.core.SilenceEngine;
import com.shc.silenceengine.io.FilePath;
/**
* @author Sri Harsha Chilakapati
*/
public class AndroidDisplayDevice implements com.shc.silenceengine.core.IDisplayDevice
{
public GLSurfaceView surfaceView;
public AndroidLauncher activity;
private double startTime;
public AndroidDisplayDevice()
{
this.startTime = SystemClock.elapsedRealtimeNanos();
this.activity = AndroidLauncher.instance;
this.surfaceView = activity.surfaceView;
}
@Override
public SilenceEngine.Platform getPlatform()
{
return SilenceEngine.Platform.ANDROID;
}
@Override
public void setSize(int width, int height)
{
if (width > height)
activity.runOnUiThread(() ->
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE));
else
activity.runOnUiThread(() ->
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT));
}
@Override
public boolean isFullscreen()
{
return true;
}
@Override
public void setFullscreen(boolean fullscreen)
{
}
@Override
public void centerOnScreen()
{
}
@Override
public void setPosition(int x, int y)
{
}
@Override
public int getWidth()
{
Point point = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(point);
return point.x;
}
@Override
public int getHeight()
{
Point point = new Point();
activity.getWindowManager().getDefaultDisplay().getSize(point);
return point.y;
}
@Override
public String getTitle()
{
return "";
}
@Override
public void setTitle(String title)
{
}
@Override
public void setIcon(FilePath filePath)
{
}
@Override
public void close()
{
}
@Override
public double nanoTime()
{
return SystemClock.elapsedRealtimeNanos() - startTime;
}
@Override
public void setVSync(boolean vSync)
{
}
@Override
public boolean hasFocus()
{
return true;
}
} |
package de.tudresden.inf.lat.born.owlapi.processor;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import de.tudresden.inf.lat.born.core.rule.BR1Rule;
import de.tudresden.inf.lat.born.core.rule.BR2Rule;
import de.tudresden.inf.lat.born.core.rule.BR3Rule;
import de.tudresden.inf.lat.born.core.rule.CR1Rule;
import de.tudresden.inf.lat.born.core.rule.CR2Rule;
import de.tudresden.inf.lat.born.core.rule.CR3Rule;
import de.tudresden.inf.lat.born.core.rule.CR4Rule;
import de.tudresden.inf.lat.born.core.rule.CompletionRule;
import de.tudresden.inf.lat.born.core.rule.FR1Rule;
import de.tudresden.inf.lat.born.core.rule.FR2Rule;
import de.tudresden.inf.lat.born.core.rule.FR3Rule;
import de.tudresden.inf.lat.born.core.rule.FormulaConstructor;
import de.tudresden.inf.lat.born.core.rule.RR1Rule;
import de.tudresden.inf.lat.born.core.rule.RR2Rule;
import de.tudresden.inf.lat.born.core.rule.TR1Rule;
import de.tudresden.inf.lat.born.core.rule.TR2Rule;
import de.tudresden.inf.lat.born.core.rule.TR3Rule;
import de.tudresden.inf.lat.born.core.term.Clause;
import de.tudresden.inf.lat.born.core.term.Symbol;
import de.tudresden.inf.lat.born.module.DefaultModuleExtractor;
import de.tudresden.inf.lat.born.module.Module;
import de.tudresden.inf.lat.born.problog.parser.Token;
import de.tudresden.inf.lat.born.problog.parser.TokenCreator;
import de.tudresden.inf.lat.born.problog.parser.TokenType;
import de.tudresden.inf.lat.born.problog.type.ProblogProgram;
import de.tudresden.inf.lat.jcel.coreontology.axiom.NominalAxiom;
import de.tudresden.inf.lat.jcel.coreontology.axiom.NormalizedIntegerAxiom;
import de.tudresden.inf.lat.jcel.coreontology.datatype.IntegerEntityManager;
import de.tudresden.inf.lat.jcel.coreontology.datatype.IntegerEntityType;
import de.tudresden.inf.lat.jcel.ontology.axiom.complex.ComplexIntegerAxiom;
import de.tudresden.inf.lat.jcel.ontology.axiom.extension.IntegerOntologyObjectFactory;
import de.tudresden.inf.lat.jcel.ontology.axiom.extension.IntegerOntologyObjectFactoryImpl;
import de.tudresden.inf.lat.jcel.ontology.normalization.OntologyNormalizer;
import de.tudresden.inf.lat.jcel.owlapi.translator.Translator;
/**
*
* @author Julian Mendez
*
*/
public class ProblogInputCreator {
private static final Logger logger = Logger.getLogger(ProblogInputCreator.class.getName());
private static final String NUMBER_OF_OWL_AXIOMS_MSG = " Number of OWL axioms: ";
private static final String NUMBER_OF_AXIOMS_MSG = " Number of axioms: ";
private static final String NUMBER_OF_NORM_AXIOMS_MSG = " Number of normalized axioms: ";
private static final String NUMBER_OF_AXIOMS_IN_MODULE = " Number of axioms in module: ";
Set<String> parseRelevantSymbols(Reader reader) throws IOException {
Objects.requireNonNull(reader);
TokenCreator c = new TokenCreator();
List<Token> tokens = c.createTokens(reader);
List<String> list = tokens.stream()
.filter(token -> (token.getType().equals(TokenType.IDENTIFIER)
|| token.getType().equals(TokenType.CONSTANT)))
.map(token -> token.getValue()).collect(Collectors.toList());
Set<String> set = new TreeSet<>();
if (list.get(0).equals(FormulaConstructor.QUERY)) {
list.remove(FormulaConstructor.QUERY);
if (list.get(0).equals(FormulaConstructor.SUB)) {
list.remove(FormulaConstructor.SUB);
if (!list.isEmpty()) {
set.add(list.iterator().next());
}
} else if (list.get(0).equals(FormulaConstructor.INST)) {
list.remove(FormulaConstructor.INST);
if (list.size() > 2) {
set.add(list.get(1));
} else if (list.size() > 1) {
set.add(list.get(0));
}
}
}
return set;
}
public List<CompletionRule> getDefaultCompletionRules() {
List<CompletionRule> completionRules = new ArrayList<>();
completionRules.add(new FR1Rule());
completionRules.add(new FR2Rule());
completionRules.add(new FR3Rule());
completionRules.add(new RR1Rule());
completionRules.add(new RR2Rule());
completionRules.add(new BR1Rule());
completionRules.add(new BR2Rule());
completionRules.add(new BR3Rule());
completionRules.add(new CR1Rule());
completionRules.add(new CR2Rule());
completionRules.add(new CR3Rule());
completionRules.add(new CR4Rule());
completionRules.add(new TR1Rule());
completionRules.add(new TR2Rule());
completionRules.add(new TR3Rule());
return completionRules;
}
void write(Writer output, ProblogProgram program) throws IOException {
Objects.requireNonNull(output);
Objects.requireNonNull(program);
BufferedWriter writer = new BufferedWriter(output);
writer.write(program.asString());
writer.flush();
writer.close();
}
List<Clause> getDeclarations(IntegerOntologyObjectFactory factory, Module module) {
Objects.requireNonNull(factory);
Objects.requireNonNull(module);
List<Clause> ret = new ArrayList<>();
AxiomRenderer renderer = new AxiomRenderer(factory);
Set<Integer> classes = new TreeSet<>();
Set<Integer> objectProperties = new TreeSet<>();
Set<Integer> individuals = new TreeSet<>();
Set<Integer> entities = module.getEntities();
entities.forEach(entity -> {
if (factory.getEntityManager().getType(entity).equals(IntegerEntityType.INDIVIDUAL)) {
individuals.add(entity);
} else if (factory.getEntityManager().getType(entity).equals(IntegerEntityType.CLASS)) {
classes.add(entity);
} else if (factory.getEntityManager().getType(entity).equals(IntegerEntityType.OBJECT_PROPERTY)) {
objectProperties.add(entity);
} else {
throw new IllegalStateException("Entity of unknown type: '" + entity + "'.");
}
});
module.getAxioms().forEach(axiom -> {
// classes.addAll(axiom.getClassesInSignature());
objectProperties.addAll(axiom.getObjectPropertiesInSignature());
// individuals.addAll(axiom.getIndividualsInSignature());
});
classes.forEach(cls -> ret.add(renderer.renderDeclarationOfClass(cls)));
objectProperties.forEach(objectProperty -> ret.add(renderer.renderDeclarationOfObjectProperty(objectProperty)));
individuals.forEach(individual -> ret.add(renderer.renderDeclarationOfIndividual(individual)));
return ret;
}
List<Clause> getClauses(IntegerOntologyObjectFactory factory, Module module) throws IOException {
Objects.requireNonNull(factory);
Objects.requireNonNull(module);
List<Clause> ontology = new ArrayList<>();
AxiomRenderer renderer = new AxiomRenderer(factory);
ontology.addAll(getDeclarations(factory, module));
module.getAxioms().forEach(axiom -> {
Clause clause = axiom.accept(renderer);
ontology.add(clause);
});
return ontology;
}
String removeApostrophes(String symbolStr0) {
String symbolStr = symbolStr0;
if (symbolStr.startsWith("" + Symbol.APOSTROPHE_CHAR) && symbolStr.endsWith("" + Symbol.APOSTROPHE_CHAR)) {
symbolStr = symbolStr.substring(1);
symbolStr = symbolStr.substring(0, symbolStr.length() - 1);
return symbolStr;
} else {
return symbolStr0;
}
}
Integer getId(Map<String, Integer> map, String symbolStr0) {
String symbolStr = removeApostrophes(symbolStr0);
if (symbolStr.equals(FormulaConstructor.TOP)) {
return IntegerEntityManager.topClassId;
} else {
return map.get(symbolStr);
}
}
public Set<Integer> getSetOfEntities(IntegerOntologyObjectFactory factory, Set<String> symbolStrSet) {
Objects.requireNonNull(factory);
Objects.requireNonNull(symbolStrSet);
Map<String, Integer> map = new TreeMap<>();
factory.getEntityManager().getEntities(IntegerEntityType.CLASS, false)
.forEach(id -> map.put(factory.getEntityManager().getName(id), id));
factory.getEntityManager().getEntities(IntegerEntityType.INDIVIDUAL, false)
.forEach(id -> map.put(factory.getEntityManager().getName(id), id));
Set<Integer> ret = new TreeSet<>();
symbolStrSet.forEach(symbolStr -> {
Integer id = getId(map, symbolStr);
if (Objects.nonNull(id)) {
ret.add(id);
}
});
return ret;
}
Set<NormalizedIntegerAxiom> removeUnnecessaryAnnotations(Set<NormalizedIntegerAxiom> axioms,
IntegerOntologyObjectFactory factory) {
Set<NormalizedIntegerAxiom> ret = new HashSet<NormalizedIntegerAxiom>();
axioms.forEach(axiom -> {
if (axiom instanceof NominalAxiom) {
NominalAxiom nominalAxiom = (NominalAxiom) axiom;
ret.add(factory.getNormalizedAxiomFactory().createNominalAxiom(nominalAxiom.getClassExpression(),
nominalAxiom.getIndividual(), new HashSet<>()));
} else {
ret.add(axiom);
}
});
return ret;
}
public String createProblogFile(boolean useOfDefaultCompletionRules, String additionalCompletionRules,
OWLOntology owlOntology, String bayesianNetwork, String query, OutputStream resultOutputStream,
ProcessorExecutionResult executionResult) throws IOException, OWLOntologyCreationException {
Objects.requireNonNull(additionalCompletionRules);
Objects.requireNonNull(owlOntology);
Objects.requireNonNull(bayesianNetwork);
Objects.requireNonNull(query);
Objects.requireNonNull(resultOutputStream);
StringBuffer sbuf = new StringBuffer();
sbuf.append(Symbol.NEW_LINE_CHAR);
sbuf.append(NUMBER_OF_OWL_AXIOMS_MSG + owlOntology.getAxiomCount());
sbuf.append(Symbol.NEW_LINE_CHAR);
ProblogProgram program = new ProblogProgram();
program.setQueryListAddendum(query);
Set<String> relevantSymbols = parseRelevantSymbols(new StringReader(query));
IntegerOntologyObjectFactory factory = new IntegerOntologyObjectFactoryImpl();
long translationStart = System.nanoTime();
logger.fine("OWL Axioms: " + owlOntology.getAxioms());
Translator translator = new Translator(owlOntology.getOWLOntologyManager().getOWLDataFactory(), factory);
Set<ComplexIntegerAxiom> axioms = translator.translateSA(owlOntology.getAxioms());
logger.fine("Integer Axioms: " + axioms);
executionResult.setTranslationTime(System.nanoTime() - translationStart);
executionResult.setOntologySize(axioms.size());
sbuf.append(NUMBER_OF_AXIOMS_MSG + axioms.size());
sbuf.append(Symbol.NEW_LINE_CHAR);
long normalizationStart = System.nanoTime();
OntologyNormalizer normalizer = new OntologyNormalizer();
Set<NormalizedIntegerAxiom> normalizedAxioms = removeUnnecessaryAnnotations(
normalizer.normalize(axioms, factory), factory);
logger.fine("Normalized Axioms: " + normalizedAxioms);
executionResult.setNormalizationTime(System.nanoTime() - normalizationStart);
executionResult.setNormalizedOntologySize(normalizedAxioms.size());
sbuf.append(NUMBER_OF_NORM_AXIOMS_MSG + normalizedAxioms.size());
sbuf.append(Symbol.NEW_LINE_CHAR);
long moduleExtractionStart = System.nanoTime();
DefaultModuleExtractor moduleExtractor = new DefaultModuleExtractor();
Set<Integer> setOfEntities = getSetOfEntities(factory, relevantSymbols);
Set<Integer> setOfClasses = new TreeSet<>();
setOfEntities.forEach(entity -> {
if (factory.getEntityManager().getType(entity).equals(IntegerEntityType.CLASS)) {
setOfClasses.add(entity);
} else if (factory.getEntityManager().getType(entity).equals(IntegerEntityType.INDIVIDUAL)) {
setOfClasses.add(entity);
Optional<Integer> classForIndivOpt = factory.getEntityManager().getAuxiliaryNominal(entity);
if (classForIndivOpt.isPresent()) {
setOfClasses.add(classForIndivOpt.get());
}
}
});
Module module = moduleExtractor.extractModule(normalizedAxioms, setOfClasses);
logger.fine("Module entities: " + module.getEntities());
logger.fine("Module axioms: " + module.getAxioms());
executionResult.setModuleExtractionTime(System.nanoTime() - moduleExtractionStart);
executionResult.setModuleSize(module.getAxioms().size());
sbuf.append(NUMBER_OF_AXIOMS_IN_MODULE + module.getAxioms().size());
sbuf.append(Symbol.NEW_LINE_CHAR);
List<Clause> clauses = getClauses(factory, module);
program.setOntology(clauses);
logger.fine("Clauses: " + program.getClauses());
if (useOfDefaultCompletionRules) {
program.setCompletionRules(getDefaultCompletionRules());
} else {
program.setCompletionRules(Collections.emptyList());
}
logger.fine("Completion Rules: " + program.getCompletionRules());
program.setAdditionalCompletionRulesAsText(additionalCompletionRules);
logger.fine("Additional Completion Rules: " + program.getAdditionalCompletionRulesAsText());
program.setBayesianNetworkAddendum(bayesianNetwork);
logger.fine("Bayesian Network: " + program.getBayesianNetworkAddendum());
write(new OutputStreamWriter(resultOutputStream), program);
return sbuf.toString();
}
} |
package com.sachin.risk.common.data.mobile;
import com.google.common.base.Splitter;
import com.sachin.risk.common.data.Constants;
import com.sachin.risk.common.data.HttpClientHolder;
import com.sachin.risk.common.data.Resolver;
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.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
/**
* @author shicheng.zhang
* @date 17-3-28
* @time 3:50
* @Description:
*/
public class MobileIp138Resolver implements Resolver<MobileInfo> {
private static final String API_URL = "http:
private static final Logger logger = LoggerFactory.getLogger(MobileIp138Resolver.class);
private static final Splitter splitter = Splitter.on("|").trimResults().omitEmptyStrings();
private static final String NOT_KNOWN = "";
@Override
public MobileInfo resolve(String param) {
HttpClient httpClient = HttpClientHolder.getHttpClient();
HttpGet httpget = new HttpGet(API_URL + param);
try {
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
String gbkHtml = EntityUtils.toString(entity, "gb2312");
Document document = Jsoup.parse(gbkHtml);
Elements tables = document.getElementsByTag("table");
if (tables.size() <= 0) {
return null;
}
Element resultTable = null;
for (Element table : tables) {
if (table.text().contains("")) {
resultTable = table;
break;
}
}
if (resultTable == null) {
return null;
}
Elements trs = resultTable.getElementsByTag("tr");
if (trs.size() <= 0) {
return null;
}
MobileInfo mobileInfo = new MobileInfo();
mobileInfo.setPrefix(param.substring(0, 7));
for (Element tr : trs) {
Elements tds = tr.getElementsByTag("td");
if (tds.size() != 2) {
continue;
}
String title = trimString(tds.get(0).text());
if ("".equals(title)) {
String value = tds.get(1).text().replaceAll("[\\u00A0]+", "|");
if (value.contains(NOT_KNOWN)) {
return null;
}
List<String> values = splitter.splitToList(value);
if (values.size() >= 1) {
mobileInfo.setProvince(values.get(0));
if (values.size() >= 2) {
if (values.get(1).endsWith("")) {
mobileInfo.setCity(values.get(1).substring(0, values.get(1).length() - 1));
} else {
mobileInfo.setCity(values.get(1));
}
}
}
} else if ("".equals(title)) {
String value = tds.get(1).text().replaceAll("[\\u00A0]+", " ");
if (value.contains(NOT_KNOWN)) {
continue;
}
mobileInfo.setCard(value);
mobileInfo.setSp(value);
}
}
if (mobileInfo.getProvince() != null && mobileInfo.getProvince().length() > 0) {
mobileInfo.setSource(Constants.IP138);
return mobileInfo;
}
} catch (Exception e) {
logger.error("resolve mobile info from ip138 error. param: {}", param, e);
}
return null;
}
private String trimString(String s) {
if (s == null) {
return null;
}
return s.trim().replace(" ", "").replaceAll("[\\u00A0]+", "");
}
} |
package com.yahoo.vespa.config.server.metrics;
import ai.vespa.util.http.VespaHttpClientBuilder;
import com.yahoo.log.LogLevel;
import com.yahoo.slime.ArrayTraverser;
import com.yahoo.slime.Inspector;
import com.yahoo.slime.Slime;
import com.yahoo.vespa.config.SlimeUtils;
import com.yahoo.yolean.Exceptions;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
* Client for reaching out to nodes in an application instance and get their
* metrics.
*
* @author olaa
* @author ogronnesby
*/
public class ClusterMetricsRetriever {
private static final Logger log = Logger.getLogger(ClusterMetricsRetriever.class.getName());
private static final String VESPA_CONTAINER = "vespa.container";
private static final String VESPA_QRSERVER = "vespa.qrserver";
private static final String VESPA_DISTRIBUTOR = "vespa.distributor";
private static final List<String> WANTED_METRIC_SERVICES = List.of(VESPA_CONTAINER, VESPA_QRSERVER, VESPA_DISTRIBUTOR);
private static final CloseableHttpClient httpClient = VespaHttpClientBuilder.create()
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(10 * 1000)
.setSocketTimeout(10 * 1000)
.build())
.build();
/**
* Call the metrics API on each host and aggregate the metrics
* into a single value, grouped by cluster.
*/
public Map<ClusterInfo, MetricsAggregator> requestMetricsGroupedByCluster(Collection<URI> hosts) {
Map<ClusterInfo, MetricsAggregator> clusterMetricsMap = new ConcurrentHashMap<>();
long startTime = System.currentTimeMillis();
Runnable retrieveMetricsJob = () ->
hosts.parallelStream().forEach(host ->
getHostMetrics(host, clusterMetricsMap)
);
ForkJoinPool threadPool = new ForkJoinPool(5);
threadPool.submit(retrieveMetricsJob);
threadPool.shutdown();
try {
threadPool.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.log(LogLevel.DEBUG, () ->
String.format("Metric retrieval for %d nodes took %d milliseconds", hosts.size(), System.currentTimeMillis() - startTime)
);
return clusterMetricsMap;
}
private static void getHostMetrics(URI hostURI, Map<ClusterInfo, MetricsAggregator> clusterMetricsMap) {
Slime responseBody = doMetricsRequest(hostURI);
var parseError = responseBody.get().field("error_message");
if (parseError.valid()) {
log.info("Failed to retrieve metrics from " + hostURI + ": " + parseError.asString());
}
Inspector services = responseBody.get().field("services");
services.traverse((ArrayTraverser) (i, servicesInspector) ->
parseService(servicesInspector, clusterMetricsMap)
);
}
private static Slime doMetricsRequest(URI hostURI) {
HttpGet get = new HttpGet(hostURI);
try (CloseableHttpResponse response = httpClient.execute(get)) {
InputStream is = response.getEntity().getContent();
Slime slime = SlimeUtils.jsonToSlime(is.readAllBytes());
is.close();
return slime;
} catch (IOException e) {
// Usually caused by applications being deleted during metric retrieval
log.warning("Was unable to fetch metrics from " + hostURI + " : " + Exceptions.toMessageString(e));
return new Slime();
}
}
private static void parseService(Inspector service, Map<ClusterInfo, MetricsAggregator> clusterMetricsMap) {
String serviceName = service.field("name").asString();
service.field("metrics").traverse((ArrayTraverser) (i, metric) ->
addMetricsToAggeregator(serviceName, metric, clusterMetricsMap)
);
}
private static void addMetricsToAggeregator(String serviceName, Inspector metric, Map<ClusterInfo, MetricsAggregator> clusterMetricsMap) {
if (!WANTED_METRIC_SERVICES.contains(serviceName)) return;
Inspector values = metric.field("values");
ClusterInfo clusterInfo = getClusterInfoFromDimensions(metric.field("dimensions"));
MetricsAggregator metricsAggregator = clusterMetricsMap.computeIfAbsent(clusterInfo, c -> new MetricsAggregator());
switch (serviceName) {
case "vespa.container":
metricsAggregator.addContainerLatency(
values.field("query_latency.sum").asDouble(),
values.field("query_latency.count").asDouble());
metricsAggregator.addFeedLatency(
values.field("feed.latency.sum").asDouble(),
values.field("feed.latency.count").asDouble());
break;
case "vespa.qrserver":
metricsAggregator.addQrLatency(
values.field("query_latency.sum").asDouble(),
values.field("query_latency.count").asDouble());
break;
case "vespa.distributor":
metricsAggregator.addDocumentCount(values.field("vds.distributor.docsstored.average").asDouble());
break;
}
}
private static ClusterInfo getClusterInfoFromDimensions(Inspector dimensions) {
return new ClusterInfo(dimensions.field("clusterid").asString(), dimensions.field("clustertype").asString());
}
} |
package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.sql.parser.OInteger;
import com.orientechnologies.orient.core.sql.parser.OTraverseProjectionItem;
import com.orientechnologies.orient.core.sql.parser.OWhereClause;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class DepthFirstTraverseStep extends AbstractTraverseStep {
public DepthFirstTraverseStep(List<OTraverseProjectionItem> projections, OWhereClause whileClause, OInteger maxDepth,
OCommandContext ctx, boolean profilingEnabled) {
super(projections, whileClause, maxDepth, ctx, profilingEnabled);
}
@Override
protected void fetchNextEntryPoints(OCommandContext ctx, int nRecords) {
OResultSet nextN = getPrev().get().syncPull(ctx, nRecords);
while (nextN.hasNext()) {
OResult item = toTraverseResult(nextN.next());
if (item == null) {
continue;
}
((OResultInternal) item).setMetadata("$depth", 0);
List stack = new ArrayList();
item.getIdentity().ifPresent(x -> stack.add(x));
((OResultInternal) item).setMetadata("$stack", stack);
List<OIdentifiable> path = new ArrayList<>();
if (item.getIdentity().isPresent()) {
path.add(item.getIdentity().get());
} else if (item.getProperty("@rid") != null) {
path.add(item.getProperty("@rid"));
}
((OResultInternal) item).setMetadata("$path", path);
if (item.isElement() && !traversed.contains(item.getElement().get().getIdentity())) {
tryAddEntryPointAtTheEnd(item, ctx);
traversed.add(item.getElement().get().getIdentity());
} else if (item.getProperty("@rid") != null && item.getProperty("@rid") instanceof OIdentifiable) {
tryAddEntryPointAtTheEnd(item, ctx);
traversed.add(((OIdentifiable) item.getProperty("@rid")).getIdentity());
}
}
}
private OResult toTraverseResult(OResult item) {
OTraverseResult res = null;
if (item instanceof OTraverseResult) {
res = (OTraverseResult) item;
} else if (item.isElement() && item.getElement().get().getIdentity().isPersistent()) {
res = new OTraverseResult();
res.setElement(item.getElement().get());
res.depth = 0;
} else if (item.getPropertyNames().size() == 1) {
Object val = item.getProperty(item.getPropertyNames().iterator().next());
if (val instanceof OIdentifiable) {
res = new OTraverseResult();
res.setElement((OIdentifiable) val);
res.depth = 0;
res.setMetadata("$depth", 0);
}
} else {
res = new OTraverseResult();
for (String key : item.getPropertyNames()) {
res.setProperty(key, item.getProperty(key));
}
for (String md : item.getMetadataKeys()) {
res.setMetadata(md, item.getMetadata(md));
}
}
return res;
}
@Override
protected void fetchNextResults(OCommandContext ctx, int nRecords) {
if (!this.entryPoints.isEmpty()) {
OTraverseResult item = (OTraverseResult) this.entryPoints.remove(0);
this.results.add(item);
for (OTraverseProjectionItem proj : projections) {
Object nextStep = proj.execute(item, ctx);
Integer depth = item.depth != null ? item.depth : (Integer) item.getMetadata("$depth");
if (this.maxDepth == null || this.maxDepth.getValue().intValue() > depth) {
addNextEntryPoints(nextStep, depth + 1, (List) item.getMetadata("$path"), (List) item.getMetadata("$stack"), ctx);
}
}
}
}
private void addNextEntryPoints(Object nextStep, int depth, List<OIdentifiable> path, List<OIdentifiable> stack,
OCommandContext ctx) {
if (nextStep instanceof OIdentifiable) {
addNextEntryPoint(((OIdentifiable) nextStep), depth, path, stack, ctx);
} else if (nextStep instanceof Iterable) {
addNextEntryPoints(((Iterable) nextStep).iterator(), depth, path, stack, ctx);
} else if (nextStep instanceof OResult) {
addNextEntryPoint(((OResult) nextStep), depth, path, stack, ctx);
}
}
private void addNextEntryPoints(Iterator nextStep, int depth, List<OIdentifiable> path, List<OIdentifiable> stack,
OCommandContext ctx) {
while (nextStep.hasNext()) {
addNextEntryPoints(nextStep.next(), depth, path, stack, ctx);
}
}
private void addNextEntryPoint(OIdentifiable nextStep, int depth, List<OIdentifiable> path, List<OIdentifiable> stack,
OCommandContext ctx) {
if (this.traversed.contains(nextStep.getIdentity())) {
return;
}
OTraverseResult res = new OTraverseResult();
res.setElement(nextStep);
res.depth = depth;
res.setMetadata("$depth", depth);
List<OIdentifiable> newPath = new ArrayList<>(path);
newPath.add(res.getIdentity().get());
res.setMetadata("$path", newPath);
List newStack = new ArrayList();
newStack.add(res.getIdentity().get());
newStack.addAll(stack);
// for (int i = 0; i < newPath.size(); i++) {
// newStack.offerLast(newPath.get(i));
res.setMetadata("$stack", newStack);
tryAddEntryPoint(res, ctx);
}
private void addNextEntryPoint(OResult nextStep, int depth, List<OIdentifiable> path, List<OIdentifiable> stack,
OCommandContext ctx) {
if (!nextStep.isElement()) {
return;
}
if (this.traversed.contains(nextStep.getElement().get().getIdentity())) {
return;
}
if (nextStep instanceof OTraverseResult) {
((OTraverseResult) nextStep).depth = depth;
((OTraverseResult) nextStep).setMetadata("$depth", depth);
List<OIdentifiable> newPath = new ArrayList<>();
newPath.addAll(path);
nextStep.getIdentity().ifPresent(x -> newPath.add(x.getIdentity()));
((OTraverseResult) nextStep).setMetadata("$path", newPath);
List reverseStack = new ArrayList();
reverseStack.addAll(newPath);
Collections.reverse(reverseStack);
List newStack = new ArrayList();
newStack.addAll(reverseStack);
((OTraverseResult) nextStep).setMetadata("$stack", newStack);
tryAddEntryPoint(nextStep, ctx);
} else {
OTraverseResult res = new OTraverseResult();
res.setElement(nextStep.getElement().get());
res.depth = depth;
res.setMetadata("$depth", depth);
List<OIdentifiable> newPath = new ArrayList<>();
newPath.addAll(path);
nextStep.getIdentity().ifPresent(x -> newPath.add(x.getIdentity()));
((OTraverseResult) nextStep).setMetadata("$path", newPath);
List reverseStack = new ArrayList();
reverseStack.addAll(newPath);
Collections.reverse(reverseStack);
List newStack = new ArrayList();
newStack.addAll(reverseStack);
((OTraverseResult) nextStep).setMetadata("$stack", newStack);
tryAddEntryPoint(res, ctx);
}
}
private void tryAddEntryPoint(OResult res, OCommandContext ctx) {
if (whileClause == null || whileClause.matchesFilters(res, ctx)) {
this.entryPoints.add(0, res);
}
if (res.isElement()) {
traversed.add(res.getElement().get().getIdentity());
} else if (res.getProperty("@rid") != null && res.getProperty("@rid") instanceof OIdentifiable) {
traversed.add(((OIdentifiable) res.getProperty("@rid")).getIdentity());
}
}
private void tryAddEntryPointAtTheEnd(OResult res, OCommandContext ctx) {
if (whileClause == null || whileClause.matchesFilters(res, ctx)) {
this.entryPoints.add(res);
}
if (res.isElement()) {
traversed.add(res.getElement().get().getIdentity());
} else if (res.getProperty("@rid") != null && res.getProperty("@rid") instanceof OIdentifiable) {
traversed.add(((OIdentifiable) res.getProperty("@rid")).getIdentity());
}
}
@Override
public String prettyPrint(int depth, int indent) {
String spaces = OExecutionStepInternal.getIndent(depth, indent);
StringBuilder result = new StringBuilder();
result.append(spaces);
result.append("+ DEPTH-FIRST TRAVERSE \n");
result.append(spaces);
result.append(" " + projections.toString());
if (whileClause != null) {
result.append("\n");
result.append(spaces);
result.append("WHILE " + whileClause.toString());
}
return result.toString();
}
} |
package org.limeprotocol.serialization.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.limeprotocol.Document;
import org.limeprotocol.DocumentCollection;
import org.limeprotocol.MediaType;
import org.limeprotocol.serialization.JacksonEnvelopeSerializer;
import org.limeprotocol.serialization.SerializationUtil;
import java.io.IOException;
import java.util.Iterator;
public class DocumentCollectionDeserializer extends JsonDeserializer<DocumentCollection> {
public DocumentCollectionDeserializer() {
}
@Override
public DocumentCollection deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
ObjectCodec objectCodec = jsonParser.getCodec();
ObjectNode objectNode = objectCodec.readTree(jsonParser);
DocumentCollection collection = new DocumentCollection();
MediaType itemType = MediaType.parse(objectNode.get("itemType").asText());
ArrayNode documentsNode = (ArrayNode) objectNode.get("items");
Document[] items = new Document[documentsNode.size()];
int i = 0;
for (Iterator iterator = documentsNode.elements(); iterator.hasNext(); i++) {
ObjectNode documentNode = (ObjectNode) iterator.next();
Document document = DocumentContainerDeserializer.getDocument(documentNode, itemType, JacksonEnvelopeSerializer.getObjectMapper());
items[i] = document;
}
int total = 0;
if (objectNode.has("total")) {
total = objectNode.get("total").asInt();
}
collection.setTotal(total);
collection.setItemType(itemType);
collection.setItems(items);
return collection;
}
} |
package io.cloudslang.content.azure.actions.utils;
import com.hp.oo.sdk.content.annotations.Action;
import com.hp.oo.sdk.content.annotations.Output;
import com.hp.oo.sdk.content.annotations.Param;
import com.hp.oo.sdk.content.annotations.Response;
import io.cloudslang.content.azure.entities.AuthorizationTokenUsingWebAPIInputs;
import io.cloudslang.content.azure.services.AuthenticationTokenUsingWebAPIImpl;
import io.cloudslang.content.constants.ReturnCodes;
import java.util.Map;
import static com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType.COMPARE_EQUAL;
import static com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType.ERROR;
import static com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType.RESOLVED;
import static io.cloudslang.content.azure.utils.AuthorizationInputNames.PROXY_HOST;
import static io.cloudslang.content.azure.utils.AuthorizationInputNames.PROXY_PASSWORD;
import static io.cloudslang.content.azure.utils.AuthorizationInputNames.PROXY_PORT;
import static io.cloudslang.content.azure.utils.AuthorizationInputNames.PROXY_USERNAME;
import static io.cloudslang.content.azure.utils.AuthorizationInputNames.*;
import static io.cloudslang.content.azure.utils.Constants.Common.*;
import static io.cloudslang.content.azure.utils.Constants.DEFAULT_PROXY_PORT;
import static io.cloudslang.content.azure.utils.Constants.DEFAULT_RESOURCE;
import static io.cloudslang.content.azure.utils.Descriptions.Common.*;
import static io.cloudslang.content.azure.utils.HttpUtils.*;
import static io.cloudslang.content.azure.utils.Inputs.CommonInputs.CLIENT_SECRET;
import static io.cloudslang.content.azure.utils.Inputs.CommonInputs.TENANT_ID;
import static io.cloudslang.content.azure.utils.Outputs.CommonOutputs.AUTH_TOKEN;
import static io.cloudslang.content.constants.OutputNames.*;
import static io.cloudslang.content.constants.ResponseNames.FAILURE;
import static io.cloudslang.content.constants.ResponseNames.SUCCESS;
import static io.cloudslang.content.httpclient.entities.HttpClientInputs.*;
import static io.cloudslang.content.utils.OutputUtilities.getFailureResultsMap;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.apache.commons.lang3.StringUtils.defaultIfEmpty;
public class GetAuthTokenUsingWebAPI {
@Action(name = "Get the authorization token for Azure",
outputs = {
@Output(value = RETURN_RESULT, description = RETURN_RESULT_DESC),
@Output(value = EXCEPTION, description = EXCEPTION_DESC),
@Output(value = STATUS_CODE, description = STATUS_CODE_DESC),
@Output(value = AUTH_TOKEN, description = AUTH_TOKEN_DESC),
},
responses = {
@Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED, description = SUCCESS_DESC),
@Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, description = FAILURE_DESC)
})
public Map<String, String> execute(@Param(value = TENANT_ID, required = true, description = TENANT_ID_DESC) String tenantId,
@Param(value = CLIENT_ID, required = true, description = CLIENT_ID_DESC) String clientId,
@Param(value = CLIENT_SECRET, required = true, encrypted = true, description = CLIENT_SECRET_DESC) String clientSecret,
@Param(value = RESOURCE, description = RESOURCE_DESC) String resource,
@Param(value = PROXY_HOST, description = PROXY_HOST_DESC) String proxyHost,
@Param(value = PROXY_PORT, description = PROXY_PORT_DESC) String proxyPort,
@Param(value = PROXY_USERNAME, description = PROXY_USERNAME_DESC) String proxyUsername,
@Param(value = PROXY_PASSWORD, encrypted = true, description = PROXY_PASSWORD_DESC) String proxyPassword,
@Param(value = TRUST_ALL_ROOTS, description = TRUST_ALL_ROOTS_DESC) String trustAllRoots,
@Param(value = X509_HOSTNAME_VERIFIER, description = X509_DESC) String x509HostnameVerifier,
@Param(value = TRUST_KEYSTORE, description = TRUST_KEYSTORE_DESC) String trustKeystore,
@Param(value = TRUST_PASSWORD, encrypted = true, description = TRUST_PASSWORD_DESC) String trustPassword) {
resource = defaultIfEmpty(resource, DEFAULT_RESOURCE);
proxyHost = defaultIfEmpty(proxyHost, EMPTY);
proxyPort = defaultIfEmpty(proxyPort, DEFAULT_PROXY_PORT);
proxyUsername = defaultIfEmpty(proxyUsername, EMPTY);
proxyPassword = defaultIfEmpty(proxyPassword, EMPTY);
trustAllRoots = defaultIfEmpty(trustAllRoots, BOOLEAN_FALSE);
x509HostnameVerifier = defaultIfEmpty(x509HostnameVerifier, STRICT);
trustKeystore = defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE);
trustPassword = defaultIfEmpty(trustPassword, CHANGEIT);
try {
final Map<String, String> result = AuthenticationTokenUsingWebAPIImpl.getAuthToken(AuthorizationTokenUsingWebAPIInputs.builder()
.tenantId(tenantId)
.clientSecret(clientSecret)
.clientId(clientId)
.resource(resource)
.proxyPort(proxyPort)
.proxyHost(proxyHost)
.proxyUsername(proxyUsername)
.proxyPassword(proxyPassword)
.trustAllRoots(trustAllRoots)
.x509HostnameVerifier(x509HostnameVerifier)
.trustKeystore(trustKeystore)
.trustPassword(trustPassword)
.build());
final String returnMessage = result.get(RETURN_RESULT);
final Map<String, String> results = getOperationResults(result, returnMessage, returnMessage, returnMessage);
final int statusCode = Integer.parseInt(result.get(STATUS_CODE));
if (statusCode == 200) {
results.put(AUTH_TOKEN, BEARER + getTokenValue(returnMessage));
} else {
return getFailureResults(tenantId, statusCode, returnMessage);
}
return results;
} catch (Exception exception) {
return getFailureResultsMap(exception);
}
}
} |
//$HeadURL: svn+ssh://lbuesching@svn.wald.intevation.de/deegree/base/trunk/resources/eclipse/files_template.xml $
package org.deegree.tools.jdbc;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.File;
import java.io.StringWriter;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMDocument;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.jaxp.OMResult;
import org.apache.axiom.om.impl.jaxp.OMSource;
import org.deegree.commons.jdbc.ConnectionManager;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.utils.StringUtils;
import org.deegree.commons.xml.CommonNamespaces;
import org.deegree.commons.xml.NamespaceBindings;
import org.deegree.commons.xml.XMLAdapter;
import org.deegree.commons.xml.XPath;
import org.deegree.cs.coordinatesystems.ICRS;
import org.deegree.geometry.Geometry;
import org.deegree.geometry.io.WKBReader;
import org.deegree.gml.GMLVersion;
import org.deegree.gml.geometry.GML3GeometryWriter;
import org.slf4j.Logger;
import com.vividsolutions.jts.io.ParseException;
public class DatabaseXMLMapping {
private static final Logger LOG = getLogger( DatabaseXMLMapping.class );
private static String namespace = "http:
private static NamespaceBindings nsc = CommonNamespaces.getNamespaceContext();
private static final TransformerFactory factory = TransformerFactory.newInstance();
private final OMFactory omFactory = OMAbstractFactory.getOMFactory();
protected Table mainTable;
private String jdbcId;
protected URL xslt;
static {
nsc.addNamespace( "dxm", namespace );
}
/**
*
* @param fileName
* @throws Exception
*/
public DatabaseXMLMapping( File file, String workspaceName ) throws Exception {
readConfig( file );
}
private void readConfig( File file )
throws Exception {
XMLAdapter adapter = new XMLAdapter( file );
// parse database connection info
OMElement rootElement = adapter.getRootElement();
jdbcId = adapter.getRequiredNodeAsString( rootElement, new XPath( "/dxm:XMLMapping/dxm:JDBCID", nsc ) );
// xslt file to transform result of xml mapping
String xsltFileName = adapter.getNodeAsString( rootElement, new XPath( "/dxm:XMLMapping/dxm:XSLT", nsc ), null );
if ( xsltFileName != null ) {
xslt = adapter.resolve( xsltFileName );
}
// parse table relations
String elementName = adapter.getRequiredNodeAsString( rootElement,
new XPath( "/dxm:XMLMapping/dxm:Table/dxm:ElementName",
nsc ) );
String select = adapter.getRequiredNodeAsString( rootElement,
new XPath( "/dxm:XMLMapping/dxm:Table/dxm:Select", nsc ) );
List<Pair<String, String>> geomFieldList = new ArrayList<Pair<String, String>>();
List<OMElement> elements = adapter.getElements( rootElement,
new XPath( "/dxm:XMLMapping/dxm:Table/dxm:GeometryColumn", nsc ) );
for ( OMElement element : elements ) {
String field = adapter.getNodeAsString( element, new XPath( ".", nsc ), null );
String crs = adapter.getNodeAsString( element, new XPath( "@crs", nsc ), null );
Pair<String, String> p = new Pair<String, String>( field, crs );
geomFieldList.add( p );
}
mainTable = new Table( elementName, select, geomFieldList );
List<OMElement> tables = adapter.getElements( rootElement, new XPath( "/dxm:XMLMapping/dxm:Table/dxm:Table",
nsc ) );
for ( OMElement element : tables ) {
parseTable( mainTable, element );
}
}
/**
* @param table
* @param element
*/
private void parseTable( Table table, OMElement element )
throws Exception {
XMLAdapter adapter = new XMLAdapter();
String elementName = adapter.getRequiredNodeAsString( element, new XPath( "dxm:ElementName", nsc ) );
String select = adapter.getRequiredNodeAsString( element, new XPath( "dxm:Select", nsc ) );
List<Pair<String, String>> geomFieldList = new ArrayList<Pair<String, String>>();
List<OMElement> elements = adapter.getElements( element, new XPath( "dxm:GeometryColumn", nsc ) );
for ( OMElement elem : elements ) {
String field = adapter.getNodeAsString( elem, new XPath( ".", nsc ), null );
String crs = adapter.getNodeAsString( elem, new XPath( "@crs", nsc ), null );
Pair<String, String> p = new Pair<String, String>( field, crs );
geomFieldList.add( p );
}
Table subTable = new Table( elementName, select, geomFieldList );
table.getTables().add( subTable );
List<OMElement> tables = adapter.getElements( element, new XPath( "dxm:Table", nsc ) );
for ( OMElement subEelement : tables ) {
parseTable( subTable, subEelement );
}
}
public void run()
throws Exception {
Connection conn = ConnectionManager.getConnection( jdbcId );
Statement stmt = null;
ResultSet rs = null;
try {
String sql = mainTable.getSelect();
stmt = conn.createStatement();
rs = stmt.executeQuery( sql );
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
Map<String, Object> row = new LinkedHashMap<String, Object>();
while ( rs.next() ) {
// create one XML document for each row of the main table
OMDocument result = omFactory.createOMDocument();
OMElement dbTable = omFactory.createOMElement( new QName( "DatabaseTable" ) );
result.addChild( dbTable );
// result.load( new StringReader( "<DatabaseTable/>" ), XMLFragment.DEFAULT_URL );
// append root table element
// Element tableElement = XMLTools.appendElement( result.getRootElement(), null, mainTable.getName() );
OMElement tableElement = omFactory.createOMElement( new QName( mainTable.getName() ) );
dbTable.addChild( tableElement );
for ( int i = 0; i < colCount; i++ ) {
String cName = rsmd.getColumnName( i + 1 ).toLowerCase();
Object value = rs.getObject( i + 1 );
row.put( cName, value );
OMElement cNameElement = omFactory.createOMElement( new QName( cName ) );
tableElement.addChild( cNameElement );
if ( value != null ) {
Pair<String, ICRS> p = mainTable.getGeometryColumn( cName );
if ( p != null ) {
handleGeometry( tableElement, p, (byte[]) value );
} else {
cNameElement.addChild( omFactory.createOMText( value.toString() ) );
}
}
}
// add sub tables if available
List<Table> tables = mainTable.getTables();
for ( Table table : tables ) {
appendTable( tableElement, conn, row, table );
}
row.clear();
if ( xslt != null ) {
result = transform( result );
}
performAction( result );
}
} catch ( Exception e ) {
LOG.error( "Could not create a XMLDocument", e );
throw e;
} finally {
// rs.close();
stmt.close();
// CSW?
// ConnectionManager.destroy();
}
}
/**
*
* @param ps
* @param conn
* @param targetRow
* @param targetTable
* @throws Exception
*/
private void appendTable( OMElement tableElement, Connection conn, Map<String, Object> targetRow, Table subTable )
throws Exception {
Statement stmt = null;
try {
String sql = subTable.getSelect();
List<String> variables = subTable.getVariables();
// replace variables with real values
for ( String variable : variables ) {
Object value = targetRow.get( variable.substring( 1, variable.length() ).toLowerCase() );
if ( value instanceof String ) {
sql = StringUtils.replaceAll( sql, variable, "'" + value.toString() + "'" );
} else if ( value != null ) {
sql = StringUtils.replaceAll( sql, variable, value.toString() );
} else {
sql = StringUtils.replaceAll( sql, variable, "'XXXXXXXdummyXXXXXXX'");
}
}
LOG.debug( sql );
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
Map<String, Object> row = new LinkedHashMap<String, Object>();
while ( rs.next() ) {
// append sub table element
// Element subTableElement = XMLTools.appendElement( tableElement, null, subTable.getName() );
OMElement subTableElement = omFactory.createOMElement( new QName( subTable.getName() ) );
tableElement.addChild( subTableElement );
for ( int i = 0; i < colCount; i++ ) {
String cName = rsmd.getColumnName( i + 1 ).toLowerCase();
Object value = rs.getObject( i + 1 );
row.put( cName, value );
if ( value != null ) {
Pair<String, ICRS> p = subTable.getGeometryColumn( cName );
OMElement cNameElement = omFactory.createOMElement( new QName( cName ) );
subTableElement.addChild( cNameElement );
if ( p != null ) {
handleGeometry( subTableElement, p, (byte[]) value );
} else {
cNameElement.addChild( omFactory.createOMText( value.toString() ) );
}
}
}
// recursion!
// append sub tables if available
List<Table> tables = subTable.getTables();
for ( Table table : tables ) {
appendTable( subTableElement, conn, row, table );
}
row.clear();
}
} catch ( Exception e ) {
LOG.error( "", e );
throw e;
} finally {
stmt.close();
}
}
/**
*
* @param tableElement
* @param p
* @param wkb
* wkb representation of the geometry
* @throws Exception
*/
private void handleGeometry( OMElement tableElement, Pair<String, ICRS> p, byte[] wkb )
throws Exception {
try {
Geometry geom = WKBReader.read( wkb, p.second );
StringWriter sw = new StringWriter();
XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter( sw );
GML3GeometryWriter geomWriter = new GML3GeometryWriter( GMLVersion.GML_32, writer );
geomWriter.export( geom );
writer.close();
OMElement geomElement = omFactory.createOMElement( new QName( p.first ) );
geomElement.addChild( omFactory.createOMText( sw.toString() ) );
tableElement.addChild( geomElement );
} catch ( ParseException e ) {
LOG.info( "WKB from the DB could not be parsed: '{}'.", e.getLocalizedMessage() );
LOG.info( "For PostGIS users: you have to select the geometry field 'asbinary(geometry)'." );
LOG.trace( "Stack trace:", e );
}
}
/**
* @param xml
* @return
* @throws Exception
*/
protected OMDocument transform( OMDocument xml )
throws Exception {
return transform( xml, null, null );
}
protected OMDocument transform( OMDocument xml, Properties outputProperties, Map<String, String> params )
throws Exception {
System.out.println( xml.getOMDocumentElement() );
Source xmlSource = new OMSource( xml.getOMDocumentElement() );
XMLAdapter xsltAdapter = new XMLAdapter( xslt );
Source xslSource = new OMSource( xsltAdapter.getRootElement() );
xslSource.setSystemId( xsltAdapter.getSystemId() );
OMResult sr = new OMResult();
try {
Transformer transformer = factory.newTransformer( xslSource );
if ( params != null ) {
for ( String key : params.keySet() ) {
transformer.setParameter( key, params.get( key ) );
}
}
if ( outputProperties != null ) {
transformer.setOutputProperties( outputProperties );
}
transformer.transform( xmlSource, sr );
} catch ( TransformerException e ) {
String transformerClassName = null;
String transformerFactoryClassName = factory.getClass().getName();
try {
transformerClassName = factory.newTransformer().getClass().getName();
} catch ( Exception e2 ) {
LOG.error( "Error creating Transformer instance." );
}
String errorMsg = "XSL transformation using stylesheet with systemId '" + xslSource.getSystemId()
+ "' and xml source with systemId '" + xmlSource.getSystemId()
+ "' failed. TransformerFactory class: " + transformerFactoryClassName
+ "', Transformer class: " + transformerClassName;
LOG.error( errorMsg, e );
throw new TransformerException( errorMsg, e );
}
return sr.getDocument();
}
protected void performAction( OMDocument xml ) {
}
} |
package iot.core.services.device.registry.client;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
import org.iotbricks.service.device.registry.api.Device;
import io.glutamate.util.concurrent.CloseableCompletionStage;
import io.vertx.core.Vertx;
import iot.core.amqp.transport.AmqpTransport;
import iot.core.services.device.registry.client.internal.AbstractDefaultClient;
public class AmqpClient extends AbstractDefaultClient {
public static class Builder {
private AmqpTransport.Builder transport;
private Duration syncTimeout = Duration.ofSeconds(5);
private Builder(final AmqpTransport.Builder transport) {
this.transport = transport;
}
public Builder transport(final AmqpTransport.Builder transport) {
this.transport = transport;
return this;
}
public AmqpTransport.Builder transport() {
return this.transport;
}
public Builder hostname(final String hostname) {
this.transport.hostname(hostname);
return this;
}
public String hostname() {
return this.transport.hostname();
}
public Builder port(final int port) {
this.transport.port(port);
return this;
}
public int port() {
return this.transport.port();
}
public Builder syncTimeout(final Duration syncTimeout) {
this.syncTimeout = syncTimeout;
return this;
}
public Duration syncTimeout() {
return this.syncTimeout;
}
public Client build(final Vertx vertx) {
return new AmqpClient(vertx, new AmqpTransport.Builder(this.transport), this.syncTimeout);
}
}
public static Builder newClient() {
return new Builder(AmqpTransport.newTransport());
}
public static Builder newClient(final AmqpTransport.Builder transport) {
Objects.requireNonNull(transport);
return new Builder(transport);
}
private final AmqpTransport transport;
private AmqpClient(final Vertx vertx, final AmqpTransport.Builder transport, final Duration syncTimeout) {
super(syncTimeout.abs());
this.transport = transport.build(vertx);
}
@Override
public void close() throws Exception {
this.transport.close();
super.close();
}
@Override
protected CloseableCompletionStage<Optional<Device>> internalFindById(final String id) {
return this.transport.request("device", "findById", id, this.transport.bodyAsOptional(Device.class));
}
@Override
protected CloseableCompletionStage<String> internalSave(final Device device) {
return this.transport.request("device", "save", device, this.transport.bodyAs(String.class));
}
@Override
protected CloseableCompletionStage<String> internalCreate(final Device device) {
return this.transport.request("device", "create", device, this.transport.bodyAs(String.class));
}
@Override
protected CloseableCompletionStage<Void> internalUpdate(final Device device) {
return this.transport.request("device", "update", device, this.transport.ignoreBody());
}
} |
package org.jpos.space;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
@SuppressWarnings("unchecked")
public class SpaceUtilTest {
@Test
public void testConstructor() throws Throwable {
new SpaceUtil();
assertTrue("Test completed without Exception", true);
}
@Test
public void testInpAll() throws Throwable {
Object[] result = SpaceUtil.inpAll(new TSpace(), "testString");
assertEquals("result.length", 0, result.length);
}
@Test
public void testInpAll1() throws Throwable {
Space sp = SpaceFactory.getSpace("testSpaceUtilSpaceUri");
SpaceUtil.nextLong(sp, "");
Object[] result = SpaceUtil.inpAll(sp, "");
assertEquals("(TSpace) sp.entries.size()", 0, ((TSpace) sp).entries.size());
assertFalse("(TSpace) sp.entries.containsKey(\"\")", ((TSpace) sp).entries.containsKey(""));
assertEquals("result.length", 1, result.length);
assertEquals("result[0]", 1L, result[0]);
}
@Test
public void testInpAllThrowsNullPointerException() throws Throwable {
try {
SpaceUtil.inpAll(null, "");
fail("Expected NullPointerException to be thrown");
} catch (NullPointerException ex) {
assertNull("ex.getMessage()", ex.getMessage());
}
}
@Test
public void testNextLong() throws Throwable {
Space sp = new TSpace();
long result = SpaceUtil.nextLong(sp, "");
assertEquals("(TSpace) sp.entries.size()", 1, ((TSpace) sp).entries.size());
assertEquals("result", 1L, result);
}
@Test
public void testNextLongThrowsNullPointerException() throws Throwable {
Space sp = new TSpace();
try {
SpaceUtil.nextLong(sp, null);
fail("Expected NullPointerException to be thrown");
} catch (NullPointerException ex) {
assertEquals("ex.getMessage()", "key=null, value=1", ex.getMessage());
assertTrue("(TSpace) sp.isEmpty()", ((TSpace) sp).isEmpty());
}
}
@Test
public void testNextLongThrowsNullPointerException1() throws Throwable {
try {
SpaceUtil.nextLong(null, "");
fail("Expected NullPointerException to be thrown");
} catch (NullPointerException ex) {
assertNull("ex.getMessage()", ex.getMessage());
}
}
@Test
public void testWipe1() throws Throwable {
SpaceUtil.wipe(SpaceFactory.getSpace(), "");
assertTrue("Test completed without Exception", true);
// dependencies on static and environment state led to removal of 1
// assertion
}
@Test
public void testWipeThrowsNullPointerException() throws Throwable {
try {
SpaceUtil.wipe(null, "");
fail("Expected NullPointerException to be thrown");
} catch (NullPointerException ex) {
assertNull("ex.getMessage()", ex.getMessage());
}
}
} |
package Utils;
import javax.xml.bind.ValidationException;
import java.security.DomainCombiner;
import java.sql.Timestamp;
import java.util.Date;
public class Validator {
public static void validateString(String s, int maxLength) throws ValidationException {
if(s != null && s.length() > maxLength) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateMandatoryString(String s) throws ValidationException {
if(s == null || s.isEmpty()) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateMandatoryString(String s, int maxLength) throws ValidationException {
if(s == null || s.isEmpty() || s.length() > maxLength) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateInteger(Integer i, int minValue, int maxValue) throws ValidationException {
if(i != null && (i < minValue || i > maxValue)) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateMandatoryInteger(Integer i) throws ValidationException {
if(i == null) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateMandatoryInteger(Integer i, int minValue, int maxValue) throws ValidationException {
if(i == null || i < minValue || i > maxValue) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateDouble(Double d, double minValue, double maxValue) throws ValidationException {
if(d != null && (d < minValue || d > maxValue)) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateMandatoryDouble(Double d) throws ValidationException {
if(d == null) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateMandatoryDouble(Double d, double minValue, double maxValue) throws ValidationException {
if(d == null || d < minValue || d > maxValue) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateMandatoryTimestamp(Timestamp timestamp) throws ValidationException {
if(timestamp == null) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateTimestampAfterToday(Timestamp timestamp) throws ValidationException {
if(timestamp != null && timestamp.before(new Date())) {
throw new ValidationException("Validation wrong.");
}
}
public static void validateTimestamp1BeforeTimestamp2(Timestamp timestamp1, Timestamp timestamp2) throws ValidationException {
if(timestamp1 != null && timestamp2 != null && timestamp1.after(timestamp2)) {
throw new ValidationException("Validation wrong.");
}
}
} |
package org.dspace.dataonemn;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nu.xom.Document;
import nu.xom.Serializer;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.eperson.EPerson;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.ibm.icu.text.DateFormat;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.commons.lang.StringEscapeUtils;
/**
* This class accepts an HTTP request and passes off to the appropriate location
* to perform an action. It is very lightweight, just for testing some initial
* setup. It will eventually be merged into other code.
*
* @author Ryan Scherle
* @author Kevin S. Clarke
**/
public class DataOneMN extends HttpServlet implements Constants {
private static final long serialVersionUID = -3545762362447908735L;
private static final Logger log = Logger.getLogger(DataOneMN.class);
private static final String XML_CONTENT_TYPE = "application/xml; charset=UTF-8";
private static final String RDF_CONTENT_TYPE = "application/rdf+xml; charset=UTF-8";
private static final String TEXT_XML_CONTENT_TYPE = "text/xml; charset=UTF-8";
private static final int DATA_FILE_COLLECTION = 1;
private static final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
private String myFiles;
private String myPackages;
private String d1NodeID;
private String d1contact;
private String d1baseURL;
private DataOneLogger myRequestLogger;
/**
Opens a DSpace context, and cleanly recovers if there is a problem opening it.
**/
private Context getContext() throws ServletException {
Context ctxt = null;
try {
ctxt = new Context();
log.debug("DSpace context initialized");
return ctxt;
}
catch (SQLException e) {
log.error("Unable to initialize DSpace context", e);
try {
if (ctxt != null) {
ctxt.complete();
}
}
catch (SQLException e2) {
log.warn("unable to close context cleanly;" + e2.getMessage(), e2);
}
throw new ServletException("Unable to initialize DSpace context", e);
}
}
private void closeContext(Context ctxt) throws ServletException {
log.debug("closing context " + ctxt);
try {
if (ctxt != null && ctxt.getDBConnection() != null) { //if the connection is null how can we commit?
ctxt.complete();
}
log.debug("DSpace context closed.");
} catch (SQLException e) {
log.warn("unable to close context cleanly;" + e.getMessage(), e);
}
}
/**
* Receives the HEAD HTTP call and passes off to the appropriate method.
**/
protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("starting doHead with request " + request.getPathInfo());
String reqPath = buildReqPath(request.getPathInfo());
log.debug("pathinfo=" + reqPath);
Context ctxt = getContext();
if (reqPath.startsWith("/object/")) {
ObjectManager objManager = new ObjectManager(ctxt, myFiles, myPackages);
describe(reqPath, response, objManager);
} else {
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
}
closeContext(ctxt);
}
/**
* Receives the HEAD POST call and passes off to the appropriate method.
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.debug("starting doPost with request " + request.getPathInfo());
String reqPath = buildReqPath(request.getPathInfo());
if (reqPath.startsWith("/error")) {
synchronizationFailed(request, response);
} else {
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
}
}
/**
* We don't implement this yet.
*/
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.debug("starting doPut with request " + request.getPathInfo());
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
}
/**
* Cleans up the URL request path.
**/
private String buildReqPath(String aPath) {
String reqPath = aPath;
// handle (and remove) the version indicator
// TODO: throw an error for requests that do not have a version indicator -- need to notify potential users first
if(reqPath.startsWith("/v1")) {
log.debug("version 1 detected, removing");
reqPath = reqPath.substring("/v1".length());
}
// remove any trailing slash, but not if the entire path is a slash
if(reqPath.endsWith("/") && reqPath.length() > 1) {
reqPath = reqPath.substring(0, reqPath.length() - 1);
}
return reqPath;
}
/**
* Receives the GET HTTP call and passes off to the appropriate method.
**/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("starting doGet with request " + request.getPathInfo()); //why is this not printing ?count parameters...
String reqPath = buildReqPath(request.getPathInfo());
String queryString = request.getQueryString();
log.debug("reqPath=" + reqPath);
Context ctxt = null;
LogEntry le = new LogEntry();
String requestIP = request.getHeader("x-forwarded-for");
if(requestIP == null) {
requestIP = request.getRemoteAddr();
}
final String requestUser = request.getRemoteUser();
le.setIPAddress(requestIP);
le.setUserAgent(request.getHeader("user-agent"));
StringBuilder subjectBuff = new StringBuilder();
if (requestUser != null){
subjectBuff.append("CN=testcn, ");
}
subjectBuff.append("DC=dataone, DC=org");
le.setSubject(subjectBuff.toString());
le.setNodeIdentifier(d1NodeID);
//code for setting the log time moved to the LogEntry class, since the format needs to work with solr
try {
ctxt = getContext();
ObjectManager objManager = new ObjectManager(ctxt, myFiles, myPackages);
if (reqPath.startsWith("/monitor/ping")) {
ping(response, objManager);
} else if (reqPath.startsWith("/log")) {
getLogRecords(request, response);
} else if(reqPath.equals("") || reqPath.equals("/") || reqPath.equals("/node")) {
getCapabilities(response);
} else if(reqPath.startsWith("/object")) {
if (reqPath.equals("/object")) {
listObjects(request, response, objManager, true);
}
else if (reqPath.equals("/object/simple")) {
listObjects(request, response, objManager, false);
}
else if (reqPath.startsWith("/object/")) {
getObject(reqPath, request.getQueryString(), response, objManager, le);
String objid = reqPath.substring("/object/".length());
log.info("logging request for object id= " + objid + " queryString=" + request.getQueryString());
le.setEvent(DataOneLogger.EVENT_READ);
myRequestLogger.log(le);
}
else {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
"Did you mean '/object' or '/object/http://dx.doi.org/...'");
}
} else if (reqPath.startsWith("/meta/")) {
getSystemMetadata(reqPath, request.getQueryString(), response, objManager);
} else if (reqPath.startsWith("/checksum/")) {
getChecksum(reqPath, response, objManager);
} else if (reqPath.startsWith("/isAuthorized/")) {
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
} else if (reqPath.startsWith("/accessRules/")) {
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
} else if (reqPath.startsWith("/error")) {
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
} else if (reqPath.startsWith("/monitor/object")) {
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
} else if (reqPath.startsWith("/monitor/event")) {
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
} else if (reqPath.startsWith("/monitor/status")) {
response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
} else if (reqPath.startsWith("/replica")) {
getReplica(reqPath, response, objManager, le);
String objid = reqPath.substring("/replica/".length());
log.info("logging request for replica object id= " + objid);
le.setEvent(DataOneLogger.EVENT_REPLICATE);
myRequestLogger.log(le);
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
} catch (Exception e) {
log.error("UNEXPECTED EXCEPTION", e);
} finally {
closeContext(ctxt);
}
}
/**
* Initializes the DSpace context, so we have access to the DSpace objects.
* Requires the location of the dspace.cfg file to be set in the web.xml.
**/
public void init() throws ServletException {
log.debug("initializing...");
ServletContext context = this.getServletContext();
String configFileName = context.getInitParameter("dspace.config");
File aConfig = new File(configFileName);
if (aConfig != null) {
if (aConfig.exists() && aConfig.canRead() && aConfig.isFile()) {
ConfigurationManager.loadConfig(aConfig.getAbsolutePath());
log.debug("DSpace config loaded from " + aConfig);
}
else if (!aConfig.exists()) {
log.fatal("dspace.cfg file at " + aConfig.getAbsolutePath() + " doesn't exist");
throw new RuntimeException(aConfig.getAbsolutePath() + " doesn't exist");
}
else if (!aConfig.canRead()) {
log.fatal("dspace.cfg file at " + aConfig.getAbsolutePath() + " cannot be read");
throw new RuntimeException("Can't read the dspace.cfg file");
}
else if (!aConfig.isFile()) {
log.fatal("dspace.cfg file at " + aConfig.getAbsolutePath() + " is not a file!");
throw new RuntimeException("Err, dspace.cfg isn't a file?");
}
}
myFiles = ConfigurationManager.getProperty("stats.datafiles.coll");
myPackages = ConfigurationManager.getProperty("stats.datapkgs.coll");
d1NodeID = ConfigurationManager.getProperty("dataone.nodeID");
d1contact = ConfigurationManager.getProperty("dataone.contact");
d1baseURL = ConfigurationManager.getProperty("dataone.baseURL");
myRequestLogger = new DataOneLogger(); //this assumes a configuration has been loaded
log.debug("initialization complete");
}
private int parseInt(HttpServletRequest request, String aParam, int aDefault) {
String intString = request.getParameter(aParam);
int intValue = aDefault;
try {
if (intString != null) {
intValue = Integer.parseInt(intString);
}
}
catch (NumberFormatException details) {
log.warn(aParam + " parameter not an int: " + intString);
}
return intValue;
}
/**
Parses a user-entered date. The date may appear in one of many common formats. If the date
format is not recognized, null is returned.
**/
private Date parseDate(HttpServletRequest request, String aParam)
throws ParseException {
String date = request.getParameter(aParam);
if (date == null) {
return null;
}
try {
return DateTimeFormat.fullDateTime().parseDateTime(date).toDate();
}
catch (IllegalArgumentException details) {}
try {
return DateTimeFormat.forPattern("yyyyMMdd").parseDateTime(date).toDate();
}
catch (IllegalArgumentException details) {}
try {
return DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(date).toDate();
}
catch (IllegalArgumentException details) {}
try {
return DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSS").parseDateTime(date).toDate();
}
catch (IllegalArgumentException details) {}
try {
return DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSSS").parseDateTime(date).toDate();
}
catch (IllegalArgumentException details) {}
// for explanation of ZZ time zone formatting
try {
return DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSZZ").parseDateTime(date).toDate();
}
catch (IllegalArgumentException details) {}
try {
return DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSSSZZ").parseDateTime(date).toDate();
}
catch (IllegalArgumentException details) {}
return null;
}
/**
Performs a basic test that this Member Node is alive
**/
private void ping(HttpServletResponse response, ObjectManager objManager) throws IOException {
log.info("ping");
// try to get a single object. If it fails, return an error.
try {
OutputStream dummyOutput = new OutputStream() { public void write(int b) throws IOException {}};
objManager.getMetadataObject("doi:10.5061/dryad.20/1", "", dummyOutput);
} catch (Exception e) {
log.error("Unable to retrieve test metadata object doi:10.5061/dryad.20/1", e);
// if there is any problem, respond with an error
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// the basic test passed; return the Node description document
getCapabilities(response);
}
/**
Returns logs of this Member Node's activities.
**/
private void getLogRecords(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.info("getLogRecords()");
final OutputStream out = response.getOutputStream();
final PrintWriter pw = new PrintWriter(out);
try{
Date from = parseDate(request, "fromDate");
Date to = parseDate(request, "toDate");
String event = request.getParameter("event");
String pidFilter = request.getParameter("pidFilter");
int start = parseInt(request, "start",
DataOneLogger.DEFAULT_START);
int count = parseInt(request, "count",
DataOneLogger.DEFAULT_COUNT);
if (myRequestLogger != null){
log.info("Request string (from) is " + request.getParameter("fromDate"));
log.info("Dates for log records; from= " + from + "; to= " + to);
DataOneLogger.LogResults r = myRequestLogger.getLogRecords(from,to,event,pidFilter,start,count);
response.setContentType(XML_CONTENT_TYPE);
pw.write(r.getLogRecords());
}
else{
RuntimeException e = new RuntimeException("DataONE logging system is not present!");
log.error("unable to get log records from nonexistent logger", e);
}
} catch (ParseException e) {
log.error("unable to parse request info", e);
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
e.getMessage());
} catch (StringIndexOutOfBoundsException e) {
log.error("Passed request did not find a match", e);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
pw.close();
}
/**
Responds with the capabilities of this Member Node.
**/
private void getCapabilities(HttpServletResponse response) throws IOException {
log.info("getCapabilities()");
response.setContentType(XML_CONTENT_TYPE);
OutputStream out = response.getOutputStream();
PrintWriter pw = new PrintWriter(out);
// basic node description
pw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" +
"<?xml-stylesheet type=\"text/xsl\" href=\"/themes/Dryad/dataOne/dataone.types.v1.xsl\"?> \n" +
"<d1:node xmlns:d1=\"http://ns.dataone.org/service/types/v1\" replicate=\"false\" synchronize=\"true\" type=\"mn\" state=\"up\"> \n" +
"<identifier>" + d1NodeID + "</identifier>\n" +
"<name>Dryad Digital Repository</name>\n" +
"<description>Dryad is an international repository of data underlying peer-reviewed scientific and medical literature.</description>\n" +
"<baseURL>" + d1baseURL + "</baseURL>\n");
// supported services
pw.write("<services>\n" +
"<service name=\"MNRead\" version=\"v1\" available=\"true\"/>\n" +
"<service name=\"MNCore\" version=\"v1\" available=\"true\"/>\n" +
"<service name=\"MNAuthorization\" version=\"v1\" available=\"false\"/>\n" +
"<service name=\"MNStorage\" version=\"v1\" available=\"false\"/>\n" +
"<service name=\"MNReplication\" version=\"v1\" available=\"false\"/>\n" +
"</services>\n");
// synchronization
pw.write("<synchronization>\n" +
"<schedule hour=\"*\" mday=\"*\" min=\"0/3\" mon=\"*\" sec=\"10\" wday=\"?\" year=\"*\"/>\n" +
"</synchronization>\n");
// other random info
pw.write("<ping success=\"true\"/>\n" +
"<subject>CN=" + d1NodeID + ", DC=dataone, DC=org</subject>\n" +
"<contactSubject>" + d1contact + "</contactSubject>\n");
// close xml
pw.write("</d1:node>\n");
pw.close();
}
/**
Retrieve a particular object from this Member Node.
**/
private void getObject(String reqPath, String reqQueryString, HttpServletResponse response, ObjectManager objManager, LogEntry logent) throws ServletException, IOException {
log.info("getObject()");
String idTimestamp = "";
String format = "";
String fileName = "";
// reqPath doesn't include query variables
String id = reqPath.substring("/object/".length());
if(reqQueryString != null) {
id = id + '?' + reqQueryString;
}
String simpleDOI = id.replace('/','_').replace(':','_');
try {
// perform corrections for timestamped IDs
// If we receive a timestamped ID, we will produce metadata records that contain timestamped IDs.
// Timestamps are always at the end of the identifier
if (id.contains("ver=")) {
int timeIndex = id.indexOf("ver=") - 1;
idTimestamp = id.substring(timeIndex);
id = id.substring(0,timeIndex);
}
if (reqPath.endsWith("/bitstream")) {
// return a bitstream
log.debug("bitstream requested");
int bitsIndex = id.indexOf("/bitstream");
id = id.substring(0,bitsIndex);
logent.setIdentifier(id);
// locate the bitstream
Item item = objManager.getDSpaceItem(id);
Bitstream bitstream = objManager.getFirstBitstream(item);
// send it to output stream
String mimeType = bitstream.getFormat().getMIMEType();
response.setContentType(mimeType);
log.debug("Setting data file MIME type to: " + mimeType);
fileName = bitstream.getName();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName);
objManager.writeBitstream(bitstream.retrieve(), response.getOutputStream());
} else if(id.contains("format=d1rem")) {
// return a (dataONE format) resource map
response.setContentType(RDF_CONTENT_TYPE);
// throw early, try not to create an output stream
Item item = objManager.getDSpaceItem(id);
log.debug("getting resource map for object id=" + id + idTimestamp);
objManager.getResourceMap(id, idTimestamp, response.getOutputStream());
logent.setIdentifier(id + idTimestamp);
} else {
// return a metadata record (file or package)
response.setContentType(XML_CONTENT_TYPE);
// throw early, try not to create an output stream
Item item = objManager.getDSpaceItem(id);
log.debug("getting science metadata object id=" + id + idTimestamp);
objManager.getMetadataObject(id, idTimestamp, response.getOutputStream());
logent.setIdentifier(id + idTimestamp);
}
} catch (NotFoundException details) {
log.error("Passed request returned not found", details);
response.setStatus(404);
String resStr = generateNotFoundResponse(id + idTimestamp, "mn.get","1020");
OutputStream out = response.getOutputStream();
PrintWriter pw = new PrintWriter(out);
pw.write(resStr);
pw.flush();
} catch (StringIndexOutOfBoundsException e) {
log.error("Passed request did not find a match", e);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch(Exception e) {
log.error("unable to getObject " + reqPath, e);
throw new ServletException("unable to getObject" + reqPath, e);
}
}
private String generateNotFoundResponse(String id, String method, String code) throws IOException{
String responseStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" +
"<error name='NotFound'" + "\n" +
" errorCode='404'" + "\n" +
" detailCode='" + code + "'\n" +
" pid=" + "\"" + StringEscapeUtils.escapeXml(id) + "\"\n" +
" nodeId='" + d1NodeID + "'>" + "\n" +
" <description>The specified object does not exist on this node.</description>" + "\n" +
" <traceInformation>" + "\n" +
" method: " + method + "\n" +
" hint: http://cn.dataone.org/cn/resolve/" + StringEscapeUtils.escapeXml(id) + "\n" +
" </traceInformation>" + "\n" +
"</error>" + "\n";
return responseStr;
}
/**
Returns the system metadata associated with an object.
**/
private void getSystemMetadata(String reqPath, String reqQueryString, HttpServletResponse response, ObjectManager objManager) throws ServletException, IOException {
log.info("getSystemMetadata()");
String id = reqPath.substring("/meta/".length());
if(reqQueryString != null) {
id = id + '?' + reqQueryString;
}
String idTimestamp = "";
// perform corrections for timestamped IDs
// If we receive a timestamped ID, we will produce metadata records that contain timestamped IDs.
// Timestamps are always at the end of the identifier
if (id.contains("ver=")) {
int timeIndex = id.indexOf("ver=") - 1;
idTimestamp = id.substring(timeIndex);
id = id.substring(0,timeIndex);
}
log.debug("id = " + id);
response.setContentType(TEXT_XML_CONTENT_TYPE); // default for /meta
try {
SystemMetadata sysMeta = new SystemMetadata(id);
XMLSerializer serializer = new XMLSerializer(response.getOutputStream());
Item item = objManager.getDSpaceItem(id);
log.debug("retrieved item with internal ID " + item.getID());
EPerson ePerson = item.getSubmitter();
String epEmail = ePerson.getEmail();
DCValue [] accDateValue = item.getMetadata("dc.date.accessioned");
String accDateString;
if (accDateValue.length >0){
accDateString = accDateValue[0].value;
}
else {
accDateString = null;
}
Date date = item.getLastModified();
String lastMod = dateFormatter.format(date);
if (reqPath.endsWith("/bitstream")) {
//build sysmeta for a bistream
Bitstream bitstream = objManager.getFirstBitstream(item);
String format = translateMIMEToDataOneFormat(bitstream.getFormat().getMIMEType());
sysMeta.setObjectFormat(format);
// Add relationship between this bitstream and the science data that describes it
sysMeta.setDescribedBy(id);
String checksum = bitstream.getChecksum();
String algorithm = bitstream.getChecksumAlgorithm();
sysMeta.setChecksum(checksum, algorithm); // reversed (?)
sysMeta.setSize(bitstream.getSize());
} else {
// build sysmeta for a science metadata object
sysMeta.setObjectFormat(DRYAD_NAMESPACE);
long size = objManager.getObjectSize(id, idTimestamp);
sysMeta.setSize(size);
// Add relationship between this science metadata and the bitstream it describes.
// Data packages don't have a bitstream, so they are skipped
Collection collect = item.getOwningCollection();
if(collect.getID() == DATA_FILE_COLLECTION) {
// how many mns can the current cns handle?
sysMeta.setDescribes(id + "/bitstream");
}
String[] checksumDetails = objManager.getObjectChecksum(id, idTimestamp);
sysMeta.setChecksum(checksumDetails[0], checksumDetails[1]);
}
//The date format in the dryad metadata appears to be acceptable
if (accDateString != null)
sysMeta.setDateUploaded(accDateString);
else {
sysMeta.setDateUploaded(lastMod);
log.warn("No acessioned date retrieved for filling DC uploaded string; will default to last modified");
}
sysMeta.setLastModified(lastMod);
sysMeta.setSubmitter(epEmail);
sysMeta.setRightsHolder(DRYAD_ADMIN);
sysMeta.setAuthoritative(d1NodeID);
sysMeta.setOrigin(d1NodeID);
sysMeta.formatOutput();
serializer.write(new Document(sysMeta));
serializer.flush();
response.getOutputStream().close();
}
catch (NotFoundException details) {
log.error("Passed request returned not found", details);
response.setStatus(404);
String resStr = generateNotFoundResponse(id,"mn.getSystemMetadata","1060");
OutputStream out = response.getOutputStream();
PrintWriter pw = new PrintWriter(out);
pw.write(resStr);
pw.flush();
}
catch (SQLException details) {
throw new ServletException("unable to retrieve System Metadata for " + reqPath, details);
}
catch (IOException details) {
throw new ServletException("unable to retrieve System Metadata for " + reqPath, details);
}
catch (StringIndexOutOfBoundsException details) {
log.error("Passed request did not find a match", details);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
private String translateMIMEToDataOneFormat(String dryadMIMEString){
return dryadMIMEString;
}
/**
Returns the basic properties of an object.
**/
private void describe(String reqPath, HttpServletResponse response, ObjectManager objManager) throws ServletException, IOException {
log.info("describe()");
String id = reqPath.substring("/object/".length());
String idTimestamp = "";
// perform corrections for timestamped IDs
// If we receive a timestamped ID, we will produce metadata records that contain timestamped IDs.
// Timestamps are always at the end of the identifier
if (id.contains("ver=")) {
int timeIndex = id.indexOf("ver=") - 1;
idTimestamp = id.substring(timeIndex);
id = id.substring(0,timeIndex);
}
try {
long length = objManager.getObjectSize(id, idTimestamp);
response.setContentLength((int) length);
if (id.endsWith("/bitstream")) {
ServletContext context = getServletContext();
log.warn("NEED TO GET CORRECT MIME TYPE");
String mimeType = "application/octet-stream";
//String mimeType = context.getMimeType("f." + format);
if (mimeType == null || mimeType.equals("")) {
mimeType = "application/octet-stream";
}
Item item = objManager.getDSpaceItem(id);
Bitstream bitstream = objManager.getFirstBitstream(item);
String format = translateMIMEToDataOneFormat(bitstream.getFormat().getMIMEType());
response.setHeader("DataONE-formatId", format);
final String[] checksumDetails = objManager.getObjectChecksum(id, idTimestamp);
final String checkSumAlg = checksumDetails[1];
final String checkSum = checksumDetails[0];
final String checkSumStr = checkSumAlg + "," + checkSum;
response.setHeader("DataONE-Checksum",checkSumStr);
response.setHeader("DataONE-SerialVersion", "1");
log.debug("Setting data file MIME type to: "
+ mimeType + " (this is configurable)");
response.setContentType(mimeType);
} else {
response.setHeader("DataONE-formatId", DRYAD_NAMESPACE);
response.setContentType(XML_CONTENT_TYPE);
final String[] checksumDetails = objManager.getObjectChecksum(id, idTimestamp);
final String checkSumAlg = checksumDetails[1];
final String checkSum = checksumDetails[0];
final String checkSumStr = checkSumAlg + "," + checkSum;
response.setHeader("DataONE-Checksum",checkSumStr);
response.setHeader("DataONE-SerialVersion", "1");
}
}
catch (NotFoundException details) {
log.error("Passed request returned not found", details);
response.setStatus(404);
response.setContentType(XML_CONTENT_TYPE);
response.setHeader("DataONE-Exception-Name", "NotFound");
response.setHeader("DataONE-Exception-DetailCode", "1380");
response.setHeader("DataONE-Exception-Description", "The specified object does not exist on this node.");
response.setHeader("DataONE-Exception-PID", StringEscapeUtils.escapeXml(id));
response.addDateHeader("Last-Modified", System.currentTimeMillis());
String resStr = generateNotFoundResponse(id, "mn.describe","1380");
response.setContentLength(resStr.length());
OutputStream out = response.getOutputStream();
PrintWriter pw = new PrintWriter(out);
pw.write(resStr);
pw.flush();
}
catch (SQLException details) {
log.error(details.getMessage(), details);
throw new ServletException(details);
}
catch (StringIndexOutOfBoundsException details) {
log.error("Passed request did not find a match", details);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
catch (Exception details) {
log.error("UNEXPECTED EXCEPTION", details);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
finally {
objManager.completeContext();
}
}
/**
Returns the checksum associated with an object.
**/
private void getChecksum(String reqPath, HttpServletResponse response, ObjectManager objManager) throws IOException {
log.info("getChecksum()");
String id = reqPath.substring("/checksum/".length());
String idTimestamp = "";
// perform corrections for timestamped IDs
// If we receive a timestamped ID, we will produce metadata records that contain timestamped IDs.
// Timestamps are always at the end of the identifier
if (id.contains("ver=")) {
int timeIndex = id.indexOf("ver=") - 1;
idTimestamp = id.substring(timeIndex);
id = id.substring(0,timeIndex);
}
response.setContentType(TEXT_XML_CONTENT_TYPE);
try {
String[] checksum = objManager.getObjectChecksum(id, idTimestamp);
PrintWriter writer = response.getWriter();
writer.print("<checksum xmlns=\"" + D1_TYPES_NAMESPACE
+ "\" algorithm=\"" + checksum[1] + "\">" + checksum[0]
+ "</checksum>");
writer.close();
}
catch (NotFoundException details) {
log.error("Passed request returned not found", details);
response.setStatus(404);
String resStr = generateNotFoundResponse(id, "mn.getChecksum","1420");
OutputStream out = response.getOutputStream();
PrintWriter pw = new PrintWriter(out);
pw.write(resStr);
pw.flush();
}
catch (SQLException details) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"unable to get checksum for " + reqPath + "; " + details.getMessage());
}
catch (IOException details) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
details.getMessage());
}
}
/**
List all objects available on this Member Node.
**/
private void listObjects(HttpServletRequest request, HttpServletResponse response,
ObjectManager objManager, boolean useTimestamps) throws IOException {
log.info("listObjects()");
String format = request.getParameter("formatId");
try {
Date from = parseDate(request, "fromDate");
Date to = parseDate(request, "toDate");
int start = parseInt(request, "start",
ObjectManager.DEFAULT_START);
int count = parseInt(request, "count",
ObjectManager.DEFAULT_COUNT);
response.setContentType(XML_CONTENT_TYPE);
if (count <= 0) {
OutputStream out = response.getOutputStream();
objManager.printList(from, to, format, out, useTimestamps);
}
else {
OutputStream out = response.getOutputStream();
objManager.printList(start, count, from, to, format, out, useTimestamps);
}
} catch (ParseException e) {
log.error("unable to parse request info", e);
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
e.getMessage());
} catch (SQLException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"unable to list objects; " + e.getMessage());
} catch (StringIndexOutOfBoundsException e) {
log.error("Passed request did not find a match", e);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
/**
Record the fact that a synchronization has failed.
**/
private void synchronizationFailed(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.info("synchronizationFailed()");
response.setStatus(HttpServletResponse.SC_OK);
// todo: send email to admin.
}
/**
Retrieve a replica of an item.
**/
private void getReplica(String reqPath, HttpServletResponse response, ObjectManager objManager, LogEntry logent) throws IOException,ServletException {
log.info("replicateObject()");
String format = "";
String fileName = "";
String id = reqPath.substring("/replica/".length());
String idTimestamp = "";
// perform corrections for timestamped IDs
// If we receive a timestamped ID, we will produce metadata records that contain timestamped IDs.
// Timestamps are always at the end of the identifier
if (id.contains("ver=")) {
int timeIndex = id.indexOf("ver=") - 1;
idTimestamp = id.substring(timeIndex);
id = id.substring(0,timeIndex);
}
log.debug("id = " + id);
String simpleDOI = id.replace('/','_').replace(':','_');
try {
if (!id.endsWith("/bitstream")) {
// return a metadata record (file or package)
format = "dap";
fileName = simpleDOI + ".xml";
response.setContentType(XML_CONTENT_TYPE);
log.debug("replicating object id=" + id +", format=" + format);
objManager.getMetadataObject(id, idTimestamp, response.getOutputStream());
logent.setIdentifier(id);
}
else {
// return a bitstream
log.debug("bitstream requested");
logent.setIdentifier(id);
// locate the bitstream
Item item = objManager.getDSpaceItem(id);
Bitstream bitstream = objManager.getFirstBitstream(item);
// send it to output stream
String mimeType = bitstream.getFormat().getMIMEType();
response.setContentType(mimeType);
log.debug("Setting data file MIME type to: " + mimeType);
fileName = bitstream.getName();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName);
objManager.writeBitstream(bitstream.retrieve(), response.getOutputStream());
}
}
catch (NotFoundException details) {
log.error("Passed request returned not found", details);
response.setStatus(404);
String resStr = generateNotFoundResponse(id, "mn.getReplica","2185");
OutputStream out = response.getOutputStream();
PrintWriter pw = new PrintWriter(out);
pw.write(resStr);
pw.flush();
} catch (StringIndexOutOfBoundsException e) {
log.error("Passed request did not find a match", e);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch(Exception e) {
log.error("unable to replicateObject " + reqPath, e);
throw new ServletException("unable to replicateObject" + reqPath, e);
}
}
} |
package org.neo4j.cluster.protocol.election;
import static junit.framework.Assert.assertNull;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.mockito.Matchers;
import org.neo4j.cluster.InstanceId;
import org.neo4j.cluster.protocol.cluster.ClusterConfiguration;
import org.neo4j.cluster.protocol.cluster.ClusterContext;
import org.neo4j.cluster.protocol.heartbeat.HeartbeatContext;
import org.neo4j.helpers.collection.Iterables;
import org.neo4j.kernel.impl.util.StringLogger;
public class ElectionContextTest
{
@Test
public void testElectionOkNoFailed()
{
Set<InstanceId> failed = new HashSet<InstanceId>();
baseTestForElectionOk( failed, false );
}
@Test
public void testElectionOkLessThanQuorumFailed()
{
Set<InstanceId> failed = new HashSet<InstanceId>();
failed.add( new InstanceId( 1 ) );
baseTestForElectionOk( failed, false );
}
@Test
public void testElectionOkMoreThanQuorumFailed()
{
Set<InstanceId> failed = new HashSet<InstanceId>();
failed.add( new InstanceId( 1 ) );
failed.add( new InstanceId( 2 ) );
baseTestForElectionOk( failed, true );
}
@Test
public void twoVotesFromSameInstanceForSameRoleShouldBeConsolidated() throws Exception
{
// Given
final String coordinatorRole = "coordinator";
HeartbeatContext heartbeatContext = mock(HeartbeatContext.class);
when( heartbeatContext.getFailed() ).thenReturn( Collections.<InstanceId>emptySet() );
Map<InstanceId, URI> members = new HashMap<InstanceId, URI>();
members.put( new InstanceId( 1 ), URI.create( "server1" ) );
members.put( new InstanceId( 2 ), URI.create( "server2" ) );
members.put( new InstanceId( 3 ), URI.create( "server3" ) );
ClusterConfiguration clusterConfiguration = mock( ClusterConfiguration.class );
when( clusterConfiguration.getMembers() ).thenReturn( members );
ClusterContext clusterContext = mock( ClusterContext.class );
when( clusterContext.getConfiguration() ).thenReturn( clusterConfiguration );
when ( clusterContext.getLogger( Matchers.<Class>any() ) ).thenReturn( mock( StringLogger.class ) );
ElectionContext toTest = new ElectionContext( Iterables.<ElectionRole, ElectionRole>iterable(
new ElectionRole( coordinatorRole ) ), clusterContext, heartbeatContext );
// When
toTest.startElectionProcess( coordinatorRole );
toTest.voted( coordinatorRole, new InstanceId( 1 ), new IntegerElectionCredentials( 100 ) );
toTest.voted( coordinatorRole, new InstanceId( 2 ), new IntegerElectionCredentials( 100 ) );
toTest.voted( coordinatorRole, new InstanceId( 2 ), new IntegerElectionCredentials( 101 ) );
// Then
assertNull( toTest.getElectionWinner( coordinatorRole ) );
assertEquals( 2, toTest.getVoteCount( coordinatorRole ) );
}
private void baseTestForElectionOk( Set<InstanceId> failed, boolean moreThanQuorum )
{
HeartbeatContext heartbeatContext = mock(HeartbeatContext.class);
when( heartbeatContext.getFailed() ).thenReturn( failed );
Map<InstanceId, URI> members = new HashMap<InstanceId, URI>();
members.put( new InstanceId( 1 ), URI.create( "server1" ) );
members.put( new InstanceId( 2 ), URI.create( "server2" ) );
members.put( new InstanceId( 3 ), URI.create( "server3" ) );
ClusterConfiguration clusterConfiguration = mock( ClusterConfiguration.class );
when( clusterConfiguration.getMembers() ).thenReturn( members );
ClusterContext clusterContext = mock( ClusterContext.class );
when( clusterContext.getConfiguration() ).thenReturn( clusterConfiguration );
ElectionContext toTest = new ElectionContext( Iterables.<ElectionRole, ElectionRole>iterable(
new ElectionRole("coordinator") ), clusterContext, heartbeatContext );
assertEquals( moreThanQuorum, !toTest.electionOk() );
}
private static final class IntegerElectionCredentials implements ElectionCredentials
{
private final int credential;
private IntegerElectionCredentials( int credential )
{
this.credential = credential;
}
@Override
public int compareTo( Object o )
{
return o instanceof IntegerElectionCredentials
? Integer.valueOf(credential).compareTo(Integer.valueOf(( (IntegerElectionCredentials) o).credential)) : 0;
}
}
} |
package de.nenick.espressomacchiato.elements;
import android.support.test.espresso.NoMatchingViewException;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import junit.framework.AssertionFailedError;
import org.junit.Test;
import de.nenick.espressomacchiato.test.views.BaseActivity;
import de.nenick.espressomacchiato.testbase.EspressoTestCase;
public class EspViewTest extends EspressoTestCase<BaseActivity> {
private static final String VIEW_WAS_CLICKED_MESSAGE = "view was clicked";
private int viewId = android.R.id.button1;
private EspView espView = EspView.byId(viewId);
private Button view;
private int messageViewId = android.R.id.text1;
private TextView messageView;
private EspTextView espTextView = EspTextView.byId(messageViewId);
@Test
public void testByAll() {
givenClickableView();
espView = EspView.byAll().withId(viewId).withIsDisplayed().build();
espView.assertIsDisplayedOnScreen();
}
@Test
public void testAssertions() {
espTextView.assertNotExist();
givenClickableView();
espView.assertIsVisible();
espView.assertIsEnabled();
espView.assertIsDisplayedOnScreen();
givenViewIsDisabled();
espView.assertIsDisabled();
givenViewIsInvisible();
espView.assertIsHidden();
givenViewIsGone();
espView.assertIsHidden();
}
@Test
public void testAssertIsDisplayedOnScreenFailure() {
givenViewOutsideOfScreen(android.R.id.text2);
EspView.byId(android.R.id.text2).assertIsVisible();
exception.expect(AssertionFailedError.class);
EspView.byId(android.R.id.text2).assertIsDisplayedOnScreen();
}
@Test
public void testClick() {
givenClickableView();
givenClickFeedbackTextView();
espView.click();
espTextView.assertTextIs(VIEW_WAS_CLICKED_MESSAGE);
}
@Test
public void testClickFailureWhenNotVisible() {
exception.expect(NoMatchingViewException.class);
exception.expectMessage("No views in hierarchy found matching: (with id: android:id/button1 and is displayed on the screen to the user)");
givenClickableView();
givenViewIsInvisible();
espView.click();
}
@Test
public void testClickSelectsOnlyVisibleView() {
givenClickableView();
givenViewIsInvisible();
givenClickableView();
givenClickFeedbackTextView();
espView.click();
espTextView.assertTextIs(VIEW_WAS_CLICKED_MESSAGE);
}
@Test
public void testExtend() {
givenClickableView();
givenClickFeedbackTextView();
MyEspView myEspView = new MyEspView(EspView.byId(viewId));
myEspView.click();
espTextView.assertTextIs(VIEW_WAS_CLICKED_MESSAGE);
}
private void givenViewIsInvisible() {
performOnUiThread(new Runnable() {
@Override
public void run() {
view.setVisibility(View.INVISIBLE);
}
});
}
private void givenViewIsGone() {
performOnUiThread(new Runnable() {
@Override
public void run() {
view.setVisibility(View.GONE);
}
});
}
private void givenViewIsDisabled() {
performOnUiThread(new Runnable() {
@Override
public void run() {
view.setEnabled(false);
}
});
}
private void givenClickableView() {
view = new Button(activityTestRule.getActivity());
view.setId(viewId);
addViewToLayout(view, BaseActivity.rootLayout);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
messageView.setText(VIEW_WAS_CLICKED_MESSAGE);
}
});
}
private void givenClickFeedbackTextView() {
messageView = new TextView(activityTestRule.getActivity());
messageView.setId(messageViewId);
addViewToLayout(messageView, BaseActivity.rootLayout);
}
private void givenViewOutsideOfScreen(int id) {
TextView textView = new TextView(getActivity());
textView.setHeight(5000);
addViewToLayout(textView, BaseActivity.rootLayout);
textView = new TextView(getActivity());
textView.setId(id);
addViewToLayout(textView, BaseActivity.rootLayout);
}
class MyEspView extends EspView {
public MyEspView(EspView template) {
super(template);
}
}
} |
package cz.seznam.euphoria.core.executor.inmem;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Strategy for emitting watermarks.
*/
public interface WatermarkEmitStrategy {
/** Default strategy used in inmem executor. */
static class Default implements WatermarkEmitStrategy {
final static ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
@Override
public void emitIfNeeded(Runnable action) {
action.run();
}
@Override
public void schedule(Runnable action) {
scheduler.scheduleAtFixedRate(action, 100, 100, TimeUnit.MILLISECONDS);
}
@Override
public void close() {
scheduler.shutdown();
}
}
/**
* Emit watermark to given collector if needed.
*/
void emitIfNeeded(Runnable action);
/**
* Schedule for periodic emitting.
*/
void schedule(Runnable action);
/**
* Terminate the strategy. Used when gracefully shutting down the executor.
*/
void close();
} |
package com.padakeji.android.ui.autowraplayoutmanager.example;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.ScrollView;
public class MyScrollView extends ScrollView {
public interface OnScrollListener {
void onScroll();
}
private int downX;
private int downY;
private int mTouchSlop;
public MyScrollView(Context context) {
super(context);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downX = (int) e.getRawX();
downY = (int) e.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int moveY = (int) e.getRawY();
if (Math.abs(moveY - downY) > mTouchSlop) {
return true;
}
}
return super.onInterceptTouchEvent(e);
}
} |
// Farrago is a relational database management system.
// This program is free software; you can redistribute it and/or
// as published by the Free Software Foundation; either version 2.1
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package net.sf.farrago.test.concurrent;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import junit.framework.TestCase;
import net.sf.farrago.trace.FarragoTrace;
import org.eigenbase.runtime.IteratorResultSet;
import org.eigenbase.util.Util;
/**
* FarragoTestConcurrentScriptedCommandGenerator creates instances of
* {@link FarragoTestConcurrentCommand} that perform specific actions in a
* specific order and within the context of a test thread
* ({@link FarragoTestConcurrentCommandExecutor}).
*
* <p>Actions are loaded from a script.
*
* TODO: Put script definition in package.html and link to it.
*
* <p>A single FarragoTestConcurrentScriptedCommandGenerator creates commands
* for multiple threads. Each thread is represented by an integer
* "thread ID" and, optionally, a String thread name. Thread IDs may
* take on any positive integer value and may be a sparse set (e.g. 1,
* 2, 5). Thread names may be any String.
*
* <p>When each command is created, it is associated with a thread and
* given an execution order. Execution order values are positive
* integers, must be unique within a thread, and may be a sparse set
* See
* {@link FarragoTestConcurrentTestCase#executeTest(FarragoTestConcurrentCommandGenerator,
* boolean)}
* for other considerations.
*
* @author Stephan Zuercher
* @version $Id$
*/
public class FarragoTestConcurrentScriptedCommandGenerator
extends FarragoTestConcurrentCommandGenerator
{
private static final String PRE_SETUP_STATE = "pre-setup";
private static final String SETUP_STATE = "setup";
private static final String POST_SETUP_STATE = "post-setup";
private static final String THREAD_STATE = "thread";
private static final String REPEAT_STATE = "repeat";
private static final String SQL_STATE = "sql";
private static final String POST_THREAD_STATE = "post-thread";
private static final String EOF_STATE = "eof";
private static final String LOCKSTEP = "@lockstep";
private static final String NOLOCKSTEP = "@nolockstep";
private static final String ENABLED = "@enabled";
private static final String DISABLED = "@disabled";
private static final String SETUP = "@setup";
private static final String END = "@end";
private static final String THREAD = "@thread";
private static final String REPEAT = "@repeat";
private static final String SYNC = "@sync";
private static final String TIMEOUT = "@timeout";
private static final String PREPARE = "@prepare";
private static final String FETCH = "@fetch";
private static final String CLOSE = "@close";
private static final String SLEEP = "@sleep";
private static final String SQL = "";
private static final String EOF = null;
private static final Object[][] STATE_TABLE = {
{ PRE_SETUP_STATE, new Object[][] { { LOCKSTEP, PRE_SETUP_STATE },
{ NOLOCKSTEP, PRE_SETUP_STATE },
{ ENABLED, PRE_SETUP_STATE },
{ DISABLED, PRE_SETUP_STATE },
{ SETUP, SETUP_STATE },
{ THREAD, THREAD_STATE } } },
{ SETUP_STATE, new Object[][] { { END, POST_SETUP_STATE },
{ SQL, SETUP_STATE } } },
{ POST_SETUP_STATE, new Object[][] { { THREAD, THREAD_STATE } } },
{ THREAD_STATE, new Object[][] { { REPEAT, REPEAT_STATE },
{ SYNC, THREAD_STATE },
{ TIMEOUT, THREAD_STATE },
{ PREPARE, THREAD_STATE },
{ FETCH, THREAD_STATE },
{ CLOSE, THREAD_STATE },
{ SLEEP, THREAD_STATE },
{ SQL, THREAD_STATE },
{ END, POST_THREAD_STATE }
} },
{ REPEAT_STATE, new Object[][] { { SYNC, REPEAT_STATE },
{ TIMEOUT, REPEAT_STATE },
{ PREPARE, REPEAT_STATE },
{ FETCH, REPEAT_STATE },
{ CLOSE, REPEAT_STATE },
{ SLEEP, REPEAT_STATE },
{ SQL, REPEAT_STATE },
{ END, THREAD_STATE } } },
{ POST_THREAD_STATE, new Object[][] { { THREAD, THREAD_STATE },
{ EOF, EOF_STATE } } }
};
private static final int FETCH_LEN = FETCH.length();
private static final int PREPARE_LEN = PREPARE.length();
private static final int REPEAT_LEN = REPEAT.length();
private static final int SLEEP_LEN = SLEEP.length();
private static final int THREAD_LEN = THREAD.length();
private static final int TIMEOUT_LEN = TIMEOUT.length();
private static final char[] spaces;
private static final char[] dashes;
private static final int BUF_SIZE = 1024;
private static final int REPEAT_READ_AHEAD_LIMIT = 65536;
static {
spaces = new char[BUF_SIZE];
dashes = new char[BUF_SIZE];
for(int i = 0; i < BUF_SIZE; i++) {
spaces[i] = ' ';
dashes[i] = '-';
}
}
public static final Integer SETUP_THREAD_ID = new Integer(-1);
private Boolean lockstep;
private Boolean disabled;
private List setupCommands = new ArrayList();
private Map threadBufferedWriters = new HashMap();
private Map threadStringWriters = new HashMap();
/**
* Constructs a new FarragoTestConcurrentScriptedCommandGenerator.
*/
public FarragoTestConcurrentScriptedCommandGenerator(String filename)
throws IOException
{
super();
parseScript(filename);
for(Iterator i = getThreadIds().iterator(); i.hasNext(); ) {
Integer threadId = (Integer)i.next();
StringWriter w = new StringWriter();
threadStringWriters.put(threadId, w);
threadBufferedWriters.put(threadId, new BufferedWriter(w));
}
StringWriter w = new StringWriter();
threadStringWriters.put(SETUP_THREAD_ID, w);
threadBufferedWriters.put(SETUP_THREAD_ID, new BufferedWriter(w));
}
boolean useLockstep()
{
if (lockstep == null) {
return false;
}
return lockstep.booleanValue();
}
boolean isDisabled()
{
if (disabled == null) {
return false;
}
return disabled.booleanValue();
}
void executeSetup(String jdbcUrl)
throws Exception
{
if (setupCommands == null || setupCommands.size() == 0) {
return;
}
Connection connection = DriverManager.getConnection(jdbcUrl);
connection.setAutoCommit(false);
try {
for(Iterator i = setupCommands.iterator(); i.hasNext(); ) {
String sql = ((String)i.next()).trim();
storeSql(SETUP_THREAD_ID, sql);
if (sql.endsWith(";")) {
sql = sql.substring(0, sql.length() - 1);
}
if (isSelect(sql)) {
Statement stmt = connection.createStatement();
try {
ResultSet rset = stmt.executeQuery(sql);
storeResults(SETUP_THREAD_ID, rset, false);
} finally {
stmt.close();
}
} else if (sql.equalsIgnoreCase("commit")) {
connection.commit();
} else if (sql.equalsIgnoreCase("rollback")) {
connection.rollback();
} else {
Statement stmt = connection.createStatement();
try {
int rows = stmt.executeUpdate(sql);
if (rows != 1) {
storeMessage(SETUP_THREAD_ID,
String.valueOf(rows)
+ " rows affected.");
} else {
storeMessage(SETUP_THREAD_ID, "1 row affected.");
}
} finally {
stmt.close();
}
}
}
} finally {
connection.rollback();
connection.close();
}
}
/**
* Parses a multi-threaded script and converts it into test
* commands.
*/
private void parseScript(String mtsqlFile)
throws IOException
{
BufferedReader in = new BufferedReader(new FileReader(mtsqlFile));
try {
String state = PRE_SETUP_STATE;
int threadId = 1;
int nextThreadId = 1;
int order = 1;
int repeatCount = 0;
while(!EOF_STATE.equals(state)) {
String line = in.readLine();
String trimmedLine = "";
if (line != null) {
trimmedLine = line.trim();
}
Map commandStateMap = lookupState(state);
String command = null;
boolean isSql = false;
if (trimmedLine.startsWith("@")) {
command = firstWord(trimmedLine);
if (!commandStateMap.containsKey(command)) {
throw new IllegalStateException(
"Command '" + command + "' not allowed in '"
+ state + "' state");
}
} else if (line == null) {
if (!commandStateMap.containsKey(EOF)) {
throw new IllegalStateException(
"Premature end of file in '" + state
+ "' state");
}
command = EOF;
} else if (trimmedLine.equals("") ||
trimmedLine.startsWith("
continue;
} else {
if (!commandStateMap.containsKey(SQL)) {
throw new IllegalStateException(
"SQL not allowed in '" + state + "' state");
}
isSql = true;
}
if (isSql) {
command = SQL;
String sql = readSql(line, in);
if (SETUP_STATE.equals(state)) {
setupCommands.add(sql.toString().trim());
} else if (THREAD_STATE.equals(state) ||
REPEAT_STATE.equals(state)) {
boolean isSelect = isSelect(sql);
for(int i = threadId; i < nextThreadId; i++) {
addCommand(
i,
order,
(isSelect
? (AbstractCommand)new SelectCommand(sql)
: (AbstractCommand)new SqlCommand(sql)));
}
order++;
} else {
assert(false);
}
} else {
// commands are handled here
if (LOCKSTEP.equals(command)) {
assert(lockstep == null):
LOCKSTEP + " and " + NOLOCKSTEP
+ " may only appear once";
lockstep = Boolean.TRUE;
} else if (NOLOCKSTEP.equals(command)) {
assert(lockstep == null):
LOCKSTEP + " and " + NOLOCKSTEP
+ " may only appear once";
lockstep = Boolean.FALSE;
} else if (DISABLED.equals(command)) {
assert(disabled == null):
DISABLED + " and " + ENABLED
+ " may only appear once";
disabled = Boolean.TRUE;
} else if (ENABLED.equals(command)) {
assert(disabled == null):
DISABLED + " and " + ENABLED
+ " may only appear once";
disabled = Boolean.FALSE;
} else if (SETUP.equals(command)) {
// nothing to do
} else if (THREAD.equals(command)) {
String threadNamesStr =
trimmedLine.substring(THREAD_LEN).trim();
StringTokenizer threadNamesTok =
new StringTokenizer(threadNamesStr, ",");
while(threadNamesTok.hasMoreTokens()) {
setThreadName(nextThreadId++,
threadNamesTok.nextToken());
}
order = 1;
} else if (REPEAT.equals(command)) {
repeatCount = Integer.parseInt(
trimmedLine.substring(REPEAT_LEN).trim());
assert(repeatCount > 0): "Repeat count must be > 0";
in.mark(REPEAT_READ_AHEAD_LIMIT);
} else if (END.equals(command)) {
if (SETUP_STATE.equals(state)) {
// nothing to do
} else if (THREAD_STATE.equals(state)) {
threadId = nextThreadId;
} else if (REPEAT_STATE.equals(state)) {
repeatCount
if (repeatCount > 0) {
try {
in.reset();
} catch(IOException e) {
throw new IllegalStateException(
"Unable to reset reader -- repeat "
+ "contents must be less than "
+ REPEAT_READ_AHEAD_LIMIT + " bytes");
}
// don't let the state change
continue;
}
} else {
assert(false);
}
} else if (SYNC.equals(command)) {
for(int i = threadId; i < nextThreadId; i++) {
addSynchronizationCommand(i, order);
}
order++;
} else if (TIMEOUT.equals(command)) {
String args =
trimmedLine.substring(TIMEOUT_LEN).trim();
String millisStr = firstWord(args);
long millis = Long.parseLong(millisStr);
assert(millis >= 0L): "Timeout must be >= 0";
String sql = readSql(skipFirstWord(args).trim(), in);
boolean isSelect = isSelect(sql);
for(int i = threadId; i < nextThreadId; i++) {
addCommand(
i,
order,
(isSelect
? (AbstractCommand)new SelectCommand(sql,
millis)
: (AbstractCommand)new SqlCommand(sql,
millis)));
}
order++;
} else if (PREPARE.equals(command)) {
String startOfSql =
trimmedLine.substring(PREPARE_LEN).trim();
String sql = readSql(startOfSql, in);
for(int i = threadId; i < nextThreadId; i++) {
addCommand(i, order, new PrepareCommand(sql));
}
order++;
} else if (FETCH.equals(command)) {
String millisStr =
trimmedLine.substring(FETCH_LEN).trim();
long millis = 0L;
if (millisStr.length() > 0) {
millis = Long.parseLong(millisStr);
assert(millis >= 0L): "Fetch timeout must be >= 0";
}
for(int i = threadId; i < nextThreadId; i++) {
addCommand(
i, order, new FetchAndPrintCommand(millis));
}
order++;
} else if (CLOSE.equals(command)) {
for(int i = threadId; i < nextThreadId; i++) {
addCloseCommand(i, order);
}
order++;
} else if (SLEEP.equals(command)) {
long millis = Long.parseLong(
trimmedLine.substring(SLEEP_LEN).trim());
assert(millis >= 0L): "Sleep timeout must be >= 0";
for(int i = threadId; i < nextThreadId; i++) {
addSleepCommand(i, order, millis);
}
order++;
} else {
assert(command == EOF): "Unknown command " + command;
}
}
state = (String)commandStateMap.get(command);
assert(state != null);
}
} finally {
in.close();
}
}
/**
* Convert a state name into a map. Map keys are the names of
* available commands (e.g. @sync), and map values are the state
* to switch to open seeing the command.
*/
private Map lookupState(String state)
{
assert(state != null);
for(int i = 0, n = STATE_TABLE.length; i < n; i++) {
if (state.equals(STATE_TABLE[i][0])) {
Object[][] stateData = (Object[][])STATE_TABLE[i][1];
HashMap result = new HashMap();
for(int j = 0, m = stateData.length; j < m; j++) {
result.put(stateData[j][0], stateData[j][1]);
}
return result;
}
}
assert(false);
return null;
}
/**
* Return the first word of the given line, assuming the line is
* trimmed. Returns the characters up the first non-whitespace
* character in the line.
*/
private String firstWord(String trimmedLine)
{
return trimmedLine.replaceFirst("\\s.*", "");
}
/**
* Return everything but the first word of the given line,
* assuming the line is trimmed. Returns the characters following
* the first series of consecutive whitespace characters in the
* line.
*/
private String skipFirstWord(String trimmedLine)
{
return trimmedLine.replaceFirst("^\\S+\\s+", "");
}
/**
* Return a block of SQL, starting with the given String. Returns
* <code>startOfSql</code> concatenated with each line from
* <code>in</code> until a line ending with a semicolon is found.
*/
private String readSql(String startOfSql, BufferedReader in)
throws IOException
{
StringBuffer sql = new StringBuffer(startOfSql);
sql.append('\n');
if (!startOfSql.trim().endsWith(";")) {
String line;
while((line = in.readLine()) != null) {
sql.append(line).append('\n');
if (line.trim().endsWith(";")) {
break;
}
}
}
return sql.toString();
}
/**
* Determine if a block of SQL is a select statment or not.
*/
private boolean isSelect(String sql)
{
BufferedReader rdr = new BufferedReader(new StringReader(sql));
try {
String line;
while((line = rdr.readLine()) != null) {
line = line.trim().toLowerCase();
if (line.startsWith("
continue;
}
if (line.startsWith("select") || line.startsWith("explain")) {
return true;
} else {
return false;
}
}
} catch(IOException e) {
assert(false): "IOException via StringReader";
} finally {
try {
rdr.close();
} catch(IOException e) {
assert(false): "IOException via StringReader";
}
}
return false;
}
/**
* Returns a map of thread ids to result data for the thread. The
* result data is an <code>String[2]</code> containing the thread
* name and the thread's output.
*/
public Map getResults()
{
TreeMap results = new TreeMap();
TreeSet threadIds = new TreeSet(getThreadIds());
threadIds.add(SETUP_THREAD_ID);
for(Iterator i = threadIds.iterator(); i.hasNext(); ) {
Integer threadId = (Integer)i.next();
String threadName = getThreadName(threadId);
try {
BufferedWriter bout =
(BufferedWriter)threadBufferedWriters.get(threadId);
bout.flush();
} catch(IOException e) {
assert(false): "IOException via StringWriter";
}
StringWriter out = (StringWriter)threadStringWriters.get(threadId);
results.put(threadId, new String[] { threadName, out.toString() });
}
return results;
}
/**
* Causes errors to be send here for custom handling. See
* {@link #customErrorHandler(FarragoTestConcurrentCommandExecutor)}.
*/
public boolean requiresCustomErrorHandling()
{
return true;
}
public void customErrorHandler(
FarragoTestConcurrentCommandExecutor executor)
{
StringBuffer message = new StringBuffer();
Throwable cause = executor.getFailureCause();
message.append(cause.getMessage());
StackTraceElement[] trace = cause.getStackTrace();
for(int i = 0; i < trace.length; i++) {
message
.append("\n\t")
.append(trace[i].toString());
}
storeMessage(executor.getThreadId(), message.toString());
}
/**
* Retrieve the output stream for the given thread id.
*
* @return a BufferedWriter on a StringWriter for the thread.
*/
private BufferedWriter getThreadWriter(Integer threadId)
{
assert(threadBufferedWriters.containsKey(threadId));
return (BufferedWriter)threadBufferedWriters.get(threadId);
}
/**
* Outputs a ResultSet for a thread.
*/
private void storeResults(Integer threadId,
ResultSet rset,
boolean timeoutSet)
throws SQLException
{
BufferedWriter out = getThreadWriter(threadId);
int[] widths = null;
try {
ResultSetMetaData meta = rset.getMetaData();
int columns = meta.getColumnCount();
String[] values = new String[columns];
String[] labels = new String[columns];
widths = new int[columns];
for(int i = 0; i < columns; i++) {
labels[i] = meta.getColumnLabel(i + 1);
widths[i] = Math.max(labels[i].length(),
meta.getColumnDisplaySize(i + 1));
}
printSeparator(out, widths);
printRow(out, labels, widths);
printSeparator(out, widths);
int rowCount = 0;
while(rset.next()) {
if (rowCount > 0 && rowCount % 100 == 0) {
printSeparator(out, widths);
printRow(out, labels, widths);
printSeparator(out, widths);
}
for(int i = 0; i < columns; i++) {
values[i] = rset.getString(i + 1);
}
printRow(out, values, widths);
rowCount++;
}
} catch (IteratorResultSet.SqlTimeoutException e) {
if (!timeoutSet) {
throw e;
}
Util.swallow(e, FarragoTrace.getTestTracer());
} finally {
printSeparator(out, widths);
try {
out.newLine();
} catch(IOException e) {
assert(false): "IOException via a StringWriter";
}
rset.close();
}
}
private void printSeparator(BufferedWriter out, int[] widths)
{
try {
for(int i = 0; i < widths.length; i++) {
if (i > 0) {
out.write("-+-");
} else {
out.write("+-");
}
int numDashes = widths[i];
while(numDashes > 0) {
out.write(dashes, 0, Math.min(numDashes, BUF_SIZE));
numDashes -= Math.min(numDashes, BUF_SIZE);
}
}
out.write("-+");
out.newLine();
} catch(IOException e) {
assert(false): "IOException on StringWriter";
}
}
/**
* Print an output table row. Something like
* <code>"| COL1 | COL2 |"</code>.
*/
private void printRow(BufferedWriter out, String[] values, int[] widths)
{
try {
for(int i = 0; i < values.length; i++) {
String value = values[i];
if (value == null) {
value = "";
}
if (i > 0) {
out.write(" | ");
} else {
out.write("| ");
}
out.write(value);
int excess = widths[i] - value.length();
while(excess > 0) {
out.write(spaces, 0, Math.min(excess, BUF_SIZE));
excess -= Math.min(excess, BUF_SIZE);
}
}
out.write(" |");
out.newLine();
} catch(IOException e) {
assert(false): "IOException on StringWriter";
}
}
/**
* Print the given SQL to the thread's output.
*/
private void storeSql(Integer threadId, String sql)
{
StringBuffer message = new StringBuffer();
BufferedReader rdr = new BufferedReader(new StringReader(sql));
try {
String line;
while((line = rdr.readLine()) != null) {
line = line.trim();
if (message.length() > 0) {
message.append('\n');
}
message.append("> ").append(line);
}
} catch(IOException e) {
assert(false): "IOException via StringReader";
} finally {
try {
rdr.close();
} catch(IOException e) {
assert(false): "IOException via StringReader";
}
}
storeMessage(threadId, message.toString());
}
/**
* Print the given message to the thread's output.
*/
private void storeMessage(Integer threadId, String message)
{
BufferedWriter out = getThreadWriter(threadId);
try {
out.write(message);
out.newLine();
} catch(IOException e) {
assert(false): "IOException on StringWriter";
}
}
private static abstract class CommandWithTimeout
extends AbstractCommand
{
private long timeout;
private CommandWithTimeout(long timeout)
{
this.timeout = timeout;
}
protected boolean setTimeout(Statement stmt)
throws SQLException
{
assert (timeout >= 0);
if (timeout > 0) {
// TODO: add support for millisecond timeouts to
// FarragoJdbcEngineStatement
assert(timeout >= 1000);
stmt.setQueryTimeout((int)(timeout / 1000));
return true;
}
return false;
}
}
/**
* SelectCommand creates and executes a SQL select statement, with
* optional timeout.
*/
private class SelectCommand extends CommandWithTimeout
{
private String sql;
private long timeout;
private SelectCommand(String sql)
{
super(0);
this.sql = sql;
}
private SelectCommand(String sql, long timeout)
{
super(timeout);
this.sql = sql;
}
protected void doExecute(FarragoTestConcurrentCommandExecutor executor)
throws SQLException
{
String properSql = sql.trim();
storeSql(executor.getThreadId(), properSql);
if (properSql.endsWith(";")) {
properSql = properSql.substring(0, properSql.length() - 1);
}
PreparedStatement stmt =
executor.getConnection().prepareStatement(properSql);
boolean timeoutSet = setTimeout(stmt);
try {
storeResults(executor.getThreadId(),
stmt.executeQuery(),
timeoutSet);
} finally {
stmt.close();
}
}
}
/**
* SelectCommand creates and executes a SQL select statement, with
* optional timeout.
*/
private class SqlCommand extends CommandWithTimeout
{
private String sql;
private long timeout;
private SqlCommand(String sql)
{
super(0);
this.sql = sql;
}
private SqlCommand(String sql, long timeout)
{
super(timeout);
this.sql = sql;
}
protected void doExecute(FarragoTestConcurrentCommandExecutor executor)
throws SQLException
{
String properSql = sql.trim();
storeSql(executor.getThreadId(), properSql);
if (properSql.endsWith(";")) {
properSql = properSql.substring(0, properSql.length() - 1);
}
if (properSql.equalsIgnoreCase("commit")) {
executor.getConnection().commit();
return;
} else if (properSql.equalsIgnoreCase("rollback")) {
executor.getConnection().rollback();
return;
}
PreparedStatement stmt =
executor.getConnection().prepareStatement(properSql);
boolean timeoutSet = setTimeout(stmt);
try {
int rows = stmt.executeUpdate();
if (rows != 1) {
storeMessage(executor.getThreadId(),
String.valueOf(rows) + " rows affected.");
} else {
storeMessage(executor.getThreadId(), "1 row affected.");
}
} catch (IteratorResultSet.SqlTimeoutException e) {
if (!timeoutSet) {
throw e;
}
Util.swallow(e, FarragoTrace.getTestTracer());
storeMessage(executor.getThreadId(), "Timeout");
} finally {
stmt.close();
}
}
}
/**
* PrepareCommand creates a {@link PreparedStatement}. Stores the
* prepared statement in the FarragoTestConcurrentCommandExecutor.
*/
private class PrepareCommand extends AbstractCommand
{
private String sql;
private PrepareCommand(String sql)
{
this.sql = sql;
}
protected void doExecute(FarragoTestConcurrentCommandExecutor executor)
throws SQLException
{
String properSql = sql.trim();
storeSql(executor.getThreadId(), properSql);
if (properSql.endsWith(";")) {
properSql = properSql.substring(0, properSql.length() - 1);
}
PreparedStatement stmt =
executor.getConnection().prepareStatement(properSql);
executor.setStatement(stmt);
}
}
/**
* FetchAndPrintCommand executes a previously prepared statement
* stored inthe FarragoTestConcurrentCommandExecutor and then outputs the
* returned rows.
*/
private class FetchAndPrintCommand extends CommandWithTimeout
{
private FetchAndPrintCommand(long timeout)
{
super(timeout);
}
protected void doExecute(FarragoTestConcurrentCommandExecutor executor)
throws SQLException
{
PreparedStatement stmt =
(PreparedStatement) executor.getStatement();
boolean timeoutSet = setTimeout(stmt);
storeResults(executor.getThreadId(),
stmt.executeQuery(),
timeoutSet);
}
}
} |
package org.ovirt.engine.ui.uicompat;
import java.util.Date;
import java.util.List;
public interface UIMessages extends com.google.gwt.i18n.client.Messages {
@DefaultMessage("One of the parameters isn''t supported (available parameter(s): {0})")
String customPropertyOneOfTheParamsIsntSupported(String parameters);
@DefaultMessage("the value for parameter <{0}> should be in the format of: <{1}>")
String customPropertyValueShouldBeInFormatReason(String parameter, String format);
@DefaultMessage("Create operation failed. Domain {0} already exists in the system.")
String createOperationFailedDcGuideMsg(String storageName);
@DefaultMessage("Name can contain only ''A-Z'', ''a-z'', ''0-9'', ''_'' or ''-'' characters, max length: {0}")
String nameCanContainOnlyMsg(int maxNameLength);
@DefaultMessage("Note: {0} will be removed!")
String detachNote(String localStoragesFormattedString);
@DefaultMessage("You are about to disconnect the Management Interface ({0}).\nAs a result, the Host might become unreachable.\n\n"
+ "Are you sure you want to disconnect the Management Interface?")
String youAreAboutToDisconnectHostInterfaceMsg(String nicName);
@DefaultMessage("Could not connect to the agent on the guest, it may be unresponsive or not installed.\nAs a result, some features may not work.")
String connectingToGuestWithNotResponsiveAgentMsg();
@DefaultMessage("This field can''t contain blanks or special characters, must be at least one character long, legal values are 0-9, a-z, ''_'', ''.'' and a length of up to {0} characters.")
String hostNameMsg(int hostNameMaxLength);
@DefaultMessage("{0} between {1} and {2}.")
String integerValidationNumberBetweenInvalidReason(String prefixMsg, int min, int max);
@DefaultMessage("{0} greater than or equal to {1}.")
String integerValidationNumberGreaterInvalidReason(String prefixMsg, int min);
@DefaultMessage("{0} less than or equal to {1}.")
String integerValidationNumberLessInvalidReason(String prefixMsg, int max);
@DefaultMessage("Field content must not exceed {0} characters.")
String lenValidationFieldMusnotExceed(int maxLength);
@DefaultMessage("Disks'' Storage Domains are not accessible.")
String vmStorageDomainIsNotAccessible();
@DefaultMessage("No Storage Domain is active.")
String noActiveStorageDomain();
@DefaultMessage("This name was already assigned to another cloned Virtual Machine.")
String alreadyAssignedClonedVmName();
@DefaultMessage("This suffix will cause a name collision with another cloned Virtual Machine: {0}.")
String suffixCauseToClonedVmNameCollision(String vmName);
@DefaultMessage("This name was already assigned to another cloned Template.")
String alreadyAssignedClonedTemplateName();
@DefaultMessage("This suffix will cause a name collision with another cloned Template: {0}.")
String suffixCauseToClonedTemplateNameCollision(String templateName);
@DefaultMessage("Create operation failed. Storage connection is already used by the following storage domain: {0}.")
String createFailedDomainAlreadyExistStorageMsg(String storageName);
@DefaultMessage("Import operation failed. Domain {0} already exists in the system.")
String importFailedDomainAlreadyExistStorageMsg(String storageName);
@DefaultMessage("Memory size is between {0} MB and {1} MB")
String memSizeBetween(int minMemSize, int maxMemSize);
@DefaultMessage("Maximum memory size is {0} MB.")
String maxMemSizeIs(int maxMemSize);
@DefaultMessage("Minimum memory size is {0} MB.")
String minMemSizeIs(int minMemSize);
@DefaultMessage("Name must contain only alphanumeric characters, \"-\", \"_\" or \".\". Maximum length: {0}.")
String nameMustConataionOnlyAlphanumericChars(int maxLen);
@DefaultMessage("Name (with suffix) can contain only alphanumeric, '.', '_' or '-' characters. Maximum length: {0}.")
String newNameWithSuffixCannotContainBlankOrSpecialChars(int maxLen);
@DefaultMessage("Import process has begun for VM(s): {0}.\nYou can check import status in the main ''Events'' tab")
String importProcessHasBegunForVms(String importedVms);
@DefaultMessage("''{0}'' Storage Domain is not active. Please activate it.")
String storageDomainIsNotActive(String storageName);
@DefaultMessage("Import process has begun for Template(s): {0}.\nYou can check import status in the main ''Events'' tab")
String importProcessHasBegunForTemplates(String importedTemplates);
@DefaultMessage("Template(s): {0} already exist on the target Export Domain. If you want to override them, please check the ''Force Override'' check-box.")
String templatesAlreadyExistonTargetExportDomain(String existingTemplates);
@DefaultMessage("VM(s): {0} already exist on the target Export Domain. If you want to override them, please check the ''Force Override'' check-box.")
String vmsAlreadyExistOnTargetExportDomain(String existingVMs);
@DefaultMessage("Shared disk(s) will not be a part of the VM export: {0}.")
String sharedDisksWillNotBePartOfTheExport(String diskList);
@DefaultMessage("Direct LUN disk(s) will not be a part of the VM export: {0}.")
String directLUNDisksWillNotBePartOfTheExport(String diskList);
@DefaultMessage("Disk snapshot(s) will not be a part of the VM export: {0}.")
String snapshotDisksWillNotBePartOfTheExport(String diskList);
@DefaultMessage("There are no disks allowing an export, only the configuration will be a part of the VM export.")
String noExportableDisksFoundForTheExport();
@DefaultMessage("Shared disk(s) will not be a part of the VM snapshot: {0}.")
String sharedDisksWillNotBePartOfTheSnapshot(String diskList);
@DefaultMessage("Direct LUN disk(s) will not be a part of the VM snapshot: {0}.")
String directLUNDisksWillNotBePartOfTheSnapshot(String diskList);
@DefaultMessage("Disk snapshot(s) will not be a part of the VM snapshot: {0}.")
String snapshotDisksWillNotBePartOfTheSnapshot(String diskList);
@DefaultMessage("There are no disks allowing a snapshot, only the configuration will be a part of the VM snapshot.")
String noExportableDisksFoundForTheSnapshot();
@DefaultMessage("Shared disk(s) will not be a part of the VM template: {0}.")
String sharedDisksWillNotBePartOfTheTemplate(String diskList);
@DefaultMessage("Direct LUN disk(s) will not be a part of the VM template: {0}.")
String directLUNDisksWillNotBePartOfTheTemplate(String diskList);
@DefaultMessage("Snapshot disk(s) will not be a part of the VM template: {0}.")
String snapshotDisksWillNotBePartOfTheTemplate(String diskList);
@DefaultMessage("There are no disks allowing an export, only the configuration will be a part of the VM template.")
String noExportableDisksFoundForTheTemplate();
@DefaultMessage("{0} (Last scan: {1})")
String diskAlignment(String alignment, String lastScanDate);
@DefaultMessage("Error connecting to Virtual Machine using SPICE:\n{0}")
String errConnectingVmUsingSpiceMsg(Object errCode);
@DefaultMessage("Error connecting to Virtual Machine using RPD:\n{0}")
String errConnectingVmUsingRdpMsg(Object errCode);
@DefaultMessage("Are you sure you want to delete snapshot from {0} with description ''{1}''?")
String areYouSureYouWantToDeleteSanpshot(Date from, Object description);
@DefaultMessage("Edit Bond Interface {0}")
String editBondInterfaceTitle(String name);
@DefaultMessage("Edit Interface {0}")
String editInterfaceTitle(String name);
@DefaultMessage("Edit Network {0}")
String editNetworkTitle(String name);
@DefaultMessage("Setup Host {0} Networks")
String setupHostNetworksTitle(String hostName);
@DefaultMessage("({0} bricks selected)")
String noOfBricksSelected(int brickCount);
@DefaultMessage("Please use your VNC client to connect to this VM.<br/><br/>Use the following parameters:<br/>IP:Port -- {0}:{1}<br/><br/> Password: {2}<br/>(note: this password is valid for {3} seconds)")
String vncInfoMessage(String hostIp, int port, String password, int seconds);
@DefaultMessage("Press {0} to Release Cursor")
String pressKeyToReleaseCursor(String key);
@DefaultMessage("LUN is already part of Storage Domain: {0}")
String lunAlreadyPartOfStorageDomainWarning(String storageDomainName);
@DefaultMessage("LUN is already used by disk: {0}")
String lunUsedByDiskWarning(String diskAlias);
@DefaultMessage("Used by VG: {0}")
String lunUsedByVG(String vgID);
@DefaultMessage("Replica count will be reduced from {0} to {1}. Are you sure you want to remove the following Brick(s)?")
String removeBricksReplicateVolumeMessage(int oldReplicaCount, int newReplicaCount);
@DefaultMessage("Break Bond {0}")
String breakBond(String bondName);
@DefaultMessage("Detach Network {0}")
String detachNetwork(String networkName);
@DefaultMessage("Remove Network {0}")
String removeNetwork(String networkName);
@DefaultMessage("Attach {0} to")
String attachTo(String name);
@DefaultMessage("Bond {0} with")
String bondWith(String name);
@DefaultMessage("Add {0} to Bond")
String addToBond(String name);
@DefaultMessage("Extend {0} with")
String extendBond(String name);
@DefaultMessage("Remove {0} from Bond")
String removeFromBond(String name);
@DefaultMessage("This might work without network {0}.")
String suggestDetachNetwork(String networkName);
@DefaultMessage("Label {0} cannot be assigned to this interface, it is already assigned to interface {1}.")
String labelInUse(String label, String ifaceName);
@DefaultMessage("Incorrect number of Total Virtual CPUs. It is not possible to compose this number from the available Virtual Sockets and Cores per Virtual Sockets")
String incorrectVCPUNumber();
@DefaultMessage("The max allowed name length is {0} for {1} VMs in pool")
String poolNameLengthInvalid(int maxLength, int vmsInPool);
@DefaultMessage("The max allowed num of VMs is {0} when the length of the pool name is {1}")
String numOfVmsInPoolInvalod(int maxLength, int vmsInPool);
@DefaultMessage("Refresh Interval: {0} sec")
String refreshInterval(int intervalSec);
@DefaultMessage("Name field is empty for host with address {0}")
String importClusterHostNameEmpty(String address);
@DefaultMessage("Root Password field is empty for host with address {0}")
String importClusterHostPasswordEmpty(String address);
@DefaultMessage("Fingerprint field is empty for host with address {0}")
String importClusterHostFingerprintEmpty(String address);
@DefaultMessage("Unable to fetch the Fingerprint of the host(s) {0,list,text}")
String unreachableGlusterHosts(List<String> hosts);
@DefaultMessage("{0} in Data Center {1} ({2})")
String networkDcDescription(String networkName, String dcName, String description);
@DefaultMessage("{0} in Data Center {1}")
String networkDc(String networkName, String dcName);
@DefaultMessage("Vnic {0} from VM {1}")
String vnicFromVm(String vnic, String vm);
@DefaultMessage("VM Interface Profile {0} from Network {1}")
String vnicProfileFromNetwork(String vnicProfile, String network);
@DefaultMessage("Vnic {0} from Template {1}")
String vnicFromTemplate(String vnic, String template);
@DefaultMessage("Non-VM networks are not supported for Cluster version {0}")
String bridlessNetworkNotSupported(String version);
@DefaultMessage("Overriding MTU configuration is not supported for Cluster version {0}")
String mtuOverrideNotSupported(String version);
@DefaultMessage("{0} VMs")
String numberOfVmsForHostsLoad(int numberOfVms);
@DefaultMessage("{0} ({1} Socket(s), {2} Core(s) per Socket)")
String cpuInfoLabel(int numberOfCpus, int numberOfSockets, int numberOfCpusPerSocket);
@DefaultMessage("{0} (from Storage Domain {1})")
String templateDiskDescription(String diskAlias, String storageDomainName);
@DefaultMessage("Virtual Machine must have at least one network interface defined to boot from network.")
String interfaceIsRequiredToBootFromNetwork();
@DefaultMessage("Virtual Machine must have at least one bootable disk defined to boot from hard disk.")
String bootableDiskIsRequiredToBootFromDisk();
@DefaultMessage("Diskless Virtual Machine cannot run in stateless mode")
String disklessVmCannotRunAsStateless();
@DefaultMessage("Given URL must not contain a scheme (e.g. ''{0}'').")
String urlSchemeMustBeEmpty(String passedScheme);
@DefaultMessage("Given URL does not contain a scheme, it must contain one of the following:\n\n{0}")
String urlSchemeMustNotBeEmpty(String allowedSchemes);
@DefaultMessage("Given URL contains invalid scheme ''{0}'', only the following schemes are allowed:\n\n{1}")
String urlSchemeInvalidScheme(String passedScheme, String allowedSchemes);
@DefaultMessage("Changing the URL of this provider might hurt the proper functioning of the following entities provided by it.\n\n{0}")
String providerUrlWarningText(String providedEntities);
// Vnic
@DefaultMessage("The virtual machine is running and NIC Hot Plug is not supported on cluster version {0} or by the operating system.")
String nicHotPlugNotSupported(String clusterVersion);
@DefaultMessage("Updating 'profile' on a running virtual machine while the NIC is plugged is not supported on cluster version {0}")
String hotProfileUpdateNotSupported(String clusterVersion);
@DefaultMessage("Custom({0})")
String customSpmPriority(int priority);
@DefaultMessage("Brick Details not supported for this Cluster''s compatibility version({0}).")
String brickDetailsNotSupportedInClusterCompatibilityVersion(String version);
@DefaultMessage("{0} ({1} Running VM(s))")
String hostNumberOfRunningVms(String hostName, int runningVms);
@DefaultMessage("{0} ({1})")
String commonMessageWithBrackets(String subject, String inBrackets);
@DefaultMessage("This Network QoS is used by {0} Vnic Profiles.\nAre you sure you want to remove this Network QoS?\n\n Profiles using this QoS:\n")
String removeNetworkQoSMessage(int numOfProfiles);
@DefaultMessage("{0} ({1} Socket(s), {2} Core(s) per Socket)")
String cpuInfoMessage(int numOfCpus, int sockets, int coresPerSocket);
@DefaultMessage("Could not fetch rebalance status of volume : {0}")
String rebalanceStatusFailed(String name);
@DefaultMessage("Could not fetch profile statistics of volume : {0}")
String volumeProfileStatisticsFailed(String volName);
@DefaultMessage("Could not fetch remove brick status of volume : {0}")
String removeBrickStatusFailed(String name);
@DefaultMessage("Are you sure you want to stop the rebalance operation on the volume : {0}?")
String confirmStopVolumeRebalance(String name);
@DefaultMessage("The following disks cannot be moved: {0}")
String cannotMoveDisks(String disks);
@DefaultMessage("The following disks cannot be copied: {0}")
String cannotCopyDisks(String disks);
@DefaultMessage("The following disks will become preallocated, and may consume considerably more space on the target: {0}")
String moveDisksPreallocatedWarning(String disks);
@DefaultMessage("Error connecting to {0} using {1} protocol")
String errorConnectingToConsole(String name, String s);
@DefaultMessage("Cannot connect to the console for {0}")
String cannotConnectToTheConsole(String vmName);
@DefaultMessage("Optimize scheduling for host weighing (ordering):\n" +
"Utilization: include weight modules in scheduling to allow best selection\n" +
"Speed: skip host weighing in case there are more than {0} pending requests")
String schedulerOptimizationInfo(int numOfRequests);
@DefaultMessage("Overbooking: Allows running cluster''s scheduling requests in parallel, " +
"without preserving resource allocation. This option allows handling a mass of " +
"scheduling requests ({0} requests), while some requests may fail due to the re-use of the " +
"same resource allocation (Use this option only if you are familiar with this behavior).")
String schedulerAllowOverbookingInfo(int numOfRequests);
@DefaultMessage("{0} (Clone/Independent)")
String vmTemplateWithCloneProvisioning(String templateName);
@DefaultMessage("{0} (Thin/Dependent)")
String vmTemplateWithThinProvisioning(String templateName);
@DefaultMessage("You are about to change the Data Center Compatibility Version. This will upgrade all the " +
"Storage Domains belonging to the Data Center, and make them unusable with versions older than {0}. " +
"Are you sure you want to continue?")
String youAreAboutChangeDcCompatibilityVersionWithUpgradeMsg(String version);
@DefaultMessage("Active (Score: {0})")
String haActive(int score);
@DefaultMessage("Volume Profile Statistics - {0}")
String volumeProfilingStatsTitle(String volumeName);
@DefaultMessage("Network couldn''t be assigned to ''{0}'' via label ''{1}''.")
String networkLabelConflict(String nicName, String labelName);
@DefaultMessage("Network should be assigned to ''{0}'' via label ''{1}''. However, for some reason it isn''t.")
String labeledNetworkNotAttached(String nicName, String labelName);
@DefaultMessage("VM Boot menu is not supported in Cluster version {0}")
String bootMenuNotSupported(String clusterVersion);
@DefaultMessage("Disk {0} from Snapshot {1}")
String diskSnapshotLabel(String diskAlias, String snapshotDescription);
@DefaultMessage("This option is not supported in Cluster version {0}")
String optionNotSupportedClusterVersionTooOld(String clusterVersion);
@DefaultMessage("This option requires SPICE display protocol to be used")
String optionRequiresSpiceEnabled();
@DefaultMessage("Random Number Generator source ''{0}'' is not supported by the cluster")
String rngSourceNotSupportedByCluster(String source);
@DefaultMessage("Current interval of profiling has been running for {0} {1} of the total {2} {3} profiling time")
String glusterVolumeCurrentProfileRunTime(int currentRunTime, String currentRunTimeUnit, int totalRunTime, String totalRunTimeUnit);
@DefaultMessage("{0} {1} have been read in the current profiling interval out of {2} {3} during profiling")
String bytesReadInCurrentProfileInterval(String currentBytesRead, String currentBytesReadUnit, String totalBytes, String totalBytesUnit);
@DefaultMessage("{0} {1} have been written in the current profiling interval out of {2} {3} during profiling")
String bytesWrittenInCurrentProfileInterval(String currentBytesWritten, String currentBytesWrittenUnit, String totalBytes, String totalBytesUnit);
@DefaultMessage("Default ({0})")
String defaultMtu(int mtu);
} |
package uk.ac.ebi.atlas.experimentpage.baseline.grouping;
import com.google.common.collect.FluentIterable;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import uk.ac.ebi.atlas.model.FactorAcrossExperiments;
import uk.ac.ebi.atlas.model.OntologyTerm;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@Named
public class FactorGroupingService {
OrganismPartGroupingService organismPartGroupingService;
@Inject
public FactorGroupingService(OrganismPartGroupingService organismPartGroupingService) {
this.organismPartGroupingService = organismPartGroupingService;
}
public JsonArray group(String defaultQueryFactorType,
Collection<FactorAcrossExperiments> factorsAcrossExperiments) {
return "ORGANISM_PART".equalsIgnoreCase(defaultQueryFactorType)
? groupOrganismPartOntologyTerms(FluentIterable.from(factorsAcrossExperiments)
.transformAndConcat(
factorAcrossExperiments -> factorAcrossExperiments.getValueOntologyTerms()
).toSet())
: new JsonArray();
}
JsonArray groupOrganismPartOntologyTerms(Collection<OntologyTerm> ontologyTermsInAllFactors) {
JsonArray result = new JsonArray();
groupingAsJson(organismPartGroupingService.getOrgansGrouping(ontologyTermsInAllFactors), "Organs", "Organ")
.ifPresent(o -> result.add(o));
groupingAsJson(organismPartGroupingService.getAnatomicalSystemsGrouping(ontologyTermsInAllFactors), "Anatomical Systems", "Anatomical system")
.ifPresent(o -> result.add(o));
return result;
}
boolean hasOntologyTerms(Map<ColumnGroup, Set<OntologyTerm>> m) {
return m.values().stream().map(s -> s.size()).reduce(0, (integer, integer2) -> integer + integer2) > 0;
}
Optional<JsonObject> groupingAsJson(Map<ColumnGroup, Set<OntologyTerm>> grouping, String name, String memberName) {
return groupsAsJson(grouping).map(a -> {
JsonObject result = new JsonObject();
result.addProperty("name", name);
result.addProperty("memberName", memberName);
result.add("groups", a);
return result;
});
}
Optional<JsonArray> groupsAsJson(Map<ColumnGroup, Set<OntologyTerm>> groups) {
if (hasOntologyTerms(groups)) {
JsonArray result = new JsonArray();
for (Map.Entry<ColumnGroup, Set<OntologyTerm>> e : groups.entrySet()) {
result.add(oneGroup(e));
}
return Optional.of(result);
} else {
return Optional.empty();
}
}
JsonObject oneGroup(Map.Entry<ColumnGroup, Set<OntologyTerm>> e) {
JsonObject thisSystemAndItsValues = e.getKey().toJson();
JsonArray factorValues = new JsonArray();
for (OntologyTerm f : e.getValue()) {
factorValues.add(new JsonPrimitive(f.accession()));
}
thisSystemAndItsValues.add("values", factorValues);
return thisSystemAndItsValues;
}
} |
package com.hazelcast.internal.partition.impl;
import com.hazelcast.config.Config;
import com.hazelcast.config.ServiceConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.internal.partition.InternalPartition;
import com.hazelcast.internal.partition.InternalPartitionService;
import com.hazelcast.internal.partition.MigrationInfo;
import com.hazelcast.internal.partition.MigrationInfo.MigrationStatus;
import com.hazelcast.internal.partition.service.TestGetOperation;
import com.hazelcast.internal.partition.service.TestMigrationAwareService;
import com.hazelcast.internal.partition.service.TestPutOperation;
import com.hazelcast.nio.Address;
import com.hazelcast.spi.PartitionMigrationEvent;
import com.hazelcast.spi.impl.operationservice.InternalOperationService;
import com.hazelcast.spi.properties.GroupProperty;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.ExpectedRuntimeException;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.TestPartitionUtils;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.hazelcast.internal.partition.impl.MigrationCommitTest.resetInternalMigrationListener;
import static com.hazelcast.spi.partition.MigrationEndpoint.DESTINATION;
import static com.hazelcast.spi.partition.MigrationEndpoint.SOURCE;
import static com.hazelcast.test.TestPartitionUtils.getReplicaVersions;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class MigrationCommitServiceTest
extends HazelcastTestSupport {
private static final int NODE_COUNT = 4;
private static final int PARTITION_COUNT = 10;
private static final int BACKUP_COUNT = 6;
private static final int PARTITION_ID_TO_MIGRATE = 0;
private volatile CountDownLatch blockMigrationStartLatch;
private TestHazelcastInstanceFactory factory;
private HazelcastInstance[] instances;
@Before
public void setup()
throws ExecutionException, InterruptedException {
blockMigrationStartLatch = new CountDownLatch(1);
factory = createHazelcastInstanceFactory(NODE_COUNT);
instances = factory.newInstances(createConfig(), NODE_COUNT);
warmUpPartitions(instances);
waitAllForSafeState(instances);
final InternalOperationService operationService = getOperationService(instances[0]);
for (int partitionId = 0; partitionId < PARTITION_COUNT; partitionId++) {
operationService.invokeOnPartition(null, new TestPutOperation(), partitionId).get();
}
assertTrueEventually(new AssertTask() {
@Override
public void run()
throws Exception {
for (int partitionId = 0; partitionId < PARTITION_COUNT; partitionId++) {
final InternalPartitionService partitionService = getPartitionService(instances[0]);
final InternalPartition partition = partitionService.getPartition(partitionId);
for (int i = 0; i <= BACKUP_COUNT; i++) {
final Address replicaAddress = partition.getReplicaAddress(i);
if (replicaAddress != null) {
final TestMigrationAwareService service = getService(replicaAddress);
assertNotNull(service.get(partitionId));
}
}
}
}
});
for (HazelcastInstance instance : instances) {
final TestMigrationAwareService service = getNodeEngineImpl(instance)
.getService(TestMigrationAwareService.SERVICE_NAME);
service.clearEvents();
}
}
@After
public void after() {
blockMigrationStartLatch.countDown();
}
@Test
public void testPartitionOwnerMoveCommit()
throws InterruptedException, TimeoutException, ExecutionException {
final int replicaIndexToClear = NODE_COUNT - 1, replicaIndexToMigrate = 0;
testSuccessfulMoveMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, replicaIndexToMigrate);
}
@Test
public void testPartitionOwnerMoveRollback()
throws InterruptedException, TimeoutException, ExecutionException {
final int replicaIndexToClear = NODE_COUNT - 1, replicaIndexToMigrate = 0;
testFailedMoveMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, replicaIndexToMigrate);
}
@Test
public void testPartitionBackupMoveCommit()
throws InterruptedException, TimeoutException, ExecutionException {
final int replicaIndexToClear = NODE_COUNT - 1, replicaIndexToMigrate = NODE_COUNT - 2;
testSuccessfulMoveMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, replicaIndexToMigrate);
}
@Test
public void testPartitionBackupMoveRollback()
throws InterruptedException, TimeoutException, ExecutionException {
final int replicaIndexToClear = NODE_COUNT - 1, replicaIndexToMigrate = NODE_COUNT - 2;
testFailedMoveMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, replicaIndexToMigrate);
}
private void testSuccessfulMoveMigration(final int partitionId, final int replicaIndexToClear,
final int replicaIndexToMigrate)
throws InterruptedException, TimeoutException, ExecutionException {
final Address destination = clearReplicaIndex(partitionId, replicaIndexToClear);
final MigrationInfo migration = createMoveMigration(partitionId, replicaIndexToMigrate, destination);
migrateWithSuccess(migration);
assertMigrationSourceCommit(migration);
assertMigrationDestinationCommit(migration);
assertPartitionDataAfterMigrations();
}
private void testFailedMoveMigration(final int partitionId, final int replicaIndexToClear, final int replicaIndexToMigrate)
throws InterruptedException, TimeoutException, ExecutionException {
final Address destination = clearReplicaIndex(partitionId, replicaIndexToClear);
final MigrationInfo migration = createMoveMigration(partitionId, replicaIndexToMigrate, destination);
migrateWithFailure(migration);
assertMigrationSourceRollback(migration);
assertMigrationDestinationRollback(migration);
assertPartitionDataAfterMigrations();
}
@Test
public void testPartitionOwnerShiftDownCommitWithOldOwnerOfKeepReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = 0, replicaIndexToClear = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 2;
testSuccessfulShiftDownMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, oldReplicaIndex, newReplicaIndex);
}
@Test
public void testPartitionOwnerShiftDownRollbackWithOldOwnerOfKeepReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = 0, replicaIndexToClear = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 2;
testFailedShiftDownMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, oldReplicaIndex, newReplicaIndex);
}
@Test
public void testPartitionOwnerShiftDownCommitWithNullOwnerOfKeepReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = 0, replicaIndexToClear = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 1;
testSuccessfulShiftDownMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, oldReplicaIndex, newReplicaIndex);
}
@Test
public void testPartitionOwnerShiftDownRollbackWithNullOwnerOfKeepReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = 0, replicaIndexToClear = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 1;
testFailedShiftDownMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, oldReplicaIndex, newReplicaIndex);
}
@Test
public void testPartitionBackupShiftDownCommitWithOldOwnerOfKeepReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = 1, replicaIndexToClear = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 2;
testSuccessfulShiftDownMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, oldReplicaIndex, newReplicaIndex);
}
@Test
public void testPartitionBackupShiftDownRollbackWithOldOwnerOfKeepReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = 1, replicaIndexToClear = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 2;
testFailedShiftDownMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, oldReplicaIndex, newReplicaIndex);
}
@Test
public void testPartitionBackupMoveCopyBackCommitWithNullOwnerOfKeepReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = 1, replicaIndexToClear = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 1;
testSuccessfulShiftDownMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, oldReplicaIndex, newReplicaIndex);
}
@Test
public void testPartitionBackupMoveCopyBackRollbackWithNullOwnerOfKeepReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = 1, replicaIndexToClear = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 1;
testFailedShiftDownMigration(PARTITION_ID_TO_MIGRATE, replicaIndexToClear, oldReplicaIndex, newReplicaIndex);
}
private void testSuccessfulShiftDownMigration(final int partitionId, final int replicaIndexToClear,
final int oldReplicaIndex, final int newReplicaIndex)
throws InterruptedException, TimeoutException, ExecutionException {
final Address destination = clearReplicaIndex(partitionId, replicaIndexToClear);
final MigrationInfo migration = createMoveCopyBackMigration(partitionId, oldReplicaIndex, newReplicaIndex, destination);
migrateWithSuccess(migration);
assertMigrationSourceCommit(migration);
assertMigrationDestinationCommit(migration);
final Address oldReplicaOwner = migration.getOldBackupReplicaOwner();
if (oldReplicaOwner != null) {
assertTrueEventually(new AssertTask() {
@Override
public void run()
throws Exception {
final TestMigrationAwareService service = getService(oldReplicaOwner);
final List<Integer> clearPartitionIds = service.getClearPartitionIds();
assertTrue(clearPartitionIds.size() == 1);
assertEquals(partitionId, (int) clearPartitionIds.get(0));
}
});
}
assertPartitionDataAfterMigrations();
}
private void testFailedShiftDownMigration(final int partitionId, final int replicaIndexToClear,
final int oldReplicaIndex, final int newReplicaIndex)
throws InterruptedException, TimeoutException, ExecutionException {
final Address destination = clearReplicaIndex(partitionId, replicaIndexToClear);
final MigrationInfo migration = createMoveCopyBackMigration(partitionId, oldReplicaIndex, newReplicaIndex, destination);
migrateWithFailure(migration);
assertMigrationSourceRollback(migration);
assertMigrationDestinationRollback(migration);
final Address oldReplicaOwner = migration.getOldBackupReplicaOwner();
if (oldReplicaOwner != null) {
assertTrueAllTheTime(new AssertTask() {
@Override
public void run()
throws Exception {
final TestMigrationAwareService service = getService(oldReplicaOwner);
final List<Integer> clearPartitionIds = service.getClearPartitionIds();
assertTrue(clearPartitionIds.isEmpty());
}
}, 5);
}
assertPartitionDataAfterMigrations();
}
@Test
public void testPartitionBackupCopyCommit()
throws InterruptedException, TimeoutException, ExecutionException {
final Address destination = clearReplicaIndex(PARTITION_ID_TO_MIGRATE, NODE_COUNT - 1);
final MigrationInfo migration = createCopyMigration(PARTITION_ID_TO_MIGRATE, NODE_COUNT - 1, destination);
migrateWithSuccess(migration);
assertMigrationDestinationCommit(migration);
assertPartitionDataAfterMigrations();
}
@Test
public void testPartitionBackupCopyRollback()
throws InterruptedException, TimeoutException, ExecutionException {
final Address destination = clearReplicaIndex(PARTITION_ID_TO_MIGRATE, NODE_COUNT - 1);
final MigrationInfo migration = createCopyMigration(PARTITION_ID_TO_MIGRATE, NODE_COUNT - 1, destination);
migrateWithFailure(migration);
assertMigrationDestinationRollback(migration);
assertPartitionDataAfterMigrations();
}
@Test
public void testPartitionBackupShiftUpCommitWithNonNullOwnerOfReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 2;
final MigrationInfo migration = createShiftUpMigration(PARTITION_ID_TO_MIGRATE, oldReplicaIndex, newReplicaIndex);
migrateWithSuccess(migration);
assertMigrationSourceCommit(migration);
assertMigrationDestinationCommit(migration);
assertPartitionDataAfterMigrations();
}
@Test
public void testPartitionBackupShiftUpRollbackWithNonNullOwnerOfReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 2;
final MigrationInfo migration = createShiftUpMigration(PARTITION_ID_TO_MIGRATE, oldReplicaIndex, newReplicaIndex);
migrateWithFailure(migration);
assertMigrationSourceRollback(migration);
assertMigrationDestinationRollback(migration);
assertPartitionDataAfterMigrations();
}
@Test
public void testPartitionBackupShiftUpCommitWithNullOwnerOfReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 2;
clearReplicaIndex(PARTITION_ID_TO_MIGRATE, newReplicaIndex);
final MigrationInfo migration = createShiftUpMigration(PARTITION_ID_TO_MIGRATE, oldReplicaIndex, newReplicaIndex);
migrateWithSuccess(migration);
assertMigrationDestinationCommit(migration);
assertPartitionDataAfterMigrations();
}
@Test
public void testPartitionBackupShiftUpRollbackWithNullOwnerOfReplicaIndex()
throws InterruptedException, TimeoutException, ExecutionException {
final int oldReplicaIndex = NODE_COUNT - 1, newReplicaIndex = NODE_COUNT - 2;
clearReplicaIndex(PARTITION_ID_TO_MIGRATE, newReplicaIndex);
final MigrationInfo migration = createShiftUpMigration(PARTITION_ID_TO_MIGRATE, oldReplicaIndex, newReplicaIndex);
migrateWithFailure(migration);
assertMigrationDestinationRollback(migration);
assertPartitionDataAfterMigrations();
}
private MigrationInfo createMoveMigration(final int partitionId, final int replicaIndex, final Address destination) {
final InternalPartition partition = getPartition(instances[0], partitionId);
final Address source = partition.getReplicaAddress(replicaIndex);
return new MigrationInfo(partitionId, source, destination, replicaIndex, -1, -1, replicaIndex);
}
private MigrationInfo createMoveCopyBackMigration(final int partitionId, final int oldReplicaIndex, final int newReplicaIndex,
final Address destination) {
final InternalPartitionImpl partition = getPartition(instances[0], partitionId);
final Address source = partition.getReplicaAddress(oldReplicaIndex);
final Address oldReplicaOwner = partition.getReplicaAddress(newReplicaIndex);
final MigrationInfo migration = new MigrationInfo(partitionId, source, destination, oldReplicaIndex, newReplicaIndex, -1,
oldReplicaIndex);
migration.setOldBackupReplicaOwner(oldReplicaOwner);
return migration;
}
private MigrationInfo createCopyMigration(final int partitionId, final int copyReplicaIndex, final Address destination) {
return new MigrationInfo(partitionId, null, destination, -1, -1, -1, copyReplicaIndex);
}
private MigrationInfo createShiftUpMigration(final int partitionId, final int oldReplicaIndex, final int newReplicaIndex) {
final InternalPartitionImpl partition = getPartition(instances[0], partitionId);
final Address source = partition.getReplicaAddress(newReplicaIndex);
final Address destination = partition.getReplicaAddress(oldReplicaIndex);
return new MigrationInfo(partitionId, source, destination, newReplicaIndex, -1, oldReplicaIndex, newReplicaIndex);
}
private Address clearReplicaIndex(final int partitionId, final int replicaIndexToClear) {
final InternalPartitionServiceImpl partitionService = (InternalPartitionServiceImpl) getPartitionService(instances[0]);
final InternalPartitionImpl partition = (InternalPartitionImpl) partitionService.getPartition(partitionId);
final Address oldReplicaOwner = partition.getReplicaAddress(replicaIndexToClear);
partition.setReplicaAddress(replicaIndexToClear, null);
final MigrationInfo migration = new MigrationInfo(0, oldReplicaOwner, null, replicaIndexToClear, -1, -1, -1);
migration.setMaster(getAddress(instances[0]));
migration.setOldBackupReplicaOwner(oldReplicaOwner);
migration.setStatus(MigrationStatus.SUCCESS);
partitionService.getMigrationManager().addCompletedMigration(migration);
partitionService.getMigrationManager().scheduleActiveMigrationFinalization(migration);
assertTrueEventually(new AssertTask() {
@Override
public void run()
throws Exception {
assertTrue(partitionService.syncPartitionRuntimeState());
}
});
assertTrueEventually(new AssertTask() {
@Override
public void run()
throws Exception {
final TestMigrationAwareService service = getService(oldReplicaOwner);
assertFalse(service.contains(partitionId));
final long[] replicaVersions = TestPartitionUtils
.getReplicaVersions(factory.getInstance(oldReplicaOwner), partitionId);
assertArrayEquals(new long[InternalPartition.MAX_BACKUP_COUNT], replicaVersions);
}
});
for (HazelcastInstance instance : instances) {
final TestMigrationAwareService service = getNodeEngineImpl(instance)
.getService(TestMigrationAwareService.SERVICE_NAME);
service.clearEvents();
}
return oldReplicaOwner;
}
private void migrateWithSuccess(final MigrationInfo migration) {
final InternalPartitionServiceImpl partitionService = (InternalPartitionServiceImpl) getPartitionService(instances[0]);
partitionService.getMigrationManager().scheduleMigration(migration);
waitAllForSafeState(instances);
}
private void migrateWithFailure(final MigrationInfo migration) {
if (!getAddress(instances[0]).equals(migration.getDestination())) {
final HazelcastInstance destinationInstance = factory.getInstance(migration.getDestination());
final RejectMigrationOnComplete destinationListener = new RejectMigrationOnComplete(destinationInstance);
final InternalPartitionServiceImpl destinationPartitionService = (InternalPartitionServiceImpl) getPartitionService(
destinationInstance);
destinationPartitionService.getMigrationManager().setInternalMigrationListener(destinationListener);
}
final InternalPartitionServiceImpl partitionService = (InternalPartitionServiceImpl) getPartitionService(instances[0]);
final CountDownMigrationRollbackOnMaster masterListener = new CountDownMigrationRollbackOnMaster(migration);
partitionService.getMigrationManager().setInternalMigrationListener(masterListener);
partitionService.getMigrationManager().scheduleMigration(migration);
assertOpenEventually(masterListener.latch);
}
private void assertMigrationSourceCommit(final MigrationInfo migration)
throws InterruptedException {
assertTrueEventually(new AssertTask() {
@Override
public void run()
throws Exception {
final TestMigrationAwareService service = getService(migration.getSource());
final String msg = getAssertMessage(migration, service);
assertFalse(service.getBeforeEvents().isEmpty());
assertFalse(service.getCommitEvents().isEmpty());
final PartitionMigrationEvent beforeEvent = service.getBeforeEvents().get(0);
final PartitionMigrationEvent sourceCommitEvent = service.getCommitEvents().get(0);
assertSourcePartitionMigrationEvent(msg, beforeEvent, migration);
assertSourcePartitionMigrationEvent(msg, sourceCommitEvent, migration);
assertReplicaVersionsAndServiceData(msg, migration.getSource(), migration.getPartitionId(),
migration.getSourceNewReplicaIndex());
}
});
}
private void assertMigrationSourceRollback(final MigrationInfo migration)
throws InterruptedException {
assertTrueEventually(new AssertTask() {
@Override
public void run()
throws Exception {
final TestMigrationAwareService service = getService(migration.getSource());
final String msg = getAssertMessage(migration, service);
assertFalse(service.getBeforeEvents().isEmpty());
assertFalse(service.getRollbackEvents().isEmpty());
final PartitionMigrationEvent beforeEvent = service.getBeforeEvents().get(0);
final PartitionMigrationEvent rollbackEvent = service.getRollbackEvents().get(0);
assertSourcePartitionMigrationEvent(msg, beforeEvent, migration);
assertSourcePartitionMigrationEvent(msg, rollbackEvent, migration);
assertReplicaVersionsAndServiceData(msg, migration.getSource(), migration.getPartitionId(),
migration.getSourceCurrentReplicaIndex());
}
});
}
private void assertMigrationDestinationCommit(final MigrationInfo migration)
throws InterruptedException {
final TestMigrationAwareService service = getService(migration.getDestination());
final String msg = getAssertMessage(migration, service);
final PartitionMigrationEvent beforeEvent = service.getBeforeEvents().get(0);
final PartitionMigrationEvent commitEvent = service.getCommitEvents().get(0);
assertDestinationPartitionMigrationEvent(msg, beforeEvent, migration);
assertDestinationPartitionMigrationEvent(msg, commitEvent, migration);
assertTrue(msg, service.contains(migration.getPartitionId()));
assertReplicaVersionsAndServiceData(msg, migration.getDestination(), migration.getPartitionId(),
migration.getDestinationNewReplicaIndex());
}
private void assertMigrationDestinationRollback(final MigrationInfo migration)
throws InterruptedException {
assertTrueEventually(new AssertTask() {
@Override
public void run()
throws Exception {
final TestMigrationAwareService service = getService(migration.getDestination());
final String msg = getAssertMessage(migration, service);
assertFalse(service.getBeforeEvents().isEmpty());
assertFalse(service.getRollbackEvents().isEmpty());
final PartitionMigrationEvent beforeEvent = service.getBeforeEvents().get(0);
final PartitionMigrationEvent destinationRollbackEvent = service.getRollbackEvents().get(0);
assertDestinationPartitionMigrationEvent(msg, beforeEvent, migration);
assertDestinationPartitionMigrationEvent(msg, destinationRollbackEvent, migration);
assertReplicaVersionsAndServiceData(msg, migration.getDestination(), migration.getPartitionId(),
migration.getDestinationCurrentReplicaIndex());
}
});
}
private void assertReplicaVersionsAndServiceData(String msg, final Address address, final int partitionId,
final int replicaIndex)
throws InterruptedException {
final TestMigrationAwareService service = getService(address);
final boolean shouldContainData = replicaIndex != -1 && replicaIndex <= BACKUP_COUNT;
assertEquals(msg, shouldContainData, service.contains(partitionId));
final long[] replicaVersions = getReplicaVersions(factory.getInstance(address), partitionId);
msg = msg + " , ReplicaVersions: " + Arrays.toString(replicaVersions);
if (shouldContainData) {
if (replicaIndex == 0) {
assertArrayEquals(msg, replicaVersions, new long[]{1, 1, 1, 1, 1, 1});
} else {
for (int i = 1; i < InternalPartition.MAX_BACKUP_COUNT; i++) {
if (i < replicaIndex || i > BACKUP_COUNT) {
assertEquals(msg + " at index: " + i, 0, replicaVersions[i - 1]);
} else {
assertEquals(msg + " at index: " + i, 1, replicaVersions[i - 1]);
}
}
}
} else {
assertArrayEquals(msg, replicaVersions, new long[]{0, 0, 0, 0, 0, 0});
}
}
private void assertPartitionDataAfterMigrations()
throws ExecutionException, InterruptedException, TimeoutException {
final InternalOperationService operationService = getOperationService(instances[0]);
for (int partitionId = 0; partitionId < PARTITION_COUNT; partitionId++) {
assertNotNull(operationService.invokeOnPartition(null, new TestGetOperation(), partitionId)
.get(10, TimeUnit.SECONDS));
}
}
private String getAssertMessage(MigrationInfo migration, TestMigrationAwareService service) {
return migration + " -> BeforeEvents: " + service.getBeforeEvents() + " , CommitEvents: " + service.getCommitEvents()
+ " , RollbackEvents: " + service.getRollbackEvents();
}
private void assertSourcePartitionMigrationEvent(final String msg, final PartitionMigrationEvent event,
final MigrationInfo migration) {
assertEquals(msg, SOURCE, event.getMigrationEndpoint());
assertEquals(msg, migration.getSourceCurrentReplicaIndex(), event.getCurrentReplicaIndex());
assertEquals(msg, migration.getSourceNewReplicaIndex(), event.getNewReplicaIndex());
}
private void assertDestinationPartitionMigrationEvent(final String msg, final PartitionMigrationEvent event,
final MigrationInfo migration) {
assertEquals(msg, DESTINATION, event.getMigrationEndpoint());
assertEquals(msg, migration.getDestinationCurrentReplicaIndex(), event.getCurrentReplicaIndex());
assertEquals(msg, migration.getDestinationNewReplicaIndex(), event.getNewReplicaIndex());
}
private Config createConfig() {
final Config config = new Config();
ServiceConfig serviceConfig = TestMigrationAwareService.createServiceConfig(BACKUP_COUNT);
config.getServicesConfig().addServiceConfig(serviceConfig);
config.setProperty(GroupProperty.PARTITION_MAX_PARALLEL_REPLICATIONS.getName(), "0");
config.setProperty(GroupProperty.PARTITION_COUNT.getName(), String.valueOf(PARTITION_COUNT));
return config;
}
private InternalPartitionImpl getPartition(final HazelcastInstance instance, final int partitionId) {
final InternalPartitionServiceImpl partitionService = (InternalPartitionServiceImpl) getPartitionService(instance);
return (InternalPartitionImpl) partitionService.getPartition(partitionId);
}
private TestMigrationAwareService getService(final Address address) {
return getNodeEngineImpl(factory.getInstance(address)).getService(TestMigrationAwareService.SERVICE_NAME);
}
private static class RejectMigrationOnComplete
extends InternalMigrationListener {
private final HazelcastInstance instance;
RejectMigrationOnComplete(HazelcastInstance instance) {
this.instance = instance;
}
@Override
public void onMigrationComplete(MigrationParticipant participant, MigrationInfo migrationInfo, boolean success) {
resetInternalMigrationListener(instance);
throw new ExpectedRuntimeException("migration is failed intentionally on complete");
}
}
private class CountDownMigrationRollbackOnMaster
extends InternalMigrationListener {
private final CountDownLatch latch = new CountDownLatch(1);
private final MigrationInfo expected;
private volatile boolean blockMigrations;
CountDownMigrationRollbackOnMaster(MigrationInfo expected) {
this.expected = expected;
}
public void onMigrationStart(MigrationParticipant participant, MigrationInfo migrationInfo) {
if (participant == MigrationParticipant.MASTER && blockMigrations) {
assertOpenEventually(blockMigrationStartLatch);
}
}
@Override
public void onMigrationComplete(MigrationParticipant participant, MigrationInfo migrationInfo, boolean success) {
if (participant == MigrationParticipant.DESTINATION) {
throw new ExpectedRuntimeException("migration is failed intentionally on complete");
}
}
@Override
public void onMigrationRollback(MigrationParticipant participant, MigrationInfo migrationInfo) {
if (participant == MigrationParticipant.MASTER && expected.equals(migrationInfo)) {
blockMigrations = true;
latch.countDown();
}
}
}
} |
package spil.language;
import spil.DiceCup;
import spil.Player;
public class English implements Language{
public English(){}
/**
* Welcome message for user with commands available.
* @return
*/
@Override
public String welcomeMsg(){
return "Welcome to the game!";
}
/**
* Asks for playername
* @return
*/
@Override
public String askForPlayerName(int playerNumber){
return "Type player " + playerNumber + "'s name";
}
/**
* Tells user that the game will start shortly.
* @return
*/
@Override
public String readyToBegin(){
return "The game is starting. The player who reaches 3000 coins is the winner. + '\n' + You can type 'help' when it's your turn, to open a help menu. ";
}
/**
* Premessage at the start of players turn, tells player help option.
* @return
*/
public String preMsg(Player player){
return "It's " + player.getName() + "s turn"; // getbank.getbalance
}
/**
* Displays the result of the dice roll.
* @return
*/
@Override
public String rollResult(DiceCup diceCup){
return "You rolled a " + diceCup.getDices()[0].getFaceValue() + " and a " + diceCup.getDices()[1].getFaceValue();
}
/**
* Switch case that displays the field message that was landed on.
* @return
*/
@Override
public String fieldMsg(DiceCup diceCup){
String fieldString;
switch (diceCup.getSum()) {
case 2: fieldString = "You've climbed to the top of the tower and found 250 coins!";
break;
case 3: fieldString = "You've fallen into the crater, it'll cost you 100 coins to get back up.";
break;
case 4: fieldString = "You've arrived at the palace gates, the guards greets you with 100 coins when you pass.";
break;
case 5: fieldString = "You've gotten lost in the cold dessert, you find a guy who sells you warm clothes costs you 20 coins.";
break;
case 6: fieldString = "You've arrived at the walled city. A man needs your help, after you've helped him he gave you 180 coins!";
break;
case 7: fieldString = "You've seen a monastery, you didn't find anything there.";
break;
case 8: fieldString = "You've walked into a black cave and taken captive, it costs you 70 coins to walk free.";
break;
case 9: fieldString = "You've found some huts in the mountains, the people that live there likes you and give you 60 coins!";
break;
case 10: fieldString = "You've arrived at the werewall. The werewolf doesn't want to let you go, you give them 80 coins, as thanks they let you walk free and roll the dice again.";
break;
case 11: fieldString = "You've fallen into the pit, a friendly man helps you back up. You give him 50 coins as thanks.";
break;
case 12: fieldString = "You've arrived at the goldmine. You find gold in there, you sell it for 650 coins!";
break;
default: fieldString = "Unknown field.";
break;
}
return fieldString;
}
/**
* Prints how many points the player have after the throw.
* @return
*/
@Override
public String postMsg(Player player){
return "After this round " + player.getName() + " has got " + player.getBank().getBalance() + " coins\n";
}
/**
* Prints who won with how many points.
* @return
*/
@Override
public String winnerMsg(Player player){
return player.getName() + " has won the game with " + player.getBank().getBalance() + "coins!";
}
/**
* Prints the available commands in the menu.
* @return
*/
@Override
public String menu(){
return "Type 1 for rules" + '\n' + "Type 2 for scoreboard" + '\n' + "Type 3 to swap dices" + '\n' + "Type 4 to end the game";
}
/**
* Prints the rules of the game.
* @return
*/
@Override
public String printRules(){
return "This is a dice game with 2 players. You roll the dices and land on a field inbetween 2 and 12. \n All fields have a different effect on your score, either positive or negative. Here's a list of all the fields: \n"
+ "2. Tower: +250 coins \n"
+ "3. Crater: -100 coins \n"
+ "4. Palace gates: +100 coins \n"
+ "5. Cold Desert: -20 coins \n"
+ "6. Walled city: +180 coins \n"
+ "7. Monastery: 0 coins \n"
+ "8. Black cave: -70 coins \n"
+ "9. Huts in the mountain: +60 coins \n"
+ "10. The Werewall (werewolf-wall): -80 coins, The player get an extra throw aswell \n"
+ "11. The pit: -50 coins \n"
+ "12. Goldmine: +650 coins";
}
/**
* Prints the score.
* @return
*/
@Override
public String printScore(Player[] players){
StringBuilder str = new StringBuilder();
str.append("The score is:");
for (int i = 0; i < players.length; i++)
str.append("\n" + players[i].getName() + " has " + players[i].getBank().getBalance() + " coins.");
return str.toString();
}
/**
* Prints how to change the dices.
* @return
*/
@Override
public String changeDices(){
return "Type how many sides the two dices should have";
}
/**
* Prints that the dices were changed successfully.
* @return
*/
@Override
public String printDiceChangeSucces(){
return "The dices have been changed.";
}
/**
* Prints a error message if the dices couldn't be changed.
* @return
*/
@Override
public String printDiceChangeNotExecuted(){
return "The dices couldn't be changed.";
}
/**
* Prints game menu.
* @return
*/
@Override
public String printGameMenu(){
return "Type 1 to continue the game\n" +
"Type 2 to change language\n" +
"Type 3 to show the score\n"+
"Type 4 to end the game";
}
/**
* Notifies of language change
* @return String
*/
@Override
public String notifyLangChange(){
return "The language is now English!";
}
} |
package src.controller;
import java.util.ArrayList;
import src.model.MapEntity_Relation;
/**
*
* @author JohnReedLOL
*/
abstract public class Entity extends DrawableThing {
// Converts an entity's name [which must be unique] into a unique base 35 number
private static final long serialVersionUID = Long.parseLong("Entity", 35);
// map_relationship_ is used in place of a map_referance_
private final MapEntity_Relation map_relationship_;
/**
* Use this to call functions contained within the MapEntity relationship
* @return map_relationship_
* @author Reed, John
*/
@Override
public MapEntity_Relation getMapRelation() {
return map_relationship_;
}
public Entity(String name, char representation,
int x_respawn_point, int y_respawn_point) {
super(name, representation);
map_relationship_ = new MapEntity_Relation( this, x_respawn_point, y_respawn_point );
inventory_ = new ArrayList<Item>();
}
private Occupation occupation_ = null;
ArrayList<Item> inventory_;
// Only 1 equipped item in iteration 1
Item equipped_item_;
//private final int max_level_;
private StatsPack my_stats_after_powerups_;
private void recalculateStats() {
//my_stats_after_powerups_.equals(my_stats_after_powerups_.add(equipped_item_.get_stats_pack_()));
}
/**
* this function levels up an entity
* @author Jessan
*/
public void levelUp() {
if(occupation_ == null){
//levelup normally
StatsPack new_stats = new StatsPack(0,1,1,1,1,1,1,1,1);
set_default_stats_pack(get_default_stats_pack_().add(new_stats));
}
//if occupation is not null/have an occupation
else {
set_default_stats_pack(occupation_.change_stats(get_default_stats_pack_()));
}
}
public void setOccupation(Occupation occupation) {
occupation_ = occupation;
}
public Occupation getOccupation(){
return occupation_;
}
public void addItemToInventory(Item item) {
inventory_.add(item);
}
} |
package VASSAL.counters;
import VASSAL.build.GameModule;
import VASSAL.build.module.BasicCommandEncoder;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.GameState;
import VASSAL.build.module.GlobalOptions;
import VASSAL.build.module.Map;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone;
import VASSAL.build.module.properties.PropertyNameSource;
import VASSAL.command.AddPiece;
import VASSAL.command.ChangePiece;
import VASSAL.command.Command;
import VASSAL.command.RemovePiece;
import VASSAL.command.SetPersistentPropertyCommand;
import VASSAL.configure.ImageSelector;
import VASSAL.configure.StringConfigurer;
import VASSAL.i18n.Localization;
import VASSAL.i18n.PieceI18nData;
import VASSAL.i18n.Resources;
import VASSAL.i18n.TranslatablePiece;
import VASSAL.property.PersistentPropertyContainer;
import VASSAL.search.AbstractImageFinder;
import VASSAL.tools.SequenceEncoder;
import VASSAL.tools.image.ImageUtils;
import VASSAL.tools.imageop.ScaledImagePainter;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.InputEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
/**
* Basic class for representing a physical component of the game. Can be e.g. a counter, a card, or an overlay.
*
* Note like traits, BasicPiece implements GamePiece (via TranslatablePiece), but UNLIKE traits it is NOT a
* Decorator, and thus must be treated specially.
*/
public class BasicPiece extends AbstractImageFinder implements TranslatablePiece, StateMergeable, PropertyNameSource, PersistentPropertyContainer,
PropertyExporter {
public static final String ID = "piece;"; // NON-NLS
private static Highlighter highlighter;
/**
* Return information about the current location of the piece through getProperty():
*
* LocationName - Current Location Name of piece as displayed in Chat Window CurrentX - Current X position CurrentY -
* Current Y position CurrentMap - Current Map name or "" if not on a map CurrentBoard - Current Board name or "" if
* not on a map CurrentZone - If the current map has a multi-zoned grid, then return the name of the Zone the piece is
* in, or "" if the piece is not in any zone, or not on a map
*/
public static final String LOCATION_NAME = "LocationName"; // NON-NLS
public static final String CURRENT_MAP = "CurrentMap"; // NON-NLS
public static final String CURRENT_BOARD = "CurrentBoard"; // NON-NLS
public static final String CURRENT_ZONE = "CurrentZone"; // NON-NLS
public static final String CURRENT_X = "CurrentX"; // NON-NLS
public static final String CURRENT_Y = "CurrentY"; // NON-NLS
public static final String OLD_LOCATION_NAME = "OldLocationName"; // NON-NLS
public static final String OLD_MAP = "OldMap"; // NON-NLS
public static final String OLD_BOARD = "OldBoard"; // NON-NLS
public static final String OLD_ZONE = "OldZone"; // NON-NLS
public static final String OLD_X = "OldX"; // NON-NLS
public static final String OLD_Y = "OldY"; // NON-NLS
public static final String BASIC_NAME = "BasicName"; // NON-NLS
public static final String PIECE_NAME = "PieceName"; // NON-NLS
public static final String LOCALIZED_BASIC_NAME = "LocalizedBasicName"; //NON-NLS
public static final String LOCALIZED_PIECE_NAME = "LocalizedPieceName"; //NON-NLS
public static final String DECK_NAME = "DeckName"; // NON-NLS
public static final String DECK_POSITION = "DeckPosition"; // NON-NLS
public static final String CLICKED_X = "ClickedX"; // NON-NLS
public static final String CLICKED_Y = "ClickedY"; // NON-NLS
public static Font POPUP_MENU_FONT = new Font(Font.DIALOG, Font.PLAIN, 11);
protected JPopupMenu popup;
protected Rectangle imageBounds;
protected ScaledImagePainter imagePainter = new ScaledImagePainter();
private Map map;
private KeyCommand[] commands;
private Stack parent;
private Point pos = new Point(0, 0);
private String id;
/*
* A set of properties used as scratch-pad storage by various Traits and processes.
* These properties are ephemeral and not stored in the GameState.
*/
private java.util.Map<Object, Object> props;
/*
* A Set of properties that must be persisted in the GameState.
* Will be created as lazily as possible since pieces that don't move will not need them,
* The current code only supports String Keys and Values. Non-strings should be serialised
* before set and de-serialised after get.
*/
private java.util.Map<Object, Object> persistentProps;
/** @deprecated Moved into own traits, retained for backward compatibility */
@Deprecated
private char cloneKey;
/** @deprecated Moved into own traits, retained for backward compatibility */
@Deprecated
private char deleteKey;
/** @deprecated Replaced by #srcOp. */
@Deprecated
protected Image image; // BasicPiece's own image
protected String imageName; // BasicPiece image name
private String commonName; // BasicPiece's name for the piece (aka "BasicName" property in Vassal Module)
public BasicPiece() {
this(ID + ";;;;");
}
/** creates a BasicPiece by passing complete type information
* @param type serialized type information (data about the piece which does not
* change during the course of a game) ready to be processed by a {@link SequenceEncoder.Decoder} */
public BasicPiece(String type) {
mySetType(type);
}
/** Sets the type information for this piece. See {@link Decorator#myGetType}
* @param type a serialized configuration string to
* set the "type information" of this piece, which is
* information that doesn't change during the course of
* a single game (e.g. Image Files, Context Menu strings,
* etc). Typically ready to be processed e.g. by
* SequenceEncoder.decode() */
@Override
public void mySetType(String type) {
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';');
st.nextToken();
cloneKey = st.nextChar('\0');
deleteKey = st.nextChar('\0');
imageName = st.nextToken();
commonName = st.nextToken();
imagePainter.setImageName(imageName);
imageBounds = null; // New image, clear the old imageBounds
commands = null;
}
/** @return The "type information" of a piece or trait is information
* that does not change during the course of a game. Image file
* names, context menu strings, etc., all should be reflected
* in the type. The type information is returned serialized string
* form, ready to be decoded by a SequenceEncoder#decode.
* @see BasicCommandEncoder */
@Override
public String getType() {
final SequenceEncoder se =
new SequenceEncoder(cloneKey > 0 ? String.valueOf(cloneKey) : "", ';');
return ID + se.append(deleteKey > 0 ? String.valueOf(deleteKey) : "")
.append(imageName)
.append(commonName).getValue();
}
/** @param map Each GamePiece belongs to a single {@link Map} */
@Override
public void setMap(Map map) {
if (map != this.map) {
commands = null;
this.map = map;
}
}
/** @return Each GamePiece belongs to a single {@link Map} */
@Override
public Map getMap() {
return getParent() == null ? map : getParent().getMap();
}
/**
* Properties can be associated with a piece -- many may be game-specific, but others
* are standard, such as the LocationName property exposed by BasicPiece -- and can
* be read through this interface. The properties may or may not need to be encoded in
* the piece's {@link #getState} method.
*
* A request to getProperty() that reaches the BasicPiece will have already checked for
* such a property key being available from any outer Decorator/Trait in the stack. Upon
* reaching BasicPiece, the search hierarchy for a matching property now becomes:
*
* (1) Specific named properties supported by BasicPiece. These include BASIC_NAME,
* PIECE_NAME, LOCATION_NAME, CURRENT_MAP, CURRENT_BOARD, CURRENT_ZONE, CURRENT_X,
* CURRENT_Y.
* (2) "Scratchpad" properties - see {@link #setProperty} for full details, but these are
* highly temporary properties intended to remain valid only during the execution of a
* single key command.
* (3) Persistent properties - see {@link #setPersistentProperty} for full details, but
* they are stored in the piece and "game state robust" - saved during save/load, and
* propagated to other players' clients in a multiplayer game.
* (4) The values of any visible "Global Property" in a Vassal module, checking the Zone
* level first, then the map level, and finally the module level.
*
* <br><br>Thus, when using this interface a piece's own properties are preferred to those of
* "Global Properties", and those in turn are searched Zone-first then Map, then Module.
* @param key String key of property to be returned
* @return Object containing new value of the specified property
*/
@Override
public Object getProperty(Object key) {
if (BASIC_NAME.equals(key)) {
return getName();
}
else if (LOCALIZED_BASIC_NAME.equals(key)) {
return getLocalizedName();
}
else
return getPublicProperty(key);
}
/**
* Properties (see {@link #getProperty}) visible in a masked (see {@link Obscurable}) piece, even when the piece is masked.
* @param key String key of property to be returned.
*/
public Object getPublicProperty(Object key) {
if (Properties.KEY_COMMANDS.equals(key)) {
return getKeyCommands();
}
else if (LOCATION_NAME.equals(key)) {
return getMap() == null ? "" : getMap().locationName(getPosition());
}
else if (PIECE_NAME.equals(key)) {
return Decorator.getOutermost(this).getName();
}
else if (LOCALIZED_PIECE_NAME.equals(key)) {
return Decorator.getOutermost(this).getLocalizedName();
}
else if (CURRENT_MAP.equals(key)) {
return getMap() == null ? "" : getMap().getConfigureName();
}
else if (DECK_NAME.equals(key)) {
return getParent() instanceof Deck ? ((Deck) getParent()).getDeckName() : "";
}
else if (DECK_POSITION.equals(key)) {
if (getParent() instanceof Deck) {
final Deck deck = (Deck) getParent();
final int size = deck.getPieceCount();
final int pos = deck.indexOf(Decorator.getOutermost(this));
return String.valueOf(size - pos + 1);
}
else {
return "0";
}
}
else if (CURRENT_BOARD.equals(key)) {
if (getMap() != null) {
final Board b = getMap().findBoard(getPosition());
if (b != null) {
return b.getName();
}
}
return "";
}
else if (CURRENT_ZONE.equals(key)) {
if (getMap() != null) {
final Zone z = getMap().findZone(getPosition());
if (z != null) {
return z.getName();
}
}
return "";
}
else if (CURRENT_X.equals(key)) {
return String.valueOf(getPosition().x);
}
else if (CURRENT_Y.equals(key)) {
return String.valueOf(getPosition().y);
}
else if (Properties.VISIBLE_STATE.equals(key)) {
return "";
}
// Check for a property in the scratch-pad properties
Object prop = props == null ? null : props.get(key);
// Check for a persistent property
if (prop == null && persistentProps != null) {
prop = persistentProps.get(key);
}
// Check for higher level properties. Each level if it exists will check the higher level if required.
if (prop == null) {
final Map map = getMap();
final Zone zone = (map == null ? null : map.findZone(getPosition()));
if (zone != null) {
prop = zone.getProperty(key);
}
else if (map != null) {
prop = map.getProperty(key);
}
else {
prop = GameModule.getGameModule().getProperty(key);
}
}
return prop;
}
/**
* Returns the localized text for a specified property if a translation is available, otherwise the non-localized version.
* Searches the same hierarchy of properties as {@link #getProperty}.
* @param key String key of property to be returned
* @return localized text of property, if available, otherwise non-localized value
*/
@Override
public Object getLocalizedProperty(Object key) {
if (BASIC_NAME.equals(key)) {
return getLocalizedName();
}
else {
return getLocalizedPublicProperty(key);
}
}
/**
* Returns the localized text for a specified property if a translation is available, otherwise the non-localized version,
* but in both cases accounting for the unit's visibility (i.e. Mask/{@link Obscurable} Traits).
* Searches the same hierarchy of properties as {@link #getProperty}.
* @param key String key of property to be returned
* @return Returns localized text of property, if available, otherwise non-localized value, accounting for Mask status.
*/
public Object getLocalizedPublicProperty(Object key) {
if (List.of(
Properties.KEY_COMMANDS,
DECK_NAME,
CURRENT_X,
CURRENT_Y,
Properties.VISIBLE_STATE
).contains(key)) {
return getProperty(key);
}
else if (LOCATION_NAME.equals(key)) {
return getMap() == null ? "" : getMap().localizedLocationName(getPosition());
}
else if (PIECE_NAME.equals(key)) {
return Decorator.getOutermost(this).getName();
}
else if (BASIC_NAME.equals(key)) {
return getLocalizedName();
}
else if (CURRENT_MAP.equals(key)) {
return getMap() == null ? "" : getMap().getLocalizedConfigureName();
}
else if (DECK_POSITION.equals(key)) {
if (getParent() instanceof Deck) {
final Deck deck = (Deck) getParent();
final int size = deck.getPieceCount();
final int pos = deck.indexOf(Decorator.getOutermost(this));
return String.valueOf(size - pos);
}
else {
return "0";
}
}
else if (CURRENT_BOARD.equals(key)) {
if (getMap() != null) {
final Board b = getMap().findBoard(getPosition());
if (b != null) {
return b.getLocalizedName();
}
}
return "";
}
else if (CURRENT_ZONE.equals(key)) {
if (getMap() != null) {
final Zone z = getMap().findZone(getPosition());
if (z != null) {
return z.getLocalizedName();
}
}
return "";
}
// Check for a property in the scratch-pad properties
Object prop = props == null ? null : props.get(key);
// Check for a persistent property
if (prop == null && persistentProps != null) {
prop = persistentProps.get(key);
}
// Check for higher level properties. Each level if it exists will check the higher level if required.
if (prop == null) {
final Map map = getMap();
final Zone zone = (map == null ? null : map.findZone(getPosition()));
if (zone != null) {
prop = zone.getLocalizedProperty(key);
}
else if (map != null) {
prop = map.getLocalizedProperty(key);
}
else {
prop = GameModule.getGameModule().getLocalizedProperty(key);
}
}
return prop;
}
/**
* Properties can be associated with a piece -- many may be game-specific, but others
* are standard, such as the LocationName property exposed by BasicPiece -- and can
* be set through this interface. The properties may or may not need to be encoded in
* the piece's {@link #getState} method.
*
* A setProperty() call which reaches BasicPiece will already have passed through all of the outer
* Decorator/Traits on the way in without finding one able to match the property.
*
* <br><br><b>NOTE:</b> Properties outside the piece CANNOT be set by this method (e.g. Global
* Properties), even though they can be read by {@link #getProperty} -- in this the two methods are
* not perfect mirrors. This method ALSO does not set persistent properties (they can only be set
* by an explicit call to {@link #setPersistentProperty}).
*
* <br><br>BasicPiece <i>does</i>, however contain a "scratchpad" for temporary properties, and for
* any call to this method that does not match a known property (which is, currently, ANY call which
* reaches this method here in BasicPiece), a scratchpad property will be set. Scratchpad properties
* are NOT saved when the game is saved, and NO arrangement is made to pass their values to other
* players' machines. Thus they should only be used internally for highly temporary values during the
* execution of a single key command. Their one other use is to store the piece's Unique ID -- and
* although this value is obviously used over periods of time much longer than a single key command,
* this is possible because the value is immutable and is refreshed to the same value whenever the
* piece is re-created e.g. when loading a save.
*
* @param key String key of property to be changed
* @param val Object containing new value of the property
*/
@Override
public void setProperty(Object key, Object val) {
if (props == null) {
props = new HashMap<>();
}
if (val == null) {
props.remove(key);
}
else {
props.put(key, val);
}
}
/**
* Setting a persistent property writes a property value into the piece (creating a new entry in the piece's persistent
* property table if the specified key does not yet exist in it). Persistent properties are game-state-robust: they are
* saved/restored with saved games, and are passed via {@link Command} to other players' clients in a multiplayer game.
* The persistent property value can then be read from the piece via e.g. {@link #getProperty}. When reading back properties
* out of a piece, the piece's built-in properties are checked first, then scratchpad properties (see {@link #setProperty}),
* then external properties such as Global Properties. If <i>only</i> persistentProperties are to be searched, use
* {@link #getPersistentProperty} instead.
*
* <br><br>In practical terms, setPersistentProperty is used mainly to implement the "Old" properties of BasicPiece (e.g.
* "OldLocationName", "OldZone", "OldMap", "OldBoard", "OldX", "OldY"). A Persistent Property is indeed nearly identical
* with {@link DynamicProperty} in storage/retrieval characteristics, and simply lacks the in-module interface for setting
* values, etc. Module Designers are thus recommended to stick with Dynamic Property traits for these functions.
*
* @param key String key naming the persistent property to be set. If a corresponding persistent property does not exist it will be created.
* @param newValue New value for the persistent property
* @return a {@link Command} object which, when passed to another player's client via logfile, server, or saved game, will allow the
* result of the "set" operation to be replicated.
*/
@Override
public Command setPersistentProperty(Object key, Object newValue) {
if (persistentProps == null) {
persistentProps = new HashMap<>();
}
final Object oldValue = newValue == null ? persistentProps.remove(key) : persistentProps.put(key, newValue);
return Objects.equals(oldValue, newValue) ? null : new SetPersistentPropertyCommand(getId(), key, oldValue, newValue);
}
/**
* @param key String key naming the persistent property whose value is to be returned.
* @return the current value of a persistent property, or null if it doesn't exist.
*/
@Override
public Object getPersistentProperty(Object key) {
return persistentProps == null ? null : persistentProps.get(key);
}
/**
* @param s Name of a module preference to be read
* @return Value of the preference
*/
protected Object prefsValue(String s) {
return GameModule.getGameModule().getPrefs().getValue(s);
}
/**
* Draws the BasicPiece's image, if it has been set
* @param g target Graphics object
* @param x x-location of the center of the piece
* @param y y-location of the center of the piece
* @param obs the Component on which this piece is being drawn
* @param zoom the scaling factor.
*/
@Override
public void draw(Graphics g, int x, int y, Component obs, double zoom) {
if (imageBounds == null) {
imageBounds = boundingBox();
}
imagePainter.draw(g, x + (int) (zoom * imageBounds.x), y + (int) (zoom * imageBounds.y), zoom, obs);
}
/**
* @return the set of key commands that will populate the a BasicPiece's right-click menu.
* This will normally be an empty array in the present age of the world, but the ability to contain a
* clone and delete command is retained for compatibility with Modules Of Ancient Times.
* In the case of BasicPiece, this method also keeps track of whether move up/down/to-top/to-bottom commands are enabled.
*
* This method is chained from "outer" Decorator components of a larger logical game piece, in the process of generating
* the complete list of key commands to build the right-click menu -- this process is originated by calling <code>getKeyCommands()</code>
* on the piece's outermost Decorator/Trait.
*/
protected KeyCommand[] getKeyCommands() {
if (commands == null) {
final ArrayList<KeyCommand> l = new ArrayList<>();
final GamePiece target = Decorator.getOutermost(this);
if (cloneKey > 0) {
l.add(new KeyCommand(Resources.getString("Editor.Clone.clone"), KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_DOWN_MASK), target));
}
if (deleteKey > 0) {
l.add(new KeyCommand(Resources.getString("Editor.Delete.delete"), KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_DOWN_MASK), target));
}
commands = l.toArray(new KeyCommand[0]);
}
final GamePiece outer = Decorator.getOutermost(this);
// This code has no function that I can see? There is no way to add these Commands.
// boolean canAdjustPosition = outer.getMap() != null && outer.getParent() != null && outer.getParent().topPiece() != getParent().bottomPiece();
// enableCommand("Move up", canAdjustPosition);
// enableCommand("Move down", canAdjustPosition);
// enableCommand("Move to top", canAdjustPosition);
// enableCommand("Move to bottom", canAdjustPosition);
enableCommand(Resources.getString("Editor.Clone.clone"), outer.getMap() != null);
enableCommand(Resources.getString("Editor.Delete.delete"), outer.getMap() != null);
return commands;
}
/**
* @param name Name of internal-to-BasicPiece key command whose enabled status it to be set
* @param enable true to enable, false to disable.
*/
private void enableCommand(String name, boolean enable) {
for (final KeyCommand command : commands) {
if (name.equals(command.getName())) {
command.setEnabled(enable);
}
}
}
/**
* @param stroke KeyStroke to query if corresponding internal-to-BasicPiece command is enabled
* @return false if no Keystroke, true if not an internal-to-BasicPiece key command, and enabled status of key command otherwise.
*/
private boolean isEnabled(KeyStroke stroke) {
if (stroke == null) {
return false;
}
for (final KeyCommand command : commands) {
if (stroke.equals(command.getKeyStroke())) {
return command.isEnabled();
}
}
return true;
}
/**
* @return piece's position on its map.
*/
@Override
public Point getPosition() {
return getParent() == null ? new Point(pos) : getParent().getPosition();
}
/**
* @param p Sets the location of this piece on its {@link Map}
*/
@Override
public void setPosition(Point p) {
if (getMap() != null && getParent() == null) {
getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this)));
}
pos = p;
if (getMap() != null && getParent() == null) {
getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this)));
}
}
/**
* @return the parent {@link Stack} of which this piece is a member, or null if not a member of any Stack
*/
@Override
public Stack getParent() {
return parent;
}
/**
* @param s sets the {@link Stack} to which this piece belongs.
*/
@Override
public void setParent(Stack s) {
parent = s;
}
/**
* @return bounding box rectangle for BasicPiece's image, if an image has been specified.
*/
@Override
public Rectangle boundingBox() {
if (imageBounds == null) {
imageBounds = ImageUtils.getBounds(imagePainter.getImageSize());
}
return new Rectangle(imageBounds);
}
/**
* @return the Shape of this piece, for purposes of selecting it by clicking on it with the mouse. In the case
* of BasicPiece, this is equivalent to the boundingBox of the BasicPiece image, if one exists. Note that the
* shape should be defined in reference to the piece's location, which is ordinarily the center of the basic
* image.
*
* <br><br>For pieces that need a non-rectangular click volume, add a {@link NonRectangular} trait.
*/
@Override
public Shape getShape() {
return boundingBox();
}
/**
* @param c GamePiece to check if equal to this one
* @return Equality check with specified game piece
*/
public boolean equals(GamePiece c) {
return c == this;
}
/**
* @return the name of this GamePiece. This is the name typed by the module designer in the configuration box
* for the BasicPiece.
*/
@Override
public String getName() {
return commonName;
}
/**
* @return the localized name of this GamePiece. This is the translated version of the name typed by the module designer
* in the configuration box for the BasicPiece. It is used to fill the "BasicName" property.
*/
@Override
public String getLocalizedName() {
final String key = TranslatablePiece.PREFIX + getName();
return Localization.getInstance().translate(key, getName());
}
/**
* The primary way for the piece or trait to receive events. {@link KeyStroke} events are forward
* to this method if they are received while the piece is selected (or as the result of e.g. a Global
* Key Command being sent to the piece). The class implementing GamePiece can respond in any way it
* likes. Actual key presses by the player, selected items from the right-click Context Menu, keystrokes
* "applied on move" by a Map that the piece has just moved on, and Global Key Commands all send KeyStrokes
* (and NamedKeyStrokes) which are passed to pieces and traits through this interface.
*
* <br><br>In the case of BasicPiece, if a key command gets here, that means it has already been seen by any and all of
* its Traits ({@link Decorator}s), as BasicPiece is the innermost member of the Decorator stack. The key events
* processed here by BasicPiece include the "move up"/"move down"/"move-to-top"/"move-to-bottom" stack-adjustment
* commands, along with legacy support for cloning and deleting.
*
* @return a {@link Command} that, when executed, will make all changes to the game state (maps, pieces, other
* pieces, etc) to duplicate what the piece did in response to this event on another machine. Often a
* {@link ChangePiece} command, but for example if this keystroke caused the piece/trait to decide to fire
* off a Global Key Command, then the Command returned would include the <i>entire</i> results of that, appended
* as subcommands.
*
* @see VASSAL.build.module.map.ForwardToKeyBuffer
*/
@Override
public Command keyEvent(KeyStroke stroke) {
getKeyCommands();
if (!isEnabled(stroke)) {
return null;
}
Command comm = null;
final GamePiece outer = Decorator.getOutermost(this);
if (cloneKey != 0 && KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_DOWN_MASK).equals(stroke)) {
final GamePiece newPiece = ((AddPiece) GameModule.getGameModule().decode(GameModule.getGameModule().encode(new AddPiece(outer)))).getTarget();
newPiece.setId(null);
GameModule.getGameModule().getGameState().addPiece(newPiece);
newPiece.setState(outer.getState());
comm = new AddPiece(newPiece);
if (getMap() != null) {
comm.append(getMap().placeOrMerge(newPiece, getPosition()));
KeyBuffer.getBuffer().remove(outer);
KeyBuffer.getBuffer().add(newPiece);
if (GlobalOptions.getInstance().autoReportEnabled() && !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) {
final String name = outer.getLocalizedName();
final String loc = getMap().locationName(outer.getPosition());
final String s;
if (loc != null) {
s = Resources.getString("BasicPiece.clone_report_1", name, loc);
}
else {
s = Resources.getString("BasicPiece.clone_report_2", name);
}
final Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s);
report.execute();
comm = comm.append(report);
}
}
}
else if (deleteKey != 0 && KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_DOWN_MASK).equals(stroke)) {
comm = new RemovePiece(outer);
if (getMap() != null && GlobalOptions.getInstance().autoReportEnabled() && !Boolean.TRUE.equals(outer.getProperty(Properties.INVISIBLE_TO_OTHERS))) {
final String name = outer.getLocalizedName();
final String loc = getMap().locationName(outer.getPosition());
final String s;
if (loc != null) {
s = Resources.getString("BasicPiece.delete_report_1", name, loc);
}
else {
s = Resources.getString("BasicPiece.delete_report_2", name);
}
final Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s);
comm = comm.append(report);
}
comm.execute();
}
else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveUpKey())) {
if (parent != null) {
final String oldState = parent.getState();
final int index = parent.indexOf(outer);
if (index < parent.getPieceCount() - 1) {
parent.insert(outer, index + 1);
comm = new ChangePiece(parent.getId(), oldState, parent.getState());
}
else {
getMap().getPieceCollection().moveToFront(parent);
}
}
else {
getMap().getPieceCollection().moveToFront(outer);
}
}
else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveDownKey())) {
if (parent != null) {
final String oldState = parent.getState();
final int index = parent.indexOf(outer);
if (index > 0) {
parent.insert(outer, index - 1);
comm = new ChangePiece(parent.getId(), oldState, parent.getState());
}
else {
getMap().getPieceCollection().moveToBack(parent);
}
}
else {
getMap().getPieceCollection().moveToBack(outer);
}
}
else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveTopKey())) {
parent = outer.getParent();
if (parent != null) {
final String oldState = parent.getState();
if (parent.indexOf(outer) < parent.getPieceCount() - 1) {
parent.insert(outer, parent.getPieceCount() - 1);
comm = new ChangePiece(parent.getId(), oldState, parent.getState());
}
else {
getMap().getPieceCollection().moveToFront(parent);
}
}
else {
getMap().getPieceCollection().moveToFront(outer);
}
}
else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveBottomKey())) {
parent = getParent();
if (parent != null) {
final String oldState = parent.getState();
if (parent.indexOf(outer) > 0) {
parent.insert(outer, 0);
comm = new ChangePiece(parent.getId(), oldState, parent.getState());
}
else {
getMap().getPieceCollection().moveToBack(parent);
}
}
else {
getMap().getPieceCollection().moveToBack(outer);
}
}
return comm;
}
/**
* @return The "state information" is information that can change during
* the course of a game. State information is saved when the game
* is saved and is transferred between players on the server. For
* example, the relative order of pieces in a stack is state
* information, but whether the stack is expanded is not.
*
* <br><br>In the case of BasicPiece, the state information includes the current
* map, x/y position, the unique Game Piece ID, and the keys and values
* of any persistent properties (see {@link #setPersistentProperty})
*/
@Override
public String getState() {
final SequenceEncoder se = new SequenceEncoder(';');
final String mapName = map == null ? "null" : map.getIdentifier(); // NON-NLS
se.append(mapName);
final Point p = getPosition();
se.append(p.x).append(p.y);
se.append(getGpId());
se.append(persistentProps == null ? 0 : persistentProps.size());
// Persistent Property values will always be String (for now).
if (persistentProps != null) {
persistentProps.forEach((key, val) -> {
se.append(key == null ? "" : key.toString());
se.append(val == null ? "" : val.toString());
});
}
return se.getValue();
}
/**
* @param s New state information serialized in string form, ready
* to be passed to a SequenceEncoder#decode. The "state information" is
* information that can change during the course of a game. State information
* is saved when the game is saved and is transferred between players on the
* server. For example, the relative order of pieces in a stack is state
* information, but whether the stack is expanded is not.
*
* <br><br>In the case of BasicPiece, the state information includes the current
* map, x/y position, the unique Game Piece ID, and the keys and values
* of any persistent properties (see {@link #setPersistentProperty})
*/
@Override
public void setState(String s) {
final GamePiece outer = Decorator.getOutermost(this);
final Map oldMap = getMap();
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(s, ';');
final String mapId = st.nextToken();
Map newMap = null;
if (!"null".equals(mapId)) { // NON-NLS
newMap = Map.getMapById(mapId);
if (newMap == null) {
Decorator.reportDataError(this, Resources.getString("Error.not_found", "Map"), "mapId=" + mapId); // NON-NLS
}
}
final Point newPos = new Point(st.nextInt(0), st.nextInt(0));
setPosition(newPos);
if (newMap != oldMap) {
if (newMap != null) {
// This will remove from oldMap
// and set the map to newMap
newMap.addPiece(outer);
}
else { // oldMap can't possibly be null if we get to here
oldMap.removePiece(outer);
setMap(null);
}
}
setGpId(st.nextToken(""));
// Persistent Property values will always be String (for now).
// Create the HashMap as lazily as possible, no point in creating it for pieces that never move
if (persistentProps != null) {
persistentProps.clear();
}
final int propCount = st.nextInt(0);
for (int i = 0; i < propCount; i++) {
if (persistentProps == null) {
persistentProps = new HashMap<>();
}
final String key = st.nextToken("");
final String val = st.nextToken("");
persistentProps.put(key, val);
}
}
/**
* For BasicPiece, the "merge" of a new state simply involves copying in the
* new one in its entirety -- if any difference is detected.
* @param newState new serialized game state string
* @param oldState old serialized game state string
*/
@Override
public void mergeState(String newState, String oldState) {
if (!newState.equals(oldState)) {
setState(newState);
}
}
/**
* Each GamePiece must have a unique String identifier. These are managed by VASSAL internally and should never
* be changed by custom code.
* @return unique ID for this piece
* @see GameState#getNewPieceId
*/
@Override
public String getId() {
return id;
}
/**
* Each GamePiece must have a unique String identifier. These are managed by VASSAL internally and should never
* be changed by custom code.
* @param id sets unique ID for this piece
* @see GameState#getNewPieceId
*/
@Override
public void setId(String id) {
this.id = id;
}
/**
* @return the Highlighter instance for drawing selected pieces. Note that since this is a static method, all pieces in a
* module will always use the same Highlighter
*/
public static Highlighter getHighlighter() {
if (highlighter == null) {
highlighter = new ColoredBorder();
}
return highlighter;
}
/**
* @param h Set the Highlighter for all pieces
*/
public static void setHighlighter(Highlighter h) {
highlighter = h;
}
/**
* @return Description of what this kind of piece is. Appears in PieceDefiner list of traits.
*/
@Override
public String getDescription() {
return Resources.getString("Editor.BasicPiece.trait_description");
}
/**
* @return the unique gamepiece ID for this piece, as stored in the Property "scratchpad"
*/
public String getGpId() {
final String id = (String) getProperty(Properties.PIECE_ID);
return id == null ? "" : id;
}
/**
* @param id stores the unique gamepiece ID for this piece into the Property "scratchpad"
*/
public void setGpId(String id) {
setProperty(Properties.PIECE_ID, id == null ? "" : id);
}
/**
* @return the help file page for this type of piece.
*/
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("BasicPiece.html"); // NON-NLS
}
/**
* @return The configurer ({@link PieceEditor} for the BasicPiece, which generates the dialog for editing the
* BasicPiece's type information in the Editor window.
*/
@Override
public PieceEditor getEditor() {
return new Ed(this);
}
/**
* Test if this BasicPiece's Type and State are equal to another
* This method is intended to be used by Unit Tests to verify that a trait
* is unchanged after going through a process such as serialization/deserialization.
*
* @param o Object to compare this Decorator to
* @return true if the Class, type and state all match
*/
public boolean testEquals(Object o) {
// Check Class type
if (! (o instanceof BasicPiece)) return false;
final BasicPiece bp = (BasicPiece) o;
// Check Type
if (! Objects.equals(cloneKey, bp.cloneKey)) return false;
if (! Objects.equals(deleteKey, bp.deleteKey)) return false;
if (! Objects.equals(imageName, bp.imageName)) return false;
if (! Objects.equals(commonName, bp.commonName)) return false;
// Check State
final String mapName1 = this.map == null ? "null" : this.map.getIdentifier(); // NON-NLS
final String mapName2 = bp.map == null ? "null" : bp.map.getIdentifier(); // NON-NLS
if (! Objects.equals(mapName1, mapName2)) return false;
if (! Objects.equals(getPosition(), bp.getPosition())) return false;
if (! Objects.equals(getGpId(), bp.getGpId())) return false;
final int pp1 = persistentProps == null ? 0 : persistentProps.size();
final int pp2 = bp.persistentProps == null ? 0 : bp.persistentProps.size();
if (! Objects.equals(pp1, pp2)) return false;
if (persistentProps != null && bp.persistentProps != null) {
for (final Object key : persistentProps.keySet()) {
if (!Objects.equals(persistentProps.get(key), bp.persistentProps.get(key)))
return false;
}
}
return true;
}
/**
* The configurer ({@link PieceEditor} for the BasicPiece, which generates the dialog for editing the
* BasicPiece's type information in the Editor window.
*/
private static class Ed implements PieceEditor {
private TraitConfigPanel panel;
private KeySpecifier cloneKeyInput;
private KeySpecifier deleteKeyInput;
private StringConfigurer pieceName;
private ImageSelector picker;
private final String state;
/**
* @param p to create PieceEditor for
*/
private Ed(BasicPiece p) {
state = p.getState();
initComponents(p);
}
/**
* @param p initializes the editor dialog for the specified BasicPiece
*/
private void initComponents(BasicPiece p) {
panel = new TraitConfigPanel();
pieceName = new StringConfigurer(p.commonName);
panel.add("Editor.name_label", pieceName);
cloneKeyInput = new KeySpecifier(p.cloneKey);
if (p.cloneKey != 0) {
panel.add(new JLabel(Resources.getString("Editor.BasicPiece.to_clone")));
panel.add(cloneKeyInput);
}
deleteKeyInput = new KeySpecifier(p.deleteKey);
if (p.deleteKey != 0) {
panel.add(new JLabel(Resources.getString("Editor.BasicPiece.to_delete")));
panel.add(deleteKeyInput);
}
picker = new ImageSelector(p.imageName);
panel.add("Editor.image_label", picker);
}
/**
* @param p BasicPiece
*/
public void reset(BasicPiece p) {
}
/**
* @return the Component for the BasicPiece configurer
*/
@Override
public Component getControls() {
return panel;
}
/**
* @return the current state string for the BasicPiece
*/
@Override
public String getState() {
return state;
}
/**
* @return the type information string for the BasicPiece based on the current values of the configurer fields
*/
@Override
public String getType() {
final SequenceEncoder se = new SequenceEncoder(cloneKeyInput.getKey(), ';');
final String type = se.append(deleteKeyInput.getKey()).append(picker.getValueString()).append(pieceName.getValueString()).getValue();
return BasicPiece.ID + type;
}
}
/**
* @return String enumeration of type and state information.
*/
@Override
public String toString() {
return super.toString() + "[name=" + getName() + ",type=" + getType() + ",state=" + getState() + "]"; // NON-NLS
}
/**
* @return Object encapsulating the internationalization data for the BasicPiece
*/
@Override
public PieceI18nData getI18nData() {
final PieceI18nData data = new PieceI18nData(this);
data.add(commonName, Resources.getString("Editor.BasicPiece.basic_piece_name_description"));
return data;
}
/**
* @return Property names exposed by the Trait or Piece. In the case of BasicPiece, there are quite a few, mainly
* dealing with past and present location.
*/
@Override
public List<String> getPropertyNames() {
final ArrayList<String> l = new ArrayList<>();
l.add(LOCATION_NAME);
l.add(CURRENT_MAP);
l.add(CURRENT_BOARD);
l.add(CURRENT_ZONE);
l.add(CURRENT_X);
l.add(CURRENT_Y);
l.add(OLD_LOCATION_NAME);
l.add(OLD_MAP);
l.add(OLD_BOARD);
l.add(OLD_ZONE);
l.add(OLD_X);
l.add(OLD_Y);
l.add(BASIC_NAME);
l.add(PIECE_NAME);
l.add(DECK_NAME);
l.add(CLICKED_X);
l.add(CLICKED_Y);
return l;
}
/**
* See {@link AbstractImageFinder}
* Adds our image (if any) to the list of images
* @param s Collection to add image names to
*/
@Override
public void addLocalImageNames(Collection<String> s) {
if (imageName != null) s.add(imageName);
}
} |
package api.soup;
import api.index.Index;
import api.util.CouldNotLoadException;
import api.util.Tuple;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import org.apache.commons.io.IOUtils;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.*;
import java.util.List;
/**
* Provides interaction with the site and external sites if desired
* User must set site prior to usage
*
* @author Gwindow
*/
public class MySoup {
/**
* The main site to make requests too
*/
private static String site;
/**
* The user agent to set in connections
*/
private static String userAgent;
/**
* The cookie manager used to save/load user cookies
*/
private static CookieManager cookieManager;
/**
* The site index.
*/
private static Index index;
/**
* If ssl or notifications are enabled. Use the android flag to set whether or not the
* api is running on android device. This has some implications for the way cookies are
* handled and should be set accordingly.
*/
private static boolean sslEnabled = true, notificationsEnabled = true, android = false;
public static void setSite(String url){
site = url;
if (!site.endsWith("/")){
site += "/";
}
if (sslEnabled){
if (!site.startsWith("https:
site = "https://" + site;
}
}
else {
if (!site.startsWith("http:
site = "http://" + site;
}
}
cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
}
public static void setSite(String url, boolean ssl){
sslEnabled = ssl;
setSite(url);
}
/**
* Set to true if using from Android, default is false
*
* @param a if we're running on Android
*/
public static void setAndroid(boolean a){
android = a;
}
/**
* Use this factory method to get a properly configured HttpURLConnection for
* connecting to the desired url
*
* @return a configured HttpURLConnection
*/
private static HttpURLConnection newHttpConnection(URL url){
try {
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", userAgent);
return connection;
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
public static void login(String url, String username, String password, Boolean keepLogged) throws CouldNotLoadException, IllegalStateException{
if (site == null){
throw new IllegalStateException("Must call MySoup.setSite before use");
}
HttpURLConnection connection = null;
try {
connection = newHttpConnection(new URL(site + url));
connection.setDoOutput(true);
connection.setRequestMethod("POST");
String params = "username=" + URLEncoder.encode(username, "UTF-8")
+ "&password=" + URLEncoder.encode(password, "UTF-8");
if (keepLogged){
params += "&keeplogged=1";
}
connection.setFixedLengthStreamingMode(params.getBytes().length);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(params);
out.flush();
out.close();
//Android automatically picks up the cookies, regular Java doesn't
if (!android){
List<HttpCookie> cookies = HttpCookie.parse(connection.getHeaderField("Set-Cookie"));
URI uri = URI.create(site);
for (HttpCookie c : cookies){
cookieManager.getCookieStore().add(uri, c);
}
}
else {
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK){
throw new CouldNotLoadException("Check username and password");
}
}
}
catch (Exception e){
e.printStackTrace();
throw new CouldNotLoadException("Could not login");
}
finally {
if (connection != null){
connection.disconnect();
}
}
loadIndex();
}
public static boolean logout(String url) throws IllegalStateException{
if (site == null){
throw new IllegalStateException("Must call MySoup.setSite before use");
}
if (isLoggedIn() && !pressLink(url + "?auth=" + getAuthKey())){
System.err.println("Failed to logout");
return false;
}
cookieManager.getCookieStore().removeAll();
index = null;
return true;
}
public static void postMethod(String url, List<Tuple<String, String>> params) throws CouldNotLoadException, IllegalStateException{
if (site == null){
throw new IllegalStateException("Must call MySoup.setSite before use");
}
HttpURLConnection connection = null;
try {
String urlParams = buildParams(params);
connection = newHttpConnection(new URL(site + url));
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setFixedLengthStreamingMode(urlParams.getBytes().length);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(urlParams);
out.flush();
out.close();
}
catch (Exception e){
e.printStackTrace();
throw new CouldNotLoadException("Could not post method to: " + url);
}
finally {
if (connection != null){
connection.disconnect();
}
}
}
/**
* Build the POST method parameters string for some list of parameters
*
* @param params params to encode for a POST method
* @return the parameters as a string
*/
private static String buildParams(List<Tuple<String, String>> params){
StringBuilder result = new StringBuilder();
try {
result.append(URLEncoder.encode(params.get(0).getA(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(params.get(0).getB(), "UTF-8"));
for (int i = 1; i < params.size(); ++i){
result.append("&");
result.append(URLEncoder.encode(params.get(i).getA(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(params.get(i).getB(), "UTF-8"));
}
}
catch (Exception e){
e.printStackTrace();
}
return result.toString();
}
public static String scrape(String url) throws CouldNotLoadException, IllegalStateException {
if (site == null){
throw new IllegalStateException("Must call MySoup.setSite before use");
}
String response = null;
HttpURLConnection connection = null;
try {
connection = newHttpConnection(new URL(site + url));
connection.setRequestProperty("User-Agent", userAgent);
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
response = IOUtils.toString(in, "UTF-8");
in.close();
}
catch (Exception e){
e.printStackTrace();
throw new CouldNotLoadException("Could not load: " + url);
}
finally {
if (connection != null){
connection.disconnect();
}
}
return response;
}
public static Object scrape(String url, Type t, final Gson gson) throws CouldNotLoadException, IllegalStateException{
if (site == null){
throw new IllegalStateException("Must call MySoup.setSite before use");
}
Object o = null;
HttpURLConnection connection = null;
try {
connection = newHttpConnection(new URL(site + url));
connection.setRequestProperty("User-Agent", userAgent);
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
o = gson.fromJson(reader, t);
in.close();
}
catch (Exception e){
e.printStackTrace();
throw new CouldNotLoadException("Could not load: " + url);
}
finally {
if (connection != null){
connection.disconnect();
}
}
return o;
}
/**
* Perform a GET request on some other website
*
* @param url the url to get
* @return the response data as a string
* @throws api.util.CouldNotLoadException if we fail to load the page
*/
public static String scrapeOther(String url) throws CouldNotLoadException {
String response = null;
HttpURLConnection connection = null;
try {
connection = newHttpConnection(new URL(url));
connection.setRequestProperty("User-Agent", userAgent);
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
response = IOUtils.toString(in, "UTF-8");
in.close();
}
catch (Exception e){
e.printStackTrace();
throw new CouldNotLoadException("Could not load: " + url);
}
finally {
if (connection != null){
connection.disconnect();
}
}
return response;
}
public static Object scrapeOther(String url, Type t, final Gson gson) throws CouldNotLoadException{
Object o = null;
HttpURLConnection connection = null;
try {
connection = newHttpConnection(new URL(url));
connection.setRequestProperty("User-Agent", userAgent);
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
o = gson.fromJson(reader, t);
in.close();
}
catch (Exception e){
e.printStackTrace();
throw new CouldNotLoadException("Could not load: " + url);
}
finally {
if (connection != null){
connection.disconnect();
}
}
return o;
}
public static boolean pressLink(String url){
if (site == null){
throw new IllegalStateException("Must call MySoup.setSite before use");
}
HttpURLConnection connection = null;
try {
connection = newHttpConnection(new URL(site + url));
connection.setRequestProperty("User-Agent", userAgent);
return connection.getResponseCode() == 200;
}
catch (ProtocolException e){
//When we're setting notifications or logging out we're redirected too many times
if (url.contains("action=notify") || url.contains("logout")){
return true;
}
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (connection != null){
connection.disconnect();
}
}
return false;
}
/**
* Load the user information index
*/
public static void loadIndex(){
index = Index.init();
if (!index.getResponse().getUserstats().getUserClass().equalsIgnoreCase("Member")
&& !index.getResponse().getUserstats().getUserClass().equalsIgnoreCase("User")){
MySoup.notificationsEnabled = true;
}
}
/**
* Get the session cookie being used for the site
*
* @return the session cookie, or null if not found
*/
public static HttpCookie getSessionCookie(){
try {
List<HttpCookie> cookies = cookieManager.getCookieStore().get(URI.create(site));
for (HttpCookie c : cookies){
if (c.getName().equalsIgnoreCase("session")){
return c;
}
}
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
public static void addCookie(HttpCookie cookie){
try {
cookieManager.getCookieStore().add(URI.create(site), cookie);
}
catch (Exception e){
e.printStackTrace();
}
}
public static String getSite(){
return site;
}
public static String getUserAgent(){
return userAgent;
}
public static void setUserAgent(String userAgent){
MySoup.userAgent = userAgent;
}
public static boolean isSslEnabled(){
return sslEnabled;
}
public static boolean isNotificationsEnabled(){
return notificationsEnabled;
}
public static Index getIndex(){
return index;
}
public static String getAuthKey(){
return index != null ? index.getResponse().getAuthkey() : null;
}
public static String getPassKey(){
return index != null ? index.getResponse().getAuthkey() : null;
}
public static boolean isLoggedIn(){
return cookieManager.getCookieStore().getCookies().size() > 0 && index != null;
}
public static int getUserId(){
return index != null ? index.getResponse().getId().intValue() : -1;
}
public static String getUsername(){
return index != null ? index.getResponse().getUsername() : null;
}
} |
package backend;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import terminal.Card;
/*ALGO:
* 1. get cardCert from smartcard and do mutual authentication between Rental Terminal - Smartcard
* 2. get card data from database
* 3. do the change (register, top up or refund)
* 4. update database + update card certificate (if needed)
*/
public class BackendRentalTerminal {
Database db = new Database();
Backend be = new Backend();
Serialization serial = new Serialization();
ByteUtils byteUtil = new ByteUtils();
CardTerminalCommunication CT = new CardTerminalCommunication();
MutualAuthentication MA = new MutualAuthentication();
public BackendRentalTerminal(){
}
private byte[] GetRTCert(){
String RTcertFile = "RTCert";
byte[] rtCert = MA.readFiles(RTcertFile); //Read Certificate from Rental Terminal
return rtCert;
}
private RSAPrivateKey GetRTPrivateKey(){
byte[] privKeyByte = MA.readFiles("RTPrivateKey");
RSAPrivateKey rtPrivKey = null;
try {
rtPrivKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privKeyByte));
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rtPrivKey;
}
/**
* REGISTER NEW CUSTOMER
* 1. Read cert from card
* 2. renew the certificate to expand the expiration date
* 3. Add customer and card data to database. NOTE: pubkey database is string
*/
public void RegisterNewCustomer(String name){
//1. read from the card and do mutual authentication
byte[] cert = MA.TerminalMutualAuth(GetRTCert(), GetRTPrivateKey());
//2a. renew the certificate
byte[] newCert = null;
try {
newCert = be.renewCertificate(cert);
} catch (RevokedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2b. extract the expiration date and pubkey from card certificate
byte[] exp = serial.getExpFromCert(newCert);
byte[] pubKey = serial.getPublicKeyFromCert(newCert);
String strPubKey = serial.SerializeByteKey(pubKey);
long expLong = byteUtil.bytesToLong(exp);
//3. add to database customer
Integer customerId = db.insertCustomer(name);
db.addSmartcard(customerId, expLong, strPubKey);
}
/**
*
* @param cardKm: the kilometers amount that stored in the card
* NOTE: for the database, the kilometers saved is the total kilometers that ever added to the card
* without the ticking
*/
public Card TopUpCard(short cardKm){
//1. read from the card and do mutual authentication
byte[] cert = MA.TerminalMutualAuth(GetRTCert(), GetRTPrivateKey());
short km = 0; //read this from card
byte[] newCert = null;
/* Get card from database */
Card card = getCardDB(cert);
try {
/* renew the certificate */
newCert = be.renewCertificate(cert);
//extract expiration date from the new certificate and convert it to Long
long expNew = byteUtil.bytesToLong(serial.getExpFromCert(newCert));
//convert the long date to string
String expString = convertLongDateToString(expNew);
card.setExpiration(expNew);
card.setStringExpiration(expString);
/* update to database */
db.updateKilometersExpiration(card.getKilometers()+ cardKm, expNew, card.getID());
//TODO update to the smartcard
card.setKilometers(km + cardKm);
} catch (RevokedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return card;
}
//Refund the kilometers
public Card refundKilometers(){
//1. read from the card and do mutual authentication
byte[] cert = MA.TerminalMutualAuth(GetRTCert(), GetRTPrivateKey());
Card card = getCardDB(cert); //2. get card data from database
card.setKilometers(0); //3. do the refund
db.updateKilometersExpiration(0, card.getExpDate(), card.getID()); /*4. update to database */
//TODO update to Card
return card;
}
/**
* Get card data from database
* @param cardPublicKey
* @return
*/
public Card getCardDB(byte[] cardPublicKey){
Card card = new Card();
String strPubKey = serial.SerializeByteKey(cardPublicKey);
ResultSet rs = db.selectCard(strPubKey);
try {
if(rs.next()){
card = new Card(rs.getInt("id"), rs.getInt("custID"), rs.getString("custName"),
rs.getInt("km"), rs.getLong("exp") , rs.getInt("revoke"), rs.getString("cardPK"));
}else{
System.out.println("That card has not been issued");
card = null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return card;
}
//convert long date to string date
private String convertLongDateToString(long expDate){
Date date=new Date(expDate);
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
String dateText = df2.format(date);
System.out.println(dateText);
return dateText;
}
} |
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.geom.Area;
import java.awt.geom.Path2D;
import java.awt.geom.RoundRectangle2D;
import java.util.Objects;
import java.util.Optional;
import javax.swing.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new GridLayout(1, 2));
DefaultListModel<String> model = new DefaultListModel<>();
model.addElement("ABC DEF GHI JKL MNO PQR STU VWX YZ");
model.addElement("111");
model.addElement("111222");
model.addElement("111222333");
model.addElement("1234567890 abc def ghi jkl mno pqr stu vwx yz");
model.addElement("bbb1");
model.addElement("bbb12");
model.addElement("1234567890-+*/=ABC DEF GHI JKL MNO PQR STU VWX YZ");
model.addElement("bbb123");
JList<String> list1 = new JList<String>(model) {
@Override public JToolTip createToolTip() {
JToolTip tip = new BalloonToolTip();
tip.setComponent(this);
return tip;
}
@Override public void updateUI() {
super.updateUI();
setCellRenderer(new TooltipListCellRenderer<>());
}
};
JList<String> list2 = new JList<String>(model) {
@Override public void updateUI() {
super.updateUI();
setCellRenderer(new TooltipListCellRenderer<>());
}
};
add(makeTitledPanel("BalloonToolTip", list1));
add(makeTitledPanel("Default JToolTip", list2));
setPreferredSize(new Dimension(320, 240));
}
private static Component makeTitledPanel(String title, Component c) {
JScrollPane scroll = new JScrollPane(c);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createTitledBorder(title));
p.add(scroll);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class TooltipListCellRenderer<E> implements ListCellRenderer<E> {
private final ListCellRenderer<? super E> renderer = new DefaultListCellRenderer();
@Override public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel l = (JLabel) renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Insets i = l.getInsets();
// Container c = SwingUtilities.getAncestorOfClass(JViewport.class, list);
// Rectangle rect = c.getBounds();
Class<JViewport> clz = JViewport.class;
Rectangle rect = Optional.ofNullable(SwingUtilities.getAncestorOfClass(clz, list))
.filter(clz::isInstance).map(clz::cast)
.map(JViewport::getBounds)
.orElseGet(Rectangle::new);
rect.width -= i.left + i.right;
FontMetrics fm = l.getFontMetrics(l.getFont());
String str = Objects.toString(value, "");
l.setToolTipText(fm.stringWidth(str) > rect.width ? str : null);
return l;
}
}
class BalloonToolTip extends JToolTip {
private HierarchyListener listener;
@Override public void updateUI() {
removeHierarchyListener(listener);
super.updateUI();
listener = e -> {
Component c = e.getComponent();
if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && c.isShowing()) {
// if (w instanceof JWindow) {
// System.out.println("Popup$HeavyWeightWindow");
// w.setBackground(new Color(0x0, true));
Optional.ofNullable(SwingUtilities.getRoot(c))
.filter(JWindow.class::isInstance).map(JWindow.class::cast)
.ifPresent(w -> w.setBackground(new Color(0x0, true)));
}
};
addHierarchyListener(listener);
setOpaque(false);
setBorder(BorderFactory.createEmptyBorder(8, 5, 0, 5));
}
@Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
d.height = 28;
return d;
}
@Override protected void paintComponent(Graphics g) {
Shape s = makeBalloonShape();
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getBackground());
g2.fill(s);
g2.setColor(getForeground());
g2.draw(s);
g2.dispose();
super.paintComponent(g);
}
private Shape makeBalloonShape() {
Insets i = getInsets();
float w = getWidth() - 1f;
float h = getHeight() - 1f;
float v = i.top * .5f;
Path2D triangle = new Path2D.Float();
triangle.moveTo(i.left + v + v, 0f);
triangle.lineTo(i.left + v, v);
triangle.lineTo(i.left + v + v + v, v);
Area area = new Area(new RoundRectangle2D.Float(0f, v, w, h - i.bottom - v, i.top, i.top));
area.add(new Area(triangle));
return area;
}
} |
package org.apache.jmeter.save;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.configuration.DefaultConfigurationSerializer;
import org.apache.jmeter.assertions.AssertionResult;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.log.Hierarchy;
import org.apache.log.Logger;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.ListedHashTree;
import org.xml.sax.SAXException;
public class SaveService implements SaveServiceConstants
{
transient private static Logger log =
Hierarchy.getDefaultHierarchy().getLoggerFor("jmeter.util");
protected static final int SAVE_NO_ASSERTIONS = 0;
protected static final int SAVE_FIRST_ASSERTION = SAVE_NO_ASSERTIONS + 1;
protected static final int SAVE_ALL_ASSERTIONS = SAVE_FIRST_ASSERTION + 1;;
/** A formatter for the time stamp. **/
protected static SimpleDateFormat formatter = null;
/** A flag to indicate whether the data type should
be saved to the test results. **/
protected static boolean saveDataType = true;
/** A flag to indicate whether the label should
be saved to the test results. **/
protected static boolean saveLabel = true;
/** A flag to indicate whether the response code should
be saved to the test results. **/
protected static boolean saveResponseCode = false;
/** A flag to indicate whether the response data should
be saved to the test results. **/
protected static boolean saveResponseData = false;
/** A flag to indicate whether the response message should
be saved to the test results. **/
protected static boolean saveResponseMessage = false;
/** A flag to indicate whether the success indicator should
be saved to the test results. **/
protected static boolean saveSuccessful = true;
/** A flag to indicate whether the thread name should
be saved to the test results. **/
protected static boolean saveThreadName = true;
/** A flag to indicate whether the time should
be saved to the test results. **/
protected static boolean saveTime = true;
/** A flag to indicate the format of the time stamp within
the test results. **/
protected static String timeStampFormat = MILLISECONDS;
/** A flag to indicate whether the time stamp should be printed
in milliseconds. **/
protected static boolean printMilliseconds = true;
/** A flag to indicate which assertion results should
be saved to the test results. Legitimate values include
none, first, all. **/
protected static String whichAssertionResults = FIRST;
protected static int assertionsResultsToSave = SAVE_NO_ASSERTIONS;
private static DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
// Initialize various variables based on properties.
static
{
readAndSetSaveProperties();
} // static initialization
public SaveService()
{
}
protected static void readAndSetSaveProperties()
{
Properties systemProps = System.getProperties();
Properties props = new Properties(systemProps);
try
{
props = JMeterUtils.getProperties(PROPS_FILE);
}
catch (Exception e)
{
log.error("SaveService.readAndSetSaveProperties: Problem loading properties file " + PROPS_FILE, e);
}
saveDataType =
TRUE.equalsIgnoreCase(props.getProperty(SAVE_DATA_TYPE_PROP,
TRUE));
saveLabel =
TRUE.equalsIgnoreCase(props.getProperty(SAVE_LABEL_PROP,
TRUE));
saveResponseCode =
TRUE.equalsIgnoreCase(props.getProperty(SAVE_RESPONSE_CODE_PROP,
TRUE));
saveResponseData =
TRUE.equalsIgnoreCase(props.getProperty(SAVE_RESPONSE_DATA_PROP,
FALSE));
saveResponseMessage =
TRUE.equalsIgnoreCase(props.getProperty(SAVE_RESPONSE_MESSAGE_PROP,
TRUE));
saveSuccessful =
TRUE.equalsIgnoreCase(props.getProperty(SAVE_SUCCESSFUL_PROP,
TRUE));
saveThreadName =
TRUE.equalsIgnoreCase(props.getProperty(SAVE_THREAD_NAME_PROP,
TRUE));
saveTime =
TRUE.equalsIgnoreCase(props.getProperty(SAVE_TIME_PROP,
TRUE));
timeStampFormat =
props.getProperty(TIME_STAMP_FORMAT_PROP, MILLISECONDS);
printMilliseconds = MILLISECONDS.equalsIgnoreCase(timeStampFormat);
if (!printMilliseconds
&& !NONE.equalsIgnoreCase(timeStampFormat)
&& (timeStampFormat != null))
{
formatter = new SimpleDateFormat(timeStampFormat);
}
whichAssertionResults = props.getProperty(ASSERTION_RESULTS_PROP,
NONE);
if (NONE.equals(whichAssertionResults))
{
assertionsResultsToSave = SAVE_NO_ASSERTIONS;
}
else if (FIRST.equals(whichAssertionResults))
{
assertionsResultsToSave = SAVE_FIRST_ASSERTION;
}
else if (ALL.equals(whichAssertionResults))
{
assertionsResultsToSave = SAVE_ALL_ASSERTIONS;
}
}
public static void saveSubTree(HashTree subTree,OutputStream writer) throws
IOException
{
Configuration config = (Configuration)getConfigsFromTree(subTree).get(0);
DefaultConfigurationSerializer saver = new DefaultConfigurationSerializer();
saver.setIndent(true);
try
{
saver.serialize(writer,config);
}
catch(SAXException e)
{
throw new IOException("SAX implementation problem");
}
catch(ConfigurationException e)
{
throw new IOException("Problem using Avalon Configuration tools");
}
}
public static SampleResult getSampleResult(Configuration config)
{
SampleResult result = new SampleResult();
result.setThreadName(config.getAttribute(THREAD_NAME,""));
result.setDataType(config.getAttribute(DATA_TYPE,""));
result.setResponseCode(config.getAttribute(RESPONSE_CODE,""));
result.setResponseMessage(config.getAttribute(RESPONSE_MESSAGE,""));
result.setTime(config.getAttributeAsLong(TIME,0L));
result.setTimeStamp(config.getAttributeAsLong(TIME_STAMP,0L));
result.setSuccessful(config.getAttributeAsBoolean(SUCCESSFUL,false));
result.setSampleLabel(config.getAttribute(LABEL,""));
result.setResponseData(getBinaryData(config.getChild(BINARY)));
Configuration[] subResults = config.getChildren(SAMPLE_RESULT_TAG_NAME);
for(int i = 0;i < subResults.length;i++)
{
result.addSubResult(getSampleResult(subResults[i]));
}
Configuration[] assResults = config.getChildren(ASSERTION_RESULT_TAG_NAME);
for(int i = 0;i < assResults.length;i++)
{
result.addAssertionResult(getAssertionResult(assResults[i]));
}
return result;
}
private static List getConfigsFromTree(HashTree subTree)
{
Iterator iter = subTree.list().iterator();
List configs = new LinkedList();
while (iter.hasNext())
{
TestElement item = (TestElement)iter.next();
DefaultConfiguration config = new DefaultConfiguration("node","node");
config.addChild(getConfigForTestElement(null,item));
List configList = getConfigsFromTree(subTree.getTree(item));
Iterator iter2 = configList.iterator();
while(iter2.hasNext())
{
config.addChild((Configuration)iter2.next());
}
configs.add(config);
}
return configs;
}
public static Configuration getConfiguration(byte[] bin)
{
DefaultConfiguration config = new DefaultConfiguration(BINARY,"JMeter Save Service");
try {
config.setValue(new String(bin,"utf-8"));
} catch(UnsupportedEncodingException e) {
log.error("",e);
}
return config;
}
public static byte[] getBinaryData(Configuration config)
{
if(config == null)
{
return new byte[0];
}
try {
return config.getValue("").getBytes("utf-8");
} catch(UnsupportedEncodingException e) {
return new byte[0];
}
}
public static AssertionResult getAssertionResult(Configuration config)
{
AssertionResult result = new AssertionResult();
result.setError(config.getAttributeAsBoolean(ERROR,false));
result.setFailure(config.getAttributeAsBoolean(FAILURE,false));
result.setFailureMessage(config.getAttribute(FAILURE_MESSAGE,""));
return result;
}
public static Configuration getConfiguration(AssertionResult assResult)
{
DefaultConfiguration config = new DefaultConfiguration(ASSERTION_RESULT_TAG_NAME,
"JMeter Save Service");
config.setAttribute(FAILURE_MESSAGE,assResult.getFailureMessage());
config.setAttribute(ERROR,""+assResult.isError());
config.setAttribute(FAILURE,""+assResult.isFailure());
return config;
}
/**
This method determines the content of the result data that
will be stored.
@param result the object containing all of the data that has
been collected.
@param funcTest an indicator of whether the user wants all
data recorded.
**/
public static Configuration getConfiguration(SampleResult result,boolean funcTest)
{
DefaultConfiguration config = new DefaultConfiguration(SAMPLE_RESULT_TAG_NAME,"JMeter Save Service");
if (saveTime)
{
config.setAttribute(TIME,""+result.getTime());
}
if (saveLabel)
{
config.setAttribute(LABEL,result.getSampleLabel());
}
if (saveResponseCode)
{
config.setAttribute(RESPONSE_CODE,result.getResponseCode());
}
if (saveResponseMessage)
{
config.setAttribute(RESPONSE_MESSAGE,result.getResponseMessage());
}
if (saveThreadName)
{
config.setAttribute(THREAD_NAME,result.getThreadName());
}
if (saveDataType)
{
config.setAttribute(DATA_TYPE,result.getDataType());
}
if (printMilliseconds)
{
config.setAttribute(TIME_STAMP,""+result.getTimeStamp());
}
else if (formatter != null)
{
String stamp = formatter.format(new Date(result.getTimeStamp()));
config.setAttribute(TIME_STAMP, stamp);
}
if (saveSuccessful)
{
config.setAttribute(SUCCESSFUL,new Boolean(result.isSuccessful()).toString());
}
SampleResult[] subResults = result.getSubResults();
for(int i = 0;i < subResults.length;i++)
{
config.addChild(getConfiguration(subResults[i],funcTest));
}
AssertionResult[] assResults = result.getAssertionResults();
if(funcTest)
{
config.addChild(getConfigForTestElement(null,result.getSamplerData()));
for(int i = 0;i < assResults.length;i++)
{
config.addChild(getConfiguration(assResults[i]));
}
config.addChild(getConfiguration(result.getResponseData()));
}
// Determine which of the assertion results to save and
// whether to save the response data
else
{
if (assertionsResultsToSave == SAVE_ALL_ASSERTIONS)
{
config.addChild(getConfigForTestElement(null,result.getSamplerData()));
for(int i = 0;i < assResults.length;i++)
{
config.addChild(getConfiguration(assResults[i]));
}
}
else if ((assertionsResultsToSave == SAVE_FIRST_ASSERTION)
&& assResults.length > 0)
{
config.addChild(getConfiguration(assResults[0]));
}
if (saveResponseData)
{
config.addChild(getConfiguration(result.getResponseData()));
}
}
return config;
}
public static Configuration getConfigForTestElement(String named,TestElement item)
{
DefaultConfiguration config = new DefaultConfiguration("testelement","testelement");
if(named != null)
{
config.setAttribute("name",named);
}
if(item.getProperty(TestElement.TEST_CLASS) != null)
{
config.setAttribute("class",(String)item.getProperty(TestElement.TEST_CLASS));
}
else
{
config.setAttribute("class",item.getClass().getName());
}
Iterator iter = item.getPropertyNames().iterator();
while (iter.hasNext())
{
String name = (String)iter.next();
Object value = item.getProperty(name);
if(value instanceof TestElement)
{
config.addChild(getConfigForTestElement(name,(TestElement)value));
}
else if(value instanceof Collection)
{
config.addChild(createConfigForCollection(name,(Collection)value));
}
else if(value != null)
{
config.addChild(createConfigForString(name,value.toString()));
}
}
return config;
}
private static Configuration createConfigForCollection(String propertyName,Collection list)
{
DefaultConfiguration config = new DefaultConfiguration("collection","collection");
if(propertyName != null)
{
config.setAttribute("name",propertyName);
}
config.setAttribute("class",list.getClass().getName());
Iterator iter = list.iterator();
while (iter.hasNext())
{
Object item = iter.next();
if(item instanceof TestElement)
{
config.addChild(getConfigForTestElement(null,(TestElement)item));
}
else if(item instanceof Collection)
{
config.addChild(createConfigForCollection(null,(Collection)item));
}
else
{
config.addChild(createConfigForString(item.toString()));
}
}
return config;
}
private static Configuration createConfigForString(String value)
{
DefaultConfiguration config = new DefaultConfiguration("string","string");
config.setValue(value);
config.setAttribute(XML_SPACE,PRESERVE);
return config;
}
private static Configuration createConfigForString(String name,String value)
{
if(value == null)
{
value = "";
}
DefaultConfiguration config = new DefaultConfiguration("property","property");
config.setAttribute("name",name);
config.setValue(value);
config.setAttribute(XML_SPACE,PRESERVE);
return config;
}
public synchronized static HashTree loadSubTree(InputStream in) throws IOException
{
try
{
Configuration config = builder.build(in);
HashTree loadedTree = generateNode(config);
return loadedTree;
}
catch(ConfigurationException e)
{
throw new IOException("Problem loading using Avalon Configuration tools");
}
catch(SAXException e)
{
throw new IOException("Problem with SAX implementation");
}
}
public static TestElement createTestElement(Configuration config) throws ConfigurationException,
ClassNotFoundException, IllegalAccessException,InstantiationException
{
TestElement element = null;
element = (TestElement)Class.forName((String)config.getAttribute("class")).newInstance();
Configuration[] children = config.getChildren();
for (int i = 0; i < children.length; i++)
{
if(children[i].getName().equals("property"))
{
try
{
element.setProperty(children[i].getAttribute("name"),
children[i].getValue());
}
catch (Exception ex)
{
log.error("Problem loading property",ex);
element.setProperty(children[i].getAttribute("name"),"");
}
}
else if(children[i].getName().equals("testelement"))
{
element.setProperty(children[i].getAttribute("name"),
createTestElement(children[i]));
}
else if(children[i].getName().equals("collection"))
{
element.setProperty(children[i].getAttribute("name"),
createCollection(children[i]));
}
}
return element;
}
private static Collection createCollection(Configuration config) throws ConfigurationException,
ClassNotFoundException,IllegalAccessException,InstantiationException
{
Collection coll = (Collection)Class.forName((String)config.getAttribute("class")).newInstance();
Configuration[] items = config.getChildren();
for (int i = 0; i < items.length; i++)
{
if(items[i].getName().equals("property"))
{
coll.add(items[i].getValue(""));
}
else if(items[i].getName().equals("testelement"))
{
coll.add(createTestElement(items[i]));
}
else if(items[i].getName().equals("collection"))
{
coll.add(createCollection(items[i]));
}
else if(items[i].getName().equals("string"))
{
coll.add(items[i].getValue(""));
}
}
return coll;
}
private static HashTree generateNode(Configuration config)
{
TestElement element = null;
try
{
element = createTestElement(config.getChild("testelement"));
}
catch(Exception e)
{
log.error("Problem loading part of file",e);
return null;
}
HashTree subTree = new ListedHashTree(element);
Configuration[] subNodes = config.getChildren("node");
for (int i = 0; i < subNodes.length; i++)
{
HashTree t = generateNode(subNodes[i]);
if(t != null)
{
subTree.add(element,t);
}
}
return subTree;
}
public static class Test extends TestCase
{
private static final String[] FILES= new String[]
{
"AssertionTestPlan.jmx",
"AuthManagerTestPlan.jmx",
"HeaderManagerTestPlan.jmx",
"InterleaveTestPlan2.jmx",
"InterleaveTestPlan.jmx",
"LoopTestPlan.jmx",
"Modification Manager.jmx",
"OnceOnlyTestPlan.jmx",
"proxy.jmx",
"ProxyServerTestPlan.jmx",
"SimpleTestPlan.jmx",
};
public Test(String name)
{
super(name);
}
public void setUp() {
}
public void testLoadAndSave() throws java.io.IOException {
byte[] original= new byte[1000000];
for (int i=0; i<FILES.length; i++) {
InputStream in= new FileInputStream(new File("testfiles/"+FILES[i]));
int len= in.read(original);
in.close();
in= new ByteArrayInputStream(original, 0, len);
HashTree tree= loadSubTree(in);
in.close();
ByteArrayOutputStream out= new ByteArrayOutputStream(1000000);
saveSubTree(tree, out);
out.close();
// We only check the length of the result. Comparing the
// actual result (out.toByteArray==original) will usually
// fail, because the order of the properties within each
// test element may change. Comparing the lengths should be
// enough to detect most problem cases...
if (len!=out.size()) {
fail("Loading file bin/testfiles/"+FILES[i]+" and "+
"saving it back changes its contents.");
}
// Note this test will fail if a property is added or
// removed to any of the components used in the test
// files. The way to solve this is to appropriately change
// the test file.
}
}
}
} |
package org.noear.weed.cache;
import java.util.Map;
import java.util.concurrent.*;
public class LocalCache implements ICacheServiceEx {
private String _cacheKeyHead;
private int _defaultSeconds;
private Map<String, Entity> _data = new ConcurrentHashMap<>();
private static ScheduledExecutorService _exec = Executors.newSingleThreadScheduledExecutor();
public LocalCache(String keyHeader, int defSeconds) {
_cacheKeyHead = keyHeader;
_defaultSeconds = defSeconds;
}
@Override
public void store(String key, Object obj, int seconds) {
synchronized (key.intern()) {
Entity ent = _data.get(key);
if (ent == null) {
ent = new Entity(obj);
_data.put(key, ent);
}else{
ent.value = obj;
ent.futureDel();
}
if (seconds > 0) {
ent.future = _exec.schedule(() -> {
_data.remove(key);
}, seconds, TimeUnit.SECONDS);
}
}
}
@Override
public Object get(String key) {
Entity ent = _data.get(key);
return ent == null ? null : ent.value;
}
@Override
public void remove(String key) {
synchronized (key.intern()) {
Entity ent = _data.remove(key);
if (ent != null) {
ent.futureDel();
}
}
}
public void clear() {
for (Entity ent : _data.values()) {
ent.futureDel();
}
_data.clear();
}
@Override
public int getDefalutSeconds() {
return _defaultSeconds;
}
@Override
public String getCacheKeyHead() {
return _cacheKeyHead;
}
private static class Entity {
public Object value;
public Future future;
public Entity(Object val) {
this.value = val;
}
protected void futureDel(){
if (future != null) {
future.cancel(true);
future = null;
}
}
}
} |
/**
* @author Nikos Arechiga
* @author Anuradha Vakil
* Toyota InfoTechnology Center, USA
* 465 N Bernardo Ave, Mountain View, CA 94043
*/
package dl.logicsolvers.drealkit;
//import proteus.logicsolvers.abstractions.*;
import interfaces.text.TextOutput;
import java.util.*;
import dl.semantics.*;
import dl.syntax.*;
import java.io.*;
import dl.logicsolvers.abstractions.LogicSolverInterface;
import dl.logicsolvers.abstractions.LogicSolverResult;
import dl.parser.PrettyPrinter;
public class dRealInterface extends LogicSolverInterface {
public double precision = 0.00001;
public boolean debug = false;
public String dRealPath = "dReal";
public void setPrecision( double precision ) {
this.precision = precision;
}
//Constructors
// Constructor with specified precision
public dRealInterface( double precision ) {
this.precision = precision;
// Generate the workspace
File drealworkspacedir = new File("/tmp/dRealWorkspace");
if (!drealworkspacedir.exists()) {
drealworkspacedir.mkdir();
}
dRealPath = finddReal();
}
// Constructor with default precision
public dRealInterface() {
this.precision = 0.00001;
// Generate the workspace
File drealworkspacedir = new File("/tmp/dRealworkspace");
if (!drealworkspacedir.exists()) {
drealworkspacedir.mkdir();
}
dRealPath = finddReal();
}
public String finddReal() {
// Find dReal installation
try {
ProcessBuilder queryPB = new ProcessBuilder("which", "dReal" );
queryPB.redirectErrorStream( true );
Process queryProcess = queryPB.start();
BufferedReader z3Says = new BufferedReader( new InputStreamReader(queryProcess.getInputStream()) );
String line = "";
if ( (line = z3Says.readLine()) != null ) {
TextOutput.info("Using automatically detected installation of dReal at: " + line );
return line;
}
queryPB = new ProcessBuilder("which", "/usr/local/bin/dReal" );
queryPB.redirectErrorStream( true );
queryProcess = queryPB.start();
z3Says = new BufferedReader( new InputStreamReader(queryProcess.getInputStream()) );
line = "";
if ( (line = z3Says.readLine()) != null ) {
TextOutput.info("Using automatically detected installation of dReal at: " + line );
return line;
}
queryPB = new ProcessBuilder("which", "/usr/bin/dReal" );
queryPB.redirectErrorStream( true );
queryProcess = queryPB.start();
z3Says = new BufferedReader( new InputStreamReader(queryProcess.getInputStream()) );
line = "";
if ( (line = z3Says.readLine()) != null ) {
TextOutput.info("Using automatically detected installation of dReal at: " + line );
return line;
}
} catch ( Exception e ) {
e.printStackTrace();
}
TextOutput.error("Unable to find an installation of dReal.");
throw new RuntimeException("Unable to find dReal!");
}
// "checkValidity" family of methods -- try to find a counterexample
public LogicSolverResult checkValidity( String filename, dLFormula thisFormula, String comment ) throws Exception {
TextOutput.debug("Entering checkValidity( string, dlformula, string) ");
dLFormula negatedFormula = thisFormula.negate();
ArrayList<dLFormula> theseFormulas = negatedFormula.splitOnAnds();
// Try to find a counterexample
//LogicSolverResult subResult = findInstance( filename, theseFormulas, comment );
LogicSolverResult subResult = findInstance( theseFormulas);
//TextOutput.debug(subResult);
// We queried the negation, so invert the result
LogicSolverResult result;
if ( subResult.satisfiability.equals("unsat") ) {
result = new LogicSolverResult("sat", "valid", new Valuation() );
TextOutput.debug("Your formula is valid");
} else if ( subResult.satisfiability.equals("delta-sat") ) {
// The valuation is then a counterexample
// but with dReal we can't be sure
result = new LogicSolverResult("unknown", "unknown", subResult.valuation );
} else {
//gibberish, I guess
result = new LogicSolverResult("unknown", "unknown", new Valuation() );
}
TextOutput.debug("Returning.");
return result;
}
// "FindInstance" family of methods
public LogicSolverResult findInstance( String filename, List<dLFormula> theseFormulas, String comment )
throws Exception {
TextOutput.debug("Entering findInstance( String, dLformula, String )");
File queryFile = writeQueryFile( filename, theseFormulas, comment );
TextOutput.debug("Running query on file: " + filename);
//TextOutput.debug(runQuery(queryFile));
return runQuery( queryFile );
}
// Automatically comment a list of formulas
protected String generateFindInstanceComment( List<dLFormula> theseFormulas ) {
String comment = ";; Find a valuation of variables that satisfies the formulas:\n;;\n";
Iterator<dLFormula> formulaIterator = theseFormulas.iterator();
int counter = 1;
while ( formulaIterator.hasNext() ) {
comment = comment + "\n;; Formula " + counter + ":\n";
comment = comment + ";; " + PrettyPrinter.print(formulaIterator.next());
counter = counter + 1;
}
return comment;
}
protected String generateCheckValidityComment( List<dLFormula> theseFormulas ) {
String comment = ";; Check (conjunctive) validity of: \n;;\n";
Iterator<dLFormula> formulaIterator = theseFormulas.iterator();
int counter = 1;
while ( formulaIterator.hasNext() ) {
comment = comment + ";; Formula " + counter + ":\n";
comment = comment + ";; " + PrettyPrinter.print(formulaIterator.next());
counter = counter + 1;
}
return comment;
}
public String timeStampComment( String comment ) {
Date date = new Date();
String stampedComment = ";; Automatically generated by Proteus on " + date.toString() + "\n\n";
stampedComment = stampedComment + comment;
return stampedComment;
}
public String commentLine( String comment ) {
return ";; " + comment + "\n";
}
// Runs dReal on a query file, written by some other function The point of this function is to allow code reuse of
// the piece that actually invokes dReal
protected LogicSolverResult runQuery( File queryFile ) throws Exception {
TextOutput.debug("Entering runQuery( File )");
LogicSolverResult result = null;
String precisionArgument = "--precision " + precision;
// ProcessBuilder queryPB = new ProcessBuilder("dReal", "--model",
// precisionArgument, queryFile.getAbsolutePath() );
ProcessBuilder queryPB = new ProcessBuilder(dRealPath, "--precision", ""+precision+"", "--model", queryFile.getAbsolutePath() );
TextOutput.debug( "Commmand is: " + queryPB.command() );
queryPB.redirectErrorStream( true );
Process queryProcess = queryPB.start();
BufferedReader dRealSays = new BufferedReader( new InputStreamReader(queryProcess.getInputStream()) );
String line;
String totalOutput = "";
while ( (line = dRealSays.readLine()) != null ) {
totalOutput += line;
//TextOutput.debug( line );
if ( line.contains("unsat")) {
result = new LogicSolverResult( "unsat", "notvalid", new Valuation() );
} else if ( line.contains("delta-sat") ) {
Valuation cex = extractModel( new File( queryFile.getAbsolutePath() + ".model") );
result = new LogicSolverResult( "delta-sat", "unknown", cex );
} else if ( line.equals("unknown") ) {
result = new LogicSolverResult( "unknown", "unknown", new Valuation() );
}
// } else {
// throw new Exception( line );
}// else {
// throw new Exception("dReal returned no output!");
//TextOutput.debug("Solver result is: ");
//TextOutput.debug( result.toString() );
if ( result == null ) {
throw new RuntimeException("dReal returned unexpected output:" + totalOutput );
}
//queryFile.delete();
return result;
}
// Extracts a counterexample from a *.model file produced after running dReal
protected Valuation extractModel( File modelFile ) throws Exception {
//TextOutput.debug("Extracting CEX...");
Valuation model = new Valuation();
// Wait for file to exist. Yeah, somehow this is a problem sometimes
//while ( (!modelFile.exists()) || (modelFile.length() == 0) ) {
// TextOutput.debug("Waiting for CEX file to exist...");
// TextOutput.debug("(yeah, sometimes this happens, somehow)");
// try {
// Thread.sleep(3000); //1000 milliseconds is one second.
// } catch(InterruptedException ex) {
// Thread.currentThread().interrupt();
TextOutput.debug("Pausing to let dReal finish writing out the CEX file...: " + modelFile.toString() );
try {
Thread.sleep(100); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
Scanner modelReader = new Scanner( modelFile );
modelReader.nextLine();
//TextOutput.debug("Discarding preamble: " + modelReader.readLine() );
String line;
while( modelReader.hasNextLine() ) {
line = modelReader.nextLine();
if (!( line.contains(",")) ) {
//TextOutput.debug("Skipping strange line: " + line);
continue;
}
//TextOutput.debug("CEX line is: " + line);
line = line.trim();
String[] tokens = line.split("\\s+");
RealVariable variable = new RealVariable( tokens[0] );
String lowerBound = tokens[2].replace("[","").replace(",","").replace("(","").replace(";","");
String upperBound = tokens[3].replace("]","").replace(")","").replace(";","");
//TextOutput.debug("lower bound: " + lowerBound );
//TextOutput.debug("upper bound: " + upperBound );
if ( (lowerBound.equals("-inf") && upperBound.equals("inf")) ||
((lowerBound.equals("-INFTY") && upperBound.equals("INFTY")) ) ) {
model.put(variable, new Real(42));
} else if ( lowerBound.equals("-inf") || upperBound.equals("-INFTY") ) {
model.put(variable, new Real( upperBound ));
} else if ( upperBound.equals("inf") || upperBound.equals("+INFTY") ) {
model.put( variable, new Real( lowerBound ));
} else {
model.put( variable, new Real( (Double.parseDouble(upperBound)
+ Double.parseDouble(lowerBound))/2 ));
}
}
//TextOutput.debug("CEX Model is: " + model.toString() );
//TextOutput.debug("Existence: " + modelFile.exists() );
//System.exit(1);
//modelFile.delete();
modelReader.close();
return model;
}
public String decorateFilename( String base ) {
return decorateFilename( "dRealWorkspace", base, "smt2" );
}
public String generateFilename() {
double randomID = Math.round(Math.random());
Date date = new Date();
//return "drealworkspace/query." +UUID.randomUUID().toString().replaceAll("-", "")+ "_"+ date.getTime() + "." + randomID + ".smt2";
return decorateFilename( "query" + date.getTime() + "." + randomID );
}
// Writes a query file for a logical formula. Note that it does not negate the formula, it just writes out
// a satisfiability query for the formula that it is given
protected File writeQueryFile( String filename, List<dLFormula> theseFormulas, String comment )
throws Exception {
String queryString = "(set-logic QF_NRA)\n\n";
// First extract the list of all the variables that occur in any of the formulas
Iterator<dLFormula> formulaIterator = theseFormulas.iterator();
Set<RealVariable> variables = new HashSet<RealVariable>();
while ( formulaIterator.hasNext() ) {
variables.addAll( formulaIterator.next().getFreeVariables() );
}
//variables.addAll(this.get_Bounds().getFreeVariables());
// Now print the variable declarations
queryString = queryString + "\n;; Variable declarations\n";
//RealVariable thisVariable;
Iterator<RealVariable> variableIterator = variables.iterator();
while ( variableIterator.hasNext() ) {
queryString = queryString + "(declare-fun " + variableIterator.next() + " () Real )\n";
}
//if ( variables.isEmpty() ) {
// RealVariable x = new RealVariable("x");
// queryString = queryString + "(declare-fun " + x.todRealString() + " () Real )\n";
// Assert each formula
formulaIterator = theseFormulas.iterator();
dLFormula thisFormula;
while ( formulaIterator.hasNext() ) {
thisFormula = formulaIterator.next();
if( debug ) {
if ( thisFormula == null ) {
TextOutput.debug("Got a null formula!");
} else {
TextOutput.debug("Currently printing out formula: "
+ PrettyPrinter.print(thisFormula) );
}
}
// thisFormula=new AndFormula(thisFormula,this.get_Bounds());
queryString = queryString + "\n;; Formula is (" + PrettyPrinter.print(thisFormula) +")\n";
queryString = queryString + "(assert " + thisFormula.todRealString() + " )\n";
}
// queryString = queryString + "\n;; Formula is (" + PrettyPrinter.print(this.get_Bounds()) +")\n";
// queryString = queryString + "(assert " + this.get_Bounds().todRealString() + " )\n";
// Print the little thing that needs to go at the end
queryString = queryString + "\n(check-sat)\n(exit)\n";
// Now generate the actual file
PrintWriter queryFile = new PrintWriter( filename );
queryFile.println( timeStampComment( comment ) + "\n" );
queryFile.println( queryString );
queryFile.close();
if( debug ) {
TextOutput.debug("Done writing file, writeQueryFile is returning");
}
return new File( filename );
}
} |
package edu.wustl.xipHost.hostControl;
import java.util.List;
import org.nema.dicom.wg23.ArrayOfObjectDescriptor;
import org.nema.dicom.wg23.ArrayOfObjectLocator;
import org.nema.dicom.wg23.ArrayOfUUID;
import org.nema.dicom.wg23.AvailableData;
import org.nema.dicom.wg23.ObjectDescriptor;
import org.nema.dicom.wg23.ObjectLocator;
import org.nema.dicom.wg23.Uuid;
import edu.wustl.xipHost.application.Application;
import edu.wustl.xipHost.avt.AVTStore;
import edu.wustl.xipHost.caGrid.AimStore;
/**
* @author Jaroslaw Krych
*
*/
public class DataStore implements Runnable {
AvailableData availableData;
Application app;
public DataStore(AvailableData availableData, Application app){
this.availableData = availableData;
this.app = app;
}
public void run() {
//1. It is excpected for IA application that AIM object will is added to the top AvailableData descriptors list.
//2. DICOM attachemnt objects are excpected to be added to the series of the AvailableData
//3. When storing AIM pairs of AIM plus DICOM degmentation objects are expected
ArrayOfUUID arrayUUIDs = new ArrayOfUUID();
List<Uuid> listUUIDs = arrayUUIDs.getUuid();
ObjectDescriptor aimDesc = availableData.getObjectDescriptors().getObjectDescriptor().get(0);
listUUIDs.add(aimDesc.getUuid());
//JK on 09/27/2009
ObjectDescriptor dicomSegDesc;
if(availableData.getPatients().getPatient().get(0).getStudies().getStudy().get(0).getSeries().getSeries().get(0).getObjectDescriptors().getObjectDescriptor().size() == 0){
}else{
dicomSegDesc = availableData.getPatients().getPatient().get(0).getStudies().getStudy().get(0).getSeries().getSeries().get(0).getObjectDescriptors().getObjectDescriptor().get(0);
listUUIDs.add(dicomSegDesc.getUuid());
}
ArrayOfObjectLocator arrayOfObjectLocator = app.getClientToApplication().getDataAsFile(arrayUUIDs, false);
if(arrayOfObjectLocator == null){
return;
}else{
List<ObjectLocator> objLocs = arrayOfObjectLocator.getObjectLocator();
boolean submitToAVT = false;
if(submitToAVT){
AVTStore avtStore = new AVTStore(objLocs);
Thread t = new Thread(avtStore);
t.start();
}
boolean submitToAIME = true;
if(submitToAIME){
AimStore aimStore = new AimStore(objLocs, null);
Thread t2 = new Thread(aimStore);
t2.start();
}
}
}
} |
package foam.nanos.auth;
import foam.core.ContextAwareSupport;
import foam.core.X;
import foam.dao.*;
import foam.mlang.MLang;
import foam.nanos.NanoService;
import foam.util.LRULinkedHashMap;
import javax.naming.AuthenticationException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
import java.util.regex.Pattern;
public class UserAndGroupAuthService
extends ContextAwareSupport
implements AuthService, NanoService
{
public static final Pattern emailPattern = Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\" +
"\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\" +
"\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\" +
"n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\" +
"031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[" +
"^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(" +
"?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?" +
"[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*" +
"\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\" +
"[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[" +
"\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@," +
";:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;" +
":\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:" +
"\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] " +
"\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]" +
"))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\" +
"n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]" +
")+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?" +
":(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[" +
"\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[" +
"\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\" +
"r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\" +
"t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\]" +
"(?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\" +
"[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\" +
"[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[" +
" \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031" +
"]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\" +
"\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:" +
"\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[" +
" \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*" +
"\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\"." +
"\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\"." +
"\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?" +
":\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n" +
")?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\." +
"|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*" +
"(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\" +
"Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\" +
"n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()" +
"<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()" +
"<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"" +
"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] " +
"\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]" +
"))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n" +
")?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]" +
")+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?" +
":(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:" +
"\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\" +
"]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)" +
"?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ " +
"\\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*" +
"\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\"" +
".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\"" +
".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?" +
":(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\" +
"n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\" +
"\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\" +
"\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\" +
"\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:" +
"(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:" +
"\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]" +
"|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)" +
"?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+" +
"|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r" +
"\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@" +
",;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@" +
",;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)" +
"(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:" +
"(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\" +
"\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(" +
"?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?" +
"=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ " +
"\\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:" +
"\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:" +
"\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:" +
"\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-" +
"\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[" +
"([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\" +
"t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(" +
"?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\" +
"n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\" +
"t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:" +
"\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:" +
"[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"" +
"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t" +
"])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:" +
"(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\" +
"\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;" +
":\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\" +
"\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:" +
"(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ " +
"\\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?" +
":(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\" +
"000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(" +
"?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(" +
"?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[" +
" \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\" +
"r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\" +
"\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\" +
"[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)" +
"?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?" +
"=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\" +
"t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)");
protected static final ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() {
@Override
protected StringBuilder initialValue() {
return new StringBuilder();
}
@Override
public StringBuilder get() {
StringBuilder b = super.get();
b.setLength(0);
return b;
}
};
protected DAO userDAO_;
protected DAO groupDAO_;
protected Map challengeMap;
public static final String HASH_METHOD = "SHA-512";
@Override
public void start() {
userDAO_ = (DAO) getX().get("localUserDAO");
groupDAO_ = (DAO) getX().get("groupDAO");
challengeMap = new LRULinkedHashMap<Long, Challenge>(20000);
}
/**
* A challenge is generated from the userID provided
* This is saved in a LinkedHashMap with ttl of 5
*/
public String generateChallenge(long userId) throws AuthenticationException {
if ( userId < 1 ) {
throw new AuthenticationException("Invalid User Id");
}
if ( userDAO_.find(userId) == null ) {
throw new AuthenticationException("User not found");
}
String generatedChallenge = UUID.randomUUID() + String.valueOf(userId);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 5);
challengeMap.put(userId, new Challenge(generatedChallenge, calendar.getTime()));
return generatedChallenge;
}
/**
* Checks the LinkedHashMap to see if the the challenge supplied is correct
* and the ttl is still valid
*
* How often should we purge this map for challenges that have expired?
*/
public X challengedLogin(long userId, String challenge) throws AuthenticationException {
if ( userId < 1 || "".equals(challenge) ) {
throw new AuthenticationException("Invalid Parameters");
}
Challenge c = (Challenge) challengeMap.get(userId);
if ( c == null ) throw new AuthenticationException("Invalid userId");
if ( ! c.getChallenge().equals(challenge) ) {
throw new AuthenticationException("Invalid Challenge");
}
if ( new Date().after(c.getTtl()) ) {
challengeMap.remove(userId);
throw new AuthenticationException("Challenge expired");
}
User user = (User) userDAO_.find(userId);
if ( user == null ) throw new AuthenticationException("User not found");
challengeMap.remove(userId);
return this.getX().put("user", user);
}
/**
* Login a user by the id provided, validate the password
* and return the user in the context.
*/
public X login(long userId, String password) throws AuthenticationException {
if ( userId < 1 || "".equals(password) ) {
throw new AuthenticationException("Invalid Parameters");
}
User user = (User) userDAO_.find(userId);
if ( user == null ) {
throw new AuthenticationException("User not found.");
}
String hashedPassword;
String storedPassword;
String salt;
try {
String[] split = user.getPassword().split(":");
salt = split[1];
storedPassword = split[0];
hashedPassword = hashPassword(password, salt);
} catch (Throwable e) {
throw new AuthenticationException("Invalid Password");
}
if ( ! hashedPassword.equals(storedPassword) ) {
throw new AuthenticationException("Invalid Password");
}
return getX().put("user", user);
}
public X loginByEmail(String email, String password) throws AuthenticationException {
if ( "".equals(email) || "".equals(password) ) {
throw new AuthenticationException("Invalid Parameters");
}
Sink sink = new ListSink();
sink = userDAO_.where(MLang.EQ(User.EMAIL, email)).limit(1).select(sink);
List data = ((ListSink) sink).getData();
if ( data == null || data.size() != 1 ) {
throw new AuthenticationException("User not found");
}
User user = (User) data.get(0);
String salt;
String hashedPassword;
String storedPassword;
try {
String[] split = user.getPassword().split(":");
salt = split[1];
storedPassword = split[0];
hashedPassword = hashPassword(password, salt);
} catch (Throwable t) {
throw new AuthenticationException("Invalid password");
}
if ( ! hashedPassword.equals(storedPassword) ) {
throw new AuthenticationException("Invalid password");
}
return getX().put("user", user);
}
public Boolean check(foam.core.X x, java.security.Permission permission) {
if ( x == null || permission == null ) return false;
User user = (User) x.get("user");
if ( user == null ) return false;
Group group = (Group) user.getGroup();
if ( group == null ) return false;
if ( userDAO_.find_(x, user.getId()) == null ) {
return false;
}
return group.implies(permission);
}
/**
* Given a context with a user, validate the password to be updated
* and return a context with the updated user information
*/
public X updatePassword(foam.core.X x, String oldPassword, String newPassword)
throws AuthenticationException {
if ( x == null || "".equals(oldPassword) || "".equals(newPassword) ) {
throw new AuthenticationException("Invalid Parameters");
}
User user = (User) userDAO_.find_(x, ((User) x.get("user")).getId());
if ( user == null ) {
throw new AuthenticationException("User not found");
}
String password = user.getPassword();
String storedPassword = password.split(":")[0];
String oldSalt = password.split(":")[1];
String hashedOldPassword;
String hashedNewPasswordOldSalt;
String hashedNewPassword;
String newSalt = generateRandomSalt();
try {
hashedOldPassword = hashPassword(oldPassword, oldSalt);
hashedNewPasswordOldSalt = hashPassword(newPassword, oldSalt);
hashedNewPassword = hashPassword(newPassword, newSalt);
} catch (NoSuchAlgorithmException e) {
throw new AuthenticationException("Invalid Password");
}
if ( ! hashedOldPassword.equals(storedPassword) ) {
throw new AuthenticationException("Invalid Password");
}
if ( hashedOldPassword.equals(hashedNewPasswordOldSalt) ) {
throw new AuthenticationException("New Password must be different");
}
user.setPassword(hashedNewPassword + ":" + newSalt);
user = userDAO_.put(user);
return this.getX().put("user", user);
}
/**
* Used to validate properties of a user. This will be called on registration of users
* Will mainly be used as a veto method.
* Users should have id, email, first name, last name, password for registration
*/
public void validateUser(User user) throws AuthenticationException {
if ( user == null ) {
throw new AuthenticationException("Invalid User");
}
if ( "".equals(user.getEmail()) ) {
throw new AuthenticationException("Email is required for creating a user");
}
if ( ! emailPattern.matcher(user.getEmail()).matches() ) {
throw new AuthenticationException("Email format is invalid");
}
if ( "".equals(user.getFirstName()) ) {
throw new AuthenticationException("First Name is required for creating a user");
}
if ( "".equals(user.getLastName()) ) {
throw new AuthenticationException("Last Name is required for creating a user");
}
if ( "".equals(user.getPassword()) ) {
throw new AuthenticationException("Password is required for creating a user");
}
if ( ! validatePassword(user.getPassword()) ) {
throw new AuthenticationException("Password needs to minimum 8 characters, contain at least one uppercase, one lowercase and a number");
}
}
public static String hashPassword(String password, String salt) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance(HASH_METHOD);
messageDigest.update(salt.getBytes());
byte[] hashedBytes = messageDigest.digest(password.getBytes());
StringBuilder hashedPasswordBuilder = new StringBuilder();
for( byte b : hashedBytes ) {
hashedPasswordBuilder.append(String.format("%02x", b & 0xFF));
}
return hashedPasswordBuilder.toString();
}
public static String generateRandomSalt() {
SecureRandom secureRandom = new SecureRandom();
byte bytes[] = new byte[20];
secureRandom.nextBytes(bytes);
StringBuilder saltBuilder = sb.get();
for ( byte b : bytes ) {
saltBuilder.append(String.format("%02x", b & 0xFF));
}
return saltBuilder.toString();
}
//Min 8 characters, at least one uppercase, one lowercase, one number
public static boolean validatePassword(String password) {
Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$");
return pattern.matcher(password).matches();
}
/**
* Just return a null user for now. Not sure how to handle the cleanup
* of the current context
*/
public void logout(X x) {}
} |
package trikita.router;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Pair;
import android.util.Property;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import java.lang.reflect.InvocationTargetException;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.WeakHashMap;
public class ViewRouter {
private final static String tag = "ViewRouter";
public final static int NO_HISTORY = 1;
// Bundle keys
final static String KEY_CLASSNAME = "className";
final static String KEY_STATE = "state";
final static String KEY_BACKSTACK = "backstack";
private static final Map<Activity, WeakReference<ViewRouter>> CACHE = new WeakHashMap<>();
private ViewGroup mParent;
private ArrayList<String> mBackstack = new ArrayList<>();
private List<Pair<String, Class<? extends View>>> mRouting =
new ArrayList<>();
public ViewRouter(ViewGroup parent) {
mParent = parent;
}
public ViewRouter(Activity a) {
CACHE.put(a, new WeakReference<>(this));
mParent = new FrameLayout(a);
a.setContentView(mParent);
}
public static ViewRouter get(View v) {
WeakReference<ViewRouter> ref = CACHE.get(v.getContext());
return (ref != null ? ref.get() : null);
}
// TODO validate uri, throw RuntimeException if it's invalid
public ViewRouter add(String uri, Class<? extends View> a) {
mRouting.add(new Pair(uri, a));
return this;
}
public boolean route(String uri) {
return route(uri, 0);
}
public boolean route(String uri, int flags) {
Map<String, String> properties = new HashMap<String, String>();
for (Pair<String, Class<? extends View>> entry : mRouting) {
properties.clear();
if (Utils.matchUri(uri, entry.first, properties)) {
View v = createView(entry.second, properties);
if ((flags & NO_HISTORY) == 0) {
mBackstack.add(uri);
}
// navigate to the matched view
mParent.removeAllViews();
mParent.addView(v);
return true;
}
}
return false;
}
public void save(Bundle b) {
b.putStringArrayList(KEY_BACKSTACK, mBackstack);
}
public void load(Bundle b) {
for (String uri : b.getStringArrayList(KEY_BACKSTACK)) {
route(uri);
}
}
public boolean back() {
if (mBackstack.size() > 1) {
mBackstack.remove(mBackstack.size() - 1);
if (mBackstack.size() > 0) {
route(mBackstack.get(mBackstack.size() - 1), NO_HISTORY);
return true;
}
}
return false;
}
private <T extends View> T createView(Class<T> cls, Map<String, String> props) {
try {
T v = cls.getConstructor(Context.class, AttributeSet.class)
.newInstance(mParent.getContext(), null);
// copy parsed uri params into the view properties
for (Map.Entry<String, String> p : props.entrySet()) {
Property<T, String> property = Property.of(cls, String.class, p.getKey());
property.set(v, p.getValue());
}
return v;
} catch (NoSuchMethodException|InstantiationException|
IllegalAccessException|InvocationTargetException e) {
throw new RuntimeException(e);
}
}
} |
package foam.nanos.auth;
import foam.core.ContextAwareSupport;
import foam.core.X;
import foam.dao.DAO;
import foam.dao.ArraySink;
import foam.dao.Sink;
import foam.mlang.MLang;
import foam.nanos.NanoService;
import foam.nanos.session.Session;
import foam.util.Email;
import foam.util.LRULinkedHashMap;
import foam.util.Password;
import foam.util.SafetyUtil;
import java.security.Permission;
import java.util.*;
import javax.naming.AuthenticationException;
import javax.security.auth.AuthPermission;
public class UserAndGroupAuthService
extends ContextAwareSupport
implements AuthService, NanoService
{
protected DAO userDAO_;
protected DAO groupDAO_;
protected DAO sessionDAO_;
// pattern used to check if password has only alphanumeric characters
java.util.regex.Pattern alphanumeric = java.util.regex.Pattern.compile("[^a-zA-Z0-9]");
public UserAndGroupAuthService(X x) {
setX(x);
}
@Override
public void start() {
userDAO_ = (DAO) getX().get("localUserDAO");
groupDAO_ = (DAO) getX().get("groupDAO");
sessionDAO_ = (DAO) getX().get("sessionDAO");
}
public User getCurrentUser(X x) throws AuthenticationException {
// fetch context and check if not null or user id is 0
Session session = x.get(Session.class);
if ( session == null || session.getUserId() == 0 ) {
throw new AuthenticationException("Not logged in");
}
// get user from session id
User user = (User) userDAO_.find(session.getUserId());
if ( user == null ) {
throw new AuthenticationException("User not found: " + session.getUserId());
}
if ( ! user.getEnabled() ) {
throw new AuthenticationException("User disabled");
}
return user;
}
/**
* A challenge is generated from the userID provided
* This is saved in a LinkedHashMap with ttl of 5
*/
public String generateChallenge(long userId) throws AuthenticationException {
throw new UnsupportedOperationException("Unsupported operation: generateChallenge");
}
/**
* Checks the LinkedHashMap to see if the the challenge supplied is correct
* and the ttl is still valid
*
* How often should we purge this map for challenges that have expired?
*/
public User challengedLogin(X x, long userId, String challenge) throws AuthenticationException {
throw new UnsupportedOperationException("Unsupported operation: challengedLogin");
}
/**
* Login a user by the id provided, validate the password
* and return the user in the context.
*/
public User login(X x, long userId, String password) throws AuthenticationException {
if ( userId < 1 || SafetyUtil.isEmpty(password) ) {
throw new AuthenticationException("Invalid Parameters");
}
User user = (User) userDAO_.find(userId);
if ( user == null ) {
throw new AuthenticationException("User not found.");
}
if ( ! user.getEnabled() ) {
throw new AuthenticationException("User disabled");
}
if ( ! Password.verify(password, user.getPassword()) ) {
throw new AuthenticationException("Invalid Password");
}
Session session = x.get(Session.class);
session.setUserId(user.getId());
session.setContext(session.getContext().put("user", user));
sessionDAO_.put(session);
return user;
}
public User loginByEmail(X x, String email, String password) throws AuthenticationException {
Sink sink = new ArraySink();
sink = userDAO_.where(MLang.EQ(User.EMAIL, email.toLowerCase())).limit(1).select(sink);
List data = ((ArraySink) sink).getArray();
if ( data == null || data.size() != 1 ) {
throw new AuthenticationException("User not found");
}
User user = (User) data.get(0);
if ( user == null ) {
throw new AuthenticationException("User not found");
}
if ( ! user.getEnabled() ) {
throw new AuthenticationException("User disabled");
}
if ( ! Password.verify(password, user.getPassword()) ) {
throw new AuthenticationException("Incorrect password");
}
Session session = x.get(Session.class);
session.setUserId(user.getId());
session.setContext(session.getContext().put("user", user));
sessionDAO_.put(session);
return user;
}
public Boolean checkPermission(foam.core.X x, Permission permission) {
if ( x == null || permission == null ) {
return false;
}
Session session = x.get(Session.class);
if ( session == null || session.getUserId() == 0 ) {
return false;
}
User user = (User) userDAO_.find(session.getUserId());
if ( user == null || ! user.getEnabled() ) {
return false;
}
try {
String groupId = (String) user.getGroup();
while ( ! SafetyUtil.isEmpty(groupId) ) {
Group group = (Group) groupDAO_.find(groupId);
if ( group == null ) break;
if ( group.implies(permission) ) return true;
groupId = group.getParent();
}
} catch (Throwable t) {
}
return false;
}
public Boolean check(foam.core.X x, String permission) {
return checkPermission(x, new AuthPermission(permission));
}
/**
* Given a context with a user, validate the password to be updated
* and return a context with the updated user information
*/
public User updatePassword(foam.core.X x, String oldPassword, String newPassword) throws AuthenticationException {
if ( x == null || SafetyUtil.isEmpty(oldPassword) || SafetyUtil.isEmpty(newPassword) ) {
throw new RuntimeException("Invalid parameters");
}
Session session = x.get(Session.class);
if ( session == null || session.getUserId() == 0 ) {
throw new AuthenticationException("User not found");
}
User user = (User) userDAO_.find(session.getUserId());
if ( user == null ) {
throw new AuthenticationException("User not found");
}
if ( ! user.getEnabled() ) {
throw new AuthenticationException("User disabled");
}
int length = newPassword.length();
if ( length < 7 || length > 32 ) {
throw new RuntimeException("Password must be 7-32 characters long");
}
if ( newPassword.equals(newPassword.toLowerCase()) ) {
throw new RuntimeException("Password must have one capital letter");
}
if ( ! newPassword.matches(".*\\d+.*") ) {
throw new RuntimeException("Password must have one numeric character");
}
if ( alphanumeric.matcher(newPassword).matches() ) {
throw new RuntimeException("Password must not contain: !@
}
// old password does not match
if ( ! Password.verify(oldPassword, user.getPassword()) ) {
throw new RuntimeException("Old password is incorrect");
}
// new password is the same
if ( Password.verify(newPassword, user.getPassword()) ) {
throw new RuntimeException("New password must be different");
}
// store new password in DAO and put in context
user = (User) user.fclone();
user.setPasswordLastModified(Calendar.getInstance().getTime());
user.setPreviousPassword(user.getPassword());
user.setPassword(Password.hash(newPassword));
// TODO: modify line to allow actual setting of password expiry in cases where users are required to periodically update their passwords
user.setPasswordExpiry(null);
user = (User) userDAO_.put(user);
session.setContext(session.getContext().put("user", user));
return user;
}
/**
* Used to validate properties of a user. This will be called on registration of users
* Will mainly be used as a veto method.
* Users should have id, email, first name, last name, password for registration
*/
public void validateUser(X x, User user) throws AuthenticationException {
if ( user == null ) {
throw new AuthenticationException("Invalid User");
}
if ( SafetyUtil.isEmpty(user.getEmail()) ) {
throw new AuthenticationException("Email is required for creating a user");
}
if ( ! Email.isValid(user.getEmail()) ) {
throw new AuthenticationException("Email format is invalid");
}
if ( SafetyUtil.isEmpty(user.getFirstName()) ) {
throw new AuthenticationException("First Name is required for creating a user");
}
if ( SafetyUtil.isEmpty(user.getLastName()) ) {
throw new AuthenticationException("Last Name is required for creating a user");
}
if ( SafetyUtil.isEmpty(user.getPassword()) ) {
throw new AuthenticationException("Password is required for creating a user");
}
if ( ! Password.isValid(user.getPassword()) ) {
throw new AuthenticationException("Password needs to minimum 8 characters, contain at least one uppercase, one lowercase and a number");
}
}
/**
* Just return a null user for now. Not sure how to handle the cleanup
* of the current context
*/
public void logout(X x) {
Session session = x.get(Session.class);
if ( session != null && session.getUserId() != 0 ) {
sessionDAO_.remove(session);
}
}
} |
package gov.nih.nci.cananolab.ui.core;
import gov.nih.nci.cananolab.dto.common.GridNodeBean;
import gov.nih.nci.cananolab.dto.particle.composition.CompositionBean;
import gov.nih.nci.cananolab.exception.BaseException;
import gov.nih.nci.cananolab.exception.GridDownException;
import gov.nih.nci.cananolab.service.common.GridService;
import gov.nih.nci.cananolab.service.common.LookupService;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.cananolab.util.Comparators;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.DateUtils;
import gov.nih.nci.cananolab.util.StringUtils;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.upload.FormFile;
import org.apache.struts.util.LabelValueBean;
/**
* This class sets up information required for all forms.
*
* @author pansu, cais
*
*/
public class InitSetup {
private InitSetup() {
}
public static InitSetup getInstance() {
return new InitSetup();
}
/**
* Queries and common_lookup table and creates a map in application context
*
* @param appContext
* @return
* @throws BaseException
*/
public Map<String, Map<String, SortedSet<String>>> getDefaultLookupTable(
ServletContext appContext) throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = null;
if (appContext.getAttribute("defaultLookupTable") == null) {
defaultLookupTable = LookupService.findAllLookups();
appContext.setAttribute("defaultLookupTable", defaultLookupTable);
} else {
defaultLookupTable = new HashMap<String, Map<String, SortedSet<String>>>(
(Map<? extends String, Map<String, SortedSet<String>>>) appContext
.getAttribute("defaultLookupTable"));
}
return defaultLookupTable;
}
/**
* Retrieve lookup attribute for lookup name from the database and store in
* the application context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param lookupAttribute
* @return
* @throws BaseException
*/
public SortedSet<String> getServletContextDefaultLookupTypes(
ServletContext appContext, String contextAttribute,
String lookupName, String lookupAttribute) throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(appContext);
SortedSet<String> types = defaultLookupTable.get(lookupName).get(
lookupAttribute);
appContext.setAttribute(contextAttribute, types);
return types;
}
/**
* Retrieve lookup attribute and other attribute for lookup name from the
* database and store in the session
*
* @param request
* @param sessionAttribute
* @param lookupName
* @param lookupAttribute
* @param otherTypeAttribute
* @aparam updateSession
* @return
* @throws BaseException
*/
public SortedSet<String> getDefaultAndOtherLookupTypes(
HttpServletRequest request, String sessionAttribute,
String lookupName, String lookupAttribute,
String otherTypeAttribute, boolean updateSession)
throws BaseException {
SortedSet<String> types = null;
if (updateSession) {
types = LookupService.getDefaultAndOtherLookupTypes(lookupName,
lookupAttribute, otherTypeAttribute);
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
public SortedSet<String> getReflectionDefaultAndOtherLookupTypes(
HttpServletRequest request, String contextAttributeForDefaults,
String sessionAttribute, String fullParentClassName,
String otherFullParentClassName, boolean updateSession)
throws Exception {
ServletContext appContext = request.getSession().getServletContext();
SortedSet<String> defaultTypes = getServletContextDefaultTypesByReflection(
appContext, contextAttributeForDefaults, fullParentClassName);
SortedSet<String> types = null;
if (updateSession) {
types = new TreeSet<String>(defaultTypes);
SortedSet<String> otherTypes = LookupService
.getAllOtherObjectTypes(otherFullParentClassName);
if (otherTypes != null)
types.addAll(otherTypes);
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
/**
* Retrieve lookup attribute and other attribute for lookup name based on
* reflection and store in the application context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param fullParentClassName
* @return
* @throws Exception
*/
public SortedSet<String> getServletContextDefaultTypesByReflection(
ServletContext appContext, String contextAttribute,
String fullParentClassName) throws Exception {
if (appContext.getAttribute(contextAttribute) == null) {
SortedSet<String> types = new TreeSet<String>();
List<String> classNames = ClassUtils
.getChildClassNames(fullParentClassName);
for (String name : classNames) {
if (!name.contains("Other")) {
String shortClassName = ClassUtils.getShortClassName(name);
String displayName = ClassUtils
.getDisplayName(shortClassName);
types.add(displayName);
}
}
appContext.setAttribute(contextAttribute, types);
return types;
} else {
return new TreeSet<String>((SortedSet<? extends String>) appContext
.getAttribute(contextAttribute));
}
}
public String getFileUriFromFormFile(FormFile file, String folderType,
String sampleName, String submitType) {
if (file != null && !StringUtils.isEmpty(file.getFileName())) {
String prefix = folderType;
if (!StringUtils.isEmpty(sampleName)
&& !StringUtils.isEmpty(submitType)
&& folderType.equals(Constants.FOLDER_PARTICLE)) {
prefix += "/" + sampleName + "/";
prefix += StringUtils
.getOneWordLowerCaseFirstLetter(submitType);
}
String timestamp = DateUtils.convertDateToString(new Date(),
"yyyyMMdd_HH-mm-ss-SSS");
return prefix + "/" + timestamp + "_" + file.getFileName();
} else {
return null;
}
}
// check whether the value is already stored in context
private Boolean isLookupInContext(HttpServletRequest request,
String lookupName, String attribute, String otherAttribute,
String value) throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(request
.getSession().getServletContext());
SortedSet<String> defaultValues = null;
if (defaultLookupTable.get(lookupName) != null) {
defaultValues = defaultLookupTable.get(lookupName).get(attribute);
}
if (defaultValues != null && defaultValues.contains(value)) {
return true;
} else {
SortedSet<String> otherValues = null;
if (defaultLookupTable.get(lookupName) != null) {
otherValues = defaultLookupTable.get(lookupName).get(
otherAttribute);
}
if (otherValues != null && otherValues.contains(value)) {
return true;
}
}
return false;
}
public void persistLookup(HttpServletRequest request, String lookupName,
String attribute, String otherAttribute, String value)
throws BaseException {
if (value == null || value.length() == 0) {
return;
}
if (isLookupInContext(request, lookupName, attribute, otherAttribute,
value)) {
return;
} else {
LookupService.saveOtherType(lookupName, otherAttribute, value);
}
}
public String getGridServiceUrl(HttpServletRequest request,
String gridHostName) throws Exception {
List<GridNodeBean> remoteNodes = getGridNodesInContext(request);
GridNodeBean theNode = GridService.getGridNodeByHostName(remoteNodes,
gridHostName);
if (theNode == null) {
throw new GridDownException("Grid node " + gridHostName
+ " is not available at this time.");
}
return theNode.getAddress();
}
public List<GridNodeBean> getGridNodesInContext(HttpServletRequest request)
throws Exception {
URL localURL = new URL(request.getRequestURL().toString());
int port = (localURL.getPort() == -1) ? 80 : localURL.getPort();
String localGridURL = localURL.getProtocol() + ":
+ localURL.getHost() + ":" + port + "/"
+ Constants.GRID_SERVICE_PATH;
GridDiscoveryServiceJob gridDiscoveryJob = new GridDiscoveryServiceJob();
List<GridNodeBean> gridNodes = gridDiscoveryJob.getAllGridNodes();
GridNodeBean localGrid = GridService.getGridNodeByURL(gridNodes,
localGridURL);
// don't remove from original list
List<GridNodeBean> remoteNodes = new ArrayList<GridNodeBean>();
remoteNodes.addAll(gridNodes);
if (localGrid != null) {
remoteNodes.remove(localGrid);
}
Collections.sort(remoteNodes,
new Comparators.GridNodeHostNameComparator());
request.getSession().getServletContext().setAttribute("allGridNodes",
remoteNodes);
return gridNodes;
}
public List<LabelValueBean> getLookupValuesAsOptions(String lookupName,
String lookupAttribute, String otherTypeAttribute) throws Exception {
List<LabelValueBean> lvBeans = new ArrayList<LabelValueBean>();
SortedSet<String> defaultValues = LookupService.findLookupValues(
lookupName, lookupAttribute);
// annotate the label of the default ones with *s.
for (String name : defaultValues) {
LabelValueBean lv = new LabelValueBean(name, name);
lvBeans.add(lv);
}
SortedSet<String> otherValues = LookupService.findLookupValues(
lookupName, otherTypeAttribute);
for (String name : otherValues) {
LabelValueBean lv = new LabelValueBean("[" + name + "]", name);
lvBeans.add(lv);
}
return lvBeans;
}
public List<LabelValueBean> getReflectionDefaultAndOtherLookupTypesAsOptions(
ServletContext appContext, String contextAttributeForDefaults,
String fullParentClassName, String otherFullParentClassName)
throws Exception {
List<LabelValueBean> lvBeans = new ArrayList<LabelValueBean>();
SortedSet<String> defaultTypes = getServletContextDefaultTypesByReflection(
appContext, contextAttributeForDefaults, fullParentClassName);
for (String type : defaultTypes) {
LabelValueBean lv = new LabelValueBean(type, type);
lvBeans.add(lv);
}
SortedSet<String> otherTypes = LookupService
.getAllOtherObjectTypes(otherFullParentClassName);
if (otherTypes != null) {
for (String type : otherTypes) {
LabelValueBean lv = new LabelValueBean("[" + type + "]", type);
lvBeans.add(lv);
}
}
return lvBeans;
}
public void setStaticOptions(ServletContext appContext) {
LabelValueBean[] booleanOptions = new LabelValueBean[] {
new LabelValueBean("true", "1"),
new LabelValueBean("false", "0") };
appContext.setAttribute("booleanOptions", booleanOptions);
LabelValueBean[] stringOperands = new LabelValueBean[] {
new LabelValueBean("equals to", "equals"),
new LabelValueBean("contains", "contains") };
appContext.setAttribute("stringOperands", stringOperands);
LabelValueBean[] booleanOperands = new LabelValueBean[] { new LabelValueBean(
"equals to", "is") };
appContext.setAttribute("booleanOperands", booleanOperands);
LabelValueBean[] numberOperands = new LabelValueBean[] {
new LabelValueBean("=", "="), new LabelValueBean(">", ">"),
new LabelValueBean(">=", ">="), new LabelValueBean("<", "<"),
new LabelValueBean("<=", "<=") };
appContext.setAttribute("numberOperands", numberOperands);
appContext.setAttribute("allCompositionSections",
CompositionBean.ALL_COMPOSITION_SECTIONS);
}
} |
package cgeo.geocaching.export;
import cgeo.geocaching.DataStore;
import cgeo.geocaching.Geocache;
import cgeo.geocaching.LogEntry;
import cgeo.geocaching.R;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.connector.gc.GCLogin;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.network.Parameters;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.Formatter;
import cgeo.geocaching.utils.AsyncTaskWithProgress;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.SynchronizedDateFormat;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.CheckBox;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
/**
* Exports offline logs in the Groundspeak Field Note format.<br>
* <br>
*
* Field Notes are simple plain text files, but poorly documented. Syntax:<br>
* <code>GCxxxxx,yyyy-mm-ddThh:mm:ssZ,Found it,"logtext"</code>
*/
class FieldnoteExport extends AbstractExport {
private static final File exportLocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/field-notes");
private static final SynchronizedDateFormat fieldNoteDateFormat = new SynchronizedDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone("UTC"), Locale.US);
private static int fieldNotesCount = 0;
protected FieldnoteExport() {
super(getString(R.string.export_fieldnotes));
}
@Override
public void export(final List<Geocache> cachesList, final Activity activity) {
final Geocache[] caches = cachesList.toArray(new Geocache[cachesList.size()]);
if (null == activity) {
// No activity given, so no user interaction possible.
// Start export with default parameters.
new ExportTask(null, false, false).execute(caches);
} else {
// Show configuration dialog
getExportOptionsDialog(caches, activity).show();
}
}
private Dialog getExportOptionsDialog(final Geocache[] caches, final Activity activity) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// AlertDialog has always dark style, so we have to apply it as well always
final View layout = View.inflate(new ContextThemeWrapper(activity, R.style.dark), R.layout.fieldnote_export_dialog, null);
builder.setView(layout);
final CheckBox uploadOption = (CheckBox) layout.findViewById(R.id.upload);
uploadOption.setChecked(Settings.getFieldNoteExportUpload());
final CheckBox onlyNewOption = (CheckBox) layout.findViewById(R.id.onlynew);
onlyNewOption.setChecked(Settings.getFieldNoteExportOnlyNew());
if (Settings.getFieldnoteExportDate() > 0) {
onlyNewOption.setText(getString(R.string.export_fieldnotes_onlynew) + " (" + Formatter.formatDateTime(Settings.getFieldnoteExportDate()) + ')');
}
builder.setPositiveButton(R.string.export, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
final boolean upload = uploadOption.isChecked();
final boolean onlyNew = onlyNewOption.isChecked();
Settings.setFieldNoteExportUpload(upload);
Settings.setFieldNoteExportOnlyNew(onlyNew);
dialog.dismiss();
new ExportTask(activity, upload, onlyNew).execute(caches);
}
});
return builder.create();
}
private class ExportTask extends AsyncTaskWithProgress<Geocache, Boolean> {
private final Activity activity;
private final boolean upload;
private final boolean onlyNew;
private File exportFile;
private static final int STATUS_UPLOAD = -1;
/**
* Instantiates and configures the task for exporting field notes.
*
* @param activity
* optional: Show a progress bar and toasts
* @param upload
* Upload the Field Note to geocaching.com
* @param onlyNew
* Upload/export only new logs since last export
*/
public ExportTask(final Activity activity, final boolean upload, final boolean onlyNew) {
super(activity, getProgressTitle(), getString(R.string.export_fieldnotes_creating), true);
this.activity = activity;
this.upload = upload;
this.onlyNew = onlyNew;
}
@Override
protected Boolean doInBackgroundInternal(final Geocache[] caches) {
final StringBuilder fieldNoteBuffer = new StringBuilder();
try {
int i = 0;
for (final Geocache cache : caches) {
if (cache.isLogOffline()) {
final LogEntry log = DataStore.loadLogOffline(cache.getGeocode());
if (!onlyNew || log.date > Settings.getFieldnoteExportDate()) {
appendFieldNote(fieldNoteBuffer, cache, log);
}
}
publishProgress(++i);
}
} catch (final Exception e) {
Log.e("FieldnoteExport.ExportTask generation", e);
return false;
}
fieldNoteBuffer.append('\n');
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return false;
}
FileUtils.mkdirs(exportLocation);
final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
exportFile = new File(exportLocation.toString() + '/' + fileNameDateFormat.format(new Date()) + ".txt");
Writer fileWriter = null;
BufferedOutputStream buffer = null;
try {
final OutputStream os = new FileOutputStream(exportFile);
buffer = new BufferedOutputStream(os);
fileWriter = new OutputStreamWriter(buffer, CharEncoding.UTF_16);
fileWriter.write(fieldNoteBuffer.toString());
} catch (final IOException e) {
Log.e("FieldnoteExport.ExportTask export", e);
return false;
} finally {
IOUtils.closeQuietly(fileWriter);
IOUtils.closeQuietly(buffer);
}
if (upload) {
publishProgress(STATUS_UPLOAD);
if (!GCLogin.getInstance().isActualLoginStatus()) {
// no need to upload (possibly large file) if we're not logged in
final StatusCode loginState = GCLogin.getInstance().login();
if (loginState != StatusCode.NO_ERROR) {
Log.e("FieldnoteExport.ExportTask upload: Login failed");
}
}
final String uri = "http:
final String page = GCLogin.getInstance().getRequestLogged(uri, null);
if (StringUtils.isBlank(page)) {
Log.e("FieldnoteExport.ExportTask get page: No data from server");
return false;
}
final String[] viewstates = GCLogin.getViewstates(page);
final Parameters uploadParams = new Parameters(
"__EVENTTARGET", "",
"__EVENTARGUMENT", "",
"ctl00$ContentBody$btnUpload", "Upload Field Note");
GCLogin.putViewstates(uploadParams, viewstates);
Network.getResponseData(Network.postRequest(uri, uploadParams, "ctl00$ContentBody$FieldNoteLoader", "text/plain", exportFile));
if (StringUtils.isBlank(page)) {
Log.e("FieldnoteExport.ExportTask upload: No data from server");
return false;
}
}
return true;
}
@Override
protected void onPostExecuteInternal(final Boolean result) {
if (null != activity) {
if (result) {
Settings.setFieldnoteExportDate(System.currentTimeMillis());
ActivityMixin.showToast(activity, getName() + ' ' + getString(R.string.export_exportedto) + ": " + exportFile.toString());
if (upload) {
ActivityMixin.showToast(activity, getString(R.string.export_fieldnotes_upload_success));
}
} else {
ActivityMixin.showToast(activity, getString(R.string.export_failed));
}
}
}
@Override
protected void onProgressUpdateInternal(final int status) {
if (null != activity) {
setMessage(getString(STATUS_UPLOAD == status ? R.string.export_fieldnotes_uploading : R.string.export_fieldnotes_creating) + " (" + fieldNotesCount + ')');
}
}
}
static void appendFieldNote(final StringBuilder fieldNoteBuffer, final Geocache cache, final LogEntry log) {
fieldNotesCount++;
fieldNoteBuffer.append(cache.getGeocode())
.append(',')
.append(fieldNoteDateFormat.format(new Date(log.date)))
.append(',')
.append(StringUtils.capitalize(log.type.type))
.append(",\"")
.append(StringUtils.replaceChars(log.log, '"', '\''))
.append("\"\n");
}
} |
package mockit.internal.core;
import java.lang.reflect.*;
import static mockit.external.asm.Opcodes.*;
import mockit.external.asm.*;
import mockit.external.asm.Type;
import mockit.internal.*;
import mockit.internal.startup.*;
import mockit.internal.state.*;
import mockit.internal.util.*;
/**
* Responsible for generating all necessary bytecode in the redefined (real) class. Such code will
* redirect calls made on "real" methods to equivalent calls on the corresponding "mock" methods.
* The original code won't be executed by the running JVM until the class redefinition is undone.
* <p/>
* Methods in the real class which have no corresponding mock method are unaffected.
* <p/>
* Any fields (static or not) in the real class remain untouched.
*/
public class RealClassModifier extends BaseClassModifier
{
private final String itFieldDesc;
private final MockMethods mockMethods;
private final int mockInstanceIndex;
private final boolean forStartupMock;
// Helper fields:
private String realSuperClassName;
protected String mockName;
private boolean mockIsStatic;
protected int varIndex;
public RealClassModifier(
ClassReader cr, Class<?> realClass, Object mock, MockMethods mockMethods,
boolean forStartupMock)
{
this(cr, getItFieldDescriptor(realClass), mock, mockMethods, forStartupMock);
setUseMockingBridge(realClass.getClassLoader());
}
protected static String getItFieldDescriptor(Class<?> realClass)
{
if (Proxy.isProxyClass(realClass)) {
//noinspection AssignmentToMethodParameter
realClass = realClass.getInterfaces()[0];
}
return Type.getDescriptor(realClass);
}
public RealClassModifier(
ClassReader cr, String realClassDesc, Object mock, MockMethods mockMethods,
boolean forStartupMock)
{
super(cr);
itFieldDesc = realClassDesc;
this.mockMethods = mockMethods;
this.forStartupMock = forStartupMock;
if (mock != null) {
mockInstanceIndex = TestRun.getMockClasses().getMocks(forStartupMock).addMock(mock);
}
else if (!mockMethods.isInnerMockClass()) {
mockInstanceIndex = -1;
}
else {
throw new IllegalArgumentException(
"An inner mock class cannot be instantiated without its enclosing instance; " +
"you must either pass a mock instance, or make the class static");
}
}
@SuppressWarnings({"DesignForExtension"})
@Override
public void visit(
int version, int access, String name, String signature, String superName, String[] interfaces)
{
super.visit(version, access, name, signature, superName, interfaces);
realSuperClassName = superName;
}
/**
* If the specified method has a mock definition, then generates bytecode to redirect calls made
* to it to the mock method. If it has no mock, does nothing.
*
* @param access not relevant
* @param name together with desc, used to identity the method in given set of mock methods
* @param signature not relevant
* @param exceptions not relevant
*
* @return null if the method was redefined, otherwise a MethodWriter that writes out the visited
* method code without changes
*/
@Override
public final MethodVisitor visitMethod(
int access, String name, String desc, String signature, String[] exceptions)
{
if ((access & ACC_SYNTHETIC) != 0) {
return super.visitMethod(access, name, desc, signature, exceptions);
}
boolean hasMock = hasMock(name, desc) || hasMockWithAlternativeName(name, desc);
if (!hasMock) {
return
shouldCopyOriginalMethodBytecode(access, name, desc, signature, exceptions) ?
super.visitMethod(access, name, desc, signature, exceptions) : null;
}
if ((access & ACC_NATIVE) != 0 && !Startup.isJava6OrLater()) {
throw new IllegalArgumentException(
"Mocking of native methods not supported under JDK 1.5: \"" + name + '\"');
}
startModifiedMethodVersion(access, name, desc, signature, exceptions);
MethodVisitor alternativeWriter = getAlternativeMethodWriter(access, desc);
if (alternativeWriter == null) {
// Uses the MethodWriter just created to produce bytecode that calls the mock method.
generateCallsForMockExecution(access, desc);
generateMethodReturn(desc);
mw.visitMaxs(1, 0); // dummy values, real ones are calculated by ASM
// All desired bytecode is written at this point, so returns null in order to avoid
// appending the original method bytecode, which would happen if mv was returned.
return null;
}
return alternativeWriter;
}
@SuppressWarnings({"UnusedDeclaration", "DesignForExtension"})
protected boolean shouldCopyOriginalMethodBytecode(
int access, String name, String desc, String signature, String[] exceptions)
{
return true;
}
@SuppressWarnings({"UnusedDeclaration", "DesignForExtension"})
protected MethodVisitor getAlternativeMethodWriter(int access, String desc)
{
return null;
}
private boolean hasMock(String name, String desc)
{
mockName = name;
boolean hasMock = mockMethods.containsMethod(name, desc);
if (hasMock) {
mockIsStatic = mockMethods.containsStaticMethod(name, desc);
}
return hasMock;
}
private boolean hasMockWithAlternativeName(String name, String desc)
{
if ("<init>".equals(name)) {
return hasMock("$init", desc);
}
else if ("<clinit>".equals(name)) {
return hasMock("$clinit", desc);
}
return false;
}
protected final void generateCallsForMockExecution(int access, String desc)
{
if ("<init>".equals(mockName) || "$init".equals(mockName)) {
generateCallToSuper();
}
generateCallToMock(access, desc);
}
protected final void generateCallToSuper()
{
mw.visitVarInsn(ALOAD, 0);
String constructorDesc = new SuperConstructorCollector(1).findConstructor(realSuperClassName);
pushDefaultValuesForParameterTypes(constructorDesc);
mw.visitMethodInsn(INVOKESPECIAL, realSuperClassName, "<init>", constructorDesc);
}
@SuppressWarnings({"DesignForExtension"})
protected void generateCallToMock(int access, String desc)
{
if ("<init>".equals(mockName)) {
// Note: trying to call a constructor on a getMock(i) instance doesn't work (for reasons
// not clear), and it's also not possible to set the "it" field before calling the mock
// constructor; so, we do the only thing that can be done for mock constructors, which is
// to instantiate a new mock object and then call the mock constructor on it.
generateInstantiationAndConstructorCall(access, desc);
}
else if (mockIsStatic) {
generateStaticMethodCall(access, desc);
}
else {
generateInstanceMethodCall(access, desc);
}
}
private void generateInstantiationAndConstructorCall(int access, String desc)
{
if (useMockingBridge) {
generateCallToMockingBridge(
MockingBridge.CALL_CONSTRUCTOR_MOCK, getMockClassInternalName(), access, mockName, desc,
null);
return;
}
generateMockObjectInstantiation();
// Generate a call to the mock constructor, with the real constructor's arguments.
generateMethodOrConstructorArguments(desc, 1);
mw.visitMethodInsn(INVOKESPECIAL, getMockClassInternalName(), "<init>", desc);
mw.visitInsn(POP);
}
protected final String getMockClassInternalName()
{
return mockMethods.getMockClassInternalName();
}
private void generateMockObjectInstantiation()
{
mw.visitTypeInsn(NEW, getMockClassInternalName());
mw.visitInsn(DUP);
}
private void generateStaticMethodCall(int access, String desc)
{
String mockClassName = getMockClassInternalName();
if (useMockingBridge) {
generateCallToMockingBridge(
MockingBridge.CALL_STATIC_MOCK, mockClassName, access, mockName, desc, null);
}
else {
int initialVar = initialLocalVariableIndexForRealMethod(access);
generateMethodOrConstructorArguments(desc, initialVar);
mw.visitMethodInsn(INVOKESTATIC, mockClassName, mockName, desc);
}
}
protected final int initialLocalVariableIndexForRealMethod(int access)
{
return (access & ACC_STATIC) == 0 ? 1 : 0;
}
private void generateInstanceMethodCall(int access, String desc)
{
String mockClassName = getMockClassInternalName();
if (useMockingBridge) {
generateCallToMockingBridge(
MockingBridge.CALL_INSTANCE_MOCK, mockClassName, access, mockName, desc,
mockInstanceIndex);
return;
}
if (mockInstanceIndex < 0) {
// No mock instance available yet.
obtainMockInstanceForInvocation(access, mockClassName);
}
else {
// A mock instance is available, so retrieve it from the global list.
generateGetMockCallWithMockInstanceIndex();
}
if ((access & ACC_STATIC) == 0 && mockMethods.isWithItField()) {
generateItFieldSetting(desc);
}
generateMockInstanceMethodInvocationWithRealMethodArgs(access, desc);
}
@SuppressWarnings({"DesignForExtension"})
protected void obtainMockInstanceForInvocation(int access, String mockClassName)
{
generateMockObjectInstantiation();
mw.visitMethodInsn(INVOKESPECIAL, mockClassName, "<init>", "()V");
}
private void generateGetMockCallWithMockInstanceIndex()
{
mw.visitIntInsn(SIPUSH, mockInstanceIndex);
String methodName = forStartupMock ? "getStartupMock" : "getMock";
mw.visitMethodInsn(
INVOKESTATIC, "mockit/internal/state/TestRun", methodName, "(I)Ljava/lang/Object;");
mw.visitTypeInsn(CHECKCAST, getMockClassInternalName());
}
private void generateItFieldSetting(String methodDesc)
{
Type[] argTypes = Type.getArgumentTypes(methodDesc);
int var = 1;
for (Type argType : argTypes) {
var += argType.getSize();
}
mw.visitVarInsn(ASTORE, var); // stores the mock instance into local variable
mw.visitVarInsn(ALOAD, var); // loads the mock instance onto the operand stack
mw.visitVarInsn(ALOAD, 0); // loads "this" onto the operand stack
mw.visitFieldInsn(PUTFIELD, getMockClassInternalName(), "it", itFieldDesc);
mw.visitVarInsn(ALOAD, var); // again loads the mock instance onto the stack
}
private void generateMockInstanceMethodInvocationWithRealMethodArgs(int access, String desc)
{
int initialVar = initialLocalVariableIndexForRealMethod(access);
generateMethodOrConstructorArguments(desc, initialVar);
mw.visitMethodInsn(INVOKEVIRTUAL, getMockClassInternalName(), mockName, desc);
}
private void generateMethodOrConstructorArguments(String desc, int initialVar)
{
Type[] argTypes = Type.getArgumentTypes(desc);
varIndex = initialVar;
for (Type argType : argTypes) {
int opcode = argType.getOpcode(ILOAD);
mw.visitVarInsn(opcode, varIndex);
varIndex += argType.getSize();
}
}
protected final void generateMethodReturn(String desc)
{
if (useMockingBridge) {
generateReturnWithObjectAtTopOfTheStack(desc);
}
else {
Type returnType = Type.getReturnType(desc);
mw.visitInsn(returnType.getOpcode(IRETURN));
}
}
} |
package autenticacao;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/**
*
* A classe ainda nao esta autenticando apenas esta com um exemplo de como percorrer uma imagem
*
*/
public class ValidadorMarcadAgua {
private final Color COR_DE_FUNDO = Color.BLACK;
/**
* Metodo que percorre uma imagem como um vetor e mostra o rgb de cada pixel
* @throws InterruptedException
*/
public boolean validar(String filePath,BufferedImage imagemPretaBuff,Color COR_FONTE, String FONTE) throws Exception {
double pixeisTotal = 0;
double pixeisDiff = 0;
try {
File imagemMarcada = new File(filePath); // Caminho da imagem original
if (!imagemMarcada.exists()) {
System.out.println("Arquivo de Imagem nao encontrado.");//Imagem nao existe
return false;
// ou Throw Exception <-
}//fecha if
BufferedImage imagemMarcadaBuff = ImageIO.read(imagemMarcada);
//Percorre a imagem com fundo preto procurando uma cor que nao seja preta
for(int i = 0; i < imagemPretaBuff.getWidth(); i++){
for(int j = 0; j < imagemPretaBuff.getHeight(); j++){
Color imagemPretaColor = new Color(imagemPretaBuff.getRGB(i, j));//aponta a referencia para a instancia(objeto) color
if (!(imagemPretaColor.equals(COR_DE_FUNDO))) {
pixeisTotal = pixeisTotal + 1;
Color imagemMarcadaColor = new Color(imagemMarcadaBuff.getRGB(i,j));//pega a cor do pixel na imagem normal na coordenada (i,j)
if (!(imagemMarcadaColor.equals(imagemPretaColor))) {//compara a cor do pixel nas duas imagens
pixeisDiff = pixeisDiff + 1;
}//fecha if
}//fecha if
}//fecha for j
}//fecha for i
double media = (pixeisDiff / pixeisTotal) * 100; //calcula a media de erros ao redor da Marca d'agua
if(media >= 35){
String resultado;
resultado = "A imagem "+imagemMarcada.getName()+" nao contem a marca!";
resultado = resultado + String.format(" (Margem de erro: %.2f %%)", media);
System.out.println(resultado);
}else{
String resultado;
resultado = "A imagem "+imagemMarcada.getName()+" tem a marca dagua!!";
resultado = resultado + String.format(" (Margem de erro: %.2f %%)", media);
System.out.println(resultado);
}//fecha else
} catch (Exception e) {
System.out.println("erro: "+ e.getMessage());//mostra a mensagem caso tenha erro
return false;
}//fecha try-catch
return true;
}//fecha validar
}//fecha class |
// Nenya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.jme.model;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;
import com.jme.bounding.BoundingBox;
import com.jme.bounding.BoundingSphere;
import com.jme.bounding.BoundingVolume;
import com.jme.image.Image;
import com.jme.image.Texture;
import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.scene.Controller;
import com.jme.scene.SharedMesh;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;
import com.jme.scene.VBOInfo;
import com.jme.scene.batch.GeomBatch;
import com.jme.scene.batch.TriangleBatch;
import com.jme.scene.state.AlphaState;
import com.jme.scene.state.CullState;
import com.jme.scene.state.FogState;
import com.jme.scene.state.LightState;
import com.jme.scene.state.RenderState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.ZBufferState;
import com.jme.system.DisplaySystem;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.InputCapsule;
import com.jme.util.export.OutputCapsule;
import com.jme.util.geom.BufferUtils;
import com.samskivert.util.PropertiesUtil;
import com.samskivert.util.StringUtil;
import com.threerings.jme.Log;
/**
* A {@link TriMesh} with a serialization mechanism tailored to stored models.
*/
public class ModelMesh extends TriMesh
implements ModelSpatial
{
/**
* No-arg constructor for deserialization.
*/
public ModelMesh ()
{
super("mesh");
}
/**
* Creates a mesh with no vertex data.
*/
public ModelMesh (String name)
{
super(name);
}
@Override // documentation inherited
public int hashCode ()
{
// hash on the name rather than the identity for consistent ordering
return getName().hashCode();
}
/**
* Reconfigures this model with a new set of (sub-)properties. Textures
* must be (re-)resolved after calling this method.
*/
public void reconfigure (Properties props)
{
configure(_solid, _textureKey, _transparent, props);
setRenderStates();
}
/**
* Configures this mesh based on the given parameters and (sub-)properties.
*
* @param texture the texture specified in the model export, if any (can be
* overridden by textures specified in the properties)
* @param solid whether or not the mesh allows back face culling
* @param transparent whether or not the mesh is (partially) transparent
*/
public void configure (
boolean solid, String texture, boolean transparent, Properties props)
{
_textureKey = texture;
_textures = (texture == null) ? null : StringUtil.parseStringArray(
props.getProperty(texture, texture));
Properties tprops = PropertiesUtil.getFilteredProperties(
props, texture);
_sphereMapped = Boolean.parseBoolean(tprops.getProperty("sphere_map"));
_filterMode = "nearest".equals(tprops.getProperty("filter")) ?
Texture.FM_NEAREST : Texture.FM_LINEAR;
_mipMapMode = getMipMapMode(tprops.getProperty("mipmap"));
_compress = Boolean.parseBoolean(tprops.getProperty("compress", "true"));
String emissive = tprops.getProperty("emissive");
if (Boolean.parseBoolean(emissive)) {
_emissive = true;
} else {
_emissiveMap = emissive;
}
_additive = Boolean.parseBoolean(tprops.getProperty("additive"));
_solid = solid;
_transparent = transparent;
String threshold = tprops.getProperty("alpha_threshold");
_alphaThreshold = (threshold == null) ?
DEFAULT_ALPHA_THRESHOLD : Float.parseFloat(threshold);
_translucent = _transparent &&
Boolean.parseBoolean(tprops.getProperty("translucent"));
}
/**
* Returns an opaque object representing this mesh's attributes. The
* object will implement {@link Object#hashCode} and {@link Object#equals}
* so that meshes with the same attributes will have identical keys.
*/
public Object getAttributeKey ()
{
return new AttributeKey(_textureKey, _textures, _sphereMapped,
_filterMode, _mipMapMode, _compress, _emissiveMap, _emissive, _additive,
_solid, _transparent, _alphaThreshold, _translucent);
}
/**
* Merges another mesh into this one. The mesh is assumed to be in the same coordinate system
* and have the same attributes.
*/
public void merge (ModelMesh mesh)
{
TriangleBatch batch = (TriangleBatch)getBatch(0);
TriangleBatch mbatch = (TriangleBatch)mesh.getBatch(0);
int vcount = batch.getVertexCount();
batch.setVertexBuffer(concatenate(batch.getVertexBuffer(), mbatch.getVertexBuffer()));
batch.setNormalBuffer(concatenate(batch.getNormalBuffer(), mbatch.getNormalBuffer()));
if (batch.getColorBuffer() != null && mbatch.getColorBuffer() != null) {
batch.setColorBuffer(concatenate(batch.getColorBuffer(), mbatch.getColorBuffer()));
}
batch.setTextureBuffer(concatenate(
batch.getTextureBuffer(0), mbatch.getTextureBuffer(0)), 0);
for (int ii = 1, nn = getTextureCount(); ii < nn; ii++) {
batch.setTextureBuffer(batch.getTextureBuffer(0), ii);
}
IntBuffer ibuf = batch.getIndexBuffer(), mibuf = mbatch.getIndexBuffer();
IntBuffer nibuf = BufferUtils.createIntBuffer(ibuf.capacity() + mibuf.capacity());
ibuf.clear();
nibuf.put(ibuf);
mibuf.clear();
while (mibuf.hasRemaining()) {
nibuf.put(mibuf.get() + vcount);
}
nibuf.clear();
batch.setIndexBuffer(nibuf);
}
/**
* Adjusts the vertices and the transform of the mesh so that the mesh's
* position lies at the center of its bounding volume.
*/
public void centerVertices ()
{
Vector3f offset = getBatch(0).getModelBound().getCenter().negate();
if (!offset.equals(Vector3f.ZERO)) {
getLocalTranslation().subtractLocal(offset);
getBatch(0).getModelBound().getCenter().set(Vector3f.ZERO);
getBatch(0).translatePoints(offset);
}
storeOriginalBuffers();
}
/**
* Adds an overlay layer to this mesh. After the mesh is rendered with
* its configured states, these states will be applied and the mesh will
* be rendered again.
*/
public void addOverlay (RenderState[] overlay)
{
if (_overlays == null) {
_overlays = new ArrayList<RenderState[]>(1);
}
_overlays.add(overlay);
}
/**
* Removes a layer from this mesh.
*/
public void removeOverlay (RenderState[] overlay)
{
if (_overlays != null) {
_overlays.remove(overlay);
if (_overlays.isEmpty()) {
_overlays = null;
}
}
}
@Override // documentation inherited
public void reconstruct (
FloatBuffer vertices, FloatBuffer normals, FloatBuffer colors,
FloatBuffer textures, IntBuffer indices)
{
super.reconstruct(vertices, normals, colors, textures, indices);
for (int ii = 1, nn = getTextureCount(); ii < nn; ii++) {
setTextureBuffer(0, getTextureBuffer(0, 0), ii);
}
// store any buffers that will be manipulated on a per-instance basis
storeOriginalBuffers();
// initialize the model if we're displaying
setRenderStates();
}
// documentation inherited from interface ModelSpatial
public Spatial putClone (Spatial store, Model.CloneCreator properties)
{
ModelMesh mstore = (ModelMesh)properties.originalToCopy.get(this);
if (mstore != null) {
return mstore;
} else if (store == null) {
mstore = new ModelMesh(getName());
} else {
mstore = (ModelMesh)store;
}
properties.originalToCopy.put(this, mstore);
mstore.normalsMode = normalsMode;
mstore.cullMode = cullMode;
for (int ii = 0; ii < RenderState.RS_MAX_STATE; ii++) {
RenderState rstate = getRenderState(ii);
if (rstate != null) {
mstore.setRenderState(rstate);
}
}
mstore.renderQueueMode = renderQueueMode;
mstore.lockedMode = lockedMode;
mstore.lightCombineMode = lightCombineMode;
mstore.textureCombineMode = textureCombineMode;
mstore.name = name;
mstore.isCollidable = isCollidable;
mstore.localRotation.set(localRotation);
mstore.localTranslation.set(localTranslation);
mstore.localScale.set(localScale);
for (Object controller : getControllers()) {
if (controller instanceof ModelController) {
mstore.addController(
((ModelController)controller).putClone(null, properties));
}
}
TriangleBatch batch = (TriangleBatch)getBatch(0),
mbatch = (TriangleBatch)mstore.getBatch(0);
mbatch.setVertexBuffer(properties.isSet("vertices") ?
batch.getVertexBuffer() :
BufferUtils.clone(batch.getVertexBuffer()));
mbatch.setColorBuffer(properties.isSet("colors") ?
batch.getColorBuffer() :
BufferUtils.clone(batch.getColorBuffer()));
mbatch.setNormalBuffer(properties.isSet("normals") ?
batch.getNormalBuffer() :
BufferUtils.clone(batch.getNormalBuffer()));
FloatBuffer texcoords;
for (int ii = 0; (texcoords = batch.getTextureBuffer(ii)) != null;
ii++) {
mbatch.setTextureBuffer(properties.isSet("texcoords") ?
texcoords : BufferUtils.clone(texcoords), ii);
}
mbatch.setIndexBuffer((properties.isSet("indices") && !_translucent) ?
batch.getIndexBuffer() :
BufferUtils.clone(batch.getIndexBuffer()));
if (properties.isSet("vboinfo")) {
mbatch.setVBOInfo(batch.getVBOInfo());
}
if (properties.isSet("obbtree")) {
mbatch.setCollisionTree(batch.getCollisionTree());
}
if (properties.isSet("displaylistid")) {
mbatch.setDisplayListID(batch.getDisplayListID());
}
if (batch.getModelBound() != null) {
mbatch.setModelBound(properties.isSet("bound") ?
batch.getModelBound() : batch.getModelBound().clone(null));
}
mstore._textureKey = _textureKey;
if (_textures != null && _textures.length > 1) {
int tidx = properties.random % _textures.length;
mstore._textures = new String[] { _textures[tidx] };
mstore._tstates = new TextureState[] { _tstates[tidx] };
mstore.setRenderState(_tstates[tidx]);
} else {
mstore._textures = _textures;
mstore._tstates = _tstates;
}
mstore._sphereMapped = _sphereMapped;
mstore._filterMode = _filterMode;
mstore._mipMapMode = _mipMapMode;
mstore._compress = _compress;
mstore._emissiveMap = _emissiveMap;
mstore._emissive = _emissive;
mstore._additive = _additive;
mstore._solid = _solid;
mstore._transparent = _transparent;
mstore._alphaThreshold = _alphaThreshold;
mstore._translucent = _translucent;
mstore._oibuf = _oibuf;
mstore._vbuf = _vbuf;
return mstore;
}
@Override // documentation inherited
public void updateWorldVectors ()
{
if (!_transformLocked) {
super.updateWorldVectors();
}
}
@Override // documentation inherited
public void read (JMEImporter im)
throws IOException
{
InputCapsule capsule = im.getCapsule(this);
setName(capsule.readString("name", null));
setLocalTranslation((Vector3f)capsule.readSavable(
"localTranslation", null));
setLocalRotation((Quaternion)capsule.readSavable(
"localRotation", null));
setLocalScale((Vector3f)capsule.readSavable(
"localScale", null));
TriangleBatch batch = (TriangleBatch)getBatch(0);
batch.setModelBound((BoundingVolume)capsule.readSavable(
"modelBound", null));
_textureKey = capsule.readString("textureKey", null);
_textures = capsule.readStringArray("textures", null);
_sphereMapped = capsule.readBoolean("sphereMapped", false);
_filterMode = capsule.readInt("filterMode", Texture.FM_LINEAR);
_mipMapMode = capsule.readInt("mipMapMode", Texture.MM_LINEAR_LINEAR);
_compress = capsule.readBoolean("compress", true);
_emissiveMap = capsule.readString("emissiveMap", null);
_emissive = capsule.readBoolean("emissive", false);
_additive = capsule.readBoolean("additive", false);
_solid = capsule.readBoolean("solid", true);
_transparent = capsule.readBoolean("transparent", false);
_alphaThreshold = capsule.readFloat("alphaThreshold",
DEFAULT_ALPHA_THRESHOLD);
_translucent = capsule.readBoolean("translucent", false);
reconstruct(capsule.readFloatBuffer("vertexBuffer", null),
capsule.readFloatBuffer("normalBuffer", null), null,
capsule.readFloatBuffer("textureBuffer", null),
capsule.readIntBuffer("indexBuffer", null));
}
@Override // documentation inherited
public void write (JMEExporter ex)
throws IOException
{
OutputCapsule capsule = ex.getCapsule(this);
capsule.write(getName(), "name", null);
capsule.write(getLocalTranslation(), "localTranslation", null);
capsule.write(getLocalRotation(), "localRotation", null);
capsule.write(getLocalScale(), "localScale", null);
capsule.write(getBatch(0).getModelBound(), "modelBound", null);
capsule.write(getVertexBuffer(0), "vertexBuffer", null);
capsule.write(getNormalBuffer(0), "normalBuffer", null);
capsule.write(getTextureBuffer(0, 0), "textureBuffer", null);
capsule.write(getIndexBuffer(0), "indexBuffer", null);
capsule.write(_textureKey, "textureKey", null);
capsule.write(_textures, "textures", null);
capsule.write(_sphereMapped, "sphereMapped", false);
capsule.write(_filterMode, "filterMode", Texture.FM_LINEAR);
capsule.write(_mipMapMode, "mipMapMode", Texture.MM_LINEAR_LINEAR);
capsule.write(_compress, "compress", true);
capsule.write(_emissiveMap, "emissiveMap", null);
capsule.write(_emissive, "emissive", false);
capsule.write(_additive, "additive", false);
capsule.write(_solid, "solid", true);
capsule.write(_transparent, "transparent", false);
capsule.write(_alphaThreshold, "alphaThreshold",
DEFAULT_ALPHA_THRESHOLD);
capsule.write(_translucent, "translucent", false);
}
// documentation inherited from interface ModelSpatial
public void expandModelBounds ()
{
// no-op
}
// documentation inherited from interface ModelSpatial
public void setReferenceTransforms ()
{
// no-op
}
// documentation inherited from interface ModelSpatial
public void lockStaticMeshes (
Renderer renderer, boolean useVBOs, boolean useDisplayLists)
{
if (useVBOs && renderer.supportsVBO()) {
VBOInfo vboinfo = new VBOInfo(true);
vboinfo.setVBOIndexEnabled(!_translucent);
setVBOInfo(vboinfo);
} else if (useDisplayLists && !_translucent) {
lockMeshes(renderer);
}
}
// documentation inherited from interface ModelSpatial
public void resolveTextures (TextureProvider tprov)
{
if (_textures == null) {
return;
}
Texture emissiveTex = null;
if (_emissiveMap != null && TextureState.getNumberOfFixedUnits() >= 2) {
TextureState tstate = tprov.getTexture(_emissiveMap);
emissiveTex = tstate.getTexture();
emissiveTex.setApply(Texture.AM_BLEND);
emissiveTex.setBlendColor(ColorRGBA.white);
}
_tstates = new TextureState[_textures.length];
for (int ii = 0; ii < _textures.length; ii++) {
_tstates[ii] = tprov.getTexture(_textures[ii]);
Texture tex = _tstates[ii].getTexture();
if (_sphereMapped) {
tex.setEnvironmentalMapMode(Texture.EM_SPHERE);
}
tex.setFilter(_filterMode);
tex.setMipmapState(_mipMapMode);
if (_compress && _tstates[ii].isS3TCAvailable()) {
Image image = tex.getImage();
int type = image.getType();
if (type == Image.RGB888) {
image.setType(Image.RGB888_DXT1);
} else if (type == Image.RGBA8888) {
image.setType(Image.RGBA8888_DXT5);
}
}
if (emissiveTex != null) {
_tstates[ii] = DisplaySystem.getDisplaySystem().
getRenderer().createTextureState();
_tstates[ii].setTexture(emissiveTex, 0);
_tstates[ii].setTexture(tex, 1);
}
}
if (_tstates[0] != null) {
setRenderState(_tstates[0]);
} else {
clearRenderState(RenderState.RS_TEXTURE);
}
}
// documentation inherited from interface ModelSpatial
public void storeMeshFrame (int frameId, boolean blend)
{
// no-op
}
// documentation inherited from interface ModelSpatial
public void setMeshFrame (int frameId)
{
// no-op
}
// documentation inherited from interface ModelSpatial
public void blendMeshFrames (int frameId1, int frameId2, float alpha)
{
// no-op
}
@Override // documentation inherited
protected void setupBatchList ()
{
batchList = new ArrayList<GeomBatch>(1);
TriangleBatch batch = new ModelBatch();
batch.setParentGeom(this);
batchList.add(batch);
}
/**
* Returns the number of textures this mesh uses (they must all share the
* same texture coordinates).
*/
protected int getTextureCount ()
{
return (_emissiveMap == null || TextureState.getNumberOfFixedUnits() < 2) ? 1 : 2;
}
/**
* For buffers that must be manipulated in some fashion, this method stores
* the originals.
*/
protected void storeOriginalBuffers ()
{
if (!_translucent) {
return;
}
IntBuffer ibuf = getIndexBuffer(0);
ibuf.rewind();
IntBuffer.wrap(_oibuf = new int[ibuf.capacity()]).put(ibuf);
FloatBuffer vbuf = getVertexBuffer(0);
vbuf.rewind();
FloatBuffer.wrap(_vbuf = new float[vbuf.capacity()]).put(vbuf);
}
/**
* Sets the model's render states (excluding the texture state, which is
* set by {@link #resolveTextures}) according to its configuration.
*/
protected void setRenderStates ()
{
if (DisplaySystem.getDisplaySystem() == null) {
return;
}
if (_backCull == null) {
initSharedStates();
}
if (_emissive) {
setRenderState(_emissiveLight);
}
if (_solid) {
setRenderState(_backCull);
}
if (_additive) {
setRenderQueueMode(Renderer.QUEUE_TRANSPARENT);
setRenderState(_addAlpha);
setRenderState(_overlayZBuffer);
setRenderState(_noFog);
} else if (_transparent) {
setRenderQueueMode(Renderer.QUEUE_TRANSPARENT);
if (_translucent) {
setRenderState(_blendAlpha);
setRenderState(_overlayZBuffer);
} else if (_alphaThreshold == DEFAULT_ALPHA_THRESHOLD) {
setRenderState(_defaultTestAlpha);
} else {
setRenderState(createTestAlpha(_alphaThreshold));
}
}
}
/**
* Locks the transform and bounds of this mesh on the assumption that its
* position will not change.
*/
protected void lockInstance ()
{
lockBounds();
_transformLocked = true;
}
/**
* Returns the mip-map mode corresponding to the given string
* (defaulting to {@link Texture#MM_LINEAR_LINEAR}).
*/
protected static int getMipMapMode (String mmode)
{
if ("none".equals(mmode)) {
return Texture.MM_NONE;
} else if ("nearest".equals(mmode)) {
return Texture.MM_NEAREST;
} else if ("linear".equals(mmode)) {
return Texture.MM_LINEAR;
} else if ("nearest_nearest".equals(mmode)) {
return Texture.MM_NEAREST_NEAREST;
} else if ("nearest_linear".equals(mmode)) {
return Texture.MM_NEAREST_LINEAR;
} else if ("linear_nearest".equals(mmode)) {
return Texture.MM_LINEAR_NEAREST;
} else {
return Texture.MM_LINEAR_LINEAR;
}
}
/**
* Initializes the states shared between all models. Requires an active
* display.
*/
protected static void initSharedStates ()
{
Renderer renderer = DisplaySystem.getDisplaySystem().getRenderer();
_backCull = renderer.createCullState();
_backCull.setCullMode(CullState.CS_BACK);
_blendAlpha = renderer.createAlphaState();
_blendAlpha.setBlendEnabled(true);
_addAlpha = renderer.createAlphaState();
_addAlpha.setBlendEnabled(true);
_addAlpha.setDstFunction(AlphaState.DB_ONE);
_defaultTestAlpha = createTestAlpha(DEFAULT_ALPHA_THRESHOLD);
_overlayZBuffer = renderer.createZBufferState();
_overlayZBuffer.setFunction(ZBufferState.CF_LEQUAL);
_overlayZBuffer.setWritable(false);
_emissiveLight = renderer.createLightState();
_emissiveLight.setGlobalAmbient(ColorRGBA.white);
_noFog = renderer.createFogState();
_noFog.setEnabled(false);
}
/**
* Creates an alpha state what will throw away fragments with alpha
* values less than or equal to the given threshold.
*/
protected static AlphaState createTestAlpha (float threshold)
{
AlphaState astate = DisplaySystem.getDisplaySystem().
getRenderer().createAlphaState();
astate.setBlendEnabled(true);
astate.setTestEnabled(true);
astate.setTestFunction(AlphaState.TF_GREATER);
astate.setReference(threshold);
return astate;
}
/**
* Concatenates the two provided buffers.
*/
protected static FloatBuffer concatenate (FloatBuffer b1, FloatBuffer b2)
{
FloatBuffer nb = BufferUtils.createFloatBuffer(b1.capacity() + b2.capacity());
b1.clear();
nb.put(b1);
b2.clear();
nb.put(b2);
nb.clear();
return nb;
}
protected static void sortTriangleCodes (int tcount)
{
// initialize the offsets for the first radix (LSB) and clear
// the counts
initByteOffsets();
// sort by the first radix and get the counts for the second
// (swapping directions in the hope of using the cache more
// effectively)
if (_stcodes == null || _stcodes.length < tcount) {
_stcodes = new int[tcount];
}
int tcode;
for (int ii = tcount - 1; ii >= 0; ii
tcode = _tcodes[ii];
_stcodes[_boffsets[tcode & 0xFF]++] = tcode;
_bcounts[(tcode >> 8) & 0xFF]++;
}
// initialize offsets for the second radix, clear counts, and
// sort by the second radix
initByteOffsets();
for (int ii = 0; ii < tcount; ii++) {
tcode = _stcodes[ii];
_tcodes[_boffsets[(tcode >> 8) & 0xFF]++] = tcode;
}
}
/**
* Sets the initial byte offsets used to place bytes within the sorted
* array using the byte counts, clearing the counts in the process.
*/
protected static void initByteOffsets ()
{
_boffsets[0] = 0;
for (int ii = 1; ii < 256; ii++) {
_boffsets[ii] = _boffsets[ii - 1] + _bcounts[ii - 1];
_bcounts[ii - 1] = 0;
}
_bcounts[255] = 0;
}
/** Sorts triangles for transparent meshes and renders overlays as well as
* the base layer. */
protected class ModelBatch extends TriangleBatch
{
@Override // documentation inherited
public void draw (Renderer r)
{
if (_translucent && isEnabled() && r.isProcessingQueue()) {
sortTriangles(r);
}
super.draw(r);
if (_overlays != null && isEnabled() && r.isProcessingQueue()) {
for (RenderState[] overlay : _overlays) {
for (RenderState rstate : overlay) {
int idx = rstate.getType();
_ostates[idx] = states[idx];
states[idx] = rstate;
}
r.draw(this);
for (RenderState rstate : overlay) {
int idx = rstate.getType();
states[idx] = _ostates[idx];
}
}
}
}
/**
* Sorts the batch's triangles by their distance to the camera.
*/
protected void sortTriangles (Renderer r)
{
// using the camera's direction in model space and the position
// and size of the model bound, find a set of plane parameters
// that determine the distance to a camera-aligned plane
// that touches the near edge of the bounding volume, as well
// as a scaling factor that brings the distance into a 16-bit
// integer range
getParentGeom().getWorldRotation().inverse().mult(
r.getCamera().getDirection(), _cdir);
BoundingVolume mbound = getModelBound();
Vector3f mc = mbound.getCenter();
float radius;
if (mbound instanceof BoundingSphere) {
radius = ((BoundingSphere)mbound).getRadius();
} else { // mbound instanceof BoundingBox
BoundingBox bbox = (BoundingBox)mbound;
radius = FastMath.sqrt(3f) * Math.max(bbox.xExtent,
Math.max(bbox.yExtent, bbox.zExtent));
}
float a = _cdir.x, b = _cdir.y, c = _cdir.z,
d = radius - a*mc.x - b*mc.y - c*mc.z,
dscale = 65535f / (radius * 2);
// premultiply the scale and averaging factor
a *= dscale / 3f;
b *= dscale / 3f;
c *= dscale / 3f;
d *= dscale;
// encode the model's triangles into integers such that the
// high 16 bits represent the original triangle index and the
// low 16 bits represent the distance to the plane. also
// increment the byte counts used for radix sorting
int tcount = getTriangleCount(), idist;
if (_tcodes == null || _tcodes.length < tcount) {
_tcodes = new int[tcount];
}
int i1, i2, i3;
for (int ii = 0, idx = 0; ii < tcount; ii++) {
i1 = _oibuf[idx++] * 3;
i2 = _oibuf[idx++] * 3;
i3 = _oibuf[idx++] * 3;
idist = (int)(
a * (_vbuf[i1++] + _vbuf[i2++] + _vbuf[i3++]) +
b * (_vbuf[i1++] + _vbuf[i2++] + _vbuf[i3++]) +
c * (_vbuf[i1++] + _vbuf[i2++] + _vbuf[i3++]) + d);
_tcodes[ii] = (ii << 16) | idist;
_bcounts[idist & 0xFF]++;
}
// sort the encoded triangles by increasing distance
sortTriangleCodes(tcount);
// reorder the triangles as dictated by the sorted codes, furthest
// triangles first
int icount = tcount * 3, idx;
if (_sibuf == null || _sibuf.length < icount) {
_sibuf = new int[icount];
}
for (int ii = tcount - 1, sidx = 0; ii >= 0; ii
idx = ((_tcodes[ii] >> 16) & 0xFFFF) * 3;
_sibuf[sidx++] = _oibuf[idx++];
_sibuf[sidx++] = _oibuf[idx++];
_sibuf[sidx++] = _oibuf[idx];
}
// copy the indices to the buffer
IntBuffer ibuf = getIndexBuffer();
ibuf.rewind();
ibuf.put(_sibuf, 0, icount);
}
/** Temporarily stores the original states. */
protected RenderState[] _ostates =
new RenderState[RenderState.RS_MAX_STATE];
}
/** A wrapper around an array of attributes that uses {@link Arrays#deepHashCode} and
* {@link Arrays#deepEquals} for hashing/comparison. */
protected static class AttributeKey
{
public AttributeKey (Object... attrs)
{
_attrs = attrs;
}
@Override // documentation inherited
public int hashCode ()
{
return Arrays.deepHashCode(_attrs);
}
@Override // documentation inherited
public boolean equals (Object other)
{
return Arrays.deepEquals(_attrs, ((AttributeKey)other)._attrs);
}
protected Object[] _attrs;
}
/** The name of the texture specified in the model file, which acts as a
* property key and a default value. */
protected String _textureKey;
/** The name of this model's textures, or <code>null</code> for none. */
protected String[] _textures;
/** Whether or not to use sphere mapping on this model's textures. */
protected boolean _sphereMapped;
/** The filter mode to use on magnification. */
protected int _filterMode;
/** The mipmap mode to use on minification. */
protected int _mipMapMode;
/** Whether or not to use compressed textures, if available. */
protected boolean _compress;
/** The emissive map, if specified. */
protected String _emissiveMap;
/** Whether or not this mesh is completely emissive. */
protected boolean _emissive;
/** Whether or not this mesh should be rendered with additive blending. */
protected boolean _additive;
/** Whether or not this mesh can enable back-face culling. */
protected boolean _solid;
/** Whether or not this mesh must be rendered as transparent. */
protected boolean _transparent;
/** The alpha threshold below which fragments are discarded. */
protected float _alphaThreshold;
/** Whether or not the triangles of this mesh should be depth-sorted before
* rendering. */
protected boolean _translucent;
/** If non-null, additional layers to render over the base layer. */
protected ArrayList<RenderState[]> _overlays;
/** For prototype meshes, the resolved texture states. */
protected TextureState[] _tstates;
/** Whether or not the transform has been locked. This operates in a
* slightly different way than JME's locking, in that it allows applying
* transformations to display lists. */
protected boolean _transformLocked;
/** For depth-sorted and skinned meshes, the array of vertices. */
protected float[] _vbuf;
/** For depth-sorted meshes, the original array of indices. */
protected int[] _oibuf;
/** The shared state for back face culling. */
protected static CullState _backCull;
/** The shared state for alpha blending. */
protected static AlphaState _blendAlpha;
/** The shared state for additive blending. */
protected static AlphaState _addAlpha;
/** The shared state for alpha testing with the default threshold. */
protected static AlphaState _defaultTestAlpha;
/** The shared state for checking, but not writing to, the z buffer. */
protected static ZBufferState _overlayZBuffer;
/** A light state that simulates emissivity. */
protected static LightState _emissiveLight;
/** A fog state that disables fog. */
protected static FogState _noFog;
/** Work vector to store the camera direction. */
protected static Vector3f _cdir = new Vector3f();
/** Work arrays used to sort triangles. */
protected static int[] _tcodes, _stcodes;
/** Holds counts of each byte and array offsets for radix sorting. */
protected static int[] _bcounts = new int[256], _boffsets = new int[256];
/** Work array used to hold indices of sorted triangles. */
protected static int[] _sibuf;
/** The default alpha threshold. */
protected static final float DEFAULT_ALPHA_THRESHOLD = 0.5f;
private static final long serialVersionUID = 1;
} |
// $Id: Sprite.java,v 1.63 2003/04/20 04:52:33 mdb Exp $
package com.threerings.media.sprite;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import com.threerings.util.DirectionCodes;
import com.threerings.media.AbstractMedia;
import com.threerings.media.Log;
import com.threerings.media.util.Path;
import com.threerings.media.util.Pathable;
/**
* The sprite class represents a single moveable object in an animated
* view. A sprite has a position and orientation within the view, and can
* be moved along a path.
*/
public abstract class Sprite extends AbstractMedia
implements DirectionCodes, Pathable
{
/**
* Constructs a sprite with an initially invalid location. Because
* sprite derived classes generally want to get in on the business
* when a sprite's location is set, it is not safe to do so in the
* constructor because their derived methods will be called before
* their constructor has been called. Thus a sprite should be fully
* constructed and <em>then</em> its location should be set.
*/
public Sprite ()
{
super(new Rectangle());
}
/**
* Constructs a sprite with the supplied bounds.
*/
public Sprite (Rectangle bounds)
{
super(bounds);
}
/**
* Returns the sprite's x position in screen coordinates. This is the
* x coordinate of the sprite's origin, not the upper left of its
* bounds.
*/
public int getX ()
{
return _ox;
}
/**
* Returns the sprite's y position in screen coordinates. This is the
* y coordinate of the sprite's origin, not the upper left of its
* bounds.
*/
public int getY ()
{
return _oy;
}
/**
* Returns the offset to the sprite's origin from the upper-left of
* the sprite's image.
*/
public int getXOffset ()
{
return _oxoff;
}
/**
* Returns the offset to the sprite's origin from the upper-left of
* the sprite's image.
*/
public int getYOffset ()
{
return _oyoff;
}
/**
* Returns the sprite's width in pixels.
*/
public int getWidth ()
{
return _bounds.width;
}
/**
* Returns the sprite's height in pixels.
*/
public int getHeight ()
{
return _bounds.height;
}
/**
* Sprites have an orientation in one of the eight cardinal
* directions: <code>NORTH</code>, <code>NORTHEAST</code>, etc.
* Derived classes can choose to override this member function and
* select a different set of images based on their orientation, or
* they can ignore the orientation information.
*
* @see DirectionCodes
*/
public void setOrientation (int orient)
{
_orient = orient;
}
/**
* Returns the sprite's orientation as one of the eight cardinal
* directions: <code>NORTH</code>, <code>NORTHEAST</code>, etc.
*
* @see DirectionCodes
*/
public int getOrientation ()
{
return _orient;
}
// documentation inherited
public void setLocation (int x, int y)
{
// start with our current bounds
Rectangle dirty = new Rectangle(_bounds);
// move ourselves
_ox = x;
_oy = y;
// we need to update our draw position which is based on the size
// of our current bounds
updateRenderOrigin();
// grow the dirty rectangle to incorporate our new bounds and pass
// the dirty region to our region manager
if (_mgr != null) {
// if our new bounds intersect our old bounds, grow a single
// dirty rectangle to incorporate them both
if (_bounds.intersects(dirty)) {
dirty.add(_bounds);
} else {
// otherwise invalidate our new bounds separately
_mgr.getRegionManager().invalidateRegion(_bounds);
}
_mgr.getRegionManager().addDirtyRegion(dirty);
}
}
// documentation inherited
public void paint (Graphics2D gfx)
{
gfx.drawRect(_bounds.x, _bounds.y, _bounds.width-1, _bounds.height-1);
}
/**
* Paint the sprite's path, if any, to the specified graphics context.
*
* @param gfx the graphics context.
*/
public void paintPath (Graphics2D gfx)
{
if (_path != null) {
_path.paint(gfx);
}
}
/**
* Returns true if the sprite's bounds contain the specified point,
* false if not.
*/
public boolean contains (int x, int y)
{
return _bounds.contains(x, y);
}
/**
* Returns true if the sprite's bounds contain the specified point,
* false if not.
*/
public boolean hitTest (int x, int y)
{
return _bounds.contains(x, y);
}
/**
* Returns whether the sprite is inside the given shape in pixel
* coordinates.
*/
public boolean inside (Shape shape)
{
return shape.contains(_ox, _oy);
}
/**
* Returns whether the sprite's drawn rectangle intersects the given
* shape in pixel coordinates.
*/
public boolean intersects (Shape shape)
{
return shape.intersects(_bounds);
}
/**
* Returns true if this sprite is currently following a path, false if
* it is not.
*/
public boolean isMoving ()
{
return (_path != null);
}
/**
* Set the sprite's active path and start moving it along its merry
* way. If the sprite is already moving along a previous path the old
* path will be lost and the new path will begin to be traversed.
*
* @param path the path to follow.
*/
public void move (Path path)
{
// if there's a previous path, let it know that it's going away
if (_path != null) {
_path.wasRemoved(this);
}
// save off this path
_path = path;
// we'll initialize it on our next tick thanks to a zero path stamp
_pathStamp = 0;
}
/**
* Cancels any path that the sprite may currently be moving along.
*/
public void cancelMove ()
{
// TODO: make sure we come to a stop on a full coordinate,
// even in the case where we aborted a path mid-traversal.
if (_path != null) {
_path.wasRemoved(this);
_path = null;
}
}
/**
* Returns the path being followed by this sprite or null if the
* sprite is not following a path.
*/
public Path getPath ()
{
return _path;
}
/**
* Called by the active path when it begins.
*/
public void pathBeginning ()
{
// nothing for now
}
/**
* Called by the active path when it has completed.
*/
public void pathCompleted (long timestamp)
{
// keep a reference to the path just completed
Path oldpath = _path;
// let the path know that it's audi
_path.wasRemoved(this);
// clear out the path we've now finished
_path = null;
// inform observers that we've finished our path
notifyObservers(new PathCompletedEvent(this, timestamp, oldpath));
}
// documentation inherited
public void tick (long tickStamp)
{
tickPath(tickStamp);
}
/**
* Ticks any path assigned to this sprite.
*
* @return true if the path relocated the sprite as a result of this
* tick, false if it remained in the same position.
*/
protected boolean tickPath (long tickStamp)
{
if (_path == null) {
return false;
}
// initialize the path if we haven't yet
if (_pathStamp == 0) {
_path.init(this, _pathStamp = tickStamp);
}
// it's possible that as a result of init() the path completed and
// removed itself with a call to pathCompleted(), so we have to be
// careful here
return (_path == null) ? true : _path.tick(this, tickStamp);
}
// documentation inherited
public void fastForward (long timeDelta)
{
// fast forward any path we're following
if (_path != null) {
_path.fastForward(timeDelta);
}
}
/**
* Update the coordinates at which the sprite image is drawn to
* reflect the sprite's current position.
*/
protected void updateRenderOrigin ()
{
// our bounds origin may differ from the sprite's origin
_bounds.x = _ox - _oxoff;
_bounds.y = _oy - _oyoff;
}
/**
* Add a sprite observer to observe this sprite's events.
*
* @param obs the sprite observer.
*/
public void addSpriteObserver (SpriteObserver obs)
{
addObserver(obs);
}
/**
* Remove a sprite observer.
*/
public void removeSpriteObserver (SpriteObserver obs)
{
removeObserver(obs);
}
/**
* Inform all sprite observers of a sprite event.
*
* @param event the sprite event.
*/
protected void notifyObservers (SpriteEvent event)
{
if (_observers != null) {
((SpriteManager)_mgr).dispatchEvent(_observers, event);
}
}
// documentation inherited
protected void toString (StringBuffer buf)
{
super.toString(buf);
buf.append(", ox=").append(_ox);
buf.append(", oy=").append(_oy);
buf.append(", oxoff=").append(_oxoff);
buf.append(", oyoff=").append(_oyoff);
}
/** The location of the sprite's origin in pixel coordinates. If the
* sprite positions itself via a hotspot that is not the upper left
* coordinate of the sprite's bounds, the offset to the hotspot should
* be maintained in {@link #_oxoff} and {@link #_oyoff}. */
protected int _ox = Integer.MIN_VALUE, _oy = Integer.MIN_VALUE;
/** The offsets from our upper left coordinate to our origin (or hot
* spot). Derived classes will need to update these values if the
* sprite's origin is not coincident with the upper left coordinate of
* its bounds. */
protected int _oxoff, _oyoff;
/** The orientation of this sprite. */
protected int _orient = NONE;
/** When moving, the path the sprite is traversing. */
protected Path _path;
/** The timestamp at which we started along our path. */
protected long _pathStamp;
} |
package org.jaxen.expr;
import java.util.Comparator;
import java.util.Iterator;
import org.jaxen.Navigator;
import org.jaxen.UnsupportedAxisException;
class NodeComparator implements Comparator {
private Navigator navigator;
NodeComparator(Navigator navigator) {
this.navigator = navigator;
}
public int compare(Object o1, Object o2) {
if (navigator == null) return 0;
if (isNonChild(o1) && isNonChild(o2)) {
try {
return compare(navigator.getParentNode(o1), navigator.getParentNode(o2));
}
catch (UnsupportedAxisException ex) {
return 0;
}
}
try {
int depth1 = getDepth(o1);
int depth2 = getDepth(o2);
Object a1 = o1;
Object a2 = o2;
while (depth1 > depth2) {
a1 = navigator.getParentNode(a1);
depth1
}
if (a1 == o2) return 1;
while (depth2 > depth1) {
a2 = navigator.getParentNode(a2);
depth2
}
if (a2 == o1) return -1;
// a1 and a2 are now at same depth; and are not the same
while (true) {
Object p1 = navigator.getParentNode(a1);
Object p2 = navigator.getParentNode(a2);
if (p1 == p2) {
return compareSiblings(p1, a1, a2);
}
a1 = p1;
a2 = p2;
}
}
catch (UnsupportedAxisException ex) {
return 0; // ???? should I throw an exception instead?
}
}
private boolean isNonChild(Object o) {
return navigator.isAttribute(o) || navigator.isNamespace(o);
}
private int compareSiblings(Object parent, Object sib1, Object sib2)
throws UnsupportedAxisException {
Iterator children = navigator.getChildAxisIterator(parent);
while (children.hasNext()) {
Object next = children.next();
if (next == sib1) return -1;
else if (next == sib2) return 1;
}
return 0;
}
private int getDepth(Object o) throws UnsupportedAxisException {
int depth = 0;
Object parent = o;
while ((parent = navigator.getParentNode(parent)) != null) {
depth++;
}
return depth;
}
} |
package org.jsmpp.session;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Hashtable;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.jsmpp.BindType;
import org.jsmpp.DefaultPDUReader;
import org.jsmpp.DefaultPDUSender;
import org.jsmpp.InterfaceVersion;
import org.jsmpp.InvalidCommandLengthException;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.NumberingPlanIndicator;
import org.jsmpp.PDUReader;
import org.jsmpp.PDUSender;
import org.jsmpp.PDUStringException;
import org.jsmpp.SMPPConstant;
import org.jsmpp.SynchronizedPDUReader;
import org.jsmpp.SynchronizedPDUSender;
import org.jsmpp.TypeOfNumber;
import org.jsmpp.bean.BindResp;
import org.jsmpp.bean.Command;
import org.jsmpp.bean.DataCoding;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.EnquireLinkResp;
import org.jsmpp.bean.QuerySmResp;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.SubmitSmResp;
import org.jsmpp.bean.UnbindResp;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.PendingResponse;
import org.jsmpp.extra.ProcessMessageException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.state.SMPPSessionState;
import org.jsmpp.util.DefaultComposer;
import org.jsmpp.util.Sequence;
/**
* @author uudashr
* @version 2.0
*
*/
public class SMPPSession {
private static final Logger logger = Logger.getLogger(SMPPSession.class);
private static final PDUSender pduSender = new SynchronizedPDUSender(new DefaultPDUSender(new DefaultComposer()));
private static final PDUReader pduReader = new SynchronizedPDUReader(new DefaultPDUReader());
private static final AtomicInteger sessionIdSequence = new AtomicInteger();
private Socket socket = new Socket();
private DataInputStream in;
private OutputStream out;
private SessionState sessionState = SessionState.CLOSED;
private SMPPSessionState stateProcessor = SMPPSessionState.CLOSED;
private final Sequence sequence = new Sequence();
private final SMPPSessionHandler sessionHandler = new SMPPSessionHandlerImpl();
private final Hashtable<Integer, PendingResponse<? extends Command>> pendingResponse = new Hashtable<Integer, PendingResponse<? extends Command>>();
private int sessionTimer = 5000;
private long transactionTimer = 2000;
private int enquireLinkToSend;
private long lastActivityTimestamp;
private MessageReceiverListener messageReceiverListener;
private SessionStateListener sessionStateListener;
private IdleActivityChecker idleActivityChecker;
private EnquireLinkSender enquireLinkSender;
private int sessionId = sessionIdSequence.incrementAndGet();
public SMPPSession() {
}
public int getSessionId() {
return sessionId;
}
public void connectAndBind(String host, int port, BindType bindType,
String systemId, String password, String systemType,
TypeOfNumber addrTon, NumberingPlanIndicator addrNpi,
String addressRange) throws IOException {
if (sequence.currentValue() != 0)
throw new IOException("Failed connecting");
socket.connect(new InetSocketAddress(host, port));
if (socket.getInputStream() == null) {
logger.fatal("InputStream is null");
} else if (socket.isInputShutdown()) {
logger.fatal("Input shutdown");
}
logger.info("Connected");
changeState(SessionState.OPEN);
try {
in = new DataInputStream(socket.getInputStream());
new PDUReaderWorker().start();
out = socket.getOutputStream();
sendBind(bindType, systemId, password, systemType,
InterfaceVersion.IF_34, addrTon, addrNpi, addressRange);
changeToBoundState(bindType);
socket.setSoTimeout(sessionTimer);
enquireLinkSender = new EnquireLinkSender();
enquireLinkSender.start();
idleActivityChecker = new IdleActivityChecker();
idleActivityChecker.start();
} catch (PDUStringException e) {
logger.error("Failed sending bind command", e);
} catch (NegativeResponseException e) {
String message = "Receive negative bind response";
logger.error(message, e);
closeSocket();
throw new IOException(message + ": " + e.getMessage());
} catch (InvalidResponseException e) {
String message = "Receive invalid response of bind";
logger.error(message, e);
closeSocket();
throw new IOException(message + ": " + e.getMessage());
} catch (ResponseTimeoutException e) {
String message = "Waiting bind response take time to long";
logger.error(message, e);
closeSocket();
throw new IOException(message + ": " + e.getMessage());
} catch (IOException e) {
logger.error("IO Error occure", e);
closeSocket();
throw e;
}
}
/**
* @param bindType
* @param systemId
* @param password
* @param systemType
* @param interfaceVersion
* @param addrTon
* @param addrNpi
* @param addressRange
* @return SMSC system id.
* @throws PDUStringException if we enter invalid bind parameter(s).
* @throws ResponseTimeoutException if there is no valid response after defined millis.
* @throws InvalidResponseException if there is invalid response found.
* @throws NegativeResponseException if we receive negative response.
* @throws IOException
*/
private String sendBind(BindType bindType, String systemId,
String password, String systemType,
InterfaceVersion interfaceVersion, TypeOfNumber addrTon,
NumberingPlanIndicator addrNpi, String addressRange)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<BindResp> pendingResp = new PendingResponse<BindResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendBind(out, bindType, seqNum, systemId, password, systemType, interfaceVersion, addrTon, addrNpi, addressRange);
} catch (IOException e) {
logger.error("Failed sending bind command", e);
pendingResponse.remove(seqNum);
throw e;
}
try {
pendingResp.waitDone();
logger.info("Bind response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
throw new NegativeResponseException(pendingResp.getResponse().getCommandStatus());
return pendingResp.getResponse().getSystemId();
}
/**
* Ensure we have proper link.
* @throws ResponseTimeoutException if there is no valid response after defined millis.
* @throws InvalidResponseException if there is invalid response found.
* @throws IOException
*/
private void enquireLink() throws ResponseTimeoutException, InvalidResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<EnquireLinkResp> pendingResp = new PendingResponse<EnquireLinkResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendEnquireLink(out, seqNum);
} catch (IOException e) {
logger.error("Failed sending enquire link", e);
pendingResponse.remove(seqNum);
throw e;
}
try {
pendingResp.waitDone();
logger.info("Enquire link response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK) {
// this is ok
logger.warn("Receive NON-OK response of enquire link");
}
}
public void unbindAndClose() {
try {
unbind();
} catch (ResponseTimeoutException e) {
logger.error("Timeout waiting unbind response", e);
} catch (InvalidResponseException e) {
logger.error("Receive invalid unbind response", e);
} catch (IOException e) {
logger.error("IO error found ", e);
}
closeSocket();
}
private void unbind() throws ResponseTimeoutException, InvalidResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<UnbindResp> pendingResp = new PendingResponse<UnbindResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendUnbind(out, seqNum);
} catch (IOException e) {
logger.error("Failed sending unbind", e);
pendingResponse.remove(seqNum);
throw e;
}
try {
pendingResp.waitDone();
logger.info("Unbind response received");
changeState(SessionState.UNBOUND);
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
logger.warn("Receive NON-OK response of unbind");
}
/**
* @param serviceType
* @param sourceAddrTon
* @param sourceAddrNpi
* @param sourceAddr
* @param destAddrTon
* @param destAddrNpi
* @param destinationAddr
* @param esmClass
* @param protocoId
* @param priorityFlag
* @param scheduleDeliveryTime
* @param validityPeriod
* @param registeredDelivery
* @param replaceIfPresent
* @param dataCoding
* @param smDefaultMsgId
* @param shortMessage
* @return message id.
* @throws PDUStringException if we enter invalid bind parameter(s).
* @throws ResponseTimeoutException if there is no valid response after defined millis.
* @throws InvalidResponseException if there is invalid response found.
* @throws NegativeResponseException if we receive negative response.
* @throws IOException
*/
public String submitShortMessage(String serviceType,
TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi,
String sourceAddr, TypeOfNumber destAddrTon,
NumberingPlanIndicator destAddrNpi, String destinationAddr,
ESMClass esmClass, byte protocoId, byte priorityFlag,
String scheduleDeliveryTime, String validityPeriod,
RegisteredDelivery registeredDelivery, byte replaceIfPresent,
DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<SubmitSmResp> pendingResp = new PendingResponse<SubmitSmResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendSubmitSm(out, seqNum, serviceType, sourceAddrTon,
sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi,
destinationAddr, esmClass, protocoId, priorityFlag,
scheduleDeliveryTime, validityPeriod, registeredDelivery,
replaceIfPresent, dataCoding, smDefaultMsgId, shortMessage);
} catch (IOException e) {
logger.error("Failed submit short message", e);
pendingResponse.remove(seqNum);
closeSocket();
throw e;
}
try {
pendingResp.waitDone();
logger.debug("Submit sm response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
logger.debug("Response timeout for submit_sm with sessionIdSequence number " + seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
throw new NegativeResponseException(pendingResp.getResponse().getCommandStatus());
return pendingResp.getResponse().getMessageId();
}
public QuerySmResult queryShortMessage(String messageId, TypeOfNumber sourceAddrTon,
NumberingPlanIndicator sourceAddrNpi, String sourceAddr)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<QuerySmResp> pendingResp = new PendingResponse<QuerySmResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendQuerySm(out, seqNum, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr);
} catch (IOException e) {
logger.error("Failed submit short message", e);
pendingResponse.remove(seqNum);
closeSocket();
throw e;
}
try {
pendingResp.waitDone();
logger.info("Query sm response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
QuerySmResp resp = pendingResp.getResponse();
if (resp.getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
throw new NegativeResponseException(resp.getCommandStatus());
if (resp.getMessageId().equals(messageId)) {
return new QuerySmResult(resp.getFinalDate(), resp.getMessageState(), resp.getErrorCode());
} else {
// message id requested not same as the returned
throw new InvalidResponseException("Requested message_id doesn't match with the result");
}
}
private void changeToBoundState(BindType bindType) {
if (bindType.equals(BindType.BIND_TX)) {
changeState(SessionState.BOUND_TX);
} else if (bindType.equals(BindType.BIND_RX)) {
changeState(SessionState.BOUND_RX);
} else if (bindType.equals(BindType.BIND_TRX)){
changeState(SessionState.BOUND_TRX);
} else {
throw new IllegalArgumentException("Bind type " + bindType + " not supported");
}
try {
socket.setSoTimeout(sessionTimer);
} catch (SocketException e) {
logger.error("Failed setting so_timeout for session timer", e);
}
}
private synchronized void changeState(SessionState newState) {
if (sessionState != newState) {
final SessionState oldState = sessionState;
sessionState = newState;
// change the session state processor
if (sessionState == SessionState.OPEN) {
stateProcessor = SMPPSessionState.OPEN;
} else if (sessionState == SessionState.BOUND_RX) {
stateProcessor = SMPPSessionState.BOUND_RX;
} else if (sessionState == SessionState.BOUND_TX) {
stateProcessor = SMPPSessionState.BOUND_TX;
} else if (sessionState == SessionState.BOUND_TRX) {
stateProcessor = SMPPSessionState.BOUND_TRX;
} else if (sessionState == SessionState.UNBOUND) {
stateProcessor = SMPPSessionState.UNBOUND;
} else if (sessionState == SessionState.CLOSED) {
stateProcessor = SMPPSessionState.CLOSED;
}
fireChangeState(newState, oldState);
}
}
private void updateActivityTimestamp() {
lastActivityTimestamp = System.currentTimeMillis();
}
private void addEnquireLinkJob() {
enquireLinkToSend++;
}
public int getSessionTimer() {
return sessionTimer;
}
public void setSessionTimer(int sessionTimer) {
this.sessionTimer = sessionTimer;
if (sessionState.isBound()) {
try {
socket.setSoTimeout(sessionTimer);
} catch (SocketException e) {
logger.error("Failed setting so_timeout for session timer", e);
}
}
}
public long getTransactionTimer() {
return transactionTimer;
}
public void setTransactionTimer(long transactionTimer) {
this.transactionTimer = transactionTimer;
}
public synchronized SessionState getSessionState() {
return sessionState;
}
public void setSessionStateListener(
SessionStateListener sessionStateListener) {
this.sessionStateListener = sessionStateListener;
}
public void setMessageReceiverListener(
MessageReceiverListener messageReceiverListener) {
this.messageReceiverListener = messageReceiverListener;
}
private void closeSocket() {
changeState(SessionState.CLOSED);
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
logger.warn("Failed closing socket", e);
}
}
}
private synchronized boolean isReadPdu() {
return sessionState.isBound() || sessionState.equals(SessionState.OPEN);
}
private void readPDU() {
try {
Command pduHeader = null;
byte[] pdu = null;
synchronized (in) {
pduHeader = pduReader.readPDUHeader(in);
pdu = pduReader.readPDU(in, pduHeader);
}
switch (pduHeader.getCommandId()) {
case SMPPConstant.CID_BIND_RECEIVER_RESP:
case SMPPConstant.CID_BIND_TRANSMITTER_RESP:
case SMPPConstant.CID_BIND_TRANSCEIVER_RESP:
updateActivityTimestamp();
stateProcessor.processBindResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_GENERIC_NACK:
updateActivityTimestamp();
stateProcessor.processGenericNack(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_ENQUIRE_LINK:
updateActivityTimestamp();
stateProcessor.processEnquireLink(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_ENQUIRE_LINK_RESP:
updateActivityTimestamp();
stateProcessor.processEnquireLinkResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_SUBMIT_SM_RESP:
updateActivityTimestamp();
stateProcessor.processSubmitSmResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_QUERY_SM_RESP:
updateActivityTimestamp();
stateProcessor.processQuerySmResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_DELIVER_SM:
updateActivityTimestamp();
stateProcessor.processDeliverSm(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_UNBIND:
updateActivityTimestamp();
stateProcessor.processUnbind(pduHeader, pdu, sessionHandler);
changeState(SessionState.UNBOUND);
break;
case SMPPConstant.CID_UNBIND_RESP:
updateActivityTimestamp();
stateProcessor.processUnbindResp(pduHeader, pdu, sessionHandler);
break;
default:
stateProcessor.processUnknownCid(pduHeader, pdu, sessionHandler);
}
} catch (InvalidCommandLengthException e) {
logger.warn("Receive invalid command length", e);
// FIXME uud: response to this error, generick nack or close socket
} catch (SocketTimeoutException e) {
addEnquireLinkJob();
//try { Thread.sleep(1); } catch (InterruptedException ee) {}
} catch (IOException e) {
closeSocket();
}
}
@Override
protected void finalize() throws Throwable {
closeSocket();
}
private void fireAcceptDeliverSm(DeliverSm deliverSm) throws ProcessMessageException {
if (messageReceiverListener != null) {
messageReceiverListener.onAcceptDeliverSm(deliverSm);
} else {
logger.warn("Receive deliver_sm but MessageReceiverListener is null. Short message = " + new String(deliverSm.getShortMessage()));
}
}
private void fireChangeState(SessionState newState, SessionState oldState) {
if (sessionStateListener != null) {
sessionStateListener.onStateChange(newState, oldState, this);
} else {
logger.warn("SessionStateListener is null");
}
}
private class SMPPSessionHandlerImpl implements SMPPSessionHandler {
public void processDeliverSm(DeliverSm deliverSm) throws ProcessMessageException {
fireAcceptDeliverSm(deliverSm);
}
@SuppressWarnings("unchecked")
public PendingResponse<Command> removeSentItem(int sequenceNumber) {
return (PendingResponse<Command>)pendingResponse.remove(sequenceNumber);
}
public void sendDeliverSmResp(int sequenceNumber) throws IOException {
try {
pduSender.sendDeliverSmResp(out, sequenceNumber);
// FIXME uud: delete this log
logger.debug("deliver_sm_resp with seq_number " + sequenceNumber + " has been sent");
} catch (PDUStringException e) {
logger.fatal("Failed sending deliver_sm_resp", e);
}
}
public void sendEnquireLinkResp(int sequenceNumber) throws IOException {
pduSender.sendEnquireLinkResp(out, sequenceNumber);
}
public void sendGenerickNack(int commandStatus, int sequenceNumber) throws IOException {
pduSender.sendGenericNack(out, commandStatus, sequenceNumber);
}
public void sendNegativeResponse(int originalCommandId, int commandStatus, int sequenceNumber) throws IOException {
pduSender.sendHeader(out, originalCommandId | SMPPConstant.MASK_CID_RESP, commandStatus, sequenceNumber);
}
public void sendUnbindResp(int sequenceNumber) throws IOException {
pduSender.sendUnbindResp(out, SMPPConstant.STAT_ESME_ROK, sequenceNumber);
}
}
private class PDUReaderWorker extends Thread {
@Override
public void run() {
logger.info("Starting PDUReaderWorker");
while (isReadPdu()) {
readPDU();
}
logger.info("PDUReaderWorker stop");
}
}
private class EnquireLinkSender extends Thread {
@Override
public void run() {
logger.info("Starting EnquireLinkSender");
while (isReadPdu()) {
long sleepTime = 1000;
if (enquireLinkToSend > 0) {
enquireLinkToSend
try {
enquireLink();
} catch (ResponseTimeoutException e) {
closeSocket();
} catch (InvalidResponseException e) {
// lets unbind gracefully
unbindAndClose();
} catch (IOException e) {
closeSocket();
}
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
logger.info("EnquireLinkSender stop");
}
}
private class IdleActivityChecker extends Thread {
@Override
public void run() {
logger.info("Starting IdleActivityChecker");
while (isReadPdu()) {
long timeLeftToEnquire = lastActivityTimestamp + sessionTimer - System.currentTimeMillis();
if (timeLeftToEnquire <= 0) {
try {
enquireLink();
} catch (ResponseTimeoutException e) {
closeSocket();
} catch (InvalidResponseException e) {
// lets unbind gracefully
unbindAndClose();
} catch (IOException e) {
closeSocket();
}
} else {
try {
Thread.sleep(timeLeftToEnquire);
} catch (InterruptedException e) {
}
}
}
logger.info("IdleActivityChecker stop");
}
}
} |
// Clirr: compares two versions of a java library for binary compatibility
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package net.sf.clirr.checks;
import net.sf.clirr.event.ApiDifference;
import net.sf.clirr.event.Severity;
import net.sf.clirr.event.ScopeSelector;
import net.sf.clirr.framework.AbstractDiffReporter;
import net.sf.clirr.framework.ApiDiffDispatcher;
import net.sf.clirr.framework.ClassChangeCheck;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.generic.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* Checks the methods of a class.
*
* @author lkuehne
*/
public class MethodSetCheck
extends AbstractDiffReporter
implements ClassChangeCheck
{
private ScopeSelector scopeSelector;
/** {@inheritDoc} */
public MethodSetCheck(ApiDiffDispatcher dispatcher, ScopeSelector scopeSelector)
{
super(dispatcher);
this.scopeSelector = scopeSelector;
}
public final void check(JavaClass compatBaseline, JavaClass currentVersion)
{
// Dont't report method problems when gender has changed, as
// really the whole API is a pile of crap then - let GenderChange check
// do it's job, and that's it
if (compatBaseline.isInterface() ^ currentVersion.isInterface())
{
return;
}
// The main problem here is to figure out which old method corresponds to which new method.
// Methods that are named differently are trated as unrelated
// For Methods that differ only in their parameter list we build a similarity table, i.e.
// for new method i and old method j we have number that charaterizes how similar
// the method signatures are (0 means equal, higher number means more different)
Map bNameToMethod = buildNameToMethodMap(compatBaseline);
Map cNameToMethod = buildNameToMethodMap(currentVersion);
checkAddedOrRemoved(bNameToMethod, cNameToMethod, compatBaseline, currentVersion);
// now the key sets of the two maps are equal,
// we only have collections of methods that have the same name
// for each name analyse the differences
for (Iterator it = bNameToMethod.keySet().iterator(); it.hasNext();)
{
String name = (String) it.next();
List baselineMethods = (List) bNameToMethod.get(name);
List currentMethods = (List) cNameToMethod.get(name);
while (baselineMethods.size() * currentMethods.size() > 0)
{
int[][] similarityTable = buildSimilarityTable(baselineMethods, currentMethods);
int min = Integer.MAX_VALUE;
int iMin = baselineMethods.size();
int jMin = currentMethods.size();
for (int i = 0; i < baselineMethods.size(); i++)
{
for (int j = 0; j < currentMethods.size(); j++)
{
final int tableEntry = similarityTable[i][j];
if (tableEntry < min)
{
min = tableEntry;
iMin = i;
jMin = j;
}
}
}
Method iMethod = (Method) baselineMethods.remove(iMin);
Method jMethod = (Method) currentMethods.remove(jMin);
check(compatBaseline, iMethod, jMethod);
}
}
}
private int[][] buildSimilarityTable(List baselineMethods, List currentMethods)
{
int[][] similarityTable = new int[baselineMethods.size()][currentMethods.size()];
for (int i = 0; i < baselineMethods.size(); i++)
{
for (int j = 0; j < currentMethods.size(); j++)
{
final Method iMethod = (Method) baselineMethods.get(i);
final Method jMethod = (Method) currentMethods.get(j);
similarityTable[i][j] = distance(iMethod, jMethod);
}
}
return similarityTable;
}
private int distance(Method m1, Method m2)
{
final Type[] m1Args = m1.getArgumentTypes();
final Type[] m2Args = m2.getArgumentTypes();
if (m1Args.length != m2Args.length)
{
return 1000 * Math.abs(m1Args.length - m2Args.length);
}
int retVal = 0;
for (int i = 0; i < m1Args.length; i++)
{
if (!m1Args[i].toString().equals(m2Args[i].toString()))
{
retVal += 1;
}
}
return retVal;
}
/**
* Checks for added or removed methods, modifies the argument maps so their key sets are equal.
*/
private void checkAddedOrRemoved(
Map bNameToMethod,
Map cNameToMethod,
JavaClass compatBaseline,
JavaClass currentVersion)
{
// create copies to avoid concurrent modification exception
Set baselineNames = new TreeSet(bNameToMethod.keySet());
Set currentNames = new TreeSet(cNameToMethod.keySet());
for (Iterator it = baselineNames.iterator(); it.hasNext();)
{
String name = (String) it.next();
if (!currentNames.contains(name))
{
Collection removedMethods = (Collection) bNameToMethod.get(name);
for (Iterator rmIterator = removedMethods.iterator(); rmIterator.hasNext();)
{
Method method = (Method) rmIterator.next();
String methodSignature = getMethodId(compatBaseline, method);
String superClass = findSuperClassWithSignature(methodSignature, currentVersion);
reportMethodRemoved(compatBaseline, method, superClass);
}
bNameToMethod.remove(name);
}
}
for (Iterator it = currentNames.iterator(); it.hasNext();)
{
String name = (String) it.next();
if (!baselineNames.contains(name))
{
Collection addedMethods = (Collection) cNameToMethod.get(name);
for (Iterator addIterator = addedMethods.iterator(); addIterator.hasNext();)
{
Method method = (Method) addIterator.next();
reportMethodAdded(currentVersion, method);
}
cNameToMethod.remove(name);
}
}
}
/**
* Searches the class hierarchy for a method that has a certtain signature.
* @param methodSignature the sig we're looking for
* @param clazz class where search starts
* @return class name of a superclass of clazz, might be null
*/
private String findSuperClassWithSignature(String methodSignature, JavaClass clazz)
{
final JavaClass[] superClasses = clazz.getSuperClasses();
for (int i = 0; i < superClasses.length; i++)
{
JavaClass superClass = superClasses[i];
final Method[] superMethods = superClass.getMethods();
for (int j = 0; j < superMethods.length; j++)
{
Method superMethod = superMethods[j];
final String superMethodSignature = getMethodId(superClass, superMethod);
if (methodSignature.equals(superMethodSignature))
{
return superClass.getClassName();
}
}
}
return null;
}
/**
* Report that a method has been removed from a class.
* @param oldClass the class where the method was available
* @param oldMethod the method that has been removed
* @param superClassName the superclass where the method is now available, might be null
*/
private void reportMethodRemoved(JavaClass oldClass, Method oldMethod, String superClassName)
{
if (superClassName == null)
{
fireDiff("Method '"
+ getMethodId(oldClass, oldMethod)
+ "' has been removed",
Severity.ERROR, oldClass, oldMethod);
}
else
{
fireDiff("Method '"
+ getMethodId(oldClass, oldMethod)
+ "' is now implemented in superclass " + superClassName,
Severity.INFO, oldClass, oldMethod);
}
}
private void reportMethodAdded(JavaClass newClass, Method newMethod)
{
final Severity severity = !newClass.isInterface() && (newClass.isFinal() || !newMethod.isAbstract())
? Severity.INFO
: Severity.ERROR;
fireDiff("Method '"
+ getMethodId(newClass, newMethod)
+ "' has been added",
severity, newClass, newMethod);
}
/**
* Builds a map from a method name to a List of methods.
*/
private Map buildNameToMethodMap(JavaClass clazz)
{
Method[] methods = clazz.getMethods();
Map retVal = new HashMap();
for (int i = 0; i < methods.length; i++)
{
Method method = methods[i];
if (!scopeSelector.isSelected(method))
{
continue;
}
final String name = method.getName();
List set = (List) retVal.get(name);
if (set == null)
{
set = new ArrayList();
retVal.put(name, set);
}
set.add(method);
}
return retVal;
}
private void check(JavaClass compatBaseline, Method baselineMethod, Method currentMethod)
{
checkParameterTypes(compatBaseline, baselineMethod, currentMethod);
checkReturnType(compatBaseline, baselineMethod, currentMethod);
checkDeclaredExceptions(compatBaseline, baselineMethod, currentMethod);
checkDeprecated(compatBaseline, baselineMethod, currentMethod);
}
private void checkParameterTypes(JavaClass compatBaseline, Method baselineMethod, Method currentMethod)
{
Type[] bArgs = baselineMethod.getArgumentTypes();
Type[] cArgs = currentMethod.getArgumentTypes();
if (bArgs.length != cArgs.length)
{
fireDiff("In Method '" + getMethodId(compatBaseline, baselineMethod)
+ "' the number of arguments has changed",
Severity.ERROR, compatBaseline, baselineMethod);
return;
}
//System.out.println("baselineMethod = " + getMethodId(compatBaseline, baselineMethod));
for (int i = 0; i < bArgs.length; i++)
{
Type bArg = bArgs[i];
Type cArg = cArgs[i];
if (bArg.toString().equals(cArg.toString()))
{
continue;
}
// TODO: Check assignability...
fireDiff("Parameter " + (i + 1) + " of '" + getMethodId(compatBaseline, baselineMethod)
+ "' has changed it's type to " + cArg,
Severity.ERROR, compatBaseline, baselineMethod);
}
}
private void checkReturnType(JavaClass compatBaseline, Method baselineMethod, Method currentMethod)
{
Type bReturnType = baselineMethod.getReturnType();
Type cReturnType = currentMethod.getReturnType();
// TODO: Check assignability...
if (!bReturnType.toString().equals(cReturnType.toString()))
{
fireDiff("Return type of Method '" + getMethodId(compatBaseline, baselineMethod)
+ "' has been changed to " + cReturnType,
Severity.ERROR, compatBaseline, baselineMethod);
}
}
private void checkDeclaredExceptions(
JavaClass compatBaseline, Method baselineMethod, Method currentMethod)
{
// TODO
}
private void checkDeprecated(JavaClass compatBaseline, Method baselineMethod, Method currentMethod)
{
boolean bIsDeprecated = isDeprecated(baselineMethod);
boolean cIsDeprecated = isDeprecated(currentMethod);
if (bIsDeprecated && !cIsDeprecated)
{
fireDiff(
"Method '" + getMethodId(compatBaseline, baselineMethod) + "' is no longer deprecated",
Severity.INFO, compatBaseline, baselineMethod);
}
else if (!bIsDeprecated && cIsDeprecated)
{
fireDiff(
"Method '" + getMethodId(compatBaseline, baselineMethod) + "' has been deprecated",
Severity.INFO, compatBaseline, baselineMethod);
}
}
/**
* Creates a human readable String that is similar to the method signature
* and identifies the method within a class.
* @param clazz the container of the method
* @param method the method to identify.
* @return a human readable id, for example "public void print(java.lang.String)"
*/
private String getMethodId(JavaClass clazz, Method method)
{
StringBuffer buf = new StringBuffer();
final String scopeDecl = ScopeSelector.getScopeDecl(method);
if (scopeDecl.length() > 0)
{
buf.append(scopeDecl);
buf.append(" ");
}
String name = method.getName();
if ("<init>".equals(name))
{
final String className = clazz.getClassName();
int idx = className.lastIndexOf('.');
name = className.substring(idx + 1);
}
else
{
buf.append(method.getReturnType());
buf.append(' ');
}
buf.append(name);
buf.append('(');
appendHumanReadableArgTypeList(method, buf);
buf.append(')');
return buf.toString();
}
private void appendHumanReadableArgTypeList(Method method, StringBuffer buf)
{
Type[] argTypes = method.getArgumentTypes();
String argSeparator = "";
for (int i = 0; i < argTypes.length; i++)
{
buf.append(argSeparator);
buf.append(argTypes[i].toString());
argSeparator = ", ";
}
}
private void fireDiff(String report, Severity severity, JavaClass clazz, Method method)
{
final String className = clazz.getClassName();
final ApiDifference diff =
new ApiDifference(report + " in " + className,
severity, className, getMethodId(clazz, method), null);
getApiDiffDispatcher().fireDiff(diff);
}
private boolean isDeprecated(Method method)
{
Attribute[] attrs = method.getAttributes();
for(int i=0; i<attrs.length; ++i)
{
if (attrs[i] instanceof org.apache.bcel.classfile.Deprecated)
{
return true;
}
}
return false;
}
} |
package jmetest.renderer.loader;
import com.jme.app.SimpleGame;
import com.jme.scene.model.XMLparser.JmeBinaryReader;
import com.jme.scene.model.XMLparser.BinaryToXML;
import com.jme.scene.model.XMLparser.Converters.MaxToJme;
import com.jme.scene.Node;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.TextureState;
import com.jme.scene.shape.Box;
import com.jme.math.Vector3f;
import com.jme.math.Quaternion;
import com.jme.math.FastMath;
import com.jme.bounding.BoundingBox;
import com.jme.renderer.ColorRGBA;
import java.io.*;
import java.net.URL;
public class TestMaxJmeWrite extends SimpleGame{
public static void main(String[] args) {
TestMaxJmeWrite app=new TestMaxJmeWrite();
app.setDialogBehaviour(SimpleGame.FIRSTRUN_OR_NOCONFIGFILE_SHOW_PROPS_DIALOG);
app.start();
}
Node globalLoad=null;
protected void simpleInitGame() {
MaxToJme C1=new MaxToJme();
try {
ByteArrayOutputStream BO=new ByteArrayOutputStream();
// URL maxFile=TestMaxJmeWrite.class.getClassLoader().getResource("jmetest/data/model/Character.3DS");
URL maxFile=TestMaxJmeWrite.class.getClassLoader().getResource("jmetest/data/model/tpot.3ds");
// URL maxFile=new File("3dsmodels/tpot.3ds").toURL();
C1.convert(new BufferedInputStream(maxFile.openStream()),BO);
JmeBinaryReader jbr=new JmeBinaryReader();
// jbr.setProperty("texulr",new File("3dsmodels").toURL());
BinaryToXML btx=new BinaryToXML();
StringWriter SW=new StringWriter();
btx.sendBinarytoXML(new ByteArrayInputStream(BO.toByteArray()),SW);
System.out.println(SW);
jbr.setProperty("bound","box");
Node r=jbr.loadBinaryFormat(new ByteArrayInputStream(BO.toByteArray()));
r.setLocalScale(.1f);
if (r.getChild(0).getControllers().size()!=0)
r.getChild(0).getController(0).setSpeed(20);
Quaternion temp=new Quaternion();
temp.fromAngleAxis(FastMath.PI/2,new Vector3f(-1,0,0));
rootNode.setLocalRotation(temp);
rootNode.attachChild(r);
} catch (IOException e) {
System.out.println("Damn exceptions:"+e);
e.printStackTrace();
}
drawAxis();
TextureState ts=display.getRenderer().getTextureState();
ts.setEnabled(true);
rootNode.setRenderState(ts);
}
private void drawAxis() {
Box Xaxis=new Box("axisX",new Vector3f(5,0,0),5f,.1f,.1f);
Xaxis.setModelBound(new BoundingBox());
Xaxis.updateModelBound();
Xaxis.setSolidColor(ColorRGBA.red);
MaterialState red=display.getRenderer().getMaterialState();
red.setEmissive(ColorRGBA.red);
red.setEnabled(true);
Xaxis.setRenderState(red);
Box Yaxis=new Box("axisY",new Vector3f(0,5,0),.1f,5f,.1f);
Yaxis.setModelBound(new BoundingBox());
Yaxis.updateModelBound();
Yaxis.setSolidColor(ColorRGBA.green);
MaterialState green=display.getRenderer().getMaterialState();
green.setEmissive(ColorRGBA.green);
green.setEnabled(true);
Yaxis.setRenderState(green);
Box Zaxis=new Box("axisZ",new Vector3f(0,0,5),.1f,.1f,5f);
Zaxis.setSolidColor(ColorRGBA.blue);
Zaxis.setModelBound(new BoundingBox());
Zaxis.updateModelBound();
MaterialState blue=display.getRenderer().getMaterialState();
blue.setEmissive(ColorRGBA.blue);
blue.setEnabled(true);
Zaxis.setRenderState(blue);
rootNode.attachChild(Xaxis);
rootNode.attachChild(Yaxis);
rootNode.attachChild(Zaxis);
}
} |
package justaway.signinwithtwitter;
import twitter4j.Status;
import twitter4j.URLEntity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
public abstract class BaseFragment extends ListFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MainActivity activity = (MainActivity) getActivity();
ListView listView = getListView();
registerForContextMenu(listView);
// Status()View
TwitterAdapter adapter = new TwitterAdapter(activity,
R.layout.tweet_row);
setListAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
view.showContextMenu();
}
});
}
public void goToTop() {
ListView listView = getListView();
if (listView == null) {
getActivity().finish();
return;
}
listView.setSelection(0);
}
public Boolean isTop() {
ListView listView = getListView();
if (listView == null) {
return false;
}
return listView.getFirstVisiblePosition() == 0 ? true : false;
}
/**
* UserStreamonStatus
*
* @param status
*/
public abstract void add(Row row);
static final int CONTEXT_MENU_REPLY_ID = 1;
static final int CONTEXT_MENU_FAV_ID = 2;
static final int CONTEXT_MENU_FAVRT_ID = 3;
static final int CONTEXT_MENU_RT_ID = 4;
static final int CONTEXT_MENU_QT_ID = 5;
static final int CONTEXT_MENU_LINK_ID = 6;
static final int CONTEXT_MENU_TOFU_ID = 7;
static final int CONTEXT_MENU_DM_ID = 8;
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
ListView listView = (ListView) view;
MainActivity activity = (MainActivity) getActivity();
Row row = (Row) listView.getItemAtPosition(info.position);
activity.setSelectedRow(row);
if (row.isDirectMessage()) {
menu.setHeaderTitle(row.getMessage().getSenderScreenName());
menu.add(0, CONTEXT_MENU_DM_ID, 0, "(DM)");
return;
}
/*
* statusActivity2..
*/
Status status = row.getStatus();
Status retweet = status.getRetweetedStatus();
menu.setHeaderTitle(status.getText());
menu.add(0, CONTEXT_MENU_REPLY_ID, 0, "");
menu.add(0, CONTEXT_MENU_QT_ID, 0, "");
menu.add(0, CONTEXT_MENU_FAV_ID, 0, "");
menu.add(0, CONTEXT_MENU_FAVRT_ID, 0, "RT");
menu.add(0, CONTEXT_MENU_RT_ID, 0, "RT");
// URL
URLEntity[] urls = retweet != null ? retweet.getURLEntities() : status
.getURLEntities();
for (URLEntity url : urls) {
menu.add(0, CONTEXT_MENU_LINK_ID, 0, url.getExpandedURL()
.toString());
}
// URL()
URLEntity[] medias = retweet != null ? retweet.getMediaEntities()
: status.getMediaEntities();
for (URLEntity url : medias) {
menu.add(0, CONTEXT_MENU_LINK_ID, 0, url.getExpandedURL()
.toString());
}
menu.add(0, CONTEXT_MENU_TOFU_ID, 0, "TofuBuster");
}
public boolean onContextItemSelected(MenuItem item) {
MainActivity activity = (MainActivity) getActivity();
Row row = activity.getSelectedRow();
Status status = row.getStatus();
Intent intent;
switch (item.getItemId()) {
case CONTEXT_MENU_REPLY_ID:
intent = new Intent(activity, PostActivity.class);
String text = "@" + status.getUser().getScreenName() + " ";
intent.putExtra("status", text);
intent.putExtra("selection", text.length());
intent.putExtra("inReplyToStatusId", status.getId());
startActivity(intent);
return true;
case CONTEXT_MENU_QT_ID:
intent = new Intent(activity, PostActivity.class);
intent.putExtra("status",
" https://twitter.com/" + status.getUser().getScreenName()
+ "/status/" + String.valueOf(status.getId()));
intent.putExtra("inReplyToStatusId", status.getId());
startActivity(intent);
return true;
case CONTEXT_MENU_DM_ID:
String msg = "D " + row.getMessage().getSenderScreenName() + " ";
intent = new Intent(activity, PostActivity.class);
intent.putExtra("status", msg);
intent.putExtra("selection", msg.length());
startActivity(intent);
return true;
case CONTEXT_MENU_RT_ID:
activity.doRetweet(status.getId());
return true;
case CONTEXT_MENU_FAV_ID:
activity.doFavorite(status.getId());
return true;
case CONTEXT_MENU_FAVRT_ID:
activity.doFavorite(status.getId());
activity.doRetweet(status.getId());
return true;
case CONTEXT_MENU_LINK_ID:
/**
* Intent
*/
// WebView
WebView webView = new WebView(activity);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setAllowFileAccess(false); // deny file://
webView.getSettings().setJavaScriptEnabled(false); // deny JavaScript
webView.getSettings().setCacheMode(
WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setBuiltInZoomControls(true);
// loadUrl
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
handler.cancel(); // deny ssl error
}
});
final String url = item.getTitle().toString();
webView.loadUrl(url);
Dialog dialog = new Dialog(activity);
LinearLayout l = new LinearLayout(activity);
l.setOrientation(LinearLayout.VERTICAL);
Button button = new Button(activity);
button.setText("");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
});
l.addView(button);
l.addView(webView);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(l);
DisplayMetrics metrics = getResources().getDisplayMetrics();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.width = (int) (metrics.widthPixels * 1);
lp.height = (int) (metrics.heightPixels * 0.8);
dialog.getWindow().setAttributes(lp);
dialog.getWindow().setGravity(Gravity.BOTTOM);
dialog.show();
return true;
case CONTEXT_MENU_TOFU_ID:
try {
intent = new Intent(
"com.product.kanzmrsw.tofubuster.ACTION_SHOW_TEXT");
intent.putExtra(Intent.EXTRA_TEXT, status.getText());
intent.putExtra(Intent.EXTRA_SUBJECT, "Justaway");
intent.putExtra("isCopyEnabled", true);
startActivity(intent); // TofuBusterstartActivity
} catch (Exception e) {
intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("https://market.android.com/details?id=com.product.kanzmrsw.tofubuster"));
startActivity(intent);
}
return true;
default:
return super.onContextItemSelected(item);
}
}
} |
package org.jfree.chart.axis;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.text.TextAnchor;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.RectangleEdge;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.category.CategoryDataset;
/**
* A specialised category axis that can display sub-categories.
*/
public class SubCategoryAxis extends CategoryAxis
implements Cloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -1279463299793228344L;
/** Storage for the sub-categories (these need to be set manually). */
private List subCategories;
/** The font for the sub-category labels. */
private Font subLabelFont = new Font("SansSerif", Font.PLAIN, 10);
/** The paint for the sub-category labels. */
private transient Paint subLabelPaint = Color.black;
/**
* Creates a new axis.
*
* @param label the axis label.
*/
public SubCategoryAxis(String label) {
super(label);
this.subCategories = new java.util.ArrayList();
}
/**
* Adds a sub-category to the axis and sends an {@link AxisChangeEvent} to
* all registered listeners.
*
* @param subCategory the sub-category (<code>null</code> not permitted).
*/
public void addSubCategory(Comparable subCategory) {
if (subCategory == null) {
throw new IllegalArgumentException("Null 'subcategory' axis.");
}
this.subCategories.add(subCategory);
notifyListeners(new AxisChangeEvent(this));
}
/**
* Returns the font used to display the sub-category labels.
*
* @return The font (never <code>null</code>).
*
* @see #setSubLabelFont(Font)
*/
public Font getSubLabelFont() {
return this.subLabelFont;
}
/**
* Sets the font used to display the sub-category labels and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getSubLabelFont()
*/
public void setSubLabelFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.subLabelFont = font;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Returns the paint used to display the sub-category labels.
*
* @return The paint (never <code>null</code>).
*
* @see #setSubLabelPaint(Paint)
*/
public Paint getSubLabelPaint() {
return this.subLabelPaint;
}
/**
* Sets the paint used to display the sub-category labels and sends an
* {@link AxisChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getSubLabelPaint()
*/
public void setSubLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.subLabelPaint = paint;
notifyListeners(new AxisChangeEvent(this));
}
/**
* Estimates the space required for the axis, given a specific drawing area.
*
* @param g2 the graphics device (used to obtain font information).
* @param plot the plot that the axis belongs to.
* @param plotArea the area within which the axis should be drawn.
* @param edge the axis location (top or bottom).
* @param space the space already reserved.
*
* @return The space required to draw the axis.
*/
public AxisSpace reserveSpace(Graphics2D g2, Plot plot,
Rectangle2D plotArea,
RectangleEdge edge, AxisSpace space) {
// create a new space object if one wasn't supplied...
if (space == null) {
space = new AxisSpace();
}
// if the axis is not visible, no additional space is required...
if (!isVisible()) {
return space;
}
space = super.reserveSpace(g2, plot, plotArea, edge, space);
double maxdim = getMaxDim(g2, edge);
if (RectangleEdge.isTopOrBottom(edge)) {
space.add(maxdim, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
space.add(maxdim, edge);
}
return space;
}
/**
* Returns the maximum of the relevant dimension (height or width) of the
* subcategory labels.
*
* @param g2 the graphics device.
* @param edge the edge.
*
* @return The maximum dimension.
*/
private double getMaxDim(Graphics2D g2, RectangleEdge edge) {
double result = 0.0;
g2.setFont(this.subLabelFont);
FontMetrics fm = g2.getFontMetrics();
Iterator iterator = this.subCategories.iterator();
while (iterator.hasNext()) {
Comparable subcategory = (Comparable) iterator.next();
String label = subcategory.toString();
Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
double dim = 0.0;
if (RectangleEdge.isLeftOrRight(edge)) {
dim = bounds.getWidth();
}
else { // must be top or bottom
dim = bounds.getHeight();
}
result = Math.max(result, dim);
}
return result;
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location.
* @param plotArea the area within which the axis should be drawn
* (<code>null</code> not permitted).
* @param dataArea the area within which the plot is being drawn
* (<code>null</code> not permitted).
* @param edge the location of the axis (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
public AxisState draw(Graphics2D g2,
double cursor,
Rectangle2D plotArea,
Rectangle2D dataArea,
RectangleEdge edge,
PlotRenderingInfo plotState) {
// if the axis is not visible, don't draw it...
if (!isVisible()) {
return new AxisState(cursor);
}
if (isAxisLineVisible()) {
drawAxisLine(g2, cursor, dataArea, edge);
}
// draw the category labels and axis label
AxisState state = new AxisState(cursor);
state = drawSubCategoryLabels(g2, plotArea, dataArea, edge, state,
plotState);
state = drawCategoryLabels(g2, plotArea, dataArea, edge, state,
plotState);
state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state,
plotState);
return state;
}
/**
* Draws the category labels and returns the updated axis state.
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param plotArea the plot area (<code>null</code> not permitted).
* @param dataArea the area inside the axes (<code>null</code> not
* permitted).
* @param edge the axis location (<code>null</code> not permitted).
* @param state the axis state (<code>null</code> not permitted).
* @param plotState collects information about the plot (<code>null</code>
* permitted).
*
* @return The updated axis state (never <code>null</code>).
*/
protected AxisState drawSubCategoryLabels(Graphics2D g2,
Rectangle2D plotArea,
Rectangle2D dataArea,
RectangleEdge edge,
AxisState state,
PlotRenderingInfo plotState) {
if (state == null) {
throw new IllegalArgumentException("Null 'state' argument.");
}
g2.setFont(this.subLabelFont);
g2.setPaint(this.subLabelPaint);
CategoryPlot plot = (CategoryPlot) getPlot();
int categoryCount = 0;
CategoryDataset dataset = plot.getDataset();
if (dataset != null) {
categoryCount = dataset.getColumnCount();
}
double maxdim = getMaxDim(g2, edge);
for (int categoryIndex = 0; categoryIndex < categoryCount;
categoryIndex++) {
double x0 = 0.0;
double x1 = 0.0;
double y0 = 0.0;
double y1 = 0.0;
if (edge == RectangleEdge.TOP) {
x0 = getCategoryStart(categoryIndex, categoryCount, dataArea,
edge);
x1 = getCategoryEnd(categoryIndex, categoryCount, dataArea,
edge);
y1 = state.getCursor();
y0 = y1 - maxdim;
}
else if (edge == RectangleEdge.BOTTOM) {
x0 = getCategoryStart(categoryIndex, categoryCount, dataArea,
edge);
x1 = getCategoryEnd(categoryIndex, categoryCount, dataArea,
edge);
y0 = state.getCursor();
y1 = y0 + maxdim;
}
else if (edge == RectangleEdge.LEFT) {
y0 = getCategoryStart(categoryIndex, categoryCount, dataArea,
edge);
y1 = getCategoryEnd(categoryIndex, categoryCount, dataArea,
edge);
x1 = state.getCursor();
x0 = x1 - maxdim;
}
else if (edge == RectangleEdge.RIGHT) {
y0 = getCategoryStart(categoryIndex, categoryCount, dataArea,
edge);
y1 = getCategoryEnd(categoryIndex, categoryCount, dataArea,
edge);
x0 = state.getCursor();
x1 = x0 + maxdim;
}
Rectangle2D area = new Rectangle2D.Double(x0, y0, (x1 - x0),
(y1 - y0));
int subCategoryCount = this.subCategories.size();
float width = (float) ((x1 - x0) / subCategoryCount);
float height = (float) ((y1 - y0) / subCategoryCount);
float xx = 0.0f;
float yy = 0.0f;
for (int i = 0; i < subCategoryCount; i++) {
if (RectangleEdge.isTopOrBottom(edge)) {
xx = (float) (x0 + (i + 0.5) * width);
yy = (float) area.getCenterY();
}
else {
xx = (float) area.getCenterX();
yy = (float) (y0 + (i + 0.5) * height);
}
String label = this.subCategories.get(i).toString();
TextUtilities.drawRotatedString(label, g2, xx, yy,
TextAnchor.CENTER, 0.0, TextAnchor.CENTER);
}
}
if (edge.equals(RectangleEdge.TOP)) {
double h = maxdim;
state.cursorUp(h);
}
else if (edge.equals(RectangleEdge.BOTTOM)) {
double h = maxdim;
state.cursorDown(h);
}
else if (edge == RectangleEdge.LEFT) {
double w = maxdim;
state.cursorLeft(w);
}
else if (edge == RectangleEdge.RIGHT) {
double w = maxdim;
state.cursorRight(w);
}
return state;
}
/**
* Tests the axis for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof SubCategoryAxis && super.equals(obj)) {
SubCategoryAxis axis = (SubCategoryAxis) obj;
if (!this.subCategories.equals(axis.subCategories)) {
return false;
}
if (!this.subLabelFont.equals(axis.subLabelFont)) {
return false;
}
if (!this.subLabelPaint.equals(axis.subLabelPaint)) {
return false;
}
return true;
}
return false;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.subLabelPaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.subLabelPaint = SerialUtilities.readPaint(stream);
}
} |
package hex.tree.gbm;
import hex.*;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import water.*;
import water.exceptions.H2OModelBuilderIllegalArgumentException;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.RebalanceDataSet;
import water.fvec.Vec;
import water.util.Log;
import water.util.MathUtils;
import water.util.Pair;
import water.util.Triple;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class GBMTest extends TestUtil {
@BeforeClass public static void stall() { stall_till_cloudsize(1); }
private abstract class PrepData { abstract int prep(Frame fr); }
static final String ignored_aircols[] = new String[] { "DepTime", "ArrTime", "AirTime", "ArrDelay", "DepDelay", "TaxiIn", "TaxiOut", "Cancelled", "CancellationCode", "Diverted", "CarrierDelay", "WeatherDelay", "NASDelay", "SecurityDelay", "LateAircraftDelay", "IsDepDelayed"};
@Test public void testGBMRegressionGaussian() {
GBMModel gbm = null;
Frame fr = null, fr2 = null;
try {
fr = parse_test_file("./smalldata/gbm_test/Mfgdata_gaussian_GBM_testing.csv");
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = fr._key;
parms._distribution = Distribution.Family.gaussian;
parms._response_column = fr._names[1]; // Row in col 0, dependent in col 1, predictor in col 2
parms._ntrees = 1;
parms._max_depth = 1;
parms._min_rows = 1;
parms._nbins = 20;
// Drop ColV2 0 (row), keep 1 (response), keep col 2 (only predictor), drop remaining cols
String[] xcols = parms._ignored_columns = new String[fr.numCols()-2];
xcols[0] = fr._names[0];
System.arraycopy(fr._names,3,xcols,1,fr.numCols()-3);
parms._learn_rate = 1.0f;
parms._score_each_iteration=true;
GBM job = new GBM(parms);
gbm = job.trainModel().get();
Assert.assertTrue(job.isStopped()); //HEX-1817
// Done building model; produce a score column with predictions
fr2 = gbm.score(fr);
//job.response() can be used in place of fr.vecs()[1] but it has been rebalanced
double sq_err = new MathUtils.SquareError().doAll(fr.vecs()[1],fr2.vecs()[0])._sum;
double mse = sq_err/fr2.numRows();
assertEquals(79152.12337641386,mse,0.1);
assertEquals(79152.12337641386,gbm._output._scored_train[1]._mse,0.1);
assertEquals(79152.12337641386,gbm._output._scored_train[1]._mean_residual_deviance,0.1);
} finally {
if( fr != null ) fr .remove();
if( fr2 != null ) fr2.remove();
if( gbm != null ) gbm.remove();
}
}
@Test public void testBasicGBM() {
// Regression tests
basicGBM("./smalldata/junit/cars.csv",
new PrepData() { int prep(Frame fr ) {fr.remove("name").remove(); return ~fr.find("economy (mpg)"); }},
false, Distribution.Family.gaussian);
basicGBM("./smalldata/junit/cars.csv",
new PrepData() { int prep(Frame fr ) {fr.remove("name").remove(); return ~fr.find("economy (mpg)"); }},
false, Distribution.Family.poisson);
basicGBM("./smalldata/junit/cars.csv",
new PrepData() { int prep(Frame fr ) {fr.remove("name").remove(); return ~fr.find("economy (mpg)"); }},
false, Distribution.Family.gamma);
basicGBM("./smalldata/junit/cars.csv",
new PrepData() { int prep(Frame fr ) {fr.remove("name").remove(); return ~fr.find("economy (mpg)"); }},
false, Distribution.Family.tweedie);
// Classification tests
basicGBM("./smalldata/junit/test_tree.csv",
new PrepData() { int prep(Frame fr) { return 1; }
},
false, Distribution.Family.multinomial);
basicGBM("./smalldata/junit/test_tree_minmax.csv",
new PrepData() { int prep(Frame fr) { return fr.find("response"); }
},
false, Distribution.Family.bernoulli);
basicGBM("./smalldata/logreg/prostate.csv",
new PrepData() { int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("CAPSULE"); }
},
false, Distribution.Family.bernoulli);
basicGBM("./smalldata/logreg/prostate.csv",
new PrepData() { int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("CAPSULE"); }
},
false, Distribution.Family.multinomial);
basicGBM("./smalldata/junit/cars.csv",
new PrepData() { int prep(Frame fr) { fr.remove("name").remove(); return fr.find("cylinders"); }
},
false, Distribution.Family.multinomial);
basicGBM("./smalldata/gbm_test/alphabet_cattest.csv",
new PrepData() { int prep(Frame fr) { return fr.find("y"); }
},
false, Distribution.Family.bernoulli);
basicGBM("./smalldata/airlines/allyears2k_headers.zip",
new PrepData() { int prep(Frame fr) {
for( String s : ignored_aircols ) fr.remove(s).remove();
return fr.find("IsArrDelayed"); }
},
false, Distribution.Family.bernoulli);
// // Bigger Tests
// basicGBM("../datasets/98LRN.CSV",
// new PrepData() { int prep(Frame fr ) {
// fr.remove("CONTROLN").remove();
// fr.remove("TARGET_D").remove();
// return fr.find("TARGET_B"); }});
// basicGBM("../datasets/UCI/UCI-large/covtype/covtype.data",
// new PrepData() { int prep(Frame fr) { return fr.numCols()-1; } });
}
@Test public void testBasicGBMFamily() {
Scope.enter();
// Classification with Bernoulli family
basicGBM("./smalldata/logreg/prostate.csv",
new PrepData() {
int prep(Frame fr) {
fr.remove("ID").remove(); // Remove not-predictive ID
int ci = fr.find("RACE"); // Change RACE to categorical
Scope.track(fr.replace(ci,fr.vecs()[ci].toCategoricalVec()));
return fr.find("CAPSULE"); // Prostate: predict on CAPSULE
}
}, false, Distribution.Family.bernoulli);
Scope.exit();
}
public GBMModel.GBMOutput basicGBM(String fname, PrepData prep, boolean validation, Distribution.Family family) {
GBMModel gbm = null;
Frame fr = null, fr2= null, vfr=null;
try {
Scope.enter();
fr = parse_test_file(fname);
int idx = prep.prep(fr); // hack frame per-test
if (family == Distribution.Family.bernoulli || family == Distribution.Family.multinomial) {
if (!fr.vecs()[idx].isCategorical()) {
Scope.track(fr.replace(idx, fr.vecs()[idx].toCategoricalVec()));
}
}
DKV.put(fr); // Update frame after hacking it
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
if( idx < 0 ) idx = ~idx;
parms._train = fr._key;
parms._response_column = fr._names[idx];
parms._ntrees = 4;
parms._distribution = family;
parms._max_depth = 4;
parms._min_rows = 1;
parms._nbins = 50;
parms._learn_rate = .2f;
parms._score_each_iteration = true;
if( validation ) { // Make a validation frame thats a clone of the training data
vfr = new Frame(fr);
DKV.put(vfr);
parms._valid = vfr._key;
}
GBM job = new GBM(parms);
gbm = job.trainModel().get();
// Done building model; produce a score column with predictions
fr2 = gbm.score(fr);
// Build a POJO, validate same results
Assert.assertTrue(gbm.testJavaScoring(fr,fr2,1e-15));
Assert.assertTrue(job.isStopped()); //HEX-1817
return gbm._output;
} finally {
if( fr != null ) fr .remove();
if( fr2 != null ) fr2.remove();
if( vfr != null ) vfr.remove();
if( gbm != null ) gbm.delete();
Scope.exit();
}
}
// Test-on-Train. Slow test, needed to build a good model.
@Test public void testGBMTrainTest() {
GBMModel gbm = null;
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
try {
Scope.enter();
parms._valid = parse_test_file("smalldata/gbm_test/ecology_eval.csv")._key;
Frame train = parse_test_file("smalldata/gbm_test/ecology_model.csv");
train.remove("Site").remove(); // Remove unique ID
int ci = train.find("Angaus"); // Convert response to categorical
Scope.track(train.replace(ci, train.vecs()[ci].toCategoricalVec()));
DKV.put(train); // Update frame after hacking it
parms._train = train._key;
parms._response_column = "Angaus"; // Train on the outcome
parms._ntrees = 5;
parms._max_depth = 5;
parms._min_rows = 10;
parms._nbins = 100;
parms._learn_rate = .2f;
parms._distribution = Distribution.Family.multinomial;
gbm = new GBM(parms).trainModel().get();
hex.ModelMetricsBinomial mm = hex.ModelMetricsBinomial.getFromDKV(gbm,parms.valid());
double auc = mm._auc._auc;
Assert.assertTrue(0.82 <= auc && auc < 0.86); // Sanely good model
double[][] cm = mm._auc.defaultCM();
Assert.assertArrayEquals(ard(ard(317, 76), ard(31, 76)), cm);
} finally {
parms._train.remove();
parms._valid.remove();
if( gbm != null ) gbm.delete();
Scope.exit();
}
}
// Predict with no actual, after training
@Test public void testGBMPredict() {
GBMModel gbm = null;
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
Frame pred=null, res=null;
Scope.enter();
try {
Frame train = parse_test_file("smalldata/gbm_test/ecology_model.csv");
train.remove("Site").remove(); // Remove unique ID
int ci = train.find("Angaus");
Scope.track(train.replace(ci, train.vecs()[ci].toCategoricalVec())); // Convert response 'Angaus' to categorical
DKV.put(train); // Update frame after hacking it
parms._train = train._key;
parms._response_column = "Angaus"; // Train on the outcome
parms._distribution = Distribution.Family.multinomial;
gbm = new GBM(parms).trainModel().get();
pred = parse_test_file("smalldata/gbm_test/ecology_eval.csv" );
pred.remove("Angaus").remove(); // No response column during scoring
res = gbm.score(pred);
// Build a POJO, validate same results
Assert.assertTrue(gbm.testJavaScoring(pred, res, 1e-15));
} finally {
parms._train.remove();
if( gbm != null ) gbm .delete();
if( pred != null ) pred.remove();
if( res != null ) res .remove();
Scope.exit();
}
}
// Adapt a trained model to a test dataset with different categoricals
@Test public void testModelAdaptMultinomial() {
GBMModel gbm = null;
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
try {
Scope.enter();
Frame v;
parms._train = ( parse_test_file("smalldata/junit/mixcat_train.csv"))._key;
parms._valid = (v=parse_test_file("smalldata/junit/mixcat_test.csv" ))._key;
parms._response_column = "Response"; // Train on the outcome
parms._ntrees = 1; // Build a CART tree - 1 tree, full learn rate, down to 1 row
parms._learn_rate = 1.0f;
parms._min_rows = 1;
parms._distribution = Distribution.Family.multinomial;
gbm = new GBM(parms).trainModel().get();
Frame res = gbm.score(v);
int[] ps = new int[(int)v.numRows()];
Vec.Reader vr = res.vecs()[0].new Reader();
for( int i=0; i<ps.length; i++ ) ps[i] = (int)vr.at8(i);
// Expected predictions are X,X,Y,Y,X,Y,Z,X,Y
// Never predicts W, the extra class in the test set.
// Badly predicts Z because 1 tree does not pick up that feature#2 can also
// be used to predict Z, and instead relies on factor C which does not appear
// in the test set.
Assert.assertArrayEquals("", ps, new int[]{1, 1, 2, 2, 1, 2, 3, 1, 2});
hex.ModelMetricsMultinomial mm = hex.ModelMetricsMultinomial.getFromDKV(gbm,parms.valid());
Assert.assertTrue(mm.r2() > 0.5);
// Build a POJO, validate same results
Assert.assertTrue(gbm.testJavaScoring(v,res,1e-15));
res.remove();
} finally {
parms._train.remove();
parms._valid.remove();
if( gbm != null ) gbm.delete();
Scope.exit();
}
}
// A test of locking the input dataset during model building.
@Test public void testModelLock() {
GBM gbm=null;
Frame fr=null;
Scope.enter();
try {
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
fr = parse_test_file("smalldata/gbm_test/ecology_model.csv");
fr.remove("Site").remove(); // Remove unique ID
int ci = fr.find("Angaus");
Scope.track(fr.replace(ci, fr.vecs()[ci].toCategoricalVec())); // Convert response 'Angaus' to categorical
DKV.put(fr); // Update after hacking
parms._train = fr._key;
parms._response_column = "Angaus"; // Train on the outcome
parms._ntrees = 10;
parms._max_depth = 10;
parms._min_rows = 1;
parms._nbins = 20;
parms._learn_rate = .2f;
parms._distribution = Distribution.Family.multinomial;
gbm = new GBM(parms);
gbm.trainModel();
try { Thread.sleep(100); } catch( Exception ignore ) { }
try {
Log.info("Trying illegal frame delete.");
fr.delete(); // Attempted delete while model-build is active
Assert.fail("Should toss IAE instead of reaching here");
} catch( IllegalArgumentException ignore ) {
} catch( DException.DistributedException de ) {
assertTrue( de.getMessage().contains("java.lang.IllegalArgumentException") );
}
Log.info("Getting model");
GBMModel model = gbm.get();
Assert.assertTrue(gbm.isStopped()); //HEX-1817
if( model != null ) model.delete();
} finally {
if( fr != null ) fr .remove();
Scope.exit();
}
}
// MSE generated by GBM with/without validation dataset should be same
@Test public void testModelScoreKeeperEqualityOnProstateBernoulli() {
final PrepData prostatePrep = new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("CAPSULE"); } };
ScoreKeeper[] scoredWithoutVal = basicGBM("./smalldata/logreg/prostate.csv", prostatePrep, false, Distribution.Family.bernoulli)._scored_train;
ScoreKeeper[] scoredWithVal = basicGBM("./smalldata/logreg/prostate.csv", prostatePrep, true , Distribution.Family.bernoulli)._scored_valid;
Assert.assertArrayEquals("GBM has to report same list of MSEs for run without/with validation dataset (which is equal to training data)", scoredWithoutVal, scoredWithVal);
}
@Test public void testModelScoreKeeperEqualityOnProstateGaussian() {
final PrepData prostatePrep = new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return ~fr.find("CAPSULE"); } };
ScoreKeeper[] scoredWithoutVal = basicGBM("./smalldata/logreg/prostate.csv", prostatePrep, false, Distribution.Family.gaussian)._scored_train;
ScoreKeeper[] scoredWithVal = basicGBM("./smalldata/logreg/prostate.csv", prostatePrep, true , Distribution.Family.gaussian)._scored_valid;
Assert.assertArrayEquals("GBM has to report same list of MSEs for run without/with validation dataset (which is equal to training data)", scoredWithoutVal, scoredWithVal);
}
@Test public void testModelScoreKeeperEqualityOnTitanicBernoulli() {
final PrepData titanicPrep = new PrepData() { @Override int prep(Frame fr) { return fr.find("survived"); } };
ScoreKeeper[] scoredWithoutVal = basicGBM("./smalldata/junit/titanic_alt.csv", titanicPrep, false, Distribution.Family.bernoulli)._scored_train;
ScoreKeeper[] scoredWithVal = basicGBM("./smalldata/junit/titanic_alt.csv", titanicPrep, true , Distribution.Family.bernoulli)._scored_valid;
Assert.assertArrayEquals("GBM has to report same list of MSEs for run without/with validation dataset (which is equal to training data)", scoredWithoutVal, scoredWithVal);
}
@Test public void testModelScoreKeeperEqualityOnTitanicMultinomial() {
final PrepData titanicPrep = new PrepData() { @Override int prep(Frame fr) { return fr.find("survived"); } };
ScoreKeeper[] scoredWithoutVal = basicGBM("./smalldata/junit/titanic_alt.csv", titanicPrep, false, Distribution.Family.multinomial)._scored_train;
ScoreKeeper[] scoredWithVal = basicGBM("./smalldata/junit/titanic_alt.csv", titanicPrep, true , Distribution.Family.multinomial)._scored_valid;
Assert.assertArrayEquals("GBM has to report same list of MSEs for run without/with validation dataset (which is equal to training data)", scoredWithoutVal, scoredWithVal);
}
@Test public void testModelScoreKeeperEqualityOnProstateMultinomial() {
final PrepData prostatePrep = new PrepData() { @Override int prep(Frame fr) { fr.remove("ID").remove(); return fr.find("RACE"); } };
ScoreKeeper[] scoredWithoutVal = basicGBM("./smalldata/logreg/prostate.csv", prostatePrep, false, Distribution.Family.multinomial)._scored_train;
ScoreKeeper[] scoredWithVal = basicGBM("./smalldata/logreg/prostate.csv", prostatePrep, true , Distribution.Family.multinomial)._scored_valid;
// FIXME: 0-tree scores don't match between WithoutVal and WithVal for multinomial - because we compute initial_MSE(_response,_vresponse)) in SharedTree.java
scoredWithoutVal = Arrays.copyOfRange(scoredWithoutVal, 1, scoredWithoutVal.length);
scoredWithVal = Arrays.copyOfRange(scoredWithVal, 1, scoredWithVal.length);
Assert.assertArrayEquals("GBM has to report same list of MSEs for run without/with validation dataset (which is equal to training data)", scoredWithoutVal, scoredWithVal);
}
@Test public void testBigCat() {
final PrepData prep = new PrepData() { @Override int prep(Frame fr) { return fr.find("y"); } };
basicGBM("./smalldata/gbm_test/50_cattest_test.csv" , prep, false, Distribution.Family.bernoulli);
basicGBM("./smalldata/gbm_test/50_cattest_train.csv", prep, false, Distribution.Family.bernoulli);
basicGBM("./smalldata/gbm_test/swpreds_1000x3.csv", prep, false, Distribution.Family.bernoulli);
}
// Test uses big data and is too slow for a pre-push
@Test @Ignore public void testKDDTrees() {
Frame tfr=null, vfr=null;
String[] cols = new String[] {"DOB", "LASTGIFT", "TARGET_D"};
try {
// Load data, hack frames
Frame inF1 = parse_test_file("bigdata/laptop/usecases/cup98LRN_z.csv");
Frame inF2 = parse_test_file("bigdata/laptop/usecases/cup98VAL_z.csv");
tfr = inF1.subframe(cols); // Just the columns to train on
vfr = inF2.subframe(cols);
inF1.remove(cols).remove(); // Toss all the rest away
inF2.remove(cols).remove();
tfr.replace(0, tfr.vec("DOB").toCategoricalVec()); // Convert 'DOB' to categorical
vfr.replace(0, vfr.vec("DOB").toCategoricalVec());
DKV.put(tfr);
DKV.put(vfr);
// Same parms for all
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._valid = vfr._key;
parms._response_column = "TARGET_D";
parms._ntrees = 3;
parms._distribution = Distribution.Family.gaussian;
// Build a first model; all remaining models should be equal
GBM job1 = new GBM(parms);
GBMModel gbm1 = job1.trainModel().get();
// Validation MSE should be equal
ScoreKeeper[] firstScored = gbm1._output._scored_valid;
// Build 10 more models, checking for equality
for( int i=0; i<10; i++ ) {
GBM job2 = new GBM(parms);
GBMModel gbm2 = job2.trainModel().get();
ScoreKeeper[] secondScored = gbm2._output._scored_valid;
// Check that MSE's from both models are equal
int j;
for( j=0; j<firstScored.length; j++ )
if (firstScored[j] != secondScored[j])
break; // Not Equals Enough
// Report on unequal
if( j < firstScored.length ) {
System.out.println("=== =============== ===");
System.out.println("=== ORIGINAL MODEL ===");
for( int t=0; t<parms._ntrees; t++ )
System.out.println(gbm1._output.toStringTree(t,0));
System.out.println("=== DIFFERENT MODEL ===");
for( int t=0; t<parms._ntrees; t++ )
System.out.println(gbm2._output.toStringTree(t,0));
System.out.println("=== =============== ===");
Assert.assertArrayEquals("GBM should have the exact same MSEs for identical parameters", firstScored, secondScored);
}
gbm2.delete();
}
gbm1.delete();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
}
}
// Test uses big data and is too slow for a pre-push
@Test @Ignore public void testMNIST() {
Frame tfr=null, vfr=null;
Scope.enter();
try {
// Load data, hack frames
tfr = parse_test_file("bigdata/laptop/mnist/train.csv.gz");
Scope.track(tfr.replace(784, tfr.vecs()[784].toCategoricalVec())); // Convert response 'C785' to categorical
DKV.put(tfr);
vfr = parse_test_file("bigdata/laptop/mnist/test.csv.gz");
Scope.track(vfr.replace(784, vfr.vecs()[784].toCategoricalVec())); // Convert response 'C785' to categorical
DKV.put(vfr);
// Same parms for all
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._valid = vfr._key;
parms._response_column = "C785";
parms._ntrees = 2;
parms._max_depth = 4;
parms._distribution = Distribution.Family.multinomial;
// Build a first model; all remaining models should be equal
GBMModel gbm = new GBM(parms).trainModel().get();
Frame pred = gbm.score(vfr);
double sq_err = new MathUtils.SquareError().doAll(vfr.lastVec(),pred.vecs()[0])._sum;
double mse = sq_err/pred.numRows();
assertEquals(3.0199, mse, 1e-15); //same results
gbm.delete();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
Scope.exit();
}
}
// HEXDEV-194: Check reproducibility for the same # of chunks (i.e., same # of nodes) and same parameters
@Test public void testReprodubility() {
Frame tfr=null;
final int N = 5;
double[] mses = new double[N];
Scope.enter();
try {
// Load data, hack frames
tfr = parse_test_file("smalldata/covtype/covtype.20k.data");
// rebalance to 256 chunks
Key dest = Key.make("df.rebalanced.hex");
RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256);
H2O.submitTask(rb);
rb.join();
tfr.delete();
tfr = DKV.get(dest).get();
// Scope.track(tfr.replace(54, tfr.vecs()[54].toCategoricalVec())._key);
// DKV.put(tfr);
for (int i=0; i<N; ++i) {
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "C55";
parms._nbins = 1000;
parms._ntrees = 5;
parms._max_depth = 8;
parms._learn_rate = 0.1f;
parms._min_rows = 10;
// parms._distribution = Family.multinomial;
parms._distribution = Distribution.Family.gaussian;
// Build a first model; all remaining models should be equal
GBMModel gbm = new GBM(parms).trainModel().get();
assertEquals(gbm._output._ntrees, parms._ntrees);
mses[i] = gbm._output._scored_train[gbm._output._scored_train.length-1]._mse;
gbm.delete();
}
} finally{
if (tfr != null) tfr.remove();
}
Scope.exit();
for( double mse : mses ) assertEquals(mse, mses[0], 1e-15);
}
// PUBDEV-557: Test dependency on # nodes (for small number of bins, but fixed number of chunks)
@Test public void testReprodubilityAirline() {
Frame tfr=null;
final int N = 1;
double[] mses = new double[N];
Scope.enter();
try {
// Load data, hack frames
tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
// rebalance to fixed number of chunks
Key dest = Key.make("df.rebalanced.hex");
RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256);
H2O.submitTask(rb);
rb.join();
tfr.delete();
tfr = DKV.get(dest).get();
// Scope.track(tfr.replace(54, tfr.vecs()[54].toCategoricalVec())._key);
// DKV.put(tfr);
for (String s : new String[]{
"DepTime", "ArrTime", "ActualElapsedTime",
"AirTime", "ArrDelay", "DepDelay", "Cancelled",
"CancellationCode", "CarrierDelay", "WeatherDelay",
"NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed"
}) {
tfr.remove(s).remove();
}
DKV.put(tfr);
for (int i=0; i<N; ++i) {
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "IsDepDelayed";
parms._nbins = 10;
parms._nbins_cats = 500;
parms._ntrees = 7;
parms._max_depth = 5;
parms._min_rows = 10;
parms._distribution = Distribution.Family.bernoulli;
parms._balance_classes = true;
parms._seed = 0;
// Build a first model; all remaining models should be equal
GBMModel gbm = new GBM(parms).trainModel().get();
assertEquals(gbm._output._ntrees, parms._ntrees);
mses[i] = gbm._output._scored_train[gbm._output._scored_train.length-1]._mse;
gbm.delete();
}
} finally {
if (tfr != null) tfr.remove();
}
Scope.exit();
for( double mse : mses )
assertEquals(0.2201826446926655, mse, 1e-8); //check for the same result on 1 nodes and 5 nodes (will only work with enough chunks), mse, 1e-8); //check for the same result on 1 nodes and 5 nodes (will only work with enough chunks)
}
@Test public void testReprodubilityAirlineSingleNode() {
Frame tfr=null;
final int N = 1;
double[] mses = new double[N];
Scope.enter();
try {
// Load data, hack frames
tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
// rebalance to fixed number of chunks
Key dest = Key.make("df.rebalanced.hex");
RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, 256);
H2O.submitTask(rb);
rb.join();
tfr.delete();
tfr = DKV.get(dest).get();
// Scope.track(tfr.replace(54, tfr.vecs()[54].toCategoricalVec())._key);
// DKV.put(tfr);
for (String s : new String[]{
"DepTime", "ArrTime", "ActualElapsedTime",
"AirTime", "ArrDelay", "DepDelay", "Cancelled",
"CancellationCode", "CarrierDelay", "WeatherDelay",
"NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed"
}) {
tfr.remove(s).remove();
}
DKV.put(tfr);
for (int i=0; i<N; ++i) {
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "IsDepDelayed";
parms._nbins = 10;
parms._nbins_cats = 500;
parms._ntrees = 7;
parms._max_depth = 5;
parms._min_rows = 10;
parms._distribution = Distribution.Family.bernoulli;
parms._balance_classes = true;
parms._seed = 0;
parms._build_tree_one_node = true;
// Build a first model; all remaining models should be equal
GBMModel gbm = new GBM(parms).trainModel().get();
assertEquals(gbm._output._ntrees, parms._ntrees);
mses[i] = gbm._output._scored_train[gbm._output._scored_train.length-1]._mse;
gbm.delete();
}
} finally {
if (tfr != null) tfr.remove();
}
Scope.exit();
for( double mse : mses )
assertEquals(0.2201826446926655, mse, 1e-8); //check for the same result on 1 nodes and 5 nodes (will only work with enough chunks)
}
// HEXDEV-223
@Test public void testCategorical() {
Frame tfr=null;
final int N = 1;
double[] mses = new double[N];
Scope.enter();
try {
tfr = parse_test_file("smalldata/gbm_test/alphabet_cattest.csv");
Scope.track(tfr.replace(1, tfr.vecs()[1].toCategoricalVec()));
DKV.put(tfr);
for (int i=0; i<N; ++i) {
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "y";
parms._ntrees = 1;
parms._max_depth = 1;
parms._learn_rate = 1;
parms._distribution = Distribution.Family.bernoulli;
// Build a first model; all remaining models should be equal
GBMModel gbm = new GBM(parms).trainModel().get();
assertEquals(gbm._output._ntrees, parms._ntrees);
hex.ModelMetricsBinomial mm = hex.ModelMetricsBinomial.getFromDKV(gbm,parms.train());
double auc = mm._auc._auc;
Assert.assertTrue(1 == auc);
mses[i] = gbm._output._scored_train[gbm._output._scored_train.length-1]._mse;
gbm.delete();
}
} finally{
if (tfr != null) tfr.remove();
}
Scope.exit();
for( double mse : mses ) assertEquals(0.0142093, mse, 1e-6);
}
// Test uses big data and is too slow for a pre-push
@Test @Ignore public void testCUST_A() {
Frame tfr=null, vfr=null, t_pred=null, v_pred=null;
GBMModel gbm=null;
Scope.enter();
try {
// Load data, hack frames
tfr = parse_test_file("./bigdata/covktr.csv");
vfr = parse_test_file("./bigdata/covkts.csv");
int idx = tfr.find("V55");
Scope.track(tfr.replace(idx, tfr.vecs()[idx].toCategoricalVec()));
Scope.track(vfr.replace(idx, vfr.vecs()[idx].toCategoricalVec()));
DKV.put(tfr);
DKV.put(vfr);
// Build model
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._valid = vfr._key;
parms._response_column = "V55";
parms._ntrees = 10;
parms._max_depth = 1;
parms._nbins = 20;
parms._min_rows = 10;
parms._learn_rate = 0.01f;
parms._distribution = Distribution.Family.multinomial;
gbm = new GBM(parms).trainModel().get();
// Report AUC from training
hex.ModelMetricsBinomial tmm = hex.ModelMetricsBinomial.getFromDKV(gbm,tfr);
hex.ModelMetricsBinomial vmm = hex.ModelMetricsBinomial.getFromDKV(gbm,vfr);
double t_auc = tmm._auc._auc;
double v_auc = vmm._auc._auc;
System.out.println("train_AUC= "+t_auc+" , validation_AUC= "+v_auc);
// Report AUC from scoring
t_pred = gbm.score(tfr);
v_pred = gbm.score(vfr);
hex.ModelMetricsBinomial tmm2 = hex.ModelMetricsBinomial.getFromDKV(gbm,tfr);
hex.ModelMetricsBinomial vmm2 = hex.ModelMetricsBinomial.getFromDKV(gbm,vfr);
assert tmm != tmm2;
assert vmm != vmm2;
double t_auc2 = tmm._auc._auc;
double v_auc2 = vmm._auc._auc;
System.out.println("train_AUC2= "+t_auc2+" , validation_AUC2= "+v_auc2);
t_pred.remove();
v_pred.remove();
// Compute the perfect AUC
double t_auc3 = AUC2.perfectAUC(t_pred.vecs()[2], tfr.vec("V55"));
double v_auc3 = AUC2.perfectAUC(v_pred.vecs()[2], vfr.vec("V55"));
System.out.println("train_AUC3= "+t_auc3+" , validation_AUC3= "+v_auc3);
Assert.assertEquals(t_auc3, t_auc , 1e-6);
Assert.assertEquals(t_auc3, t_auc2, 1e-6);
Assert.assertEquals(v_auc3, v_auc , 1e-6);
Assert.assertEquals(v_auc3, v_auc2, 1e-6);
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if( t_pred != null ) t_pred.remove();
if( v_pred != null ) v_pred.remove();
if (gbm != null) gbm.delete();
Scope.exit();
}
}
static double _AUC = 1;
static double _MSE = 0.24850374695598948;
static double _R2 = 0.005985012176042082;
static double _LogLoss = 0.690155;
@Test
public void testNoRowWeights() {
Frame tfr = null, vfr = null;
GBMModel gbm = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/no_weights.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._seed = 0xdecaf;
parms._min_rows = 1;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm = (ModelMetricsBinomial)gbm._output._training_metrics;
assertEquals(_AUC, mm.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
Frame pred = gbm.score(parms.train());
hex.ModelMetricsBinomial mm2 = hex.ModelMetricsBinomial.getFromDKV(gbm, parms.train());
assertEquals(_AUC, mm2.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm2.mse(), 1e-8);
assertEquals(_R2, mm2.r2(), 1e-6);
assertEquals(_LogLoss, mm2.logloss(), 1e-6);
pred.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) gbm.delete();
Scope.exit();
}
}
@Test
public void testRowWeightsOne() {
Frame tfr = null, vfr = null;
Scope.enter();
GBMModel gbm = null;
try {
tfr = parse_test_file("smalldata/junit/weights_all_ones.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._weights_column = "weight";
parms._seed = 0xdecaf;
parms._min_rows = 1;
parms._max_depth = 2;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm = (ModelMetricsBinomial)gbm._output._training_metrics;
assertEquals(_AUC, mm.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
Frame pred = gbm.score(parms.train());
hex.ModelMetricsBinomial mm2 = hex.ModelMetricsBinomial.getFromDKV(gbm, parms.train());
assertEquals(_AUC, mm2.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm2.mse(), 1e-8);
assertEquals(_R2, mm2.r2(), 1e-6);
assertEquals(_LogLoss, mm2.logloss(), 1e-6);
pred.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) gbm.delete();
Scope.exit();
}
}
@Test
public void testRowWeightsTwo() {
Frame tfr = null, vfr = null;
Scope.enter();
GBMModel gbm = null;
try {
tfr = parse_test_file("smalldata/junit/weights_all_twos.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._weights_column = "weight";
parms._seed = 0xdecaf;
parms._min_rows = 2; //Must be adapted to the weights
parms._max_depth = 2;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm = (ModelMetricsBinomial)gbm._output._training_metrics;
assertEquals(_AUC, mm.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
Frame pred = gbm.score(parms.train());
hex.ModelMetricsBinomial mm2 = hex.ModelMetricsBinomial.getFromDKV(gbm, parms.train());
assertEquals(_AUC, mm2.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm2.mse(), 1e-8);
assertEquals(_R2, mm2.r2(), 1e-6);
assertEquals(_LogLoss, mm2.logloss(), 1e-6);
pred.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) gbm.delete();
Scope.exit();
}
}
@Test
public void testRowWeightsTiny() {
Frame tfr = null, vfr = null;
Scope.enter();
GBMModel gbm = null;
try {
tfr = parse_test_file("smalldata/junit/weights_all_tiny.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._weights_column = "weight";
parms._seed = 0xdecaf;
parms._min_rows = 0.01242; //Must be adapted to the weights
parms._max_depth = 2;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm = (ModelMetricsBinomial)gbm._output._training_metrics;
assertEquals(_AUC, mm.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
Frame pred = gbm.score(parms.train());
hex.ModelMetricsBinomial mm2 = hex.ModelMetricsBinomial.getFromDKV(gbm, parms.train());
assertEquals(_AUC, mm2.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm2.mse(), 1e-8);
assertEquals(_R2, mm2.r2(), 1e-6);
assertEquals(_LogLoss, mm2.logloss(), 1e-6);
pred.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) gbm.delete();
Scope.exit();
}
}
@Test
public void testNoRowWeightsShuffled() {
Frame tfr = null, vfr = null;
GBMModel gbm = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/no_weights_shuffled.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._seed = 0xdecaf;
parms._min_rows = 1;
parms._max_depth = 2;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm = (ModelMetricsBinomial)gbm._output._training_metrics;
assertEquals(_AUC, mm.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
Frame pred = gbm.score(parms.train());
hex.ModelMetricsBinomial mm2 = hex.ModelMetricsBinomial.getFromDKV(gbm, parms.train());
assertEquals(_AUC, mm2.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm2.mse(), 1e-8);
assertEquals(_R2, mm2.r2(), 1e-6);
assertEquals(_LogLoss, mm2.logloss(), 1e-6);
pred.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) gbm.delete();
Scope.exit();
}
}
@Test
public void testRowWeights() {
Frame tfr = null, vfr = null;
GBMModel gbm = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/weights.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._weights_column = "weight";
parms._seed = 0xdecaf;
parms._min_rows = 1;
parms._max_depth = 2;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm = (ModelMetricsBinomial)gbm._output._training_metrics;
assertEquals(_AUC, mm.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm.mse(), 1e-8);
assertEquals(_R2, mm.r2(), 1e-6);
assertEquals(_LogLoss, mm.logloss(), 1e-6);
Frame pred = gbm.score(parms.train());
hex.ModelMetricsBinomial mm2 = hex.ModelMetricsBinomial.getFromDKV(gbm, parms.train());
assertEquals(_AUC, mm2.auc_obj()._auc, 1e-8);
assertEquals(_MSE, mm2.mse(), 1e-8);
assertEquals(_R2, mm2.r2(), 1e-6);
assertEquals(_LogLoss, mm2.logloss(), 1e-6);
pred.remove();
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) gbm.delete();
Scope.exit();
}
}
@Test
public void testNFold() {
Frame tfr = null, vfr = null;
GBMModel gbm = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/weights.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._weights_column = "weight";
parms._seed = 123;
parms._min_rows = 1;
parms._max_depth = 2;
parms._nfolds = 2;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm = (ModelMetricsBinomial)gbm._output._cross_validation_metrics;
assertEquals(0.6296296296296297, mm.auc_obj()._auc, 1e-8);
assertEquals(0.28640022521234304, mm.mse(), 1e-8);
assertEquals(-0.145600900849372169, mm.r2(), 1e-6);
assertEquals(0.7674117059335286, mm.logloss(), 1e-6);
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) {
gbm.deleteCrossValidationModels();
gbm.delete();
}
Scope.exit();
}
}
@Test
public void testNfoldsOneVsRest() {
Frame tfr = null;
GBMModel gbm1 = null;
GBMModel gbm2 = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/weights.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._min_rows = 1;
parms._max_depth = 2;
parms._nfolds = (int) tfr.numRows();
parms._fold_assignment = Model.Parameters.FoldAssignmentScheme.Modulo;
parms._ntrees = 3;
parms._seed = 12345;
parms._learn_rate = 1e-3f;
gbm1 = new GBM(parms).trainModel().get();
//parms._nfolds = (int) tfr.numRows() + 1; //This is now an error
gbm2 = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm1 = (ModelMetricsBinomial)gbm1._output._cross_validation_metrics;
ModelMetricsBinomial mm2 = (ModelMetricsBinomial)gbm2._output._cross_validation_metrics;
assertEquals(mm1.auc_obj()._auc, mm2.auc_obj()._auc, 1e-12);
assertEquals(mm1.mse(), mm2.mse(), 1e-12);
assertEquals(mm1.r2(), mm2.r2(), 1e-12);
assertEquals(mm1.logloss(), mm2.logloss(), 1e-12);
//TODO: add check: the correct number of individual models were built. PUBDEV-1690
} finally {
if (tfr != null) tfr.remove();
if (gbm1 != null) {
gbm1.deleteCrossValidationModels();
gbm1.delete();
}
if (gbm2 != null) {
gbm2.deleteCrossValidationModels();
gbm2.delete();
}
Scope.exit();
}
}
@Test
public void testNfoldsInvalidValues() {
Frame tfr = null;
GBMModel gbm1 = null;
GBMModel gbm2 = null;
GBMModel gbm3 = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/weights.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "response";
parms._min_rows = 1;
parms._seed = 12345;
parms._max_depth = 2;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
parms._nfolds = 0;
gbm1 = new GBM(parms).trainModel().get();
parms._nfolds = 1;
try {
Log.info("Trying nfolds==1.");
gbm2 = new GBM(parms).trainModel().get();
Assert.fail("Should toss H2OModelBuilderIllegalArgumentException instead of reaching here");
} catch(H2OModelBuilderIllegalArgumentException e) {}
parms._nfolds = -99;
try {
Log.info("Trying nfolds==-99.");
gbm3 = new GBM(parms).trainModel().get();
Assert.fail("Should toss H2OModelBuilderIllegalArgumentException instead of reaching here");
} catch(H2OModelBuilderIllegalArgumentException e) {}
} finally {
if (tfr != null) tfr.remove();
if (gbm1 != null) gbm1.delete();
if (gbm2 != null) gbm2.delete();
if (gbm3 != null) gbm3.delete();
Scope.exit();
}
}
@Test
public void testNfoldsCVAndValidation() {
Frame tfr = null, vfr = null;
GBMModel gbm = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/weights.csv");
vfr = parse_test_file("smalldata/junit/weights.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._valid = vfr._key;
parms._response_column = "response";
parms._seed = 12345;
parms._min_rows = 1;
parms._max_depth = 2;
parms._nfolds = 3;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
try {
Log.info("Trying N-fold cross-validation AND Validation dataset provided.");
gbm = new GBM(parms).trainModel().get();
} catch(H2OModelBuilderIllegalArgumentException e) {
Assert.fail("Should not toss H2OModelBuilderIllegalArgumentException.");
}
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) {
gbm.deleteCrossValidationModels();
gbm.delete();
}
Scope.exit();
}
}
@Test
public void testNfoldsConsecutiveModelsSame() {
Frame tfr = null;
Vec old = null;
GBMModel gbm1 = null;
GBMModel gbm2 = null;
Scope.enter();
try {
tfr = parse_test_file("smalldata/junit/cars_20mpg.csv");
tfr.remove("name").remove(); // Remove unique id
tfr.remove("economy").remove();
old = tfr.remove("economy_20mpg");
tfr.add("economy_20mpg", old.toCategoricalVec()); // response to last column
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "economy_20mpg";
parms._min_rows = 1;
parms._seed = 12345;
parms._max_depth = 2;
parms._nfolds = 3;
parms._ntrees = 3;
parms._learn_rate = 1e-3f;
gbm1 = new GBM(parms).trainModel().get();
gbm2 = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm1 = (ModelMetricsBinomial)gbm1._output._cross_validation_metrics;
ModelMetricsBinomial mm2 = (ModelMetricsBinomial)gbm2._output._cross_validation_metrics;
assertEquals(mm1.auc_obj()._auc, mm2.auc_obj()._auc, 1e-12);
assertEquals(mm1.mse(), mm2.mse(), 1e-12);
assertEquals(mm1.r2(), mm2.r2(), 1e-12);
assertEquals(mm1.logloss(), mm2.logloss(), 1e-12);
} finally {
if (tfr != null) tfr.remove();
if (old != null) old.remove();
if (gbm1 != null) {
gbm1.deleteCrossValidationModels();
gbm1.delete();
}
if (gbm2 != null) {
gbm2.deleteCrossValidationModels();
gbm2.delete();
}
Scope.exit();
}
}
@Test
public void testNfoldsColumn() {
Frame tfr = null;
GBMModel gbm1 = null;
try {
tfr = parse_test_file("smalldata/junit/cars_20mpg.csv");
tfr.remove("name").remove(); // Remove unique id
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "economy_20mpg";
parms._fold_column = "cylinders";
Vec old = tfr.remove("cylinders");
tfr.add("cylinders",old.toCategoricalVec());
DKV.put(tfr);
parms._ntrees = 10;
GBM job1 = new GBM(parms);
gbm1 = job1.trainModel().get();
Assert.assertTrue(gbm1._output._cross_validation_models.length == 5);
old.remove();
} finally {
if (tfr != null) tfr.remove();
if (gbm1 != null) {
gbm1.deleteCrossValidationModels();
gbm1.delete();
}
}
}
@Test
public void testNfoldsColumnNumbersFrom0() {
Frame tfr = null;
Vec old = null;
GBMModel gbm1 = null;
try {
tfr = parse_test_file("smalldata/junit/cars_20mpg.csv");
tfr.remove("name").remove(); // Remove unique id
new MRTask() {
@Override
public void map(Chunk c) {
for (int i=0;i<c.len();++i) {
if (c.at8(i) == 3) c.set(i, 0);
if (c.at8(i) == 4) c.set(i, 1);
if (c.at8(i) == 5) c.set(i, 2);
if (c.at8(i) == 6) c.set(i, 3);
if (c.at8(i) == 8) c.set(i, 4);
}
}
}.doAll(tfr.vec("cylinders"));
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "economy_20mpg";
parms._fold_column = "cylinders";
parms._ntrees = 10;
GBM job1 = new GBM(parms);
gbm1 = job1.trainModel().get();
Assert.assertTrue(gbm1._output._cross_validation_models.length == 5);
} finally {
if (tfr != null) tfr.remove();
if (old != null) old.remove();
if (gbm1 != null) {
gbm1.deleteCrossValidationModels();
gbm1.delete();
}
}
}
@Test
public void testNfoldsColumnCategorical() {
Frame tfr = null;
Vec old = null;
GBMModel gbm1 = null;
try {
tfr = parse_test_file("smalldata/junit/cars_20mpg.csv");
tfr.remove("name").remove(); // Remove unique id
old = tfr.remove("cylinders");
tfr.add("folds", old.toCategoricalVec());
old.remove();
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "economy_20mpg";
parms._fold_column = "folds";
parms._ntrees = 10;
GBM job1 = new GBM(parms);
gbm1 = job1.trainModel().get();
Assert.assertTrue(gbm1._output._cross_validation_models.length == 5);
} finally {
if (tfr != null) tfr.remove();
if (old != null) old.remove();
if (gbm1 != null) {
gbm1.deleteCrossValidationModels();
gbm1.delete();
}
}
}
@Test
public void testNFoldAirline() {
Frame tfr = null, vfr = null;
GBMModel gbm = null;
Scope.enter();
try {
tfr = parse_test_file("./smalldata/airlines/allyears2k_headers.zip");
for (String s : new String[]{
"DepTime", "ArrTime", "ActualElapsedTime",
"AirTime", "ArrDelay", "DepDelay", "Cancelled",
"CancellationCode", "CarrierDelay", "WeatherDelay",
"NASDelay", "SecurityDelay", "LateAircraftDelay", "IsArrDelayed"
}) {
tfr.remove(s).remove();
}
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "IsDepDelayed";
parms._seed = 234;
parms._min_rows = 2;
parms._nfolds = 3;
parms._max_depth = 5;
parms._ntrees = 5;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
ModelMetricsBinomial mm = (ModelMetricsBinomial)gbm._output._cross_validation_metrics;
assertEquals(0.7264331810371721, mm.auc_obj()._auc, 1e-4); // 1 node
assertEquals(0.22686348162897116, mm.mse(), 1e-4);
assertEquals(0.09039195554728074, mm.r2(), 1e-4);
assertEquals(0.6461880794975307, mm.logloss(), 1e-4);
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) {
gbm.deleteCrossValidationModels();
gbm.delete();
}
Scope.exit();
}
}
// just a simple sanity check - not a golden test
@Test
public void testDistributions() {
Frame tfr = null, vfr = null, res= null;
GBMModel gbm = null;
for (Distribution.Family dist : new Distribution.Family[]{
Distribution.Family.AUTO,
Distribution.Family.gaussian,
Distribution.Family.poisson,
Distribution.Family.gamma,
Distribution.Family.tweedie
}) {
Scope.enter();
try {
tfr = parse_test_file("smalldata/glm_test/cancar_logIn.csv");
vfr = parse_test_file("smalldata/glm_test/cancar_logIn.csv");
for (String s : new String[]{
"Merit", "Class"
}) {
Scope.track(tfr.replace(tfr.find(s), tfr.vec(s).toCategoricalVec()));
Scope.track(vfr.replace(vfr.find(s), vfr.vec(s).toCategoricalVec()));
}
DKV.put(tfr);
DKV.put(vfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "Cost";
parms._seed = 0xdecaf;
parms._distribution = dist;
parms._min_rows = 1;
parms._ntrees = 30;
// parms._offset_column = "logInsured"; //POJO scoring not supported for offsets
parms._learn_rate = 1e-3f;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
res = gbm.score(vfr);
Assert.assertTrue(gbm.testJavaScoring(vfr,res,1e-15));
res.remove();
ModelMetricsRegression mm = (ModelMetricsRegression)gbm._output._training_metrics;
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (res != null) res.remove();
if (gbm != null) gbm.delete();
Scope.exit();
}
}
}
@Test
public void testStochasticGBM() {
Frame tfr = null, vfr = null;
GBMModel gbm = null;
float[] sample_rates = new float[]{0.2f, 0.4f, 0.6f, 0.8f, 1.0f};
float[] col_sample_rates = new float[]{0.2f, 0.4f, 0.6f, 0.8f, 1.0f};
Map<Double, Pair<Float,Float>> hm = new TreeMap<>();
for (float sample_rate : sample_rates) {
for (float col_sample_rate : col_sample_rates) {
Scope.enter();
try {
tfr = parse_test_file("./smalldata/gbm_test/ecology_model.csv");
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "Angaus"; //regression
parms._seed = 234;
parms._min_rows = 2;
parms._max_depth = 10;
parms._ntrees = 2;
parms._col_sample_rate = col_sample_rate;
parms._sample_rate = sample_rate;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
ModelMetricsRegression mm = (ModelMetricsRegression)gbm._output._training_metrics;
hm.put(mm.mse(), new Pair<>(sample_rate, col_sample_rate));
} finally {
if (tfr != null) tfr.remove();
if (vfr != null) vfr.remove();
if (gbm != null) gbm.delete();
Scope.exit();
}
}
}
double fullDataMSE = hm.entrySet().iterator().next().getKey();
Iterator<Map.Entry<Double, Pair<Float, Float>>> it;
int i=0;
Pair<Float, Float> last = null;
// iterator over results (min to max MSE) - best to worst
for (it=hm.entrySet().iterator(); it.hasNext(); ++i) {
Map.Entry<Double, Pair<Float,Float>> n = it.next();
if (i>0) Assert.assertTrue(n.getKey() > fullDataMSE); //any sampling should make training set MSE worse
Log.info( "MSE: " + n.getKey() + ", "
+ ", row sample: " + ((Pair)n.getValue()).getKey()
+ ", col sample: " + ((Pair)n.getValue()).getValue());
last=n.getValue();
}
// worst training MSE should belong to the most sampled case
Assert.assertTrue(last.getKey()==sample_rates[0]);
Assert.assertTrue(last.getValue()==col_sample_rates[0]);
}
@Test
public void testStochasticGBMHoldout() {
Frame tfr = null;
Key[] ksplits = new Key[0];
try{
tfr=parse_test_file("./smalldata/gbm_test/ecology_model.csv");
SplitFrame sf = new SplitFrame(tfr,new double[] { 0.5, 0.5 },new Key[] { Key.make("train.hex"), Key.make("test.hex")});
// Invoke the job
sf.exec().get();
ksplits = sf._destination_frames;
GBMModel gbm = null;
float[] sample_rates = new float[]{0.2f, 0.4f, 0.8f, 1.0f};
float[] col_sample_rates = new float[]{0.4f, 0.8f, 1.0f};
float[] col_sample_rates_per_tree = new float[]{0.4f, 0.6f, 1.0f};
Map<Double, Triple<Float>> hm = new TreeMap<>();
for (float sample_rate : sample_rates) {
for (float col_sample_rate : col_sample_rates) {
for (float col_sample_rate_per_tree : col_sample_rates_per_tree) {
Scope.enter();
try {
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = ksplits[0];
parms._valid = ksplits[1];
parms._response_column = "Angaus"; //regression
parms._seed = 234;
parms._min_rows = 2;
parms._max_depth = 12;
parms._ntrees = 6;
parms._col_sample_rate = col_sample_rate;
parms._col_sample_rate_per_tree = col_sample_rate_per_tree;
parms._sample_rate = sample_rate;
// Build a first model; all remaining models should be equal
gbm = new GBM(parms).trainModel().get();
// too slow, but passes (now)
// // Build a POJO, validate same results
// Frame pred = gbm.score(tfr);
// Assert.assertTrue(gbm.testJavaScoring(tfr,pred,1e-15));
// pred.remove();
ModelMetricsRegression mm = (ModelMetricsRegression)gbm._output._validation_metrics;
hm.put(mm.mse(), new Triple<>(sample_rate, col_sample_rate, col_sample_rate_per_tree));
} finally {
if (gbm != null) gbm.delete();
Scope.exit();
}
}
}
}
Iterator<Map.Entry<Double, Triple<Float>>> it;
Triple<Float> last = null;
// iterator over results (min to max MSE) - best to worst
for (it=hm.entrySet().iterator(); it.hasNext();) {
Map.Entry<Double, Triple<Float>> n = it.next();
Log.info( "MSE: " + n.getKey()
+ ", row sample: " + n.getValue().v1
+ ", col sample: " + n.getValue().v2
+ ", col sample per tree: " + n.getValue().v3);
last=n.getValue();
}
// worst validation MSE should belong to the most overfit case (1.0, 1.0, 1.0)
Assert.assertTrue(last.v1==sample_rates[sample_rates.length-1]);
Assert.assertTrue(last.v2==col_sample_rates[col_sample_rates.length-1]);
Assert.assertTrue(last.v3==col_sample_rates_per_tree[col_sample_rates_per_tree.length-1]);
} finally {
if (tfr != null) tfr.remove();
for (Key k : ksplits)
if (k!=null) k.remove();
}
}
// PUBDEV-2476 Check reproducibility for the same # of chunks (i.e., same # of nodes) and same parameters
@Test public void testChunks() {
Frame tfr;
int[] chunks = new int[]{1,2,2,39,39,500};
final int N = chunks.length;
double[] mses = new double[N];
for (int i=0; i<N; ++i) {
Scope.enter();
// Load data, hack frames
tfr = parse_test_file("smalldata/covtype/covtype.20k.data");
// rebalance to a given number of chunks
Key dest = Key.make("df.rebalanced.hex");
RebalanceDataSet rb = new RebalanceDataSet(tfr, dest, chunks[i]);
H2O.submitTask(rb);
rb.join();
tfr.delete();
tfr = DKV.get(dest).get();
assertEquals(tfr.vec(0).nChunks(), chunks[i]);
// Scope.track(tfr.replace(54, tfr.vecs()[54].toCategoricalVec())._key);
DKV.put(tfr);
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = tfr._key;
parms._response_column = "C55";
parms._seed = 1234;
parms._col_sample_rate_per_tree = 0.5f;
parms._col_sample_rate = 0.3f;
parms._ntrees = 5;
parms._max_depth = 5;
// Build a first model; all remaining models should be equal
GBM job = new GBM(parms);
GBMModel drf = job.trainModel().get();
assertEquals(drf._output._ntrees, parms._ntrees);
mses[i] = drf._output._scored_train[drf._output._scored_train.length-1]._mse;
drf.delete();
if (tfr != null) tfr.remove();
Scope.exit();
}
for (int i=0; i<mses.length; ++i) {
Log.info("trial: " + i + " -> MSE: " + mses[i]);
}
for(double mse : mses)
assertEquals(mse, mses[0], 1e-10);
}
@Test public void testLaplace() {
GBMModel gbm = null;
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
Frame pred=null, res=null;
Scope.enter();
try {
Frame train = parse_test_file("smalldata/gbm_test/ecology_model.csv");
train.remove("Site").remove(); // Remove unique ID
train.remove("Method").remove(); // Remove categorical
DKV.put(train); // Update frame after hacking it
parms._train = train._key;
parms._response_column = "DSDist"; // Train on the outcome
parms._distribution = Distribution.Family.laplace;
GBM job = new GBM(parms);
gbm = job.trainModel().get();
pred = parse_test_file("smalldata/gbm_test/ecology_eval.csv" );
res = gbm.score(pred);
// Build a POJO, validate same results
Assert.assertTrue(gbm.testJavaScoring(pred, res, 1e-15));
} finally {
parms._train.remove();
if( gbm != null ) gbm .delete();
if( pred != null ) pred.remove();
if( res != null ) res .remove();
Scope.exit();
}
}
} |
package water.rapids;
import water.MRTask;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.VecUtils;
import java.util.Random;
import static water.util.RandomUtils.getRNG;
public class ASTKFold extends ASTPrim {
@Override
public String[] args() { return new String[]{"ary", "nfolds", "seed"}; }
@Override public int nargs() { return 1+3; } // (kfold_column x nfolds seed)
@Override
public String str() { return "kfold_column"; }
public static Vec kfoldColumn(Vec v, final int nfolds, final long seed) {
new MRTask() {
@Override public void map(Chunk c) {
long start = c.start();
for( int i=0; i<c._len; ++i ) {
int fold = Math.abs(getRNG(start + seed + i).nextInt()) % nfolds;
c.set(i,fold);
}
}
}.doAll(v);
return v;
}
public static Vec moduloKfoldColumn(Vec v, final int nfolds) {
new MRTask() {
@Override public void map(Chunk c) {
long start = c.start();
for( int i=0; i<c._len; ++i)
c.set(i, (int) ((start + i) % nfolds));
}
}.doAll(v);
return v;
}
public static Vec stratifiedKFoldColumn(Vec y, final int nfolds, final long seed) {
// for each class, generate a fold column (never materialized)
// therefore, have a seed per class to be used by the map call
if( !(y.isCategorical() || (y.isNumeric() && y.isInt())) )
throw new IllegalArgumentException("stratification only applies to integer and categorical columns. Got: " + y.get_type_str());
final long[] classes = new VecUtils.CollectDomain().doAll(y).domain();
final int nClass = y.isNumeric() ? classes.length : y.domain().length;
final long[] seeds = new long[nClass]; // seed for each regular fold column (one per class)
for( int i=0;i<nClass;++i)
seeds[i] = getRNG(seed + i).nextLong();
return new MRTask() {
private int getFoldId(long absoluteRow, long seed) {
return Math.abs(getRNG(absoluteRow + seed).nextInt()) % nfolds;
}
// dress up the foldColumn (y[1]) as follows:
// 1. For each testFold and each classLabel loop over the response column (y[0])
// 2. If the classLabel is the current response and the testFold is the foldId
// for the current row and classLabel, then set the foldColumn to testFold
// How this balances labels per fold:
// Imagine that a KFold column was generated for each class. Observe that this
// makes the outer loop a way of selecting only the test rows from each fold
// (i.e., the holdout rows). Each fold is balanced sequentially in this way
// since y[1] is only updated if the current row happens to be a holdout row
// for the given classLabel.
// Next observe that looping over each classLabel filters down each KFold
// so that it contains labels for just THAT class. This is how the balancing
// can be made so that it is independent of the chunk distribution and the
// per chunk class distribution.
// Downside is this performs nfolds*nClass passes over each Chunk. For
// "reasonable" classification problems, this could be 100 passes per Chunk.
@Override public void map(Chunk[] y) {
long start = y[0].start();
for(int testFold=0; testFold < nfolds; ++testFold) {
for(int classLabel = 0; classLabel < nClass; ++classLabel) {
for(int row=0;row<y[0]._len;++row ) {
if( y[0].at8(row) == (classes==null?classLabel:classes[classLabel]) ) {
if( testFold == getFoldId(start+row,seeds[classLabel]) )
y[1].set(row,testFold);
}
}
}
}
}
}.doAll(new Frame(y,y.makeZero()))._fr.vec(1);
}
@Override ValFrame apply( Env env, Env.StackHelp stk, AST asts[] ) {
Vec foldVec = stk.track(asts[1].exec(env)).getFrame().anyVec().makeZero();
int nfolds = (int)asts[2].exec(env).getNum();
long seed = (long)asts[3].exec(env).getNum();
return new ValFrame(new Frame(kfoldColumn(foldVec,nfolds,seed==-1?new Random().nextLong():seed)));
}
}
class ASTModuloKFold extends ASTPrim {
@Override
public String[] args() { return new String[]{"ary", "nfolds"}; }
@Override public int nargs() { return 1+2; } // (modulo_kfold_column x nfolds)
@Override
public String str() { return "modulo_kfold_column"; }
@Override ValFrame apply( Env env, Env.StackHelp stk, AST asts[] ) {
Vec foldVec = stk.track(asts[1].exec(env)).getFrame().anyVec().makeZero();
int nfolds = (int)asts[2].exec(env).getNum();
return new ValFrame(new Frame(ASTKFold.moduloKfoldColumn(foldVec,nfolds)));
}
}
class ASTStratifiedKFold extends ASTPrim {
@Override
public String[] args() { return new String[]{"ary", "nfolds", "seed"}; }
@Override public int nargs() { return 1+3; } // (stratified_kfold_column x nfolds seed)
@Override
public String str() { return "stratified_kfold_column"; }
@Override ValFrame apply( Env env, Env.StackHelp stk, AST asts[] ) {
Vec foldVec = stk.track(asts[1].exec(env)).getFrame().anyVec().makeZero();
int nfolds = (int)asts[2].exec(env).getNum();
long seed = (long)asts[3].exec(env).getNum();
return new ValFrame(new Frame(ASTKFold.stratifiedKFoldColumn(foldVec,nfolds,seed==-1?new Random().nextLong():seed)));
}
} |
package hclient;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RequestFactory {
private final static int DEFAULT_MAX_REQUESTS_PER_MINUTE = 20;
private final static Logger LOGGER = LoggerFactory.getLogger( RequestFactory.class );
private static Map<String, Integer> maxRequestsPerMinuteForHost = new ConcurrentHashMap<String, Integer>();
private static Map<String, Long> lastRequestForHost = new ConcurrentHashMap<String, Long>();
static {
maxRequestsPerMinuteForHost.put("www.amazon.fr", 15);
}
public static HttpPost getPost( URL url, URL referer ) {
URI uri;
try {
uri = url.toURI();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return null;
}
HttpPost httppost = new HttpPost( uri );
if (referer != null) {
httppost.setHeader("Referer", referer.toString());
}
httppost.setHeader("Accept", "*/*");
httppost.setHeader("Accept-Language", "en-US,en;q=0.5");
wait( uri.getHost() );
return httppost;
}
public static URI getURI( String url ) throws URISyntaxException {
String urlString = url.replaceAll("\\s", "%20");
String[] elements = urlString.split("/");
if (elements.length>0) {
for (int i=2;i<elements.length; i++) {
elements[i] = elements[i].replace(":", "%3A");
elements[i] = elements[i].replace("[", "%5B");
elements[i] = elements[i].replace("]", "%5D");
elements[i] = elements[i].replace("&", "%26");
elements[i] = elements[i].replace("'", "%27");
}
urlString = StringUtils.join( elements, '/');
if (url.endsWith("/")) {
urlString += "/";
}
}
return new URI( urlString );
}
public static HttpGet getGet( URL url, String referer ) throws URISyntaxException {
HttpGet httpget = new HttpGet( getURI( url.toString() ) );
httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpget.setHeader("Accept-Language", "en-US,en;q=0.5");
if (referer != null) {
httpget.setHeader("Referer", referer);
}
wait( url.getHost() );
return httpget;
}
private static void wait( String host ) {
int maxRequestsPerMinute = DEFAULT_MAX_REQUESTS_PER_MINUTE;
if (maxRequestsPerMinuteForHost != null && maxRequestsPerMinuteForHost.containsKey( host )) {
maxRequestsPerMinute = maxRequestsPerMinuteForHost.get(host);
}
int delayBetweenRequests = (1000 * 60) / maxRequestsPerMinute;
long nextRequest = System.currentTimeMillis();
if (lastRequestForHost.containsKey( host )) {
nextRequest = lastRequestForHost.get( host ) + delayBetweenRequests;
}
while (!(System.currentTimeMillis() > nextRequest) ) {
try {
Thread.sleep( 200 );
} catch (InterruptedException e) {
}
}
lastRequestForHost.put( host, System.currentTimeMillis() );
}
} |
package app.hongs.util;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*
* <p>
* asXxx,toXxx ,
* asXxx ,
* toXxx , JSON.
* , null;
* defoult, declare, .
* </p>
*
* <p>
* List,Set,Map ArayList,LinkedHashSet,LinkedHashMap.
* listOf Arrays.asList , .
* </p>
*
* @author Hongs
*/
public final class Synt {
private static final Number ZERO = 0 ;
private static final String EMPT = "";
private static final Boolean FALS = false;
/**
* Each.run EachLeaf.run
* LOOP.NEXT
* LOOP.LAST
*/
public static enum LOOP { NEXT , LAST };
private static final Pattern SEXP = Pattern.compile("\\s*,\\s*");
private static final Pattern MEXP = Pattern.compile("\\s*:\\s*");
private static final Pattern TEXP = Pattern.compile("\\s*[\\s\\+,;]\\s*");
private static final Pattern WEXP = Pattern.compile("\\s*[\\p{Space}\\p{Punct}\\u3000-\\u303F]\\s*");
/**
* : [min,max] (min,max)
*/
private static final Pattern RNGP = Pattern.compile("^([\\(\\[])?(.*?),(.*?)([\\]\\)])?$");
/**
* : False, No, Off, F, N, O, 0
*/
public static final Pattern FAKE = Pattern.compile("(|0|O|N|F|NO|OFF|FALSE)", Pattern.CASE_INSENSITIVE);
/**
* : True , Yes, On, T, Y, I, 1
*/
public static final Pattern TRUE = Pattern.compile( "(1|I|Y|T|ON|YES|TRUE)" , Pattern.CASE_INSENSITIVE);
/**
* List
* :
* @param objs
* @return
*/
public static List listOf(Object... objs) {
return new ArrayList (Arrays.asList(objs));
}
/**
* Set
* :
* @param objs
* @return
*/
public static Set setOf (Object... objs) {
return new LinkedHashSet(Arrays.asList(objs));
}
/**
* Map
* : ,
* @param objs
* @return
*/
public static Map mapOf (Object... objs) {
if ( objs.length % 2 != 0 ) {
throw new IndexOutOfBoundsException("mapOf must provide even numbers of entries");
}
int idx = 0;
Map map = new LinkedHashMap();
while ( idx < objs.length ) {
map.put ( objs [idx ++] , objs [idx ++] );
}
return map;
}
/**
*
* asArray val , JSON
* @param val
* @return
*/
public static Object[] toArray(Object val) {
if (val == null) {
return null;
}
if (val instanceof String) {
if ("".equals(val)) {
return new Object[0];
}
String text = ( (String) val).trim( );
if (text.startsWith("[") && text.endsWith("]")) {
return ((List) Data.toObject(text))
.toArray ( );
} else {
return SEXP.split(text);
}
}
return asArray(val);
}
/**
* List
* asArray val , JSON
* @param val
* @return
*/
public static List toList(Object val) {
if (val == null) {
return null;
}
if (val instanceof String) {
if ("".equals(val)) {
return new ArrayList();
}
String text = ( (String) val).trim( );
if (text.startsWith("[") && text.endsWith("]")) {
return (List) Data.toObject (text);
} else {
return new ArrayList(
Arrays.asList(SEXP.split(text))
);
}
}
return asList(val);
}
/**
* Set
* asArray val , JSON
* @param val
* @return
*/
public static Set toSet (Object val) {
if (val == null) {
return null;
}
if (val instanceof String) {
if ("".equals(val)) {
return new LinkedHashSet();
}
String text = ( (String) val).trim( );
if (text.startsWith("[") && text.endsWith("]")) {
return new LinkedHashSet(
(List) Data.toObject (text)
);
} else {
return new LinkedHashSet(
Arrays.asList(SEXP.split(text))
);
}
}
return asSet (val);
}
/**
* Map
* asArray val , JSON
* @param val
* @return
*/
public static Map toMap (Object val) {
if (val == null) {
return null;
}
if (val instanceof String) {
if ("".equals(val)) {
return new LinkedHashMap();
}
String text = ( (String) val).trim( );
if (text.startsWith("{") && text.endsWith("}")) {
return (Map ) Data.toObject (text);
} else {
Map m = new LinkedHashMap();
for(String s : SEXP.split (text)) {
String[] a = MEXP.split (s, 2);
if ( 2 > a.length ) {
m.put( a[0], a[0] );
} else {
m.put( a[0], a[1] );
}
}
return m ;
}
}
return asMap (val);
}
/**
*
* List,Set,Map ,
* @param val
* @return
*/
public static Object[] asArray(Object val) {
if (val == null) {
return null;
}
if (val instanceof Object[] ) {
return (Object[]) val;
} else if (val instanceof List) {
return ((List)val).toArray();
} else if (val instanceof Set ) {
return ((Set) val).toArray();
} else if (val instanceof Map ) {
return ((Map) val).values( ).toArray();
} else {
return new Object[ ] { val };
}
}
/**
* List
* ,Set,Map List, List
* @param val
* @return
*/
public static List asList(Object val) {
if (val == null) {
return null;
}
if (val instanceof List) {
return ( List) val ;
} else if (val instanceof Set ) {
return new ArrayList(( Set ) val);
} else if (val instanceof Map ) {
return new ArrayList(((Map ) val).values());
} else if (val instanceof Object[]) {
return new ArrayList(Arrays.asList((Object[]) val));
} else {
List lst = new ArrayList ();
lst.add(val);
return lst ;
}
}
/**
* Set
* ,List,Map Set, Set
* @param val
* @return
*/
public static Set asSet (Object val) {
if (val == null) {
return null;
}
if (val instanceof Set ) {
return ( Set ) val ;
} else if (val instanceof List) {
return new LinkedHashSet((List) val);
} else if (val instanceof Map ) {
return new LinkedHashSet(((Map) val).values());
} else if (val instanceof Object[]) {
return new LinkedHashSet(Arrays.asList((Object[]) val));
} else {
Set set = new LinkedHashSet();
set.add(val);
return set ;
}
}
/**
* List
* Map , Map ,
* .
* @param val
* @return
*/
public static Map asMap (Object val) {
if (val == null) {
return null;
}
if (val instanceof Map ) {
return ( Map ) val ;
}
// Map
throw new ClassCastException("'" + val + "' can not be cast to Map");
}
/**
*
*
* @param val
* @return
*/
public static String asString(Object val) {
val = asSingle(val);
if (val == null) {
return null;
}
return val.toString();
}
/**
*
* ,
* @param val
* @return
*/
public static Integer asInt(Object val) {
val = asNumber(val);
if (val == null) {
return null;
}
if (val instanceof Number) {
return ((Number) val ).intValue( );
} else
if (val instanceof String) {
String str = ((String) val).trim();
try {
return new BigDecimal(str).intValue();
} catch (NumberFormatException ex) {
throw new ClassCastException("'" + val + "' can not be cast to int");
}
}
return (Integer) val;
}
/**
*
* ,
* @param val
* @return
*/
public static Long asLong(Object val) {
val = asNumber(val);
if (val == null) {
return null;
}
if (val instanceof Number) {
return ((Number) val ).longValue();
} else
if (val instanceof String) {
String str = ((String) val).trim();
try {
return new BigDecimal(str).longValue();
} catch (NumberFormatException ex) {
throw new ClassCastException("'" + val + "' can not be cast to long");
}
}
return (Long) val;
}
/**
*
* ,
* @param val
* @return
*/
public static Float asFloat(Object val) {
val = asNumber(val);
if (val == null) {
return null;
}
if (val instanceof Number) {
return ((Number) val).floatValue();
} else
if (val instanceof String) {
String str = ((String) val).trim();
try {
return new BigDecimal(str).floatValue();
} catch (NumberFormatException ex) {
throw new ClassCastException("'" + val + "' can not be cast to float");
}
}
return (Float) val;
}
/**
*
* ,
* @param val
* @return
*/
public static Double asDouble(Object val) {
val = asNumber(val);
if (val == null) {
return null;
}
if (val instanceof Number) {
return ((Number)val).doubleValue();
} else
if (val instanceof String) {
String str = ((String) val).trim();
try {
return new BigDecimal(str).doubleValue();
} catch (NumberFormatException ex) {
throw new ClassCastException("'" + val + "' can not be cast to double");
}
}
return (Double) val;
}
/**
*
* ,
* @param val
* @return
*/
public static Short asShort(Object val) {
val = asNumber(val);
if (val == null) {
return null;
}
if (val instanceof Number) {
return ((Number) val).shortValue();
} else
if (val instanceof String) {
String str = ((String) val).trim();
try {
return new BigDecimal(str).shortValue();
} catch (NumberFormatException ex) {
throw new ClassCastException("'" + val + "' can not be cast to short");
}
}
return (Short) val;
}
/**
*
* ,
* @param val
* @return
*/
public static Byte asByte(Object val) {
val = asNumber(val);
if (val == null) {
return null;
}
if (val instanceof Number) {
return ((Number) val ).byteValue();
} else
if (val instanceof String) {
String str = ((String) val).trim();
try {
return new BigDecimal(str).byteValue();
} catch (NumberFormatException ex) {
throw new ClassCastException("'" + val + "' can not be cast to byte");
}
}
return (Byte) val;
}
/**
*
* , , true
* @param val
* @return
*/
public static Boolean asBool(Object val) {
val = asNumber(val);
if (val == null) {
return null;
}
if (val instanceof Number) {
return ((Number) val ).intValue( ) != 0;
} else if (val instanceof String) {
String str = ((String) val).trim();
if (TRUE.matcher(str).matches( ) ) {
return true ;
} else
if (FAKE.matcher(str).matches( ) ) {
return false;
} else {
throw new ClassCastException("'" + str + "' can not be cast to boolean");
}
}
return (Boolean) val;
}
/**
* , ,
* @param val
* @return
*/
private static Object asNumber(Object val) {
val = asSingle(val);
if (val == null) {
return null;
}
if (EMPT.equals(val)) {
return null;
}
if (val instanceof Date) {
val = ( (Date) val ).getTime();
}
return val;
}
/**
* servlet requestMap ,
* @param val
* @return
*/
private static Object asSingle(Object val) {
if (val == null) {
return null;
}
try {
if (val instanceof Object[]) {
return ((Object[]) val )[0];
} else
if (val instanceof List) {
return ((List) val ).get(0);
} else
if (val instanceof Set ) {
return ((Set ) val ).toArray()[0];
} else
if (val instanceof Map ) {
return ((Map ) val ).values( ).toArray()[0];
}
} catch (IndexOutOfBoundsException ex) {
return null;
}
return val;
}
/**
* Set
*
* declare(Object, T)
*
* Set
* : +,;
* @param val
* @return
*/
public static Set<String> toTerms(Object val) {
if (val == null) {
return null;
}
if (val instanceof String) {
String s = ((String) val).trim();
if ("".equals(s)) {
return new LinkedHashSet();
}
String[] a = TEXP.split (s);
List b = Arrays.asList(a);
return new LinkedHashSet(b);
}
return asSet(val);
}
/**
* Set
*
* declare(Object, T)
*
* Set
* : +,;.:!?'"
* @param val
* @return
*/
public static Set<String> toWords(Object val) {
if (val == null) {
return null;
}
if (val instanceof String) {
String s = ((String) val).trim();
if ("".equals(s)) {
return new LinkedHashSet();
}
String[] a = WEXP.split (s);
List b = Arrays.asList(a);
return new LinkedHashSet(b);
}
return asSet(val);
}
/**
*
* [min,max] (min,max) {min,max,gte,lte}
* , , true
* @param val
* @return
*/
public static Object[] toRange(Object val) {
if (val == null || "".equals(val)) {
return null;
}
if (val instanceof String ) {
String vs = declare(val, "");
Matcher m = RNGP.matcher(vs);
if (m.matches()) {
String m2 = m.group (2 ).trim();
String m3 = m.group (3 ).trim();
return new Object[] {
! "".equals(m2) ? m2 : null,
! "".equals(m3) ? m3 : null,
!"(".equals(m.group ( 1 ) ),
!")".equals(m.group ( 4 ) )
};
}
throw new ClassCastException("'"+val+"' can not be cast to range");
}
Object[] arr;
if (val instanceof Object[]) {
arr = (Object[ ]) val;
} else if (val instanceof List) {
arr = ((List)val).toArray();
} else {
throw new ClassCastException("'"+val+"' can not be cast to range");
}
switch (arr.length) {
case 4:
Boolean lte, gte;
try {
lte = defoult(asBool(arr[2]), false);
gte = defoult(asBool(arr[3]), false);
}
catch (ClassCastException e) {
throw new ClassCastException("Range index 2,3 must be boolean: "+arr);
}
return new Object[] {
arr[0], arr[1], lte , gte
};
case 2:
return new Object[] {
arr[0], arr[1], true, true
};
default:throw new ClassCastException("Range index size must be 2 or 4: "+arr);
}
}
/**
* cls
* string,number(int,long...) ;
* cls Boolean :
* 0 true,
* false,
* 1,y,t,yes,true ,
* 0,n,f,no,false ;
* cls Array,List,Set :
* val List,Set,Map Array,List,Set val ,
* val Map values;
* Map .
* asXxx .
* @param <T>
* @param val
* @param cls
* @return
*/
public static <T> T declare(Object val, Class<T> cls) {
if (cls == null) {
throw new NullPointerException("declare cls can not be null");
}
if (val == null) {
return null;
}
if (Object[].class.isAssignableFrom(cls)) {
val = asArray(val);
} else
if (List.class.isAssignableFrom(cls)) {
val = asList(val);
} else
if (Set.class.isAssignableFrom(cls)) {
val = asSet(val);
} else
if (Map.class.isAssignableFrom(cls)) {
val = asMap(val);
} else
if (String.class.isAssignableFrom(cls)) {
val = asString(val);
} else
if (Integer.class.isAssignableFrom(cls)) {
val = asInt(val);
} else
if (Long.class.isAssignableFrom(cls)) {
val = asLong(val);
} else
if (Float.class.isAssignableFrom(cls)) {
val = asFloat(val);
} else
if (Double.class.isAssignableFrom(cls)) {
val = asDouble(val);
} else
if (Short.class.isAssignableFrom(cls)) {
val = asShort(val);
} else
if (Byte.class.isAssignableFrom(cls)) {
val = asByte(val);
} else
if (Boolean.class.isAssignableFrom(cls)) {
val = asBool(val);
}
return (T) val;
}
/**
* val def
* val def
* declare(Object, Class)
* @param <T>
* @param val
* @param def
* @return
*/
public static <T> T declare(Object val, T def) {
if (def == null) {
throw new NullPointerException("declare def can not be null");
}
val = declare(val, def.getClass());
if (val == null) {
return def;
}
return (T) val;
}
/**
* (null )
* @param <T>
* @param vals
* @return
*/
public static <T> T defoult(T... vals) {
for (T val : vals) {
if (val != null) {
return val ;
}
}
return null;
}
/**
* (null )
* Java8
*
* @param <T>
* @param val
* @param vals java7 , Supplier
* @return
*/
public static <T> T defoult(T val, Defn<T>... vals) {
if (val != null) {
return val ;
}
for (Defn<T> def : vals) {
val = def.get();
if (val != null) {
return val ;
}
}
return null;
}
/**
* (null,false,0,"" , javascript)
* @param <T>
* @param vals
* @return
*/
public static <T> T defxult(T... vals) {
for (T val : vals) {
if (val != null
&& !FALS.equals(val)
&& !EMPT.equals(val)
&& !ZERO.equals(val)) {
return val ;
}
}
return null;
}
/**
* (null,false,0,"" , javascript)
* Java8
*
* @param <T>
* @param val
* @param vals java7 , Supplier
* @return
*/
public static <T> T defxult(T val, Defn<T>... vals) {
if (val != null
&& !FALS.equals(val)
&& !EMPT.equals(val)
&& !ZERO.equals(val)) {
return val ;
}
for (Defn<T> def : vals) {
val = def.get();
if (val != null
&& !FALS.equals(val)
&& !EMPT.equals(val)
&& !ZERO.equals(val)) {
return val ;
}
}
return null;
}
/**
* Map
* @param data
* @param conv
* @return
*/
public static Map filter(Map data, Each conv) {
Map dat = new LinkedHashMap();
for (Object o : data.entrySet()) {
Map.Entry e = (Map.Entry) o;
Object k = e.getKey( );
Object v = e.getValue();
v = conv.run(v, k, -1 );
if (v == LOOP.NEXT) {
continue;
}
if (v == LOOP.LAST) {
break;
}
dat.put(k, v);
}
return dat;
}
/**
* Set
* @param data
* @param conv
* @return
*/
public static Set filter(Set data, Each conv) {
Set dat = new LinkedHashSet();
for (Object v : data) {
v = conv.run(v, null, -1);
if (v == LOOP.NEXT) {
continue;
}
if (v == LOOP.LAST) {
break;
}
dat.add(v);
}
return dat;
}
/**
* List
* @param data
* @param conv
* @return
*/
public static List filter(List data, Each conv) {
List dat = new ArrayList();
for (int i = 0; i < data.size(); i++) {
Object v = data.get(i);
v = conv.run(v, null, i);
if (v == LOOP.NEXT) {
continue;
}
if (v == LOOP.LAST) {
break;
}
dat.add(v);
}
return dat;
}
/**
*
* @param data
* @param conv
* @return
*/
public static Object[] filter(Object[] data, Each conv) {
List dat = new ArrayList();
for (int i = 0; i < data.length; i++) {
Object v = data[i];
v = conv.run(v, null, i);
if (v == LOOP.NEXT) {
continue;
}
if (v == LOOP.LAST) {
break;
}
dat.add(v);
}
return dat.toArray();
}
/**
*
* @param data
* @param conv
* @return
*/
public static Map digest(Map data, Deep conv) {
return filter(data, new EachLeaf(conv));
}
/**
*
* @param data
* @param conv
* @return
*/
public static Set digest(Set data, Deep conv) {
return filter(data, new EachLeaf(conv));
}
/**
*
* @param data
* @param conv
* @return
*/
public static List digest(List data, Deep conv) {
return filter(data, new EachLeaf(conv));
}
/**
*
* @param data
* @param conv
* @return
*/
public static Object[] digest(Object[] data, Deep conv) {
return filter(data, new EachLeaf(conv));
}
/
/**
*
* @param <T>
*/
public static interface Defn<T> {
public T get();
}
public static interface Each {
public Object run(Object v, Object k, int i);
}
public static interface Deep {
public Object run(Object v, List p);
}
private static class EachLeaf implements Each {
private final Deep deep;
private final List path;
public EachLeaf(Deep leaf) {
this.deep = leaf;
this.path = new ArrayList( );
}
@Override
public Object run(Object v, Object k, int i) {
List p = new ArrayList(path);
p.add(i != -1 ? i : k );
if (v instanceof Map ) {
return filter((Map ) v, this);
} else
if (v instanceof Set ) {
return filter((Set ) v, this);
} else
if (v instanceof List) {
return filter((List) v, this);
} else
if (v instanceof Object[]) {
return filter((Object[]) v, this);
} else {
return deep.run(v, p);
}
}
}
} |
package org.mobicents.ss7;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import javolution.util.FastSet;
import org.apache.log4j.Logger;
import org.mobicents.protocols.ss7.scheduler.Scheduler;
import org.mobicents.protocols.ss7.scheduler.Task;
import org.mobicents.protocols.ss7.m3ua.impl.oam.M3UAShellExecutor;
import org.mobicents.protocols.ss7.sccp.impl.oam.SccpExecutor;
import org.mobicents.ss7.linkset.oam.LinksetExecutor;
import org.mobicents.ss7.management.console.Subject;
import org.mobicents.ss7.management.transceiver.ChannelProvider;
import org.mobicents.ss7.management.transceiver.ChannelSelectionKey;
import org.mobicents.ss7.management.transceiver.ChannelSelector;
import org.mobicents.ss7.management.transceiver.Message;
import org.mobicents.ss7.management.transceiver.MessageFactory;
import org.mobicents.ss7.management.transceiver.ShellChannel;
import org.mobicents.ss7.management.transceiver.ShellServerChannel;
/**
* @author amit bhayani
* @author kulikov
*/
public class ShellExecutor extends Task {
Logger logger = Logger.getLogger(ShellExecutor.class);
private ChannelProvider provider;
private ShellServerChannel serverChannel;
private ShellChannel channel;
private ChannelSelector selector;
private ChannelSelectionKey skey;
private MessageFactory messageFactory = null;
private String rxMessage = "";
private String txMessage = "";
private volatile boolean started = false;
private String address;
private int port;
private volatile LinksetExecutor linksetExecutor = null;
private volatile M3UAShellExecutor m3UAShellExecutor = null;
private volatile SccpExecutor sccpExecutor = null;
public ShellExecutor(Scheduler scheduler) throws IOException {
super(scheduler);
}
public SccpExecutor getSccpExecutor() {
return sccpExecutor;
}
public void setSccpExecutor(SccpExecutor sccpExecutor) {
this.sccpExecutor = sccpExecutor;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public void start() throws IOException {
logger.info("Starting SS7 management shell environment");
provider = ChannelProvider.provider();
serverChannel = provider.openServerChannel();
InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port);
serverChannel.bind(inetSocketAddress);
selector = provider.openSelector();
skey = serverChannel.register(selector, SelectionKey.OP_ACCEPT);
messageFactory = ChannelProvider.provider().getMessageFactory();
this.logger.info(String.format("ShellExecutor listening at %s", inetSocketAddress));
this.started = true;
this.activate(false);
scheduler.submit(this,scheduler.MANAGEMENT_QUEUE);
}
public void stop() {
this.started = false;
try {
skey.cancel();
if (channel != null) {
channel.close();
}
serverChannel.close();
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
this.logger.info("Stopped ShellExecutor service");
}
public LinksetExecutor getLinksetExecutor() {
return linksetExecutor;
}
public void setLinksetExecutor(LinksetExecutor linksetExecutor) {
this.linksetExecutor = linksetExecutor;
}
public M3UAShellExecutor getM3UAShellExecutor() {
return m3UAShellExecutor;
}
public void setM3UAShellExecutor(M3UAShellExecutor shellExecutor) {
m3UAShellExecutor = shellExecutor;
}
public int getQueueNumber()
{
return scheduler.MANAGEMENT_QUEUE;
}
public long perform() {
if(!this.started)
return 0;
try {
FastSet<ChannelSelectionKey> keys = selector.selectNow();
for (FastSet.Record record = keys.head(), end = keys.tail(); (record = record.getNext()) != end;) {
ChannelSelectionKey key = (ChannelSelectionKey) keys.valueOf(record);
if (key.isAcceptable()) {
accept();
} else if (key.isReadable()) {
ShellChannel chan = (ShellChannel) key.channel();
Message msg = (Message) chan.receive();
if (msg != null) {
rxMessage = msg.toString();
System.out.println("received " + rxMessage);
if (rxMessage.compareTo("disconnect") == 0) {
this.txMessage = "Bye";
chan.send(messageFactory.createMessage(txMessage));
} else {
String[] options = rxMessage.split(" ");
Subject subject = Subject.getSubject(options[0]);
if (subject == null) {
chan.send(messageFactory.createMessage("Invalid Subject"));
} else {
// Nullify examined options
//options[0] = null;
switch (subject) {
case LINKSET:
if(this.linksetExecutor == null){
this.txMessage = "Error! LinksetExecutor is null";
} else{
this.txMessage = this.linksetExecutor.execute(options);
}
break;
case SCTP:
case M3UA:
if(this.m3UAShellExecutor == null){
this.txMessage = "Error! M3UAShellExecutor is null";
} else {
this.txMessage = this.m3UAShellExecutor.execute(options);
}
break;
case SCCP:
if(this.sccpExecutor == null){
this.txMessage = "Error! SccpExecutor is null";
} else {
this.txMessage = this.sccpExecutor.execute(options);
}
break;
default:
this.txMessage = "Invalid Subject";
break;
}
chan.send(messageFactory.createMessage(this.txMessage));
}
} // if (rxMessage.compareTo("disconnect")
} // if (msg != null)
// TODO Handle message
rxMessage = "";
} else if (key.isWritable() && txMessage.length() > 0) {
if (this.txMessage.compareTo("Bye") == 0) {
this.closeChannel();
}
// else {
// ShellChannel chan = (ShellChannel) key.channel();
// System.out.println("Sending " + txMessage);
// chan.send(messageFactory.createMessage(txMessage));
this.txMessage = "";
}
}
} catch (IOException e) {
logger.error("IO Exception while operating on ChannelSelectionKey. Client CLI connection will be closed now", e);
try {
this.closeChannel();
} catch (IOException e1) {
logger.error("IO Exception while closing Channel", e);
}
} catch (Exception e){
logger.error("Exception while operating on ChannelSelectionKey. Client CLI connection will be closed now", e);
try {
this.closeChannel();
} catch (IOException e1) {
logger.error("IO Exception while closing Channel", e);
}
}
if(this.started)
scheduler.submit(this,scheduler.MANAGEMENT_QUEUE);
return 0;
}
private void accept() throws IOException {
channel = serverChannel.accept();
skey.cancel();
skey = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
private void closeChannel() throws IOException {
if (channel != null) {
try {
this.channel.close();
} catch (IOException e) {
logger.error("Error closing channel", e);
}
}
skey.cancel();
skey = serverChannel.register(selector, SelectionKey.OP_ACCEPT);
}
} |
package net.littlebigisland.droidibus.ibus;
/**
* This should be better explained. Basically, we hold an enum with two values,
* the source system and the method name that actually creates the data for the method
* we want. Of course the Source system tells you which class you'll find these methods in.
* e.x. OnBoardMonitor == BoardMonitorSystemCommand
*/
public enum IBusCommandsEnum {
// BoardMonitor to IKE Commands
BMToIKEGetIgnitionStatus(DeviceAddressEnum.OnBoardMonitor, "getIgnitionStatus"),
BMToIKEGetTime(DeviceAddressEnum.OnBoardMonitor, "getTime"),
BMToIKEGetDate(DeviceAddressEnum.OnBoardMonitor, "getDate"),
BMToIKEGetOutdoorTemp(DeviceAddressEnum.OnBoardMonitor, "getOutdoorTemp"),
BMToIKEGetFuel1(DeviceAddressEnum.OnBoardMonitor, "getFuel1"),
BMToIKEGetFuel2(DeviceAddressEnum.OnBoardMonitor, "getFuel2"),
BMToIKEGetRange(DeviceAddressEnum.OnBoardMonitor, "getRange"),
BMToIKEGetAvgSpeed(DeviceAddressEnum.OnBoardMonitor, "getAvgSpeed"),
BMToIKEResetFuel1(DeviceAddressEnum.OnBoardMonitor, "resetFuel1"),
BMToIKEResetFuel2(DeviceAddressEnum.OnBoardMonitor, "resetFuel2"),
BMToIKEResetAvgSpeed(DeviceAddressEnum.OnBoardMonitor, "resetAvgSpeed"),
BMToIKESetTime(DeviceAddressEnum.OnBoardMonitor, "setTime"),
BMToIKESetDate(DeviceAddressEnum.OnBoardMonitor, "setDate"),
// BoardMonitor to Radio Commands
BMToRadioGetStatus(DeviceAddressEnum.OnBoardMonitor, "getRadioStatus"),
BMToRadioCDStatus(DeviceAddressEnum.OnBoardMonitor, "sendCDPlayerMessage"),
BMToRadioPwrPress(DeviceAddressEnum.OnBoardMonitor, "sendRadioPwrPress"),
BMToRadioPwrRelease(DeviceAddressEnum.OnBoardMonitor, "sendRadioPwrRelease"),
BMToRadioTonePress(DeviceAddressEnum.OnBoardMonitor, "sendTonePress"),
BMToRadioToneRelease(DeviceAddressEnum.OnBoardMonitor, "sendToneRelease"),
BMToRadioModePress(DeviceAddressEnum.OnBoardMonitor, "sendModePress"),
BMToRadioModeRelease(DeviceAddressEnum.OnBoardMonitor, "sendModeRelease"),
BMToRadioVolumeUp(DeviceAddressEnum.OnBoardMonitor, "sendVolumeUp"),
BMToRadioVolumeDown(DeviceAddressEnum.OnBoardMonitor, "sendVolumeDown"),
BMToRadioTuneFwdPress(DeviceAddressEnum.OnBoardMonitor, "sendSeekFwdPress"),
BMToRadioTuneFwdRelease(DeviceAddressEnum.OnBoardMonitor, "sendSeekFwdRelease"),
BMToRadioTuneRevPress(DeviceAddressEnum.OnBoardMonitor, "sendSeekRevPress"),
BMToRadioTuneRevRelease(DeviceAddressEnum.OnBoardMonitor, "sendSeekRevRelease"),
BMToRadioFMPress(DeviceAddressEnum.OnBoardMonitor, "sendFMPress"),
BMToRadioFMRelease(DeviceAddressEnum.OnBoardMonitor, "sendFMRelease"),
BMToRadioAMPress(DeviceAddressEnum.OnBoardMonitor, "sendAMPress"),
BMToRadioAMRelease(DeviceAddressEnum.OnBoardMonitor, "sendAMRelease"),
BMToRadioInfoPress(DeviceAddressEnum.OnBoardMonitor, "sendInfoPress"),
BMToRadioInfoRelease(DeviceAddressEnum.OnBoardMonitor, "sendInfoRelease"),
// BoardMonitor to Light Control Module Commands
BMToLCMGetDimmerStatus(DeviceAddressEnum.OnBoardMonitor, "getLightDimmerStatus"),
// BoardMonitor to General Module Commands
BMToGMGetDoorStatus(DeviceAddressEnum.OnBoardMonitor, "getDoorsRequest"),
// BoardMonitor to Global Broadcast Address Commands
BMToGlobalBroadcastAliveMessage(DeviceAddressEnum.OnBoardMonitor, "sendAliveMessage"),
// Steering Wheel to Radio Commands
SWToRadioVolumeUp(DeviceAddressEnum.MultiFunctionSteeringWheel, "sendVolumeUp"),
SWToRadioVolumeDown(DeviceAddressEnum.MultiFunctionSteeringWheel, "sendVolumeDown"),
SWToRadioTuneFwdPress(DeviceAddressEnum.MultiFunctionSteeringWheel, "sendTuneFwdPress"),
SWToRadioTuneFwdRelease(DeviceAddressEnum.MultiFunctionSteeringWheel, "sendTuneFwdRelease"),
SWToRadioTuneRevPress(DeviceAddressEnum.MultiFunctionSteeringWheel, "sendTunePrevPress"),
SWToRadioTuneRevRelease(DeviceAddressEnum.MultiFunctionSteeringWheel, "sendTunePrevRelease");
private final DeviceAddressEnum system;
private final String methodName;
IBusCommandsEnum(DeviceAddressEnum system, String methodName) {
this.system = system;
this.methodName = methodName;
}
public DeviceAddressEnum getSystem(){
return system;
}
public String getMethodName(){
return methodName;
}
} |
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.ensembl.healthcheck.AssemblyNameInfo;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.SqlTemplate;
import org.ensembl.healthcheck.util.Utils;
/**
* Checks that meta_value contents in the meta table are OK. Only one meta table at a time is done here; checks for the consistency of the
* meta table across species are done in MetaCrossSpecies.
*/
public class MetaValues extends SingleDatabaseTestCase {
private boolean isSangerVega = false;
public MetaValues() {
addToGroup("post_genebuild");
addToGroup("release");
addToGroup("compara-ancestral");
addToGroup("pre-compara-handover");
addToGroup("post-compara-handover");
setTeamResponsible(Team.RELEASE_COORDINATOR);
setSecondTeamResponsible(Team.GENEBUILD);
setDescription("Check that meta_value contents in the meta table are OK");
}
/**
* Checks that meta_value contents in the meta table are OK.
*
* @param dbre
* The database to check.
* @return True if the test passed.
*/
public boolean run(final DatabaseRegistryEntry dbre) {
isSangerVega = dbre.getType() == DatabaseType.SANGER_VEGA;
boolean result = true;
Connection con = dbre.getConnection();
Species species = dbre.getSpecies();
if (species == Species.ANCESTRAL_SEQUENCES) {
// The rest of the tests are not relevant for the ancestral sequences DB
return result;
}
if (!isSangerVega) {// do not check for sangervega
result &= checkOverlappingRegions(con);
}
result &= checkAssemblyMapping(con);
result &= checkTaxonomyID(dbre);
result &= checkAssemblyWeb(dbre);
if (dbre.getType() == DatabaseType.CORE) {
result &= checkDates(dbre);
result &= checkGenebuildID(con);
}
result &= checkCoordSystemTableCases(con);
result &= checkBuildLevel(dbre);
result &= checkSample(dbre);
//Use an AssemblyNameInfo object to get the assembly information
AssemblyNameInfo assembly = new AssemblyNameInfo(con);
String metaTableAssemblyDefault = assembly.getMetaTableAssemblyDefault();
logger.finest("assembly.default from meta table: " + metaTableAssemblyDefault);
String dbNameAssemblyVersion = assembly.getDBNameAssemblyVersion();
logger.finest("Assembly version from DB name: " + dbNameAssemblyVersion);
String metaTableAssemblyVersion = assembly.getMetaTableAssemblyVersion();
logger.finest("meta table assembly version: " + metaTableAssemblyVersion);
String metaTableAssemblyPrefix = assembly.getMetaTableAssemblyPrefix();
logger.finest("meta table assembly prefix: " + metaTableAssemblyPrefix);
if (metaTableAssemblyVersion == null || metaTableAssemblyDefault == null || metaTableAssemblyPrefix == null || dbNameAssemblyVersion == null) {
ReportManager.problem(this, con, "Cannot get all information from meta table - check for null values");
} else {
// Check that assembly prefix is valid and corresponds to this species
// Prefix is OK as long as it starts with the valid one
Species dbSpecies = dbre.getSpecies();
String correctPrefix = Species.getAssemblyPrefixForSpecies(dbSpecies);
if (!isSangerVega) {// do not check this for sangervega
if (correctPrefix == null) {
logger.info("Can't get correct assembly prefix for " + dbSpecies.toString());
} else {
if (!metaTableAssemblyPrefix.toUpperCase().startsWith(correctPrefix.toUpperCase())) {
ReportManager.problem(this, con, "Database species is " + dbSpecies + " but assembly prefix " + metaTableAssemblyPrefix + " should have prefix beginning with " + correctPrefix);
result = false;
} else {
ReportManager.correct(this, con, "Meta table assembly prefix (" + metaTableAssemblyPrefix + ") is correct for " + dbSpecies);
}
}
}
}
result &= checkGenebuildMethod(dbre);
result &= checkAssemblyAccessionUpdate(dbre);
result &= checkRepeatAnalysis(dbre);
result &= checkForSchemaPatchLineBreaks(dbre);
return result;
} // run
// this HC will check the Meta table contains the assembly.overlapping_regions and
// that it is set to false (so no overlapping regions in the genome)
private boolean checkOverlappingRegions(Connection con) {
boolean result = true;
// check that certain keys exist
String[] metaKeys = { "assembly.overlapping_regions" };
for (int i = 0; i < metaKeys.length; i++) {
String metaKey = metaKeys[i];
int rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key='" + metaKey + "'");
if (rows == 0) {
result = false;
ReportManager.problem(this, con, "No entry in meta table for " + metaKey + ". It might need to run the misc-scripts/overlapping_regions.pl script");
} else {
String[] metaValue = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='" + metaKey + "'");
if (metaValue[0].equals("1")) {
// there are overlapping regions !! API might behave oddly
ReportManager.problem(this, con, "There are overlapping regions in the database (e.g. two versions of the same chromosomes). The API"
+ " might have unexpected results when trying to map features to that coordinate system.");
result = false;
} else {
ReportManager.correct(this, con, metaKey + " entry present");
}
}
}
return result;
}
private boolean checkAssemblyMapping(Connection con) {
boolean result = true;
// Check formatting of assembly.mapping entries; should be of format
// coord_system1{:default}|coord_system2{:default} with optional third
// coordinate system
// and all coord systems should be valid from coord_system
// can also have # instead of | as used in unfinished contigs etc
Pattern assemblyMappingPattern = Pattern.compile("^([a-zA-Z0-9.]+):?([a-zA-Z0-9._]+)?[\\|#]([a-zA-Z0-9._]+):?([a-zA-Z0-9._]+)?([\\|#]([a-zA-Z0-9.]+):?([a-zA-Z0-9._]+)?)?$");
String[] validCoordSystems = DBUtils.getColumnValues(con, "SELECT name FROM coord_system");
String[] mappings = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.mapping'");
for (int i = 0; i < mappings.length; i++) {
Matcher matcher = assemblyMappingPattern.matcher(mappings[i]);
if (!matcher.matches()) {
result = false;
ReportManager.problem(this, con, "Coordinate system mapping " + mappings[i] + " is not in the correct format");
} else {
// if format is OK, check coord systems are valid
boolean valid = true;
String cs1 = matcher.group(1);
String assembly1 = matcher.group(2);
String cs2 = matcher.group(3);
String assembly2 = matcher.group(4);
String cs3 = matcher.group(6);
String assembly3 = matcher.group(7);
if (!Utils.stringInArray(cs1, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Source co-ordinate system " + cs1 + " is not in the coord_system table");
}
if (!Utils.stringInArray(cs2, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Target co-ordinate system " + cs2 + " is not in the coord_system table");
}
// third coordinate system is optional
if (cs3 != null && !Utils.stringInArray(cs3, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Third co-ordinate system in mapping (" + cs3 + ") is not in the coord_system table");
}
if (valid) {
ReportManager.correct(this, con, "Coordinate system mapping " + mappings[i] + " is OK");
}
result &= valid;
// check that coord_system:version pairs listed here exist in the coord_system table
result &= checkCoordSystemVersionPairs(con, cs1, assembly1, cs2, assembly2, cs3, assembly3);
// check that coord systems are specified in lower-case
result &= checkCoordSystemCase(con, cs1, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs2, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs3, "meta assembly.mapping");
}
}
return result;
}
/**
* Check that coordinate system:assembly pairs in assembly.mappings match what's in the coord system table
*/
private boolean checkCoordSystemVersionPairs(Connection con, String cs1, String assembly1, String cs2, String assembly2, String cs3, String assembly3) {
boolean result = true;
List<String> coordSystemsAndVersions = DBUtils.getColumnValuesList(con, "SELECT CONCAT_WS(':',name,version) FROM coord_system");
result &= checkCoordSystemPairInList(con, cs1, assembly1, coordSystemsAndVersions);
result &= checkCoordSystemPairInList(con, cs2, assembly2, coordSystemsAndVersions);
if (cs3 != null) {
result &= checkCoordSystemPairInList(con, cs3, assembly3, coordSystemsAndVersions);
}
return result;
}
/**
* Check if a particular coordinate system:version pair is in a list. Deal with nulls appropriately.
*/
private boolean checkCoordSystemPairInList(Connection con, String cs, String assembly, List<String> coordSystems) {
boolean result = true;
String toCompare = (assembly != null) ? cs + ":" + assembly : cs;
if (!coordSystems.contains(toCompare)) {
ReportManager.problem(this, con, "Coordinate system name/version " + toCompare + " in assembly.mapping does not appear in coord_system table.");
result = false;
}
return result;
}
/**
* @return true if cs is all lower case (or null), false otherwise.
*/
private boolean checkCoordSystemCase(Connection con, String cs, String desc) {
if (cs == null) {
return true;
}
boolean result = true;
if (cs.equals(cs.toLowerCase())) {
ReportManager.correct(this, con, "Co-ordinate system name " + cs + " all lower case in " + desc);
result = true;
} else {
ReportManager.problem(this, con, "Co-ordinate system name " + cs + " is not all lower case in " + desc);
result = false;
}
return result;
}
/**
* Check that all coord systems in the coord_system table are lower case.
*/
private boolean checkCoordSystemTableCases(Connection con) {
// TODO - table name in report
boolean result = true;
String[] coordSystems = DBUtils.getColumnValues(con, "SELECT name FROM coord_system");
for (int i = 0; i < coordSystems.length; i++) {
result &= checkCoordSystemCase(con, coordSystems[i], "coord_system");
}
return result;
}
private boolean checkTaxonomyID(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// Check that the taxonomy ID matches a known one.
// The taxonomy ID-species mapping is held in the Species class.
Species species = dbre.getSpecies();
String dbTaxonID = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='species.taxonomy_id'");
logger.finest("Taxonomy ID from database: " + dbTaxonID);
if (dbTaxonID.equals(Species.getTaxonomyID(species))) {
ReportManager.correct(this, con, "Taxonomy ID " + dbTaxonID + " is correct for " + species.toString());
} else {
result = false;
ReportManager.problem(this, con, "Taxonomy ID " + dbTaxonID + " in database is not correct - should be " + Species.getTaxonomyID(species) + " for " + species.toString());
}
return result;
}
private boolean checkAssemblyWeb(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// Check that the taxonomy ID matches a known one.
// The taxonomy ID-species mapping is held in the Species class.
String[] allowedTypes = {"GenBank Assembly ID", "EMBL-Bank WGS Master"};
String[] allowedSources = {"NCBI", "ENA", "DDBJ"};
String WebType = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.web_accession_type'");
String WebSource = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.web_accession_source'");
if (WebType.length() > 0) {
if (!Utils.stringInArray(WebType, allowedTypes, true)) {
result = false;
ReportManager.problem(this, con, "Web accession type " + WebType + " is not allowed");
}
}
if (WebSource.length() > 0) {
if (!Utils.stringInArray(WebSource, allowedSources, true)) {
result = false;
ReportManager.problem(this, con, "Web accession source " + WebSource + " is not allowed");
}
}
return result;
}
private boolean checkDates(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] keys = { "genebuild.start_date", "assembly.date", "genebuild.initial_release_date", "genebuild.last_geneset_update" };
String date = "[0-9]{4}-[0-9]{2}";
String[] regexps = { date + "-[a-zA-Z]*", date, date, date };
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
String regexp = regexps[i];
String value = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='" + key + "'");
if (value == null || value.length() == 0) {
ReportManager.problem(this, con, "No " + key + " entry in meta table");
result = false;
}
result &= checkMetaKey(con, key, value, regexp);
if (result) {
result &= checkDateFormat(con, key, value);
}
if (result) {
ReportManager.correct(this, con, key + " is present & in a valid format");
}
}
// some more checks for sanity of dates
int startDate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.start_date'").replaceAll("[^0-9]", "")).intValue();
int initialReleaseDate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.initial_release_date'").replaceAll("[^0-9]", "")).intValue();
int lastGenesetUpdate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.last_geneset_update'").replaceAll("[^0-9]", "")).intValue();
// check for genebuild.start_date >= genebuild.initial_release_date (not allowed as we cannot release a gene set before
// downloaded the evidence)
if (startDate >= initialReleaseDate) {
result = false;
ReportManager.problem(this, con, "genebuild.start_date is greater than or equal to genebuild.initial_release_date");
}
// check for genebuild.initial_release_date > genebuild.last_geneset_update (not allowed as we cannot update a gene set before
// its initial public release)
if (initialReleaseDate > lastGenesetUpdate) {
result = false;
ReportManager.problem(this, con, "genebuild.initial_release_date is greater than or equal to genebuild.last_geneset_update");
}
// check for current genebuild.last_geneset_update <= previous release genebuild.last_geneset_update
// AND the number of genes or transcripts or exons between the two releases has changed
// If the gene set has changed in any way since the previous release then the date should have been updated.
DatabaseRegistryEntry previous = getEquivalentFromSecondaryServer(dbre);
if (previous == null) {
return result;
}
Connection previousCon = previous.getConnection();
String previousLastGenesetUpdateString = DBUtils.getRowColumnValue(previousCon, "SELECT meta_value FROM meta WHERE meta_key='genebuild.last_geneset_update'").replaceAll("-", "");
if (previousLastGenesetUpdateString == null || previousLastGenesetUpdateString.length() == 0) {
ReportManager.problem(this, con, "Problem parsing last geneset update entry from previous database.");
return false;
}
int previousLastGenesetUpdate;
try {
previousLastGenesetUpdate = Integer.valueOf(previousLastGenesetUpdateString).intValue();
} catch (NumberFormatException e) {
ReportManager.problem(this, con, "Problem parsing last geneset update entry from previous database: " + Arrays.toString(e.getStackTrace()));
return false;
}
if (lastGenesetUpdate <= previousLastGenesetUpdate) {
int currentGeneCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM gene");
int currentTranscriptCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM transcript");
int currentExonCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM exon");
int previousGeneCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM gene");
int previousTranscriptCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM transcript");
int previousExonCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM exon");
if (currentGeneCount != previousGeneCount || currentTranscriptCount != previousTranscriptCount || currentExonCount != previousExonCount) {
ReportManager.problem(this, con, "Last geneset update entry is the same or older than the equivalent entry in the previous release and the number of genes, transcripts or exons has changed.");
result = false;
}
}
return result;
}
private boolean checkMetaKey(Connection con, String key, String s, String regexp) {
if (regexp != null) {
if (!s.matches(regexp)) {
ReportManager.problem(this, con, key + " " + s + " is not in correct format - should match " + regexp);
return false;
}
}
return true;
}
private boolean checkDateFormat(Connection con, String key, String s) {
int year = Integer.parseInt(s.substring(0, 4));
if (year < 2003 || year > 2050) {
ReportManager.problem(this, con, "Year part of " + key + " (" + year + ") is incorrect");
return false;
}
int month = Integer.parseInt(s.substring(5, 7));
if (month < 1 || month > 12) {
ReportManager.problem(this, con, "Month part of " + key + " (" + month + ") is incorrect");
return false;
}
return true;
}
private boolean checkGenebuildID(Connection con) {
String gbid = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.id'");
logger.finest("genebuild.id from database: " + gbid);
if (gbid == null || gbid.length() == 0) {
ReportManager.problem(this, con, "No genebuild.id entry in meta table");
return false;
} else if (!gbid.matches("[0-9]+")) {
ReportManager.problem(this, con, "genebuild.id " + gbid + " is not numeric");
return false;
}
ReportManager.correct(this, con, "genebuild.id " + gbid + " is present and numeric");
return true;
}
/**
* Check that at least some sort of genebuild.level-type key is present.
*/
private boolean checkBuildLevel(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] Tables = { "gene", "transcript", "exon", "repeat_feature", "dna_align_feature", "protein_align_feature", "simple_feature", "prediction_transcript", "prediction_exon" };
int exists = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta where meta_key like '%build.level'");
if (exists == 0) {
ReportManager.problem(this, con, "GB: No %build.level entries in the meta table - run ensembl/misc-scripts/meta_levels.pl");
}
int count = 0;
for (int i = 0; i < Tables.length; i++) {
String Table = Tables[i];
int rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM " + Table);
int key = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key = '" + Table + "build.level' ");
int toplevel = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM " + Table
+ " t, seq_region_attrib sra, attrib_type at WHERE t.seq_region_id = sra.seq_region_id AND sra.attrib_type_id = at.attrib_type_id AND at.code = 'toplevel' ");
if (rows != 0) {
if (key == 0) {
if (rows == toplevel) {
ReportManager.problem(this, con, "Table " + Table + " should have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
} else {
if (rows != toplevel) {
ReportManager.problem(this, con, "Table " + Table + " has some non toplevel regions, should not have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
}
} else {
if (key != 0) {
ReportManager.problem(this, con, "Empty table " + Table + " should not have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
}
}
if (count == Tables.length) {
ReportManager.correct(this, con, "Toplevel flags correctly set");
result = true;
}
return result;
}
/**
* Check that the genebuild.method entry exists and has one of the allowed values.
*/
private boolean checkGenebuildMethod(DatabaseRegistryEntry dbre) {
boolean result = true;
// only valid for core databases
if (dbre.getType() != DatabaseType.CORE) {
return true;
}
String[] allowedMethods = { "full_genebuild", "projection_build", "import", "mixed_strategy_build" };
Connection con = dbre.getConnection();
String method = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.method'");
if (method.equals("")) {
ReportManager.problem(this, con, "No genebuild.method entry present in Meta table");
return false;
}
if (!Utils.stringInArray(method, allowedMethods, true)) {
ReportManager.problem(this, con, "genebuild.method value " + method + " is not in list of allowed methods");
result = false;
} else {
ReportManager.correct(this, con, "genebuild.method " + method + " is valid");
}
return result;
}
private boolean checkAssemblyAccessionUpdate(DatabaseRegistryEntry dbre) {
boolean result = true;
// only valid for core databases
if (dbre.getType() != DatabaseType.CORE) {
return true;
}
Connection con = dbre.getConnection();
String currentAssemblyAccession = DBUtils.getMetaValue(con, "assembly.accession");
String currentAssemblyName = DBUtils.getMetaValue(con, "assembly.name");
if (currentAssemblyAccession.equals("")) {
ReportManager.problem(this, con, "No assembly.accession entry present in Meta table");
return false;
}
if (currentAssemblyName.equals("")) {
ReportManager.problem(this, con, "No assembly.name entry present in Meta table");
return false;
}
DatabaseRegistryEntry sec = getEquivalentFromSecondaryServer(dbre);
if (sec == null) {
logger.warning("Can't get equivalent database for " + dbre.getName());
return true;
}
logger.finest("Equivalent database on secondary server is " + sec.getName());
Connection previousCon = sec.getConnection();
String previousAssemblyAccession = DBUtils.getMetaValue(previousCon, "assembly.accession");
String previousAssemblyName = DBUtils.getMetaValue(previousCon, "assembly.name");
long currentAssemblyChecksum = DBUtils.getChecksum(con, "assembly");
long previousAssemblyChecksum = DBUtils.getChecksum(previousCon, "assembly");
boolean assemblyChanged = false;
boolean assemblyTableChanged = false;
boolean assemblyExceptionTableChanged = false;
if (currentAssemblyChecksum != previousAssemblyChecksum) {
assemblyTableChanged = true;
} else {
if (dbre.getSpecies() != Species.HOMO_SAPIENS) {
// compare assembly_exception tables (patches only) from each database
try {
Statement previousStmt = previousCon.createStatement();
Statement currentStmt = con.createStatement();
String sql = "SELECT * FROM assembly_exception WHERE exc_type LIKE ('PATCH_%') ORDER BY assembly_exception_id";
ResultSet previousRS = previousStmt.executeQuery(sql);
ResultSet currentRS = currentStmt.executeQuery(sql);
boolean assExSame = DBUtils.compareResultSets(currentRS, previousRS, this, "", false, false, "assembly_exception", false);
currentRS.close();
previousRS.close();
currentStmt.close();
previousStmt.close();
assemblyExceptionTableChanged = !assExSame;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
assemblyChanged = assemblyTableChanged || assemblyExceptionTableChanged;
if (assemblyChanged == previousAssemblyAccession.equals(currentAssemblyAccession) && previousAssemblyName.equals(currentAssemblyName) ) {
result = false;
String errorMessage = "assembly.accession and assembly.name values need to be updated when "
+ "the assembly table changes or new patches are added to the assembly exception table\n"
+ "previous assembly.accession: " + previousAssemblyAccession + " assembly.name: " + previousAssemblyName
+ " current assembly.accession: " + currentAssemblyAccession + " assembly.name: " + currentAssemblyName + "\n"
+ "assembly table changed:";
if (assemblyTableChanged) {
errorMessage += " yes;";
} else {
errorMessage += " no;";
}
errorMessage += " assembly exception patches changed:";
if (assemblyExceptionTableChanged) {
errorMessage += " yes";
} else {
errorMessage += " no";
}
ReportManager.problem(this, con, errorMessage);
}
if (result) {
ReportManager.correct(this, con, "assembly.accession and assembly.name values are correct");
}
return result;
}
/**
* Check that all meta_values with meta_key 'repeat.analysis' reference analysis.logic_name
*/
private boolean checkRepeatAnalysis(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] repeatAnalyses = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta LEFT JOIN analysis ON meta_value = logic_name WHERE meta_key = 'repeat.analysis' AND analysis_id IS NULL");
if (repeatAnalyses.length > 0) {
ReportManager.problem(this, con, "The following values for meta_key repeat.analysis don't have a corresponding logic_name entry in the analysis table: " + Utils.arrayToString(repeatAnalyses,",") );
} else {
ReportManager.correct(this, con, "All values for meta_key repeat.analysis have a corresponding logic_name entry in the analysis table");
}
return result;
}
private boolean checkForSchemaPatchLineBreaks(DatabaseRegistryEntry dbre) {
SqlTemplate t = DBUtils.getSqlTemplate(dbre);
String metaKey = "patch";
String sql = "select meta_id from meta where meta_key =? and species_id IS NULL and meta_value like ?";
List<Integer> ids = t.queryForDefaultObjectList(sql, Integer.class, metaKey, "%\n%");
if(!ids.isEmpty()) {
String idsJoined = Utils.listToString(ids, ",");
String usefulSql = "select * from meta where meta_id IN ("+idsJoined+")";
String msg = String.format("The meta ids [%s] had values with linebreaks.\nUSEFUL SQL: %s", idsJoined, usefulSql);
ReportManager.problem(this, dbre.getConnection(), msg);
return false;
}
return true;
}
private boolean checkSample(DatabaseRegistryEntry dbre) {
SqlTemplate t = DBUtils.getSqlTemplate(dbre);
String metaKey = "sample.location_text";
String sql = "select meta_value from meta where meta_key = ?";
List<String> value = t.queryForDefaultObjectList(sql, String.class, metaKey);
if (!value.isEmpty()) {
String linkedKey = "sample.location_param";
String linkedSql = "select meta_value from meta where meta_key = ?";
List<String> linkedValue = t.queryForDefaultObjectList(linkedSql, String.class, linkedKey);
if(!linkedValue.equals(value)) {
ReportManager.problem(this, dbre.getConnection(), "Keys " + metaKey + " and " + linkedKey + " do not have same value");
return false;
}
}
return true;
}
} // MetaValues |
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.ensembl.healthcheck.AssemblyNameInfo;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.SqlTemplate;
import org.ensembl.healthcheck.util.Utils;
/**
* Checks that meta_value contents in the meta table are OK. Only one meta table at a time is done here; checks for the consistency of the
* meta table across species are done in MetaCrossSpecies.
*/
public class MetaValues extends SingleDatabaseTestCase {
private boolean isSangerVega = false;
public MetaValues() {
addToGroup("post_genebuild");
addToGroup("release");
addToGroup("compara-ancestral");
addToGroup("pre-compara-handover");
addToGroup("post-compara-handover");
setTeamResponsible(Team.GENEBUILD);
setSecondTeamResponsible(Team.RELEASE_COORDINATOR);
setDescription("Check that meta_value contents in the meta table are OK");
}
/**
* Checks that meta_value contents in the meta table are OK.
*
* @param dbre
* The database to check.
* @return True if the test passed.
*/
public boolean run(final DatabaseRegistryEntry dbre) {
isSangerVega = dbre.getType() == DatabaseType.SANGER_VEGA;
boolean result = true;
Connection con = dbre.getConnection();
Species species = dbre.getSpecies();
if (species == Species.ANCESTRAL_SEQUENCES) {
// The rest of the tests are not relevant for the ancestral sequences DB
return result;
}
if (!isSangerVega && dbre.getType() != DatabaseType.VEGA) {// do not check for sangervega
result &= checkOverlappingRegions(con);
}
result &= checkAssemblyMapping(con);
result &= checkTaxonomyID(dbre);
result &= checkAssemblyWeb(dbre);
if (dbre.getType() == DatabaseType.CORE) {
result &= checkDates(dbre);
result &= checkGenebuildID(con);
result &= checkGenebuildMethod(dbre);
result &= checkAssemblyAccessionUpdate(dbre);
}
result &= checkCoordSystemTableCases(con);
result &= checkBuildLevel(dbre);
result &= checkSample(dbre);
//Use an AssemblyNameInfo object to get the assembly information
AssemblyNameInfo assembly = new AssemblyNameInfo(con);
String metaTableAssemblyDefault = assembly.getMetaTableAssemblyDefault();
logger.finest("assembly.default from meta table: " + metaTableAssemblyDefault);
String dbNameAssemblyVersion = assembly.getDBNameAssemblyVersion();
logger.finest("Assembly version from DB name: " + dbNameAssemblyVersion);
String metaTableAssemblyVersion = assembly.getMetaTableAssemblyVersion();
logger.finest("meta table assembly version: " + metaTableAssemblyVersion);
String metaTableAssemblyPrefix = assembly.getMetaTableAssemblyPrefix();
logger.finest("meta table assembly prefix: " + metaTableAssemblyPrefix);
if (metaTableAssemblyVersion == null || metaTableAssemblyDefault == null || metaTableAssemblyPrefix == null || dbNameAssemblyVersion == null) {
ReportManager.problem(this, con, "Cannot get all information from meta table - check for null values");
} else {
// Check that assembly prefix is valid and corresponds to this species
// Prefix is OK as long as it starts with the valid one
Species dbSpecies = dbre.getSpecies();
String correctPrefix = Species.getAssemblyPrefixForSpecies(dbSpecies);
if (!isSangerVega) {// do not check this for sangervega
if (correctPrefix == null) {
logger.info("Can't get correct assembly prefix for " + dbSpecies.toString());
} else {
if (!metaTableAssemblyPrefix.toUpperCase().startsWith(correctPrefix.toUpperCase())) {
ReportManager.problem(this, con, "Database species is " + dbSpecies + " but assembly prefix " + metaTableAssemblyPrefix + " should have prefix beginning with " + correctPrefix + " There should not be any version number, check Species.java is using the right value");
result = false;
}
}
}
}
result &= checkRepeatAnalysis(dbre);
result &= checkForSchemaPatchLineBreaks(dbre);
return result;
} // run
// this HC will check the Meta table contains the assembly.overlapping_regions and
// that it is set to false (so no overlapping regions in the genome)
private boolean checkOverlappingRegions(Connection con) {
boolean result = true;
// check that certain keys exist
String[] metaKeys = { "assembly.overlapping_regions" };
for (int i = 0; i < metaKeys.length; i++) {
String metaKey = metaKeys[i];
int rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key='" + metaKey + "'");
if (rows == 0) {
result = false;
ReportManager.problem(this, con, "No entry in meta table for " + metaKey + ". It might need to run the misc-scripts/overlapping_regions.pl script");
} else {
String[] metaValue = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='" + metaKey + "'");
if (metaValue[0].equals("1")) {
// there are overlapping regions !! API might behave oddly
ReportManager.problem(this, con, "There are overlapping regions in the database (e.g. two versions of the same chromosomes). The API"
+ " might have unexpected results when trying to map features to that coordinate system.");
result = false;
}
}
}
return result;
}
private boolean checkAssemblyMapping(Connection con) {
boolean result = true;
// Check formatting of assembly.mapping entries; should be of format
// coord_system1{:default}|coord_system2{:default} with optional third
// coordinate system
// and all coord systems should be valid from coord_system
// can also have # instead of | as used in unfinished contigs etc
Pattern assemblyMappingPattern = Pattern.compile("^([a-zA-Z0-9.]+):?([a-zA-Z0-9._]+)?[\\|#]([a-zA-Z0-9._]+):?([a-zA-Z0-9._]+)?([\\|#]([a-zA-Z0-9.]+):?([a-zA-Z0-9._]+)?)?$");
String[] validCoordSystems = DBUtils.getColumnValues(con, "SELECT name FROM coord_system");
String[] mappings = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.mapping'");
for (int i = 0; i < mappings.length; i++) {
Matcher matcher = assemblyMappingPattern.matcher(mappings[i]);
if (!matcher.matches()) {
result = false;
ReportManager.problem(this, con, "Coordinate system mapping " + mappings[i] + " is not in the correct format");
} else {
// if format is OK, check coord systems are valid
boolean valid = true;
String cs1 = matcher.group(1);
String assembly1 = matcher.group(2);
String cs2 = matcher.group(3);
String assembly2 = matcher.group(4);
String cs3 = matcher.group(6);
String assembly3 = matcher.group(7);
if (!Utils.stringInArray(cs1, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Source co-ordinate system " + cs1 + " is not in the coord_system table");
}
if (!Utils.stringInArray(cs2, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Target co-ordinate system " + cs2 + " is not in the coord_system table");
}
// third coordinate system is optional
if (cs3 != null && !Utils.stringInArray(cs3, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Third co-ordinate system in mapping (" + cs3 + ") is not in the coord_system table");
}
if (valid) {
ReportManager.correct(this, con, "Coordinate system mapping " + mappings[i] + " is OK");
}
result &= valid;
// check that coord_system:version pairs listed here exist in the coord_system table
result &= checkCoordSystemVersionPairs(con, cs1, assembly1, cs2, assembly2, cs3, assembly3);
// check that coord systems are specified in lower-case
result &= checkCoordSystemCase(con, cs1, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs2, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs3, "meta assembly.mapping");
}
}
return result;
}
/**
* Check that coordinate system:assembly pairs in assembly.mappings match what's in the coord system table
*/
private boolean checkCoordSystemVersionPairs(Connection con, String cs1, String assembly1, String cs2, String assembly2, String cs3, String assembly3) {
boolean result = true;
List<String> coordSystemsAndVersions = DBUtils.getColumnValuesList(con, "SELECT CONCAT_WS(':',name,version) FROM coord_system");
result &= checkCoordSystemPairInList(con, cs1, assembly1, coordSystemsAndVersions);
result &= checkCoordSystemPairInList(con, cs2, assembly2, coordSystemsAndVersions);
if (cs3 != null) {
result &= checkCoordSystemPairInList(con, cs3, assembly3, coordSystemsAndVersions);
}
return result;
}
/**
* Check if a particular coordinate system:version pair is in a list. Deal with nulls appropriately.
*/
private boolean checkCoordSystemPairInList(Connection con, String cs, String assembly, List<String> coordSystems) {
boolean result = true;
String toCompare = (assembly != null) ? cs + ":" + assembly : cs;
if (!coordSystems.contains(toCompare)) {
ReportManager.problem(this, con, "Coordinate system name/version " + toCompare + " in assembly.mapping does not appear in coord_system table.");
result = false;
}
return result;
}
/**
* @return true if cs is all lower case (or null), false otherwise.
*/
private boolean checkCoordSystemCase(Connection con, String cs, String desc) {
if (cs == null) {
return true;
}
boolean result = true;
if (cs.equals(cs.toLowerCase())) {
ReportManager.correct(this, con, "Co-ordinate system name " + cs + " all lower case in " + desc);
result = true;
} else {
ReportManager.problem(this, con, "Co-ordinate system name " + cs + " is not all lower case in " + desc);
result = false;
}
return result;
}
/**
* Check that all coord systems in the coord_system table are lower case.
*/
private boolean checkCoordSystemTableCases(Connection con) {
// TODO - table name in report
boolean result = true;
String[] coordSystems = DBUtils.getColumnValues(con, "SELECT name FROM coord_system");
for (int i = 0; i < coordSystems.length; i++) {
result &= checkCoordSystemCase(con, coordSystems[i], "coord_system");
}
return result;
}
private boolean checkTaxonomyID(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// Check that the taxonomy ID matches a known one.
// The taxonomy ID-species mapping is held in the Species class.
Species species = dbre.getSpecies();
String dbTaxonID = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='species.taxonomy_id'");
logger.finest("Taxonomy ID from database: " + dbTaxonID);
if (dbTaxonID.equals(Species.getTaxonomyID(species))) {
ReportManager.correct(this, con, "Taxonomy ID " + dbTaxonID + " is correct for " + species.toString());
} else {
result = false;
ReportManager.problem(this, con, "Taxonomy ID " + dbTaxonID + " in database is not correct - should be " + Species.getTaxonomyID(species) + " for " + species.toString());
}
return result;
}
private boolean checkAssemblyWeb(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// Check that the taxonomy ID matches a known one.
// The taxonomy ID-species mapping is held in the Species class.
String[] allowedTypes = {"GenBank Assembly ID", "EMBL-Bank WGS Master"};
String[] allowedSources = {"NCBI", "ENA", "DDBJ"};
String WebType = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.web_accession_type'");
String WebSource = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.web_accession_source'");
if (WebType.length() > 0) {
if (!Utils.stringInArray(WebType, allowedTypes, true)) {
result = false;
ReportManager.problem(this, con, "Web accession type " + WebType + " is not allowed");
}
}
if (WebSource.length() > 0) {
if (!Utils.stringInArray(WebSource, allowedSources, true)) {
result = false;
ReportManager.problem(this, con, "Web accession source " + WebSource + " is not allowed");
}
}
return result;
}
private boolean checkDates(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] keys = { "genebuild.start_date", "assembly.date", "genebuild.initial_release_date", "genebuild.last_geneset_update" };
String date = "[0-9]{4}-[0-9]{2}";
String[] regexps = { date + "-[a-zA-Z]*", date, date, date };
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
String regexp = regexps[i];
String value = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='" + key + "'");
if (value == null || value.length() == 0) {
ReportManager.problem(this, con, "No " + key + " entry in meta table");
result = false;
}
result &= checkMetaKey(con, key, value, regexp);
if (result) {
result &= checkDateFormat(con, key, value);
}
if (result) {
ReportManager.correct(this, con, key + " is present & in a valid format");
}
}
// some more checks for sanity of dates
int startDate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.start_date'").replaceAll("[^0-9]", "")).intValue();
int initialReleaseDate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.initial_release_date'").replaceAll("[^0-9]", "")).intValue();
int lastGenesetUpdate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.last_geneset_update'").replaceAll("[^0-9]", "")).intValue();
// check for genebuild.start_date >= genebuild.initial_release_date (not allowed as we cannot release a gene set before
// downloaded the evidence)
if (startDate >= initialReleaseDate) {
result = false;
ReportManager.problem(this, con, "genebuild.start_date is greater than or equal to genebuild.initial_release_date");
}
// check for genebuild.initial_release_date > genebuild.last_geneset_update (not allowed as we cannot update a gene set before
// its initial public release)
if (initialReleaseDate > lastGenesetUpdate) {
result = false;
ReportManager.problem(this, con, "genebuild.initial_release_date is greater than or equal to genebuild.last_geneset_update");
}
// check for current genebuild.last_geneset_update <= previous release genebuild.last_geneset_update
// AND the number of genes or transcripts or exons between the two releases has changed
// If the gene set has changed in any way since the previous release then the date should have been updated.
DatabaseRegistryEntry previous = getEquivalentFromSecondaryServer(dbre);
if (previous == null) {
return result;
}
Connection previousCon = previous.getConnection();
String previousLastGenesetUpdateString = DBUtils.getRowColumnValue(previousCon, "SELECT meta_value FROM meta WHERE meta_key='genebuild.last_geneset_update'").replaceAll("-", "");
if (previousLastGenesetUpdateString == null || previousLastGenesetUpdateString.length() == 0) {
ReportManager.problem(this, con, "Problem parsing last geneset update entry from previous database.");
return false;
}
int previousLastGenesetUpdate;
try {
previousLastGenesetUpdate = Integer.valueOf(previousLastGenesetUpdateString).intValue();
} catch (NumberFormatException e) {
ReportManager.problem(this, con, "Problem parsing last geneset update entry from previous database: " + Arrays.toString(e.getStackTrace()));
return false;
}
if (lastGenesetUpdate <= previousLastGenesetUpdate) {
int currentGeneCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM gene");
int currentTranscriptCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM transcript");
int currentExonCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM exon");
int previousGeneCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM gene");
int previousTranscriptCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM transcript");
int previousExonCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM exon");
if (currentGeneCount != previousGeneCount || currentTranscriptCount != previousTranscriptCount || currentExonCount != previousExonCount) {
ReportManager.problem(this, con, "Last geneset update entry is the same or older than the equivalent entry in the previous release and the number of genes, transcripts or exons has changed.");
result = false;
}
}
return result;
}
private boolean checkMetaKey(Connection con, String key, String s, String regexp) {
if (regexp != null) {
if (!s.matches(regexp)) {
ReportManager.problem(this, con, key + " " + s + " is not in correct format - should match " + regexp);
return false;
}
}
return true;
}
private boolean checkDateFormat(Connection con, String key, String s) {
int year = Integer.parseInt(s.substring(0, 4));
if (year < 2003 || year > 2050) {
ReportManager.problem(this, con, "Year part of " + key + " (" + year + ") is incorrect");
return false;
}
int month = Integer.parseInt(s.substring(5, 7));
if (month < 1 || month > 12) {
ReportManager.problem(this, con, "Month part of " + key + " (" + month + ") is incorrect");
return false;
}
return true;
}
private boolean checkGenebuildID(Connection con) {
String gbid = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.id'");
logger.finest("genebuild.id from database: " + gbid);
if (gbid == null || gbid.length() == 0) {
ReportManager.problem(this, con, "No genebuild.id entry in meta table");
return false;
} else if (!gbid.matches("[0-9]+")) {
ReportManager.problem(this, con, "genebuild.id " + gbid + " is not numeric");
return false;
}
ReportManager.correct(this, con, "genebuild.id " + gbid + " is present and numeric");
return true;
}
/**
* Check that at least some sort of genebuild.level-type key is present.
*/
private boolean checkBuildLevel(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] Tables = { "gene", "transcript", "exon", "repeat_feature", "dna_align_feature", "protein_align_feature", "simple_feature", "prediction_transcript", "prediction_exon" };
int exists = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta where meta_key like '%build.level'");
if (exists == 0) {
ReportManager.problem(this, con, "GB: No %build.level entries in the meta table - run ensembl/misc-scripts/meta_levels.pl");
}
int count = 0;
for (int i = 0; i < Tables.length; i++) {
String Table = Tables[i];
int rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM " + Table);
int key = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key = '" + Table + "build.level' ");
int toplevel = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM " + Table
+ " t, seq_region_attrib sra, attrib_type at WHERE t.seq_region_id = sra.seq_region_id AND sra.attrib_type_id = at.attrib_type_id AND at.code = 'toplevel' ");
if (rows != 0) {
if (key == 0) {
if (rows == toplevel) {
ReportManager.problem(this, con, "Table " + Table + " should have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
} else {
if (rows != toplevel) {
ReportManager.problem(this, con, "Table " + Table + " has some non toplevel regions, should not have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
}
} else {
if (key != 0) {
ReportManager.problem(this, con, "Empty table " + Table + " should not have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
}
}
if (count == Tables.length) {
ReportManager.correct(this, con, "Toplevel flags correctly set");
result = true;
}
return result;
}
/**
* Check that the genebuild.method entry exists and has one of the allowed values.
*/
private boolean checkGenebuildMethod(DatabaseRegistryEntry dbre) {
boolean result = true;
String[] allowedMethods = { "full_genebuild", "projection_build", "import", "mixed_strategy_build" };
Connection con = dbre.getConnection();
String method = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.method'");
if (method.equals("")) {
ReportManager.problem(this, con, "No genebuild.method entry present in Meta table");
return false;
}
if (!Utils.stringInArray(method, allowedMethods, true)) {
ReportManager.problem(this, con, "genebuild.method value " + method + " is not in list of allowed methods");
result = false;
} else {
ReportManager.correct(this, con, "genebuild.method " + method + " is valid");
}
return result;
}
private boolean checkAssemblyAccessionUpdate(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String currentAssemblyAccession = DBUtils.getMetaValue(con, "assembly.accession");
String currentAssemblyName = DBUtils.getMetaValue(con, "assembly.name");
if (currentAssemblyAccession.equals("")) {
ReportManager.problem(this, con, "No assembly.accession entry present in Meta table");
return false;
}
if (!currentAssemblyAccession.matches("^GC.*")){
ReportManager.problem(this, con, "Meta key assembly.accession does not start with GC");
return false;
}
if (currentAssemblyName.equals("")) {
ReportManager.problem(this, con, "No assembly.name entry present in Meta table");
return false;
}
DatabaseRegistryEntry sec = getEquivalentFromSecondaryServer(dbre);
if (sec == null) {
logger.warning("Can't get equivalent database for " + dbre.getName());
return true;
}
logger.finest("Equivalent database on secondary server is " + sec.getName());
Connection previousCon = sec.getConnection();
String previousAssemblyAccession = DBUtils.getMetaValue(previousCon, "assembly.accession");
String previousAssemblyName = DBUtils.getMetaValue(previousCon, "assembly.name");
long currentAssemblyChecksum = DBUtils.getChecksum(con, "assembly");
long previousAssemblyChecksum = DBUtils.getChecksum(previousCon, "assembly");
boolean assemblyChanged = false;
boolean assemblyTableChanged = false;
boolean assemblyExceptionTableChanged = false;
if (currentAssemblyChecksum != previousAssemblyChecksum) {
assemblyTableChanged = true;
} else {
if (dbre.getSpecies() != Species.HOMO_SAPIENS) {
// compare assembly_exception tables (patches only) from each database
try {
Statement previousStmt = previousCon.createStatement();
Statement currentStmt = con.createStatement();
String sql = "SELECT * FROM assembly_exception WHERE exc_type LIKE ('PATCH_%') ORDER BY assembly_exception_id";
ResultSet previousRS = previousStmt.executeQuery(sql);
ResultSet currentRS = currentStmt.executeQuery(sql);
boolean assExSame = DBUtils.compareResultSets(currentRS, previousRS, this, "", false, false, "assembly_exception", false);
currentRS.close();
previousRS.close();
currentStmt.close();
previousStmt.close();
assemblyExceptionTableChanged = !assExSame;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
assemblyChanged = assemblyTableChanged || assemblyExceptionTableChanged;
if (assemblyChanged == previousAssemblyAccession.equals(currentAssemblyAccession) && previousAssemblyName.equals(currentAssemblyName) ) {
result = false;
String errorMessage = "assembly.accession and assembly.name values need to be updated when "
+ "the assembly table changes or new patches are added to the assembly exception table\n"
+ "previous assembly.accession: " + previousAssemblyAccession + " assembly.name: " + previousAssemblyName
+ " current assembly.accession: " + currentAssemblyAccession + " assembly.name: " + currentAssemblyName + "\n"
+ "assembly table changed:";
if (assemblyTableChanged) {
errorMessage += " yes;";
} else {
errorMessage += " no;";
}
errorMessage += " assembly exception patches changed:";
if (assemblyExceptionTableChanged) {
errorMessage += " yes";
} else {
errorMessage += " no";
}
ReportManager.problem(this, con, errorMessage);
}
if (result) {
ReportManager.correct(this, con, "assembly.accession and assembly.name values are correct");
}
return result;
}
/**
* Check that all meta_values with meta_key 'repeat.analysis' reference analysis.logic_name
* Also check that repeatmask is one of them
*/
private boolean checkRepeatAnalysis(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] repeatAnalyses = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta LEFT JOIN analysis ON meta_value = logic_name WHERE meta_key = 'repeat.analysis' AND analysis_id IS NULL");
if (repeatAnalyses.length > 0) {
result = false;
ReportManager.problem(this, con, "The following values for meta_key repeat.analysis don't have a corresponding logic_name entry in the analysis table: " + Utils.arrayToString(repeatAnalyses,",") );
} else {
ReportManager.correct(this, con, "All values for meta_key repeat.analysis have a corresponding logic_name entry in the analysis table");
}
if (dbre.getType() == DatabaseType.CORE) {
int repeatMask = DBUtils.getRowCount(con, "SELECT count(*) FROM meta WHERE meta_key = 'repeat.analysis' AND (meta_value like 'repeatmask_repbase%' or meta_value = 'repeatmask')");
if (repeatMask == 0) {
result = false;
ReportManager.problem(this, con, "There is no entry in meta for repeatmask repeat.analysis");
} else {
ReportManager.correct(this, con, "Repeatmask is present in meta table for repeat.analysis");
}
}
return result;
}
private boolean checkForSchemaPatchLineBreaks(DatabaseRegistryEntry dbre) {
SqlTemplate t = DBUtils.getSqlTemplate(dbre);
String metaKey = "patch";
String sql = "select meta_id from meta where meta_key =? and species_id IS NULL and meta_value like ?";
List<Integer> ids = t.queryForDefaultObjectList(sql, Integer.class, metaKey, "%\n%");
if(!ids.isEmpty()) {
String idsJoined = Utils.listToString(ids, ",");
String usefulSql = "select * from meta where meta_id IN ("+idsJoined+")";
String msg = String.format("The meta ids [%s] had values with linebreaks.\nUSEFUL SQL: %s", idsJoined, usefulSql);
ReportManager.problem(this, dbre.getConnection(), msg);
return false;
}
return true;
}
private boolean checkSample(DatabaseRegistryEntry dbre) {
SqlTemplate t = DBUtils.getSqlTemplate(dbre);
String metaKey = "sample.location_text";
String sql = "select meta_value from meta where meta_key = ?";
List<String> value = t.queryForDefaultObjectList(sql, String.class, metaKey);
if (!value.isEmpty()) {
String linkedKey = "sample.location_param";
String linkedSql = "select meta_value from meta where meta_key = ?";
List<String> linkedValue = t.queryForDefaultObjectList(linkedSql, String.class, linkedKey);
if(!linkedValue.equals(value)) {
ReportManager.problem(this, dbre.getConnection(), "Keys " + metaKey + " and " + linkedKey + " do not have same value");
return false;
}
}
return true;
}
} // MetaValues |
package org.ine.telluride.jaer.eyeinthesky;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.*;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.graphics.FrameAnnotater;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GL;
import java.awt.*;
public class JoshCrossTracker extends EventFilter2D implements FrameAnnotater {
private int power = getPrefs().getInt("JoshCrossTracker.power", 8);
private int ignoreRadius = getPrefs().getInt("JoshCrossTracker.ignoreRadius", 10);
private float flipSlope = getPrefs().getFloat("JoshCrossTracker.flipSlope", 1.1f);
private double coefficients[][];
private double m,x1,y1,length;
private boolean xHorizontal = true;
private double maxDist;
public JoshCrossTracker(AEChip chip) {
super(chip);
resetFilter();
setPropertyTooltip("power","weight of event is inverse of distance to model raised to this power; increase to discount distance more quickly");
setPropertyTooltip("ignoreRadius","ignore events within this radius in pixels of center of cross");
setPropertyTooltip("flipSlope","when slope of cross crosses this slope in degrees then flip the slope over");
}
public Object getFilterState() {
return null;
}
public void resetFilter() {
coefficients = new double[3][9];
length = 50;
//start near center
coefficients[0][0]=4487.929789503349;
coefficients[0][1]=-5880.26899138613;
coefficients[0][2]=1.747913285251941E-164;
coefficients[0][3]=1.2319050791956217E-164;
coefficients[0][4]=0.9999999999999944;
coefficients[0][5]=-91.79054108226751;
coefficients[0][6]=9.747673002237948E-165;
coefficients[0][7]=124.71706338316264;
coefficients[0][8]=2123.9070962374158;
coefficients[1][0]=4176.715697500955;
coefficients[1][1]=9052.402841852214;
coefficients[1][2]=0.9999999999999944;
coefficients[1][3]=-156.8891673679832;
coefficients[1][4]=1.5610213512990959E-62;
coefficients[1][5]=1.5428048695524322E-62;
coefficients[1][6]=-118.08915361547771;
coefficients[1][7]=4.588689436053689E-63;
coefficients[1][8]=6179.080184987505;
updatePrediction();
}
public void initFilter() {
}
public EventPacket<?> filterPacket(EventPacket<?> in) {
if(!isFilterEnabled()) return in;
if(maxDist == 0)
maxDist = Math.sqrt(chip.getSizeX() * chip.getSizeX() + chip.getSizeY() * chip.getSizeY());
checkOutputPacketEventType(PolarityEvent.class);
OutputEventIterator outItr= out.outputIterator();
for(Object o : in) {
PolarityEvent ein = (PolarityEvent) o;
PolarityEvent eout = (PolarityEvent) outItr.nextOutput();
if(updateCoefficients(ein))
ein.polarity = PolarityEvent.Polarity.On;
else
ein.polarity = PolarityEvent.Polarity.Off;
eout.copyFrom(ein);
}
return out;
}
public void annotate(float[][][] frame) {}
public void annotate(Graphics2D g) {}
public void annotate(GLAutoDrawable drawable) {
if (!isAnnotationEnabled()) {
return;
}
GL gl = drawable.getGL();
gl.glLineWidth(3);
gl.glBegin((GL.GL_LINES));
gl.glColor3d(1, 0, 0);
double c[] = getCenter();
double c1 = c[0];
double c2 = c[1];
double xBottom,xTop,yLeft,yRight;
double xOffset, yOffset;
if(xHorizontal) {
xOffset = (length)/Math.sqrt(1 + (-1/m)*(-1/m));
yOffset = xOffset * -1/m;
} else {
yOffset = (length)/Math.sqrt(1 + (-1/m)*(-1/m));
xOffset = yOffset * -1/m;
}
xBottom = c1 - xOffset;
xTop = c1 + xOffset;
yLeft = c2 - yOffset;
yRight = c2 + yOffset;
gl.glVertex2d(xBottom, yLeft);
gl.glVertex2d(xTop, yRight);
gl.glEnd();
gl.glBegin((GL.GL_LINES));
gl.glColor3d(0, 0, 1);
if(xHorizontal) {
xOffset = (length)/Math.sqrt(1 + m*m);
yOffset = xOffset * m;
} else {
yOffset = (length)/Math.sqrt(1 + m*m);
xOffset = yOffset * m;
}
xBottom = c1 - xOffset;
xTop = c1 + xOffset;
yLeft = c2 - yOffset;
yRight = c2 + yOffset;
gl.glVertex2d(xBottom, yLeft);
gl.glVertex2d(xTop, yRight);
gl.glEnd();
drawCircle(gl, c1, c2);
}
private boolean updateCoefficients(PolarityEvent e) {
double var1 = xHorizontal ? e.x : e.y;
double var2 = xHorizontal ? e.y : e.x;
//calculate distance from the current point to both of the two lines
double A1,B1,C1,A2,B2,C2;
A1 = m;
B1 = -1;
C1 = y1;
A2 = 1;
B2 = m;
C2 = -x1;
double dist1 = Math.abs(A1 * var1 + B1 * var2 + C1)/Math.sqrt(A1*A1 + B1*B1);
double dist2 = Math.abs(A2 * var1 + B2 * var2 + C2)/Math.sqrt(A2*A2 + B2*B2);
//get the coordinates of the center
double c[] = getCenter();
double c1 = c[0];
double c2 = c[1];
//calculate distance to the center
double distC = Math.sqrt(Math.pow(e.x - c1,2) + Math.pow(e.y - c2,2));
// PROJECTED DISTANCE - NOT CURRENTLY BEING USED, SO COMMENTED OUT
// double projectedDistance = Math.sqrt(Math.pow(distC,2) - Math.pow(Math.min(dist1,dist2),2));
// if(Math.pow(distC,2) - Math.pow(Math.min(dist1,dist2),2) < 0) {
// return false;
//if too close to center or too far, ignore event
if( (distC <= ignoreRadius) || (distC > ((length) + ignoreRadius)) )
return false;
double weight, iWeight;
if(dist1 <= dist2) {
//if closer to the first line, update those coefficients
weight = 0.1 * Math.pow((maxDist - dist1)/maxDist,power);
iWeight = 1.0 - weight;
coefficients[0][0] = iWeight * coefficients[0][0] + (weight * var1 * var1) ;
coefficients[0][1] = iWeight * coefficients[0][1] + (weight * -2 * var1 * var2) ;
coefficients[0][2] = iWeight * coefficients[0][2];
coefficients[0][3] = iWeight * coefficients[0][3];
coefficients[0][4] = iWeight * coefficients[0][4] + weight ;
coefficients[0][5] = iWeight * coefficients[0][5] + (weight * -2 * var2) ;
coefficients[0][6] = iWeight * coefficients[0][6];
coefficients[0][7] = iWeight * coefficients[0][7] + (weight * 2 * var1) ;
coefficients[0][8] = iWeight * coefficients[0][8] + (weight * var2 * var2) ;
} else {
//otherwise update coefficients for second line
weight = 0.01 * Math.pow((maxDist - dist2)/maxDist,power);
iWeight = 1.0 - weight;
coefficients[1][0] = iWeight * coefficients[1][0] + (weight * var2 * var2) ;
coefficients[1][1] = iWeight * coefficients[1][1] + (weight * 2 * var1 * var2) ;
coefficients[1][2] = iWeight * coefficients[1][2] + weight ;
coefficients[1][3] = iWeight * coefficients[1][3] + (weight * -2 * var1) ;
coefficients[1][4] = iWeight * coefficients[1][4];
coefficients[1][5] = iWeight * coefficients[1][5];
coefficients[1][6] = iWeight * coefficients[1][6] + (weight * -2 * var2) ;
coefficients[1][7] = iWeight * coefficients[1][7];
coefficients[1][8] = iWeight * coefficients[1][8] + (weight * var1 * var1) ;
}
weight = 0.05 * weight; //update length prediction more slowly then other parameters
iWeight = 1.0 - weight;
length = iWeight * length + weight * ((2.0*distC)-(double)ignoreRadius); //calculate length (based on fact we ignore events too close to center)
if(Math.abs(m) > flipSlope) {
log.info(("FLIP!")); //flipping the coordinate frame rotate counter clockwise 90 deg then reflect across y-axis
double temp = coefficients[0][0];
coefficients[0][0] = coefficients[0][8];
coefficients[0][8] = temp;
temp = coefficients[0][5];
coefficients[0][5] = -coefficients[0][7];
coefficients[0][7] = -temp;
temp = coefficients[1][0];
coefficients[1][0] = coefficients[1][8];
coefficients[1][8] = temp;
temp = coefficients[1][3];
coefficients[1][3] = coefficients[1][6];
coefficients[1][6] = temp;
xHorizontal = !xHorizontal;
}
updatePrediction();
return true;
}
private void updatePrediction() {
//combines coefficient contributions from both lines, weighting them equally
double weight1 = 0.5;
double weight2 = 0.5;
for(int i = 0; i<coefficients[0].length; i++) {
coefficients[2][i] = weight1*coefficients[0][i] + weight2*coefficients[1][i];
}
//now update predictions from coefficients -- derived using sage math
m = -(2*coefficients[2][1]*coefficients[2][2]*coefficients[2][4] - coefficients[2][2]*coefficients[2][5]*coefficients[2][7] - coefficients[2][3]*coefficients[2][4]*coefficients[2][6])/(4*coefficients[2][0]*coefficients[2][2]*coefficients[2][4] - coefficients[2][2]*coefficients[2][7]*coefficients[2][7] - coefficients[2][4]*coefficients[2][6]*coefficients[2][6]);
x1 = -1.0/2.0*(4*coefficients[2][0]*coefficients[2][3]*coefficients[2][4] - 2*coefficients[2][1]*coefficients[2][4]*coefficients[2][6] - coefficients[2][3]*Math.pow(coefficients[2][7],2) + coefficients[2][5]*coefficients[2][6]*coefficients[2][7])/(4*coefficients[2][0]*coefficients[2][2]*coefficients[2][4] - coefficients[2][2]*Math.pow(coefficients[2][7],2) - coefficients[2][4]*Math.pow(coefficients[2][6],2));
y1 = -1.0/2.0*(4*coefficients[2][0]*coefficients[2][2]*coefficients[2][5] - coefficients[2][5]*Math.pow(coefficients[2][6],2) - (2*coefficients[2][1]*coefficients[2][2] - coefficients[2][3]*coefficients[2][6])*coefficients[2][7])/(4*coefficients[2][0]*coefficients[2][2]*coefficients[2][4] - coefficients[2][2]*Math.pow(coefficients[2][7],2) - coefficients[2][4]*Math.pow(coefficients[2][6],2));
}
private double[] getCenter() {
//determine coordinates of center
double c[] = new double[2];
if(xHorizontal) {
c[0] = (x1/m - y1) / (m + 1.0/m);
c[1] = m*c[0]+y1;
} else {
c[1] = (x1/m - y1) / (m + 1.0/m);
c[0] = m*c[1]+y1;
}
return c;
}
private static void drawCircle( GL gl, double xc, double yc ) {
double r = 2; // Radius.
gl.glBegin( GL.GL_TRIANGLE_FAN );
gl.glColor3d(0,1,1);
gl.glVertex2d( xc, yc ); // Center.
for(double a = 0; a <= 360; a+=60 ) {
double ang = Math.toRadians( a );
double x = xc + (r*Math.cos( ang ));
double y = yc + (r*Math.sin( ang ));
gl.glVertex2d( x, y );
}
gl.glEnd();
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
getPrefs().putInt("JoshCrossTracker.power",power);
}
public int getIgnoreRadius() {
return ignoreRadius;
}
public float getFlipSlope() {
return flipSlope;
}
public void setFlipSlope(float flipSlope) {
this.flipSlope = flipSlope;
getPrefs().putFloat("JoshCrossTracker.flipSlope",flipSlope);
}
public void setIgnoreRadius(int ignoreRadius) {
this.ignoreRadius = ignoreRadius;
getPrefs().putInt("JoshCrossTracker.ignoreRadius",ignoreRadius);
}
} |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc330.commands.autocommands;
import org.usfirst.frc330.Robot;
import org.usfirst.frc330.commands.ArmPID_on;
import org.usfirst.frc330.commands.BuzzerBeepTimed;
import org.usfirst.frc330.commands.CenterGrabberClose;
import org.usfirst.frc330.commands.CenterGrabberOpen;
import org.usfirst.frc330.commands.CheckDone;
import org.usfirst.frc330.commands.DriveDistanceAtAbsAngle_NoTurn;
import org.usfirst.frc330.commands.DriveDistanceAtRelAngle_NoTurn;
import org.usfirst.frc330.commands.DriveWaypoint;
import org.usfirst.frc330.commands.LeftGrabberClose;
import org.usfirst.frc330.commands.OpenAllGrabbers;
import org.usfirst.frc330.commands.RightGrabberClose;
import org.usfirst.frc330.commands.SetArmPosition;
import org.usfirst.frc330.commands.SetLiftPosition;
import org.usfirst.frc330.commands.SetMastPosition;
import org.usfirst.frc330.commands.SetWristAngle;
import org.usfirst.frc330.commands.ShiftHigh;
import org.usfirst.frc330.commands.ShiftLow;
import org.usfirst.frc330.commands.TurnAngleAggressive;
import org.usfirst.frc330.commands.TurnGyroAbs;
import org.usfirst.frc330.commands.TurnGyroWaypoint;
import org.usfirst.frc330.commands.Wait;
import org.usfirst.frc330.commands.WristPID_on;
import org.usfirst.frc330.constants.ArmPos;
import org.usfirst.frc330.constants.ChassisConst;
import org.usfirst.frc330.constants.LiftPos;
import org.usfirst.frc330.constants.MastPos;
import org.usfirst.frc330.wpilibj.PIDGains;
import edu.wpi.first.wpilibj.command.BBCommand;
import edu.wpi.first.wpilibj.command.BBCommandGroup;
public class MuchoQueso extends BBCommandGroup {
public MuchoQueso() {
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
PIDGains HardScrub = new PIDGains(0.3, 0, 0, 0, 1.0, 0.5, "HardScrub"); //p, i, d, f, maxOutput, maxOutputStep, name
//Hold joint angles, open grabbers, close center grabber
addParallel(new ArmPID_on());
addParallel(new WristPID_on());
addSequential(new ShiftLow());
addSequential(new OpenAllGrabbers());
addParallel(new CenterGrabberClose());
addSequential(new Wait(0.1));
//Start raising the arm
addParallel(new SetWristAngle(5.0));
addParallel(new SetArmPosition(33.0, 2.0));
addSequential(new Wait(0.1));
//Drive to second station while loading first tote
BBCommand driveCommand = new DriveWaypoint(0.0, 92.0, 1.5, 3.0, false); //X Y Tol Timeout Stop
addParallel(driveCommand);
addSequential(new SetLiftPosition(LiftPos.dropOff));
addSequential(new Wait(0.5));
addSequential(new SetLiftPosition(LiftPos.justOverOneTote));
addSequential(new Wait(0.25));
// addSequential(new Wait(3.30));
//Pickup second tote
addSequential(new SetLiftPosition(LiftPos.dropOff), 0.5);
addSequential(new CheckDone(driveCommand));
driveCommand = new DriveDistanceAtAbsAngle_NoTurn(24, 0.0, 1.5, 1.5, false);
addParallel(driveCommand); //Dist Angle Tol
addSequential(new Wait(0.5));
addSequential(new SetLiftPosition(5.0));
addSequential(new CheckDone(driveCommand));
addSequential(new DriveDistanceAtAbsAngle_NoTurn(-4.0, 0.0, 1.5, 0.5, false));
addParallel(new SetLiftPosition(17.3));
addSequential(new Wait(0.1)); //reduced from 0.2
// addSequential(new Wait(3.30));
//Drive back from second tote
BBCommand moveArm = new SetArmPosition(-15, 4.0);
driveCommand = new DriveDistanceAtAbsAngle_NoTurn(-28 , 0.0, 1.5, 1.5, false); //double distance, double angle, double tolerance, double timeout
addParallel(driveCommand); //Dist Angl Tol
addSequential(new Wait(1.3));
addParallel(moveArm);
addSequential(new CheckDone(driveCommand));
// addSequential(new Wait(3.30));
//Drop First Can
addSequential(new CheckDone(moveArm));
addSequential(new CenterGrabberOpen());
addParallel(new SetWristAngle(0.0, 3.0, 0.5)); //angle tolerance timeout
addSequential(new SetArmPosition(-35, 2.0));
// addSequential(new Wait(3.30));
//Drive Backwards to clear dropped can
addSequential( new DriveDistanceAtAbsAngle_NoTurn(-12 , 0.0, 1.5, 1.0, false));
// addSequential(new Wait(3.30));
//Drive to last location
PIDGains GyroLow = new PIDGains(0.03, 0.00, 0.02, 0.0, 1.0, 1.0, "GyroLow"); //p, i, d, f, maxOutput, maxOutputStep
// addSequential(new TurnGyroWaypoint(0.0, -155.0, 4.0, 3.0, GyroLow, ChassisConst.GyroDriveHigh));
addSequential(new TurnGyroAbs(179.0,5.0, 3.0, false, true, GyroLow, ChassisConst.GyroTurnHigh));
addParallel(new SetArmPosition(-12.0, 1.0));
addSequential(new Wait(3.30));
driveCommand = new DriveWaypoint(0.0, 40.0, 4.0, 3.0, false, ChassisConst.DriveLow, ChassisConst.DriveHigh, GyroLow, ChassisConst.GyroDriveHigh);
addParallel(driveCommand);
addParallel(new SetLiftPosition(LiftPos.justOverOneTote));
addSequential(new Wait(0.2));
addSequential(new CheckDone(driveCommand));
addSequential(new Wait(3.30));
//Grab last can
addParallel(new CenterGrabberClose());
addSequential(new Wait(0.2));
addParallel(new SetArmPosition(ArmPos.verticalAngle, 1.0));
addSequential(new Wait(3.30));
//Drive to last tote
addSequential(new DriveWaypoint(0.0, -10.0, 4.0, 3.0, true));
addSequential(new Wait(3.30));
//Load third tote
addSequential(new SetLiftPosition(LiftPos.dropOff));
addSequential(new Wait(3.30));
addParallel(new DriveDistanceAtRelAngle_NoTurn(6.0, 0.0, 1.5)); //Dist Angle Tol
addSequential(new Wait(0.7));
addParallel(new SetLiftPosition(LiftPos.carry));
addSequential(new Wait(0.3)); //could possibly reduce one tenth
//Turn 90
addSequential(new TurnAngleAggressive(90.0, 2.0)); //angle, timeout
addSequential(new ShiftHigh());
addSequential(new DriveDistanceAtAbsAngle_NoTurn(90.0, 90.0, 4.0)); //Dist Angl Tol
addSequential(new SetLiftPosition(LiftPos.dropOff));
addSequential(new ShiftLow());
addSequential(new DriveDistanceAtAbsAngle_NoTurn(-20.0, 90.0, 4.0)); //Dist Angl Tol
addSequential(new BuzzerBeepTimed());
addSequential(new BuzzerBeepTimed());
addSequential(new BuzzerBeepTimed());
}
protected void end() {
Robot.logger.println("MuchoQueso end time: " + this.timeSinceInitialized());
}
} |
package net.malisis.core.renderer;
import static net.minecraftforge.common.util.ForgeDirection.*;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.util.ForgeDirection;
/**
* @author Ordinastie
*
*/
public class ConnectedTextureIcon extends MalisisIcon
{
private static int NONE = 0;
private static int LEFT = 1;
private static int TOP = 1 << 1;
private static int RIGHT = 1 << 2;
private static int BOTTOM = 1 << 3;
private static int FULL = LEFT | TOP | RIGHT | BOTTOM;
//@formatter:off
public static ForgeDirection[][] sides = { { WEST, NORTH, EAST, SOUTH },
{ WEST, NORTH, EAST, SOUTH },
{ EAST, UP, WEST, DOWN },
{ WEST, UP, EAST, DOWN },
{ NORTH, UP, SOUTH, DOWN },
{ SOUTH, UP, NORTH, DOWN }};
//@formatter:on
private MalisisIcon[] icons = new MalisisIcon[16];
public ConnectedTextureIcon(TextureMap register, String name)
{
this.name = name;
CTPart part = new CTPart(name);
register.setTextureEntry(name, part);
part = new CTPart(name + "2");
register.setTextureEntry(name + "2", part);
}
private void initIcons(CTPart part)
{
TextureIcon icon = new TextureIcon(part);
double size = 1D / 3D;
if (part.getIconName().equals(name))
{
icons[LEFT | TOP] = icon.clone().clip(0, 0, size, size);
icons[TOP] = icon.clone().clip(size, 0, size, size);
icons[RIGHT | TOP] = icon.clone().clip(2 * size, 0, size, size);
icons[LEFT] = icon.clone().clip(0, size, size, size);
icons[NONE] = icon.clone().clip(size, size, size, size);
icons[RIGHT] = icon.clone().clip(2 * size, size, size, size);
icons[LEFT | BOTTOM] = icon.clone().clip(0, 2 * size, size, size);
icons[BOTTOM] = icon.clone().clip(size, 2 * size, size, size);
icons[RIGHT | BOTTOM] = icon.clone().clip(2 * size, 2 * size, size, size);
}
else
{
icons[LEFT | TOP | BOTTOM] = icon.clone().clip(0, 0, size, size);
icons[TOP | BOTTOM] = icon.clone().clip(size, 0, size, size);
icons[LEFT | RIGHT | TOP] = icon.clone().clip(2 * size, 0, size, size);
icons[LEFT | RIGHT] = icon.clone().clip(0, size, size, size);
icons[FULL] = icon.clone().clip(size, size, size, size);
//icons[LEFT | RIGHT] = icon.clone().clip(2 * size, size, size, size);
icons[LEFT | RIGHT | BOTTOM] = icon.clone().clip(0, 2 * size, size, size);
//icons[TOP | BOTTOM] = icon.clone().clip(size, 2 * size, size, size);
icons[RIGHT | TOP | BOTTOM] = icon.clone().clip(2 * size, 2 * size, size, size);
}
}
public IIcon getFullIcon()
{
return icons[FULL];
}
public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side)
{
int connections = getConnections2(world, x, y, z, side);
MalisisIcon icon = icons[connections];
return icon;
}
private int getConnections2(IBlockAccess world, int x, int y, int z, int side)
{
Block block = world.getBlock(x, y, z);
ForgeDirection dir = getOrientation(side);
int connection = 0;
for (int i = 0; i < 4; i++)
{
if (world.getBlock(x + sides[dir.ordinal()][i].offsetX, y + sides[dir.ordinal()][i].offsetY, z
+ sides[dir.ordinal()][i].offsetZ) == block)
connection |= (1 << i);
}
return ~connection & 15;
}
private class CTPart extends TextureAtlasSprite
{
protected CTPart(String name)
{
super(name);
}
@Override
public void initSprite(int width, int height, int x, int y, boolean rotated)
{
super.initSprite(width, height, x, y, rotated);
ConnectedTextureIcon.this.initIcons(this);
}
}
} |
package org.jfree.chart.renderer.category;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import org.jfree.chart.LegendItem;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.AreaRendererEndType;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleEdge;
import org.jfree.util.PublicCloneable;
/**
* A category item renderer that draws area charts. You can use this renderer
* with the {@link CategoryPlot} class. The example shown here is generated
* by the <code>AreaChartDemo1.java</code> program included in the JFreeChart
* Demo Collection:
* <br><br>
* <img src="../../../../../images/AreaRendererSample.png"
* alt="AreaRendererSample.png" />
*/
public class AreaRenderer extends AbstractCategoryItemRenderer
implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -4231878281385812757L;
/** A flag that controls how the ends of the areas are drawn. */
private AreaRendererEndType endType;
/**
* Creates a new renderer.
*/
public AreaRenderer() {
super();
this.endType = AreaRendererEndType.TAPER;
setBaseLegendShape(new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0));
}
/**
* Returns a token that controls how the renderer draws the end points.
* The default value is {@link AreaRendererEndType#TAPER}.
*
* @return The end type (never <code>null</code>).
*
* @see #setEndType
*/
public AreaRendererEndType getEndType() {
return this.endType;
}
/**
* Sets a token that controls how the renderer draws the end points, and
* sends a {@link RendererChangeEvent} to all registered listeners.
*
* @param type the end type (<code>null</code> not permitted).
*
* @see #getEndType()
*/
public void setEndType(AreaRendererEndType type) {
ParamChecks.nullNotPermitted(type, "type");
this.endType = type;
fireChangeEvent();
}
/**
* Returns a legend item for a series.
*
* @param datasetIndex the dataset index (zero-based).
* @param series the series index (zero-based).
*
* @return The legend item.
*/
public LegendItem getLegendItem(int datasetIndex, int series) {
// if there is no plot, there is no dataset to access...
CategoryPlot cp = getPlot();
if (cp == null) {
return null;
}
// check that a legend item needs to be displayed...
if (!isSeriesVisible(series) || !isSeriesVisibleInLegend(series)) {
return null;
}
CategoryDataset dataset = cp.getDataset(datasetIndex);
String label = getLegendItemLabelGenerator().generateLabel(dataset,
series);
String description = label;
String toolTipText = null;
if (getLegendItemToolTipGenerator() != null) {
toolTipText = getLegendItemToolTipGenerator().generateLabel(
dataset, series);
}
String urlText = null;
if (getLegendItemURLGenerator() != null) {
urlText = getLegendItemURLGenerator().generateLabel(dataset,
series);
}
Shape shape = lookupLegendShape(series);
Paint paint = lookupSeriesPaint(series);
Paint outlinePaint = lookupSeriesOutlinePaint(series);
Stroke outlineStroke = lookupSeriesOutlineStroke(series);
LegendItem result = new LegendItem(label, description, toolTipText,
urlText, shape, paint, outlineStroke, outlinePaint);
result.setLabelFont(lookupLegendTextFont(series));
Paint labelPaint = lookupLegendTextPaint(series);
if (labelPaint != null) {
result.setLabelPaint(labelPaint);
}
result.setDataset(dataset);
result.setDatasetIndex(datasetIndex);
result.setSeriesKey(dataset.getRowKey(series));
result.setSeriesIndex(series);
return result;
}
/**
* Draw a single data item.
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param dataArea the data plot area.
* @param plot the plot.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param dataset the dataset.
* @param row the row index (zero-based).
* @param column the column index (zero-based).
* @param pass the pass index.
*/
public void drawItem(Graphics2D g2, CategoryItemRendererState state,
Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis,
ValueAxis rangeAxis, CategoryDataset dataset, int row, int column,
int pass) {
// do nothing if item is not visible or null
if (!getItemVisible(row, column)) {
return;
}
Number value = dataset.getValue(row, column);
if (value == null) {
return;
}
PlotOrientation orientation = plot.getOrientation();
RectangleEdge axisEdge = plot.getDomainAxisEdge();
int count = dataset.getColumnCount();
float x0 = (float) domainAxis.getCategoryStart(column, count, dataArea,
axisEdge);
float x1 = (float) domainAxis.getCategoryMiddle(column, count,
dataArea, axisEdge);
float x2 = (float) domainAxis.getCategoryEnd(column, count, dataArea,
axisEdge);
x0 = Math.round(x0);
x1 = Math.round(x1);
x2 = Math.round(x2);
if (this.endType == AreaRendererEndType.TRUNCATE) {
if (column == 0) {
x0 = x1;
}
else if (column == getColumnCount() - 1) {
x2 = x1;
}
}
double yy1 = value.doubleValue();
double yy0 = 0.0;
if (this.endType == AreaRendererEndType.LEVEL) {
yy0 = yy1;
}
if (column > 0) {
Number n0 = dataset.getValue(row, column - 1);
if (n0 != null) {
yy0 = (n0.doubleValue() + yy1) / 2.0;
}
}
double yy2 = 0.0;
if (column < dataset.getColumnCount() - 1) {
Number n2 = dataset.getValue(row, column + 1);
if (n2 != null) {
yy2 = (n2.doubleValue() + yy1) / 2.0;
}
}
else if (this.endType == AreaRendererEndType.LEVEL) {
yy2 = yy1;
}
RectangleEdge edge = plot.getRangeAxisEdge();
float y0 = (float) rangeAxis.valueToJava2D(yy0, dataArea, edge);
float y1 = (float) rangeAxis.valueToJava2D(yy1, dataArea, edge);
float y2 = (float) rangeAxis.valueToJava2D(yy2, dataArea, edge);
float yz = (float) rangeAxis.valueToJava2D(0.0, dataArea, edge);
double labelXX = x1;
double labelYY = y1;
g2.setPaint(getItemPaint(row, column));
g2.setStroke(getItemStroke(row, column));
GeneralPath area = new GeneralPath();
if (orientation == PlotOrientation.VERTICAL) {
area.moveTo(x0, yz);
area.lineTo(x0, y0);
area.lineTo(x1, y1);
area.lineTo(x2, y2);
area.lineTo(x2, yz);
}
else if (orientation == PlotOrientation.HORIZONTAL) {
area.moveTo(yz, x0);
area.lineTo(y0, x0);
area.lineTo(y1, x1);
area.lineTo(y2, x2);
area.lineTo(yz, x2);
double temp = labelXX;
labelXX = labelYY;
labelYY = temp;
}
area.closePath();
g2.setPaint(getItemPaint(row, column));
g2.fill(area);
// draw the item labels if there are any...
if (isItemLabelVisible(row, column)) {
drawItemLabel(g2, orientation, dataset, row, column, labelXX,
labelYY, (value.doubleValue() < 0.0));
}
// submit the current data point as a crosshair candidate
int datasetIndex = plot.indexOf(dataset);
updateCrosshairValues(state.getCrosshairState(),
dataset.getRowKey(row), dataset.getColumnKey(column), yy1,
datasetIndex, x1, y1, orientation);
// add an item entity, if this information is being collected
EntityCollection entities = state.getEntityCollection();
if (entities != null) {
addItemEntity(entities, dataset, row, column, area);
}
}
/**
* Tests this instance for equality with an arbitrary object.
*
* @param obj the object to test (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof AreaRenderer)) {
return false;
}
AreaRenderer that = (AreaRenderer) obj;
if (!this.endType.equals(that.endType)) {
return false;
}
return super.equals(obj);
}
/**
* Returns an independent copy of the renderer.
*
* @return A clone.
*
* @throws CloneNotSupportedException should not happen.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
} |
package org.vitrivr.cineast.core.setup;
import java.util.ArrayList;
import org.vitrivr.adampro.grpc.AdamGrpc.AckMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.AckMessage.Code;
import org.vitrivr.adampro.grpc.AdamGrpc.AttributeDefinitionMessage;
import org.vitrivr.adampro.grpc.AdamGrpc.AttributeType;
import org.vitrivr.adampro.grpc.AdamGrpc.CreateEntityMessage;
import org.vitrivr.cineast.core.data.entities.MultimediaMetadataDescriptor;
import org.vitrivr.cineast.core.data.entities.MultimediaObjectDescriptor;
import org.vitrivr.cineast.core.data.entities.SegmentDescriptor;
import org.vitrivr.cineast.core.db.ADAMproWrapper;
import com.google.common.collect.ImmutableMap;
public class ADAMproEntityCreator implements EntityCreator {
/**
* Wrapper used to send messages to ADAM pro.
*/
private ADAMproWrapper adampro = new ADAMproWrapper();
/**
* Initialises the main entity holding information about multimedia objects in the ADAMpro
* storage engine.
*/
@Override
public boolean createMultiMediaObjectsEntity(){
ArrayList<AttributeDefinitionMessage> attributes = new ArrayList<>(8);
AttributeDefinitionMessage.Builder builder = AttributeDefinitionMessage.newBuilder();
attributes.add(builder.setName("id").setAttributetype(AttributeType.STRING).setPk(true).putAllParams(ImmutableMap.of("indexed", "true")).build());
attributes.add(builder.setName("mediatype").setAttributetype(AttributeType.INT).setPk(false).putAllParams(ImmutableMap.of("indexed", "true")).build());
attributes.add(builder.setName("name").setAttributetype(AttributeType.STRING).setPk(false).build());
attributes.add(builder.setName("path").setAttributetype(AttributeType.STRING).setPk(false).build());
CreateEntityMessage message = CreateEntityMessage.newBuilder().setEntity(MultimediaObjectDescriptor.ENTITY).addAllAttributes(attributes).build();
AckMessage ack = adampro.createEntityBlocking(message);
if(ack.getCode() == AckMessage.Code.OK){
LOGGER.info("Successfully created multimedia object entity.");
}else{
LOGGER.error("Error occurred during creation of multimedia object entity: {}", ack.getMessage());
}
return ack.getCode() == Code.OK;
}
/**
* Initialises the entity responsible for holding metadata information about multimedia objects in a ADAMpro
* storage.
*
* @see EntityCreator
*/
@Override
public boolean createMetadataEntity() {
ArrayList<AttributeDefinitionMessage> fields = new ArrayList<>(4);
AttributeDefinitionMessage.Builder builder = AttributeDefinitionMessage.newBuilder();
fields.add(builder.setName("metadataId").setAttributetype(AttributeType.AUTO).setPk(true).putAllParams(ImmutableMap.of("indexed", "true")).build());
fields.add(builder.setName("objectId").setAttributetype(AttributeType.STRING).setPk(false).putAllParams(ImmutableMap.of("indexed", "true")).build());
fields.add(builder.setName("key").setAttributetype(AttributeType.STRING).setPk(false).putAllParams(ImmutableMap.of("indexed", "true")).build());
fields.add(builder.setName("value").setAttributetype(AttributeType.STRING).setPk(false).build());
CreateEntityMessage message = CreateEntityMessage.newBuilder().setEntity(MultimediaMetadataDescriptor.ENTITY).addAllAttributes(fields).build();
AckMessage ack = adampro.createEntityBlocking(message);
if(ack.getCode() == AckMessage.Code.OK){
LOGGER.info("Successfully created metadata entity.");
}else{
LOGGER.error("Error occurred during creation of metadata entity: {}", ack.getMessage());
}
return ack.getCode() == Code.OK;
}
/**
* Initialises the entity responsible for holding information about segments of a multimedia object in the
* ADAMpro storage engine.
*
* @see EntityCreator
*/
@Override
public boolean createSegmentEntity(){
ArrayList<AttributeDefinitionMessage> fields = new ArrayList<>(4);
AttributeDefinitionMessage.Builder builder = AttributeDefinitionMessage.newBuilder();
fields.add(builder.setName("id").setAttributetype(AttributeType.STRING).setPk(true).putAllParams(ImmutableMap.of("indexed", "true")).build());
fields.add(builder.setName("objectId").setAttributetype(AttributeType.STRING).setPk(false).putAllParams(ImmutableMap.of("indexed", "true")).build());
fields.add(builder.setName("segmentnumber").setAttributetype(AttributeType.INT).setPk(false).build());
fields.add(builder.setName("segmentstart").setAttributetype(AttributeType.INT).setPk(false).build());
fields.add(builder.setName("segmentend").setAttributetype(AttributeType.INT).setPk(false).build());
CreateEntityMessage message = CreateEntityMessage.newBuilder().setEntity(SegmentDescriptor.ENTITY).addAllAttributes(fields).build();
AckMessage ack = adampro.createEntityBlocking(message);
if(ack.getCode() == AckMessage.Code.OK){
LOGGER.info("Successfully created segment entity.");
}else{
LOGGER.error("Error occurred during creation of segment entity: {}", ack.getMessage());
}
return ack.getCode() == Code.OK;
}
/* (non-Javadoc)
* @see org.vitrivr.cineast.core.setup.IEntityCreator#createFeatureEntity(java.lang.String, boolean)
*/
@Override
public boolean createFeatureEntity(String featurename, boolean unique){
return createFeatureEntity(featurename, unique, "feature");
}
/* (non-Javadoc)
* @see org.vitrivr.cineast.core.setup.IEntityCreator#createFeatureEntity(java.lang.String, boolean, java.lang.String)
*/
@Override
public boolean createFeatureEntity(String featurename, boolean unique, String...featrueNames){
ArrayList<AttributeDefinitionMessage> fields = new ArrayList<>();
AttributeDefinitionMessage.Builder builder = AttributeDefinitionMessage.newBuilder();
fields.add(builder.setName("id").setAttributetype(AttributeType.STRING).setPk(unique).putAllParams(ImmutableMap.of("indexed", "true")).build());
for(String feature : featrueNames){
fields.add(builder.setName(feature).setAttributetype(AttributeType.FEATURE).setPk(false).build());
}
CreateEntityMessage message = CreateEntityMessage.newBuilder().setEntity(featurename.toLowerCase()).addAllAttributes(fields).build();
AckMessage ack = adampro.createEntityBlocking(message);
if(ack.getCode() == AckMessage.Code.OK){
LOGGER.info("successfully created feature entity {}", featurename);
}else{
LOGGER.error("error creating feature entity {}: {}", featurename, ack.getMessage());
}
return ack.getCode() == Code.OK;
}
/* (non-Javadoc)
* @see org.vitrivr.cineast.core.setup.IEntityCreator#createFeatureEntity(java.lang.String, boolean, org.vitrivr.cineast.core.setup.EntityCreator.AttributeDefinition)
*/
@Override
public boolean createFeatureEntity(String featurename, boolean unique, AttributeDefinition... attributes) {
ArrayList<AttributeDefinitionMessage> fields = new ArrayList<>();
AttributeDefinitionMessage.Builder builder = AttributeDefinitionMessage.newBuilder();
fields.add(builder.setName("id").setAttributetype(AttributeType.STRING).setPk(unique).putAllParams(ImmutableMap.of("indexed", "true")).build());
for(AttributeDefinition attribute : attributes){
fields.add(builder.setName(attribute.name).setAttributetype(mapAttributeType(attribute.type)).setPk(false).build());
}
CreateEntityMessage message = CreateEntityMessage.newBuilder().setEntity(featurename.toLowerCase()).addAllAttributes(fields).build();
AckMessage ack = adampro.createEntityBlocking(message);
if(ack.getCode() == AckMessage.Code.OK){
LOGGER.info("successfully created feature entity {}", featurename);
}else{
LOGGER.error("error creating feature entity {}: {}", featurename, ack.getMessage());
}
return ack.getCode() == Code.OK;
}
/* (non-Javadoc)
* @see org.vitrivr.cineast.core.setup.IEntityCreator#createIdEntity(java.lang.String, org.vitrivr.cineast.core.setup.EntityCreator.AttributeDefinition)
*/
@Override
public boolean createIdEntity(String entityName, AttributeDefinition...attributes){
ArrayList<AttributeDefinitionMessage> fieldList = new ArrayList<>();
AttributeDefinitionMessage.Builder builder = AttributeDefinitionMessage.newBuilder();
fieldList.add(builder.setName("id").setAttributetype(AttributeType.STRING).setPk(true).putAllParams(ImmutableMap.of("indexed", "true")).build());
for(AttributeDefinition attribute : attributes){
fieldList.add(builder.setName(attribute.name).setAttributetype(mapAttributeType(attribute.type)).setPk(false).build());
}
CreateEntityMessage message = CreateEntityMessage.newBuilder().setEntity(entityName.toLowerCase()).addAllAttributes(fieldList).build();
AckMessage ack = adampro.createEntityBlocking(message);
if(ack.getCode() == AckMessage.Code.OK){
LOGGER.info("successfully created feature entity {}", entityName);
}else{
LOGGER.error("error creating feature entity {}: {}", entityName, ack.getMessage());
}
return ack.getCode() == Code.OK;
}
/* (non-Javadoc)
* @see org.vitrivr.cineast.core.setup.IEntityCreator#existsEntity(java.lang.String)
*/
@Override
public boolean existsEntity(String entityName){
return this.adampro.existsEntityBlocking(entityName);
}
/* (non-Javadoc)
* @see org.vitrivr.cineast.core.setup.IEntityCreator#close()
*/
@Override
public void close(){
this.adampro.close();
}
public static final AttributeType mapAttributeType(org.vitrivr.cineast.core.setup.AttributeDefinition.AttributeType type){
switch(type){
case AUTO:
return AttributeType.AUTO;
case BOOLEAN:
return AttributeType.BOOLEAN;
case DOUBLE:
return AttributeType.DOUBLE;
case FEATURE:
return AttributeType.FEATURE;
case FLOAT:
return AttributeType.FLOAT;
case GEOGRAPHY:
return AttributeType.GEOGRAPHY;
case GEOMETRY:
return AttributeType.GEOMETRY;
case INT:
return AttributeType.INT;
case LONG:
return AttributeType.LONG;
case SERIAL:
return AttributeType.SERIAL;
case STRING:
return AttributeType.STRING;
case TEXT:
return AttributeType.TEXT;
default:
return AttributeType.UNKOWNAT;
}
}
} |
package com.github.seratch.jslack;
import com.github.seratch.jslack.api.methods.request.team.TeamAccessLogsRequest;
import com.github.seratch.jslack.api.methods.request.team.TeamBillableInfoRequest;
import com.github.seratch.jslack.api.methods.request.team.TeamInfoRequest;
import com.github.seratch.jslack.api.methods.request.team.TeamIntegrationLogsRequest;
import com.github.seratch.jslack.api.methods.request.team.profile.TeamProfileGetRequest;
import com.github.seratch.jslack.api.methods.request.users.UsersListRequest;
import com.github.seratch.jslack.api.methods.response.team.TeamAccessLogsResponse;
import com.github.seratch.jslack.api.methods.response.team.TeamBillableInfoResponse;
import com.github.seratch.jslack.api.methods.response.team.TeamInfoResponse;
import com.github.seratch.jslack.api.methods.response.team.TeamIntegrationLogsResponse;
import com.github.seratch.jslack.api.methods.response.team.profile.TeamProfileGetResponse;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
@Slf4j
public class Slack_team_Test {
Slack slack = Slack.getInstance();
String token = System.getenv(Constants.SLACK_TEST_OAUTH_ACCESS_TOKEN);
@Test
public void teamAccessLogs() throws Exception {
TeamAccessLogsResponse response = slack.methods().teamAccessLogs(TeamAccessLogsRequest.builder()
.token(token)
.build());
if (response.isOk()) {
// when you pay for this team
assertThat(response.isOk(), is(true));
assertThat(response.getError(), is(nullValue()));
} else {
// when you don't pay for this team
assertThat(response.isOk(), is(false));
assertThat(response.getError(), is("paid_only"));
}
}
@Test
public void teamBillableInfo() throws Exception {
String user = slack.methods().usersList(UsersListRequest.builder().token(token).build()).getMembers().get(0).getId();
TeamBillableInfoResponse response = slack.methods().teamBillableInfo(TeamBillableInfoRequest.builder()
.token(token)
.user(user)
.build());
assertThat(response.isOk(), is(true));
}
@Test
public void teamInfo() throws Exception {
TeamInfoResponse response = slack.methods().teamInfo(TeamInfoRequest.builder()
.token(token)
.build());
assertThat(response.isOk(), is(true));
}
@Test
public void teamIntegrationLogs() throws Exception {
String user = slack.methods().usersList(UsersListRequest.builder().token(token).build()).getMembers().get(0).getId();
TeamIntegrationLogsResponse response = slack.methods().teamIntegrationLogs(TeamIntegrationLogsRequest.builder()
.token(token)
.user(user)
.build());
assertThat(response.isOk(), is(true));
}
@Test
public void teamProfileGet() throws Exception {
TeamProfileGetResponse response = slack.methods().teamProfileGet(TeamProfileGetRequest.builder().token(token).build());
assertThat(response.isOk(), is(true));
}
} |
package com.google.research.bleth.utils;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.dev.LocalDatastoreService;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.research.bleth.simulator.AbstractSimulation;
import com.google.research.bleth.simulator.AwakenessStrategyFactory;
import com.google.research.bleth.simulator.MovementStrategyFactory;
import com.google.research.bleth.simulator.Schema;
import com.google.research.bleth.simulator.TracingSimulation;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@RunWith(MockitoJUnitRunner.class)
public class QueriesIT {
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
.setAutoIdAllocationPolicy(LocalDatastoreService.AutoIdAllocationPolicy.SCATTERED));
private static final String ENTITY_KIND = "entityKind";
private static final String NON_EXISTING_PROPERTY = "nonExistingProperty";
private static final String EXISTING_PROPERTY = "existingProperty";
private static final String PROPERTY_A = "propertyA";
private static final String PROPERTY_B = "propertyB";
private static final String PROPERTY_C = "propertyC";
@Before
public void setUp() {
helper.setUp();
}
@After
public void tearDown() {
helper.tearDown();
}
// Join Test Cases.
@Test
public void createThreeSimulations_shouldRetrieveThreeStatsEntities() {
int simulationsNum = 3; // Number of simulations to create.
int roundsNum = 5;
int rowsNum = 2;
int colsNum = 2;
int beaconsNum = 1;
int observersNum = 1;
int awakenessCycle = 2;
int awakenessDuration = 1;
double transmissionRadius = 2.0;
// Create simulations.
for (int i = 0; i < simulationsNum; i++) {
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
}
// Retrieve stats of all simulations.
List<Entity> stats = Queries.join(Schema.SimulationMetadata.entityKind, Schema.StatisticsState.entityKindDistance,
Schema.StatisticsState.simulationId, Optional.empty());
assertThat(stats.size()).isEqualTo(simulationsNum);
}
@Test
public void createThreeSimulationsMatchingSimpleCondition_shouldRetrieveThreeStatsEntities() {
int simulationsNum = 3; // Number of simulation matching the filter condition.
int roundsNum = 5;
int rowsNum = 2;
int colsNum = 2;
int beaconsNum = 1;
int observersNum = 1;
int awakenessCycle = 2;
int awakenessDuration = 1;
double transmissionRadius = 2.0;
// Set a simple predicate (filter).
Query.FilterPredicate filterByRowsNum =
new Query.FilterPredicate(Schema.SimulationMetadata.rowsNum, Query.FilterOperator.EQUAL, rowsNum);
// Create simulations matching the filter's condition.
for (int i = 0; i < simulationsNum; i++) {
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
}
// Retrieve stats of all simulations matching the filter's condition.
List<Entity> stats = Queries.join(Schema.SimulationMetadata.entityKind, Schema.StatisticsState.entityKindDistance,
Schema.StatisticsState.simulationId, Optional.of(filterByRowsNum));
assertThat(stats.size()).isEqualTo(simulationsNum);
}
@Test
public void createThreeSimulationsMatchingCondition_shouldRetrieveThreeStatsEntities() {
int simulationsNum = 3; // Number of simulation matching the filter condition.
int roundsNum = 5;
int rowsNum = 2;
int colsNum = 2;
int beaconsNum = 1;
int observersNum = 1;
int awakenessCycle = 2;
int awakenessDuration = 1;
double transmissionRadius = 2.0;
// Set simple predicates.
Query.FilterPredicate filterByRowsNum =
new Query.FilterPredicate(Schema.SimulationMetadata.rowsNum, Query.FilterOperator.EQUAL, rowsNum);
Query.FilterPredicate filterByColsNum =
new Query.FilterPredicate(Schema.SimulationMetadata.colsNum, Query.FilterOperator.EQUAL, colsNum);
// Compose simple predicates to create a filter.
Query.CompositeFilter composedQueryFilter = Query.CompositeFilterOperator.and(filterByRowsNum, filterByColsNum);
// Create simulations with matching the filter's condition.
for (int i = 0; i < simulationsNum; i++) {
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
}
// Retrieve stats of all simulations matching the filter's condition.
List<Entity> stats = Queries.join(Schema.SimulationMetadata.entityKind, Schema.StatisticsState.entityKindDistance,
Schema.StatisticsState.simulationId, Optional.of(composedQueryFilter));
assertThat(stats.size()).isEqualTo(simulationsNum);
}
@Test
public void createThreeSimulationsMatchingConditionAndOneSimulationNonMatching_shouldRetrieveThreeStatsEntities() {
int simulationsNum = 3; // Number of simulation matching the filter condition.
int roundsNum = 5;
int rowsNum = 2;
int colsNum = 2;
int beaconsNum = 1;
int observersNum = 1;
int awakenessCycle = 2;
int awakenessDuration = 1;
double transmissionRadius = 2.0;
// Set simple predicates.
Query.FilterPredicate filterByRowsNum =
new Query.FilterPredicate(Schema.SimulationMetadata.rowsNum, Query.FilterOperator.EQUAL, rowsNum);
Query.FilterPredicate filterByColsNum =
new Query.FilterPredicate(Schema.SimulationMetadata.colsNum, Query.FilterOperator.EQUAL, colsNum);
// Compose simple predicates to create a filter.
Query.CompositeFilter composedQueryFilter = Query.CompositeFilterOperator.and(filterByRowsNum, filterByColsNum);
// Create simulations matching the filter's condition.
for (int i = 0; i < simulationsNum; i++) {
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
}
// Create another simulation which does not match the condition.
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum + 1)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
// Retrieve stats of all simulations matching the filter's condition.
List<Entity> stats = Queries.join(Schema.SimulationMetadata.entityKind, Schema.StatisticsState.entityKindDistance,
Schema.StatisticsState.simulationId, Optional.of(composedQueryFilter));
assertThat(stats.size()).isEqualTo(simulationsNum);
}
@Test
public void createThreeSimulationsNotMatchingConditionAndOneSimulationMatching_shouldRetrieveThreeStatsEntities() {
int matchingSimulationsNum = 1;
int totalSimulationsNum = 4;
int roundsNum = 5;
int rowsNum = 2;
int colsNum = 2;
int beaconsNum = 1;
int observersNum = 1;
int awakenessCycle = 2;
int awakenessDuration = 1;
double transmissionRadius = 2.0;
// Set simple predicates.
Query.FilterPredicate filterByRowsNum =
new Query.FilterPredicate(Schema.SimulationMetadata.rowsNum, Query.FilterOperator.EQUAL, rowsNum);
Query.FilterPredicate filterByColsNum =
new Query.FilterPredicate(Schema.SimulationMetadata.colsNum, Query.FilterOperator.EQUAL, colsNum);
// Compose simple predicates to create a filter.
Query.CompositeFilter composedQueryFilter = Query.CompositeFilterOperator.and(filterByRowsNum, filterByColsNum);
// Create simulations not matching the filter's condition.
for (int i = 0; i < totalSimulationsNum - matchingSimulationsNum; i++) {
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum + 1)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
}
// Create another simulation matching the condition.
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
// Retrieve stats of all simulations matching the filter's condition.
List<Entity> stats = Queries.join(Schema.SimulationMetadata.entityKind, Schema.StatisticsState.entityKindDistance,
Schema.StatisticsState.simulationId, Optional.of(composedQueryFilter));
assertThat(stats.size()).isEqualTo(matchingSimulationsNum);
}
@Test
public void noSimulationsMatchingCondition_shouldRetrieveEmptyList() {
int simulationsNum = 3; // Number of simulations to create.
int roundsNum = 5;
int rowsNum = 2;
int colsNum = 2;
int beaconsNum = 1;
int observersNum = 1;
int awakenessCycle = 2;
int awakenessDuration = 1;
double transmissionRadius = 2.0;
// Set simple predicates.
Query.FilterPredicate filterByRowsNum =
new Query.FilterPredicate(Schema.SimulationMetadata.rowsNum, Query.FilterOperator.EQUAL, rowsNum + 1);
Query.FilterPredicate filterByColsNum =
new Query.FilterPredicate(Schema.SimulationMetadata.colsNum, Query.FilterOperator.EQUAL, colsNum + 1);
// Compose simple predicates to create a filter.
Query.CompositeFilter composedQueryFilter = Query.CompositeFilterOperator.and(filterByRowsNum, filterByColsNum);
// Create simulations with rowsNum and colsNum matching the condition.
for (int i = 0; i < simulationsNum; i++) {
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
}
// Retrieve stats of all simulations matching the filter's condition.
List<Entity> stats = Queries.join(Schema.SimulationMetadata.entityKind, Schema.StatisticsState.entityKindDistance,
Schema.StatisticsState.simulationId, Optional.of(composedQueryFilter));
assertThat(stats).isEmpty();
}
@Test
public void noSimulationsExists_shouldRetrieveEmptyList() {
List<Entity> stats = Queries.join(Schema.SimulationMetadata.entityKind, Schema.StatisticsState.entityKindDistance,
Schema.StatisticsState.simulationId, Optional.empty());
assertThat(stats).isEmpty();
}
@Test
public void provideFilterOfNonExistingProperty_shouldRetrieveEmptyList() {
int roundsNum = 5;
int rowsNum = 2;
int colsNum = 2;
int beaconsNum = 1;
int observersNum = 1;
int awakenessCycle = 2;
int awakenessDuration = 1;
double transmissionRadius = 2.0;
// Create and run a single simulation.
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
// Set a simple filter by non existing property.
Query.FilterPredicate nonExistingPropertyFilter =
new Query.FilterPredicate(NON_EXISTING_PROPERTY, Query.FilterOperator.EQUAL, 0);
// Retrieve stats of all simulations matching the filter's condition.
List<Entity> stats = Queries.join(Schema.SimulationMetadata.entityKind, Schema.StatisticsState.entityKindDistance,
Schema.StatisticsState.simulationId, Optional.of(nonExistingPropertyFilter));
assertThat(stats).isEmpty();
}
@Test
public void provideNonExistingForeignKey_shouldRetrieveEmptyList() {
int roundsNum = 5;
int rowsNum = 2;
int colsNum = 2;
int beaconsNum = 1;
int observersNum = 1;
int awakenessCycle = 2;
int awakenessDuration = 1;
double transmissionRadius = 2.0;
// Create and run a single simulation.
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build();
simulation.run();
// Retrieve stats of all simulations matching the filter's condition.
List<Entity> stats = Queries.join(Schema.SimulationMetadata.entityKind, Schema.StatisticsState.entityKindDistance,
NON_EXISTING_PROPERTY, Optional.empty());
assertThat(stats).isEmpty();
}
// Single-property Aggregation Test Cases.
@Test
public void writeThreeEntitiesWithProperty_shouldCalculateAverageOfThreeValues() {
writeEntityWithProperty(ENTITY_KIND, EXISTING_PROPERTY, 1.5);
writeEntityWithProperty(ENTITY_KIND, EXISTING_PROPERTY, 0.5);
writeEntityWithProperty(ENTITY_KIND, EXISTING_PROPERTY, 4.0);
List<Entity> entities = retrieveEntities(ENTITY_KIND);
double expectedAverage = 2.0;
double actualAverage = Queries.average(entities, EXISTING_PROPERTY);
assertThat(actualAverage).isEqualTo(expectedAverage);
}
@Test
public void writeTwoEntitiesWithPropertyAndOneEntityWithoutProperty_shouldCalculateAverageOfTwoValues() {
writeEntityWithProperty(ENTITY_KIND, EXISTING_PROPERTY, 1.5);
writeEntityWithProperty(ENTITY_KIND, EXISTING_PROPERTY, 0.5);
writeEntityWithoutProperty(ENTITY_KIND);
List<Entity> entities = retrieveEntities(ENTITY_KIND);
double expectedAverage = 1.0;
double actualAverage = Queries.average(entities, EXISTING_PROPERTY);
assertThat(actualAverage).isEqualTo(expectedAverage);
}
@Test
public void noEntitiesExists_shouldCalculateAverageAsNaN() {
List<Entity> entities = retrieveEntities(ENTITY_KIND);
double expectedAverage = Double.NaN;
double actualAverage = Queries.average(entities, EXISTING_PROPERTY);
assertThat(actualAverage).isEqualTo(expectedAverage);
}
@Test
public void writeSingleEntityWithoutProperty_shouldCalculateAverageAsNaN() {
writeEntityWithoutProperty(ENTITY_KIND);
List<Entity> entities = retrieveEntities(ENTITY_KIND);
double expectedAverage = Double.NaN;
double actualAverage = Queries.average(entities, EXISTING_PROPERTY);
assertThat(actualAverage).isEqualTo(expectedAverage);
}
@Test
public void writeEntityWithNonDoubleCastableProperty_shouldThrowException() {
writeEntityWithStringProperty(ENTITY_KIND, EXISTING_PROPERTY, "notCastable");
List<Entity> entities = retrieveEntities(ENTITY_KIND);
assertThrows(ClassCastException.class, () -> Queries.average(entities, EXISTING_PROPERTY));
}
// Multiple-properties Aggregation Test Cases.
@Test
public void writeMultipleEntitiesWithMultipleProperties_shouldCalculateAverageAsExpected() {
// Write multiple entities with multiple properties/
Map<String, Double> firstEntityPropertiesValues = new HashMap<>();
firstEntityPropertiesValues.put(PROPERTY_A, 1.0);
firstEntityPropertiesValues.put(PROPERTY_B, 1.5);
firstEntityPropertiesValues.put(PROPERTY_C, 2.0);
writeEntityWithProperties(ENTITY_KIND, firstEntityPropertiesValues);
Map<String, Double> secondEntityPropertiesValues = new HashMap<>();
secondEntityPropertiesValues.put(PROPERTY_A, 0.0);
secondEntityPropertiesValues.put(PROPERTY_B, 1.5);
secondEntityPropertiesValues.put(PROPERTY_C, 0.0);
writeEntityWithProperties(ENTITY_KIND, secondEntityPropertiesValues);
Map<String, Double> thirdEntityPropertiesValues = new HashMap<>();
thirdEntityPropertiesValues.put(PROPERTY_A, 2.0);
thirdEntityPropertiesValues.put(PROPERTY_B, 1.5);
thirdEntityPropertiesValues.put(PROPERTY_C, 4.0);
writeEntityWithProperties(ENTITY_KIND, thirdEntityPropertiesValues);
List<Entity> entities = retrieveEntities(ENTITY_KIND);
Set<String> properties = new HashSet<>(Arrays.asList(PROPERTY_A, PROPERTY_B, PROPERTY_C));
Map<String, Double> expectedResult = new HashMap<>();
expectedResult.put(PROPERTY_A, 1.0);
expectedResult.put(PROPERTY_B, 1.5);
expectedResult.put(PROPERTY_C, 2.0);
Map<String, Double> actualResult = Queries.average(entities, properties);
assertThat(actualResult).containsExactlyEntriesIn(expectedResult);
}
@Test
public void writeMultipleEntitiesWithMissingProperties_shouldCalculateAverageAsExpected() {
// Write multiple entities with multiple properties/
Map<String, Double> firstEntityPropertiesValues = new HashMap<>();
firstEntityPropertiesValues.put(PROPERTY_A, 1.0);
writeEntityWithProperties(ENTITY_KIND, firstEntityPropertiesValues);
Map<String, Double> secondEntityPropertiesValues = new HashMap<>();
secondEntityPropertiesValues.put(PROPERTY_A, 0.0);
secondEntityPropertiesValues.put(PROPERTY_B, 1.5);
writeEntityWithProperties(ENTITY_KIND, secondEntityPropertiesValues);
Map<String, Double> thirdEntityPropertiesValues = new HashMap<>();
thirdEntityPropertiesValues.put(PROPERTY_A, 2.0);
thirdEntityPropertiesValues.put(PROPERTY_B, 1.5);
writeEntityWithProperties(ENTITY_KIND, thirdEntityPropertiesValues);
List<Entity> entities = retrieveEntities(ENTITY_KIND);
Set<String> properties = new HashSet<>(Arrays.asList(PROPERTY_A, PROPERTY_B, PROPERTY_C));
Map<String, Double> expectedResult = new HashMap<>();
expectedResult.put(PROPERTY_A, 1.0);
expectedResult.put(PROPERTY_B, 1.5);
expectedResult.put(PROPERTY_C, Double.NaN);
Map<String, Double> actualResult = Queries.average(entities, properties);
assertThat(actualResult).containsExactlyEntriesIn(expectedResult);
}
// Simulation Deletion.
@Test
public void writeSingleSimulationAndDelete_shouldDeleteAllRelatedData() {
int roundsNum = 5;
int rowsNum = 2;
int colsNum = 2;
int beaconsNum = 1;
int observersNum = 1;
int awakenessCycle = 2;
int awakenessDuration = 1;
double transmissionRadius = 2.0;
AbstractSimulation simulation = new TracingSimulation.Builder()
.setMaxNumberOfRounds(roundsNum)
.setRowNum(rowsNum + 1)
.setColNum(colsNum)
.setBeaconsNum(beaconsNum)
.setObserversNum(observersNum)
.setTransmissionThresholdRadius(transmissionRadius)
.setBeaconMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setObserverMovementStrategyType(MovementStrategyFactory.Type.RANDOM)
.setAwakenessCycle(awakenessCycle)
.setAwakenessDuration(awakenessDuration)
.setAwakenessStrategyType(AwakenessStrategyFactory.Type.FIXED)
.build(); // Write simulation metadata
simulation.run(); // Write board states and stats
Queries.delete(simulation.getId());
assertThat(retrieveEntities(Schema.StatisticsState.entityKindBeaconsObservedPercent)).isEmpty();
assertThat(retrieveEntities(Schema.StatisticsState.entityKindDistance)).isEmpty();
assertThat(retrieveEntities(Schema.BoardState.entityKindReal)).isEmpty();
assertThat(retrieveEntities(Schema.BoardState.entityKindEstimated)).isEmpty();
assertThat(retrieveEntities(Schema.SimulationMetadata.entityKind)).isEmpty();
}
private void writeEntityWithProperty(String entityKind, String property, double value) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity entity = new Entity(entityKind);
entity.setProperty(property, value);
datastore.put(entity);
}
private void writeEntityWithProperties(String entityKind, Map<String, Double> propertiesValues) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity entity = new Entity(entityKind);
for (Map.Entry<String, Double> entry : propertiesValues.entrySet()) {
entity.setProperty(entry.getKey(), entry.getValue());
}
datastore.put(entity);
}
private void writeEntityWithoutProperty(String entityKind) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity entity = new Entity(entityKind);
datastore.put(entity);
}
private void writeEntityWithStringProperty(String entityKind, String property, String value) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity entity = new Entity(entityKind);
entity.setProperty(property, value);
datastore.put(entity);
}
private List<Entity> retrieveEntities(String entityKind) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query entitiesQuery = new Query(entityKind);
PreparedQuery entitiesPreparedQuery = datastore.prepare(entitiesQuery);
return entitiesPreparedQuery.asList(FetchOptions.Builder.withDefaults());
}
} |
package com.rultor.agents.req;
import com.jcabi.log.VerboseProcess;
import com.jcabi.xml.XMLDocument;
import com.rultor.agents.shells.SSH;
import com.rultor.agents.shells.Shell;
import com.rultor.agents.shells.Sshd;
import com.rultor.spi.Agent;
import com.rultor.spi.Profile;
import com.rultor.spi.Talk;
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.xembly.Directives;
/**
* Integration tests for ${@link StartsRequest}.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 1.4
*/
public final class StartsRequestITCase {
/**
* Temp directory.
* @checkstyle VisibilityModifierCheck (5 lines)
*/
@Rule
public final transient TemporaryFolder temp = new TemporaryFolder();
/**
* StartsRequest can start a request.
* @throws Exception In case of error.
*/
@Test
public void startsDeployRequest() throws Exception {
final File repo = this.repo();
final Agent agent = new StartsRequest(
new Profile.Fixed(
new XMLDocument(
"<p><deploy><script>echo HEY</script></deploy></p>"
)
)
);
final Talk talk = new Talk.InFile();
talk.modify(
new Directives().xpath("/talk")
.add("request").attr("id", "abcd")
.add("type").set("deploy").up()
.add("args")
.add("arg").attr("name", "head").set(repo.toString()).up()
.add("arg").attr("name", "head_branch").set("master").up()
);
agent.execute(talk);
this.exec(talk);
}
/**
* StartsRequest can start a release request.
* @throws Exception In case of error.
*/
@Test
public void startsReleaseRequest() throws Exception {
final File repo = this.repo();
final Agent agent = new StartsRequest(
new Profile.Fixed(
new XMLDocument(
"<p><release><script>echo HEY</script></release></p>"
)
)
);
final Talk talk = new Talk.InFile();
talk.modify(
new Directives().xpath("/talk")
.add("request").attr("id", "a8b9c0")
.add("type").set("release").up()
.add("args")
.add("arg").attr("name", "head").set(repo.toString()).up()
.add("arg").attr("name", "head_branch").set("master").up()
.add("arg").attr("name", "tag").set("1.0-beta").up()
);
agent.execute(talk);
this.exec(talk);
}
/**
* StartsRequest can start a merge request.
* @throws Exception In case of error.
*/
@Test
public void startsMergeRequest() throws Exception {
final File repo = this.repo();
final Agent agent = new StartsRequest(
new Profile.Fixed(
new XMLDocument(
"<p><merge><script>echo HEY</script></merge></p>"
)
)
);
final Talk talk = new Talk.InFile();
talk.modify(
new Directives().xpath("/talk")
.add("request").attr("id", "a1b2c3")
.add("type").set("merge").up()
.add("args")
.add("arg").attr("name", "head").set(repo.toString()).up()
.add("arg").attr("name", "head_branch").set("master").up()
.add("arg").attr("name", "fork").set(repo.toString()).up()
.add("arg").attr("name", "fork_branch").set("frk").up()
);
agent.execute(talk);
this.exec(talk);
}
/**
* Execute script from daemon.
* @param talk Talk to use
* @throws IOException If fails
*/
private void exec(final Talk talk) throws IOException {
final String script = StringUtils.join(
"set -x\n",
"set -e\n",
"set -o pipefail\n",
"docker=echo\n",
String.format("cd %s\n", this.temp.newFolder()),
talk.read().xpath("/talk/daemon/script/text()").get(0)
);
final Sshd sshd = new Sshd(this.temp.newFolder());
final int port = sshd.start();
new Shell.Empty(
new Shell.Safe(
new SSH("localhost", port, sshd.login(), sshd.key())
)
).exec(script);
}
/**
* Create empty Git repo.
* @return Its location
* @throws IOException If fails
*/
private File repo() throws IOException {
final File repo = this.temp.newFolder();
new VerboseProcess(
new ProcessBuilder().command(
"/bin/bash",
"-c",
StringUtils.join(
"git init .;",
"git config user.email test@rultor.com;",
"git config user.name test;",
"echo 'hello, world!' > hello.txt;",
"git add .;",
"git commit -am 'first file';",
"git checkout -b frk;",
"echo 'good bye!' > hello.txt;",
"git commit -am 'modified file';",
"git checkout master;",
"git config receive.denyCurrentBranch ignore"
)
).directory(repo)
).stdout();
return repo;
}
} |
package integration;
import org.junit.Test;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class StaticPageRequestMappingTests extends IntegrationTestBase {
@Test
public void getHomePage() throws Exception {
checkPage("/");
}
@Test
public void getAboutPage() throws Exception {
checkPage("/about");
}
@Test
public void getJobsPage() throws Exception {
checkPage("/jobs");
}
@Test
public void getServicesPage() throws Exception {
checkPage("/services");
}
@Test
public void getSigninPage() throws Exception {
checkPage("/signin");
}
@Test
public void getStylePage() throws Exception {
checkPage("/style");
}
@Test
public void getLogosAndUsagePage() throws Exception {
checkPage("/logos");
}
private void checkPage(String page) throws Exception {
this.mockMvc.perform(get(page))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith("text/html"));
}
@Test
public void getAStaticPageWithSlashAtEnd() throws Exception {
checkPage("/about/");
}
@Test
public void getRobotsFile() throws Exception {
this.mockMvc.perform(get("/robots.txt"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("User-agent")));
}
@Test
public void doesNotGetIndexPage() throws Exception {
this.mockMvc.perform(get("/index"))
.andExpect(status().isNotFound());
}
} |
package network.aika.network;
import network.aika.Document;
import network.aika.Model;
import network.aika.neuron.INeuron;
import network.aika.neuron.Neuron;
import network.aika.neuron.Synapse;
import network.aika.neuron.activation.Activation;
import network.aika.neuron.relation.Relation;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.util.stream.Collectors;
import static network.aika.neuron.Synapse.OUTPUT;
import static network.aika.neuron.relation.Relation.EQUALS;
import static network.aika.neuron.relation.AncestorRelation.Type.COMMON_ANCESTOR;
import static network.aika.neuron.relation.AncestorRelation.Type.IS_ANCESTOR_OF;
import static network.aika.neuron.relation.AncestorRelation.Type.NOT_ANCESTOR_OF;
public class AncestorRelationTest {
@Test
public void testAncestorRelation() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = Neuron.init(m.createNeuron("B"),
5.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(10.0)
.setRecurrent(false)
.setIdentity(true)
.setBias(-10.0),
new Relation.Builder()
.setFrom(0)
.setTo(OUTPUT)
.setRelation(EQUALS)
);
Neuron outC = Neuron.init(m.createNeuron("C"),
5.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(10.0)
.setRecurrent(false)
.setBias(-10.0),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inB)
.setWeight(10.0)
.setRecurrent(false)
.setBias(-10.0),
new Relation.Builder()
.setFrom(0)
.setTo(1)
.setAncestorRelation(IS_ANCESTOR_OF),
new Relation.Builder()
.setFrom(0)
.setTo(OUTPUT)
.setRelation(EQUALS),
new Relation.Builder()
.setFrom(1)
.setTo(OUTPUT)
.setRelation(EQUALS)
);
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 1);
Activation outC1 = outC.getActivation(doc, 0, 1, false);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(outC1);
}
@Test
public void testAncestorRelation1() {
Model m = new Model();
Document doc = m.createDocument("aaaaaaaaaa", 0);
Neuron inA = m.createNeuron("A");
Neuron nB = Neuron.init(m.createNeuron("B"), 5.0, INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(10.0)
.setBias(-10.0)
.setRecurrent(false)
.setIdentity(true),
new Relation.Builder()
.setFrom(0)
.setTo(OUTPUT)
.setRelation(EQUALS)
);
Neuron nC = Neuron.init(m.createNeuron("C"), 5.0, INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(10.0)
.setBias(-10.0)
.setRecurrent(false)
.setIdentity(true),
new Relation.Builder()
.setFrom(0)
.setTo(OUTPUT)
.setRelation(EQUALS)
);
Neuron nD = Neuron.init(m.createNeuron("D"), 5.0, INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(nB)
.setWeight(10.0)
.setBias(-10.0)
.setRecurrent(false)
.setSynapseId(0),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(nC)
.setWeight(10.0)
.setBias(-10.0)
.setRecurrent(false)
.setSynapseId(1),
new Relation.Builder()
.setFrom(0)
.setTo(1)
.setAncestorRelation(COMMON_ANCESTOR),
new Relation.Builder()
.setFrom(0)
.setTo(OUTPUT)
.setRelation(EQUALS)
);
inA.addInput(doc, 0, 1);
doc.process();
Assert.assertFalse(nD.getActivations(doc, true).collect(Collectors.toList()).isEmpty());
}
@Test
public void testAncestorRelation2() {
Model m = new Model();
Document doc = m.createDocument("aaaaaaaaaa", 0);
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
Neuron nC = Neuron.init(m.createNeuron("C"), 5.0, INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(10.0)
.setBias(-10.0)
.setRecurrent(false)
.setSynapseId(0),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inB)
.setWeight(10.0)
.setBias(-10.0)
.setRecurrent(false)
.setSynapseId(1),
new Relation.Builder()
.setFrom(0)
.setTo(1)
.setAncestorRelation(COMMON_ANCESTOR),
new Relation.Builder()
.setFrom(0)
.setTo(OUTPUT)
.setRelation(EQUALS)
);
inA.addInput(doc, 0, 1);
inB.addInput(doc, 1, 2);
doc.process();
Assert.assertTrue(nC.getActivations(doc, true).collect(Collectors.toList()).isEmpty());
}
@Ignore
@Test
public void testNotAncestorOfRelation() {
Model m = new Model();
Neuron inA = m.createNeuron("A");
Neuron inB = Neuron.init(m.createNeuron("B"),
5.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(10.0)
.setRecurrent(false)
.setIdentity(true)
.setBias(-10.0),
new Relation.Builder()
.setFrom(0)
.setTo(OUTPUT)
.setRelation(EQUALS)
);
Neuron outC = Neuron.init(m.createNeuron("C"),
5.0,
INeuron.Type.EXCITATORY,
new Synapse.Builder()
.setSynapseId(0)
.setNeuron(inA)
.setWeight(10.0)
.setRecurrent(false)
.setBias(-10.0),
new Synapse.Builder()
.setSynapseId(1)
.setNeuron(inB)
.setWeight(10.0)
.setRecurrent(false)
.setBias(-10.0),
new Relation.Builder()
.setFrom(1)
.setTo(OUTPUT)
.setAncestorRelation(NOT_ANCESTOR_OF),
new Relation.Builder()
.setFrom(0)
.setTo(OUTPUT)
.setRelation(EQUALS),
new Relation.Builder()
.setFrom(1)
.setTo(OUTPUT)
.setRelation(EQUALS)
);
Document doc = m.createDocument("aaaaaaaaaa", 0);
inA.addInput(doc, 0, 1);
Activation outC1 = outC.getActivation(doc, 0, 1, false);
System.out.println(doc.activationsToString(false, false, true));
Assert.assertNotNull(outC1);
}
} |
package org.interfaceit;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.assertj.core.api.Assertions;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
/**
* @author aro_tech
*
*/
public class IntegrationTestsWithFiles {
private DelegateMethodGenerator underTest = new DelegateMethodGenerator();
// private Set<String> imports;
private static File tmpDir;
private static File examplesDir;
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUp() throws Exception {
tmpDir = new File("./tmp");
examplesDir = new File("./examples");
tmpDir.mkdirs();
// imports = new HashSet<>();
}
@AfterClass
public static void tearDown() throws Exception {
for(File f: tmpDir.listFiles()) {
f.delete();
}
tmpDir.delete();
}
/**
* Test Java file generation
*/
@Test
public void can_write_mockito_to_file() {
File resultFile = underTest.generateClassToFile(tmpDir, "MockitoEnabled", Mockito.class, "org.interfaceit.test",
5);
URL expectedURL = this.getClass().getResource("/MockitoEnabled.txt");
File expected = new File(expectedURL.getPath());
//System.out.println(resultFile.getAbsolutePath());
Assertions.assertThat(resultFile).exists().canRead();
List<String> resultLines = readTrimmedLines(resultFile.toPath());
List<String> expectedLines = readTrimmedLines(expected.toPath());
Assertions.assertThat(resultLines).hasSameSizeAs(expectedLines).containsAll(expectedLines);
}
@Test
public void build_examples() {
final String packageName = "org.example";
File resultFile = underTest.generateClassToFile(examplesDir, "Mockito", org.mockito.Mockito.class, packageName,
4);
Assertions.assertThat(resultFile).exists().canRead();
resultFile = underTest.generateClassToFile(examplesDir, "AssertJ", org.assertj.core.api.Assertions.class, packageName,
4);
Assertions.assertThat(resultFile).exists().canRead();
resultFile = underTest.generateClassToFile(examplesDir, "Math", java.lang.Math.class, packageName,
4);
Assertions.assertThat(resultFile).exists().canRead();
}
private static List<String> readTrimmedLines(Path path) {
try {
return Files.lines(path).filter(s -> s.trim().length() > 0).map(s -> s.trim()).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
return new ArrayList<String>();
}
}
} |
package org.apache.commons.collections;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public abstract class AbstractTestMap extends AbstractTestObject {
// These instance variables are initialized with the reset method.
// Tests for map methods that alter the map (put, putAll, remove)
// first call reset() to create the map and its views; then perform
// the modification on the map; perform the same modification on the
// confirmed; and then call verify() to ensure that the map is equal
// to the confirmed, that the already-constructed collection views
// are still equal to the confirmed's collection views.
protected Map map;
protected Set entrySet;
protected Set keySet;
protected Collection values;
protected Map confirmed;
/**
* JUnit constructor.
*
* @param testName the test name
*/
public AbstractTestMap(String testName) {
super(testName);
}
/**
* Returns true if the maps produced by
* {@link #makeEmptyMap()} and {@link #makeFullMap()}
* support the <code>put</code> and <code>putAll</code> operations
* adding new mappings.
* <p>
* Default implementation returns true.
* Override if your collection class does not support put adding.
*/
protected boolean isPutAddSupported() {
return true;
}
/**
* Returns true if the maps produced by
* {@link #makeEmptyMap()} and {@link #makeFullMap()}
* support the <code>put</code> and <code>putAll</code> operations
* changing existing mappings.
* <p>
* Default implementation returns true.
* Override if your collection class does not support put changing.
*/
protected boolean isPutChangeSupported() {
return true;
}
/**
* Returns true if the maps produced by
* {@link #makeEmptyMap()} and {@link #makeFullMap()}
* support the <code>setValue</code> operation on entrySet entries.
* <p>
* Default implementation returns isPutChangeSupported().
* Override if your collection class does not support setValue but does
* support put changing.
*/
protected boolean isSetValueSupported() {
return isPutChangeSupported();
}
/**
* Returns true if the maps produced by
* {@link #makeEmptyMap()} and {@link #makeFullMap()}
* support the <code>remove</code> and <code>clear</code> operations.
* <p>
* Default implementation returns true.
* Override if your collection class does not support removal operations.
*/
protected boolean isRemoveSupported() {
return true;
}
/**
* Returns true if the maps produced by
* {@link #makeEmptyMap()} and {@link #makeFullMap()}
* supports null keys.
* <p>
* Default implementation returns true.
* Override if your collection class does not support null keys.
*/
protected boolean isAllowNullKey() {
return true;
}
/**
* Returns true if the maps produced by
* {@link #makeEmptyMap()} and {@link #makeFullMap()}
* supports null values.
* <p>
* Default implementation returns true.
* Override if your collection class does not support null values.
*/
protected boolean isAllowNullValue() {
return true;
}
/**
* Returns true if the maps produced by
* {@link #makeEmptyMap()} and {@link #makeFullMap()}
* supports duplicate values.
* <p>
* Default implementation returns true.
* Override if your collection class does not support duplicate values.
*/
protected boolean isAllowDuplicateValues() {
return true;
}
/**
* Returns the set of keys in the mappings used to test the map. This
* method must return an array with the same length as {@link
* #getSampleValues()} and all array elements must be different. The
* default implementation constructs a set of String keys, and includes a
* single null key if {@link #isAllowNullKey()} returns <code>true</code>.
*/
protected Object[] getSampleKeys() {
Object[] result = new Object[] {
"blah", "foo", "bar", "baz", "tmp", "gosh", "golly", "gee",
"hello", "goodbye", "we'll", "see", "you", "all", "again",
"key",
"key2",
(isAllowNullKey()) ? null : "nonnullkey"
};
return result;
}
protected Object[] getOtherKeys() {
return getOtherNonNullStringElements();
}
protected Object[] getOtherValues() {
return getOtherNonNullStringElements();
}
/**
* Returns a list of string elements suitable for return by
* {@link #getOtherKeys()} or {@link #getOtherValues}.
*
* <p>Override getOtherElements to returnthe results of this method if your
* collection does not support heterogenous elements or the null element.
* </p>
*/
protected Object[] getOtherNonNullStringElements() {
return new Object[] {
"For","then","despite","space","I","would","be","brought",
"From","limits","far","remote","where","thou","dost","stay"
};
}
/**
* Returns the set of values in the mappings used to test the map. This
* method must return an array with the same length as
* {@link #getSampleKeys()}. The default implementation constructs a set of
* String values and includes a single null value if
* {@link #isAllowNullValue()} returns <code>true</code>, and includes
* two values that are the same if {@link #isAllowDuplicateValues()} returns
* <code>true</code>.
*/
protected Object[] getSampleValues() {
Object[] result = new Object[] {
"blahv", "foov", "barv", "bazv", "tmpv", "goshv", "gollyv", "geev",
"hellov", "goodbyev", "we'llv", "seev", "youv", "allv", "againv",
(isAllowNullValue()) ? null : "nonnullvalue",
"value",
(isAllowDuplicateValues()) ? "value" : "value2",
};
return result;
}
/**
* Returns a the set of values that can be used to replace the values
* returned from {@link #getSampleValues()}. This method must return an
* array with the same length as {@link #getSampleValues()}. The values
* returned from this method should not be the same as those returned from
* {@link #getSampleValues()}. The default implementation constructs a
* set of String values and includes a single null value if
* {@link #isAllowNullValue()} returns <code>true</code>, and includes two values
* that are the same if {@link #isAllowDuplicateValues()} returns
* <code>true</code>.
*/
protected Object[] getNewSampleValues() {
Object[] result = new Object[] {
(isAllowNullValue() && isAllowDuplicateValues()) ? null : "newnonnullvalue",
"newvalue",
(isAllowDuplicateValues()) ? "newvalue" : "newvalue2",
"newblahv", "newfoov", "newbarv", "newbazv", "newtmpv", "newgoshv",
"newgollyv", "newgeev", "newhellov", "newgoodbyev", "newwe'llv",
"newseev", "newyouv", "newallv", "newagainv",
};
return result;
}
/**
* Helper method to add all the mappings described by {@link
* #getSampleKeys()} and {@link #getSampleValues()}.
*/
protected void addSampleMappings(Map m) {
Object[] keys = getSampleKeys();
Object[] values = getSampleValues();
for(int i = 0; i < keys.length; i++) {
try {
m.put(keys[i], values[i]);
} catch (NullPointerException exception) {
assertTrue("NullPointerException only allowed to be thrown " +
"if either the key or value is null.",
keys[i] == null || values[i] == null);
assertTrue("NullPointerException on null key, but " +
"isNullKeySupported is not overridden to return false.",
keys[i] == null || !isAllowNullKey());
assertTrue("NullPointerException on null value, but " +
"isNullValueSupported is not overridden to return false.",
values[i] == null || !isAllowNullValue());
assertTrue("Unknown reason for NullPointer.", false);
}
}
assertEquals("size must reflect number of mappings added.",
keys.length, m.size());
}
/**
* Return a new, empty {@link Map} to be used for testing.
*
* @return the map to be tested
*/
protected abstract Map makeEmptyMap();
/**
* Return a new, populated map. The mappings in the map should match the
* keys and values returned from {@link #getSampleKeys()} and {@link
* #getSampleValues()}. The default implementation uses makeEmptyMap()
* and calls {@link #addSampleMappings} to add all the mappings to the
* map.
*
* @return the map to be tested
*/
protected Map makeFullMap() {
Map m = makeEmptyMap();
addSampleMappings(m);
return m;
}
/**
* Implements the superclass method to return the map to be tested.
*
* @return the map to be tested
*/
public Object makeObject() {
return makeEmptyMap();
}
/**
* Override to return a map other than HashMap as the confirmed map.
*
* @return a map that is known to be valid
*/
protected Map makeConfirmedMap() {
return new HashMap();
}
/**
* Test to ensure the test setup is working properly. This method checks
* to ensure that the getSampleKeys and getSampleValues methods are
* returning results that look appropriate. That is, they both return a
* non-null array of equal length. The keys array must not have any
* duplicate values, and may only contain a (single) null key if
* isNullKeySupported() returns true. The values array must only have a null
* value if useNullValue() is true and may only have duplicate values if
* isAllowDuplicateValues() returns true.
*/
public void testSampleMappings() {
Object[] keys = getSampleKeys();
Object[] values = getSampleValues();
Object[] newValues = getNewSampleValues();
assertTrue("failure in test: Must have keys returned from " +
"getSampleKeys.", keys != null);
assertTrue("failure in test: Must have values returned from " +
"getSampleValues.", values != null);
// verify keys and values have equivalent lengths (in case getSampleX are
// overridden)
assertEquals("failure in test: not the same number of sample " +
"keys and values.", keys.length, values.length);
assertEquals("failure in test: not the same number of values and new values.",
values.length, newValues.length);
// verify there aren't duplicate keys, and check values
for(int i = 0; i < keys.length - 1; i++) {
for(int j = i + 1; j < keys.length; j++) {
assertTrue("failure in test: duplicate null keys.",
(keys[i] != null || keys[j] != null));
assertTrue("failure in test: duplicate non-null key.",
(keys[i] == null || keys[j] == null ||
(!keys[i].equals(keys[j]) &&
!keys[j].equals(keys[i]))));
}
assertTrue("failure in test: found null key, but isNullKeySupported " +
"is false.", keys[i] != null || isAllowNullKey());
assertTrue("failure in test: found null value, but isNullValueSupported " +
"is false.", values[i] != null || isAllowNullValue());
assertTrue("failure in test: found null new value, but isNullValueSupported " +
"is false.", newValues[i] != null || isAllowNullValue());
assertTrue("failure in test: values should not be the same as new value",
values[i] != newValues[i] &&
(values[i] == null || !values[i].equals(newValues[i])));
}
}
// tests begin here. Each test adds a little bit of tested functionality.
// Many methods assume previous methods passed. That is, they do not
// exhaustively recheck things that have already been checked in a previous
// test methods.
/**
* Test to ensure that makeEmptyMap and makeFull returns a new non-null
* map with each invocation.
*/
public void testMakeMap() {
Map em = makeEmptyMap();
assertTrue("failure in test: makeEmptyMap must return a non-null map.",
em != null);
Map em2 = makeEmptyMap();
assertTrue("failure in test: makeEmptyMap must return a non-null map.",
em != null);
assertTrue("failure in test: makeEmptyMap must return a new map " +
"with each invocation.", em != em2);
Map fm = makeFullMap();
assertTrue("failure in test: makeFullMap must return a non-null map.",
fm != null);
Map fm2 = makeFullMap();
assertTrue("failure in test: makeFullMap must return a non-null map.",
fm != null);
assertTrue("failure in test: makeFullMap must return a new map " +
"with each invocation.", fm != fm2);
}
/**
* Tests Map.isEmpty()
*/
public void testMapIsEmpty() {
resetEmpty();
assertEquals("Map.isEmpty() should return true with an empty map",
true, map.isEmpty());
verify();
resetFull();
assertEquals("Map.isEmpty() should return false with a non-empty map",
false, map.isEmpty());
verify();
}
/**
* Tests Map.size()
*/
public void testMapSize() {
resetEmpty();
assertEquals("Map.size() should be 0 with an empty map",
0, map.size());
verify();
resetFull();
assertEquals("Map.size() should equal the number of entries " +
"in the map", getSampleKeys().length, map.size());
verify();
}
/**
* Tests {@link Map#clear()}. If the map {@link #isRemoveSupported()}
* can add and remove elements}, then {@link Map#size()} and
* {@link Map#isEmpty()} are used to ensure that map has no elements after
* a call to clear. If the map does not support adding and removing
* elements, this method checks to ensure clear throws an
* UnsupportedOperationException.
*/
public void testMapClear() {
if (!isRemoveSupported()) {
try {
resetFull();
map.clear();
fail("Expected UnsupportedOperationException on clear");
} catch (UnsupportedOperationException ex) {}
return;
}
resetEmpty();
map.clear();
confirmed.clear();
verify();
resetFull();
map.clear();
confirmed.clear();
verify();
}
/**
* Tests Map.containsKey(Object) by verifying it returns false for all
* sample keys on a map created using an empty map and returns true for
* all sample keys returned on a full map.
*/
public void testMapContainsKey() {
Object[] keys = getSampleKeys();
resetEmpty();
for(int i = 0; i < keys.length; i++) {
assertTrue("Map must not contain key when map is empty",
!map.containsKey(keys[i]));
}
verify();
resetFull();
for(int i = 0; i < keys.length; i++) {
assertTrue("Map must contain key for a mapping in the map. " +
"Missing: " + keys[i], map.containsKey(keys[i]));
}
verify();
}
/**
* Tests Map.containsValue(Object) by verifying it returns false for all
* sample values on an empty map and returns true for all sample values on
* a full map.
*/
public void testMapContainsValue() {
Object[] values = getSampleValues();
resetEmpty();
for(int i = 0; i < values.length; i++) {
assertTrue("Empty map must not contain value",
!map.containsValue(values[i]));
}
verify();
resetFull();
for(int i = 0; i < values.length; i++) {
assertTrue("Map must contain value for a mapping in the map.",
map.containsValue(values[i]));
}
verify();
}
/**
* Tests Map.equals(Object)
*/
public void testMapEquals() {
resetEmpty();
assertTrue("Empty maps unequal.", map.equals(confirmed));
verify();
resetFull();
assertTrue("Full maps unequal.", map.equals(confirmed));
verify();
resetFull();
// modify the HashMap created from the full map and make sure this
// change results in map.equals() to return false.
Iterator iter = confirmed.keySet().iterator();
iter.next();
iter.remove();
assertTrue("Different maps equal.", !map.equals(confirmed));
resetFull();
assertTrue("equals(null) returned true.", !map.equals(null));
assertTrue("equals(new Object()) returned true.",
!map.equals(new Object()));
verify();
}
/**
* Tests Map.get(Object)
*/
public void testMapGet() {
resetEmpty();
Object[] keys = getSampleKeys();
Object[] values = getSampleValues();
for (int i = 0; i < keys.length; i++) {
assertTrue("Empty map.get() should return null.",
map.get(keys[i]) == null);
}
verify();
resetFull();
for (int i = 0; i < keys.length; i++) {
assertEquals("Full map.get() should return value from mapping.",
values[i], map.get(keys[i]));
}
}
/**
* Tests Map.hashCode()
*/
public void testMapHashCode() {
resetEmpty();
assertTrue("Empty maps have different hashCodes.",
map.hashCode() == confirmed.hashCode());
resetFull();
assertTrue("Equal maps have different hashCodes.",
map.hashCode() == confirmed.hashCode());
}
/**
* Tests Map.toString(). Since the format of the string returned by the
* toString() method is not defined in the Map interface, there is no
* common way to test the results of the toString() method. Thereforce,
* it is encouraged that Map implementations override this test with one
* that checks the format matches any format defined in its API. This
* default implementation just verifies that the toString() method does
* not return null.
*/
public void testMapToString() {
resetEmpty();
assertTrue("Empty map toString() should not return null",
map.toString() != null);
verify();
resetFull();
assertTrue("Empty map toString() should not return null",
map.toString() != null);
verify();
}
/**
* Compare the current serialized form of the Map
* against the canonical version in CVS.
*/
public void testEmptyMapCompatibility() throws IOException, ClassNotFoundException {
/**
* Create canonical objects with this code
Map map = makeEmptyMap();
if (!(map instanceof Serializable)) return;
writeExternalFormToDisk((Serializable) map, getCanonicalEmptyCollectionName(map));
*/
// test to make sure the canonical form has been preserved
Map map = makeEmptyMap();
if (map instanceof Serializable && !skipSerializedCanonicalTests()) {
Map map2 = (Map) readExternalFormFromDisk(getCanonicalEmptyCollectionName(map));
assertEquals("Map is empty", 0, map2.size());
}
}
/**
* Compare the current serialized form of the Map
* against the canonical version in CVS.
*/
public void testFullMapCompatibility() throws IOException, ClassNotFoundException {
/**
* Create canonical objects with this code
Map map = makeFullMap();
if (!(map instanceof Serializable)) return;
writeExternalFormToDisk((Serializable) map, getCanonicalFullCollectionName(map));
*/
// test to make sure the canonical form has been preserved
Map map = makeFullMap();
if (map instanceof Serializable && !skipSerializedCanonicalTests()) {
Map map2 = (Map) readExternalFormFromDisk(getCanonicalFullCollectionName(map));
assertEquals("Map is the right size", getSampleKeys().length, map2.size());
}
}
/**
* Tests Map.put(Object, Object)
*/
public void testMapPut() {
resetEmpty();
Object[] keys = getSampleKeys();
Object[] values = getSampleValues();
Object[] newValues = getNewSampleValues();
if (isPutAddSupported()) {
for (int i = 0; i < keys.length; i++) {
Object o = map.put(keys[i], values[i]);
confirmed.put(keys[i], values[i]);
verify();
assertTrue("First map.put should return null", o == null);
assertTrue("Map should contain key after put",
map.containsKey(keys[i]));
assertTrue("Map should contain value after put",
map.containsValue(values[i]));
}
if (isPutChangeSupported()) {
for (int i = 0; i < keys.length; i++) {
Object o = map.put(keys[i], newValues[i]);
confirmed.put(keys[i], newValues[i]);
verify();
assertEquals("Map.put should return previous value when changed",
values[i], o);
assertTrue("Map should still contain key after put when changed",
map.containsKey(keys[i]));
assertTrue("Map should contain new value after put when changed",
map.containsValue(newValues[i]));
// if duplicates are allowed, we're not guaranteed that the value
// no longer exists, so don't try checking that.
if (!isAllowDuplicateValues()) {
assertTrue("Map should not contain old value after put when changed",
!map.containsValue(values[i]));
}
}
} else {
try {
// two possible exception here, either valid
map.put(keys[0], newValues[0]);
fail("Expected IllegalArgumentException or UnsupportedOperationException on put (change)");
} catch (IllegalArgumentException ex) {
} catch (UnsupportedOperationException ex) {}
}
} else if (isPutChangeSupported()) {
resetEmpty();
try {
map.put(keys[0], values[0]);
fail("Expected UnsupportedOperationException or IllegalArgumentException on put (add) when fixed size");
} catch (IllegalArgumentException ex) {
} catch (UnsupportedOperationException ex) {
}
resetFull();
int i = 0;
for (Iterator it = map.keySet().iterator(); it.hasNext() && i < newValues.length; i++) {
Object key = it.next();
Object o = map.put(key, newValues[i]);
Object value = confirmed.put(key, newValues[i]);
verify();
assertEquals("Map.put should return previous value when changed",
value, o);
assertTrue("Map should still contain key after put when changed",
map.containsKey(key));
assertTrue("Map should contain new value after put when changed",
map.containsValue(newValues[i]));
// if duplicates are allowed, we're not guaranteed that the value
// no longer exists, so don't try checking that.
if (!isAllowDuplicateValues()) {
assertTrue("Map should not contain old value after put when changed",
!map.containsValue(values[i]));
}
}
} else {
try {
map.put(keys[0], values[0]);
fail("Expected UnsupportedOperationException on put (add)");
} catch (UnsupportedOperationException ex) {}
}
}
/**
* Tests Map.putAll(map)
*/
public void testMapPutAll() {
if (!isPutAddSupported()) {
if (!isPutChangeSupported()) {
Map temp = makeFullMap();
resetEmpty();
try {
map.putAll(temp);
fail("Expected UnsupportedOperationException on putAll");
} catch (UnsupportedOperationException ex) {}
}
return;
}
resetEmpty();
Map m2 = makeFullMap();
map.putAll(m2);
confirmed.putAll(m2);
verify();
resetEmpty();
m2 = makeConfirmedMap();
Object[] keys = getSampleKeys();
Object[] values = getSampleValues();
for(int i = 0; i < keys.length; i++) {
m2.put(keys[i], values[i]);
}
map.putAll(m2);
confirmed.putAll(m2);
verify();
}
/**
* Tests Map.remove(Object)
*/
public void testMapRemove() {
if (!isRemoveSupported()) {
try {
resetFull();
map.remove(map.keySet().iterator().next());
fail("Expected UnsupportedOperationException on remove");
} catch (UnsupportedOperationException ex) {}
return;
}
resetEmpty();
Object[] keys = getSampleKeys();
Object[] values = getSampleValues();
for(int i = 0; i < keys.length; i++) {
Object o = map.remove(keys[i]);
assertTrue("First map.remove should return null", o == null);
}
verify();
resetFull();
for(int i = 0; i < keys.length; i++) {
Object o = map.remove(keys[i]);
confirmed.remove(keys[i]);
verify();
assertEquals("map.remove with valid key should return value",
values[i], o);
}
Object[] other = getOtherKeys();
resetFull();
int size = map.size();
for (int i = 0; i < other.length; i++) {
Object o = map.remove(other[i]);
assertEquals("map.remove for nonexistent key should return null",
o, null);
assertEquals("map.remove for nonexistent key should not " +
"shrink map", size, map.size());
}
verify();
}
/**
* Tests that the {@link Map#values} collection is backed by
* the underlying map for clear().
*/
public void testValuesClearChangesMap() {
if (!isRemoveSupported()) return;
// clear values, reflected in map
resetFull();
Collection values = map.values();
assertTrue(map.size() > 0);
assertTrue(values.size() > 0);
values.clear();
assertTrue(map.size() == 0);
assertTrue(values.size() == 0);
// clear map, reflected in values
resetFull();
values = map.values();
assertTrue(map.size() > 0);
assertTrue(values.size() > 0);
map.clear();
assertTrue(map.size() == 0);
assertTrue(values.size() == 0);
}
/**
* Tests that the {@link Map#keySet} collection is backed by
* the underlying map for clear().
*/
public void testKeySetClearChangesMap() {
if (!isRemoveSupported()) return;
// clear values, reflected in map
resetFull();
Set keySet = map.keySet();
assertTrue(map.size() > 0);
assertTrue(keySet.size() > 0);
keySet.clear();
assertTrue(map.size() == 0);
assertTrue(keySet.size() == 0);
// clear map, reflected in values
resetFull();
keySet = map.keySet();
assertTrue(map.size() > 0);
assertTrue(keySet.size() > 0);
map.clear();
assertTrue(map.size() == 0);
assertTrue(keySet.size() == 0);
}
/**
* Tests that the {@link Map#entrySet()} collection is backed by
* the underlying map for clear().
*/
public void testEntrySetClearChangesMap() {
if (!isRemoveSupported()) return;
// clear values, reflected in map
resetFull();
Set entrySet = map.entrySet();
assertTrue(map.size() > 0);
assertTrue(entrySet.size() > 0);
entrySet.clear();
assertTrue(map.size() == 0);
assertTrue(entrySet.size() == 0);
// clear map, reflected in values
resetFull();
entrySet = map.entrySet();
assertTrue(map.size() > 0);
assertTrue(entrySet.size() > 0);
map.clear();
assertTrue(map.size() == 0);
assertTrue(entrySet.size() == 0);
}
public void testValuesRemoveChangesMap() {
resetFull();
Object[] sampleValues = getSampleValues();
Collection values = map.values();
for (int i = 0; i < sampleValues.length; i++) {
if (map.containsValue(sampleValues[i])) {
while (values.contains(sampleValues[i])) {
try {
values.remove(sampleValues[i]);
} catch (UnsupportedOperationException e) {
// if values.remove is unsupported, just skip this test
return;
}
}
assertTrue(
"Value should have been removed from the underlying map.",
!map.containsValue(sampleValues[i]));
}
}
}
/**
* Tests that the {@link Map#keySet} set is backed by
* the underlying map by removing from the keySet set
* and testing if the key was removed from the map.
*/
public void testKeySetRemoveChangesMap() {
resetFull();
Object[] sampleKeys = getSampleKeys();
Set keys = map.keySet();
for (int i = 0; i < sampleKeys.length; i++) {
try {
keys.remove(sampleKeys[i]);
} catch (UnsupportedOperationException e) {
// if key.remove is unsupported, just skip this test
return;
}
assertTrue(
"Key should have been removed from the underlying map.",
!map.containsKey(sampleKeys[i]));
}
}
// TODO: Need:
// testValuesRemovedFromEntrySetAreRemovedFromMap
// same for EntrySet/KeySet/values's
// Iterator.remove, removeAll, retainAll
/**
* Utility methods to create an array of Map.Entry objects
* out of the given key and value arrays.<P>
*
* @param keys the array of keys
* @param values the array of values
* @return an array of Map.Entry of those keys to those values
*/
private Map.Entry[] makeEntryArray(Object[] keys, Object[] values) {
Map.Entry[] result = new Map.Entry[keys.length];
for (int i = 0; i < keys.length; i++) {
Map map = makeConfirmedMap();
map.put(keys[i], values[i]);
result[i] = (Map.Entry) map.entrySet().iterator().next();
}
return result;
}
/**
* Bulk test {@link Map#entrySet()}. This method runs through all of
* the tests in {@link AbstractTestSet}.
* After modification operations, {@link #verify()} is invoked to ensure
* that the map and the other collection views are still valid.
*
* @return a {@link AbstractTestSet} instance for testing the map's entry set
*/
public BulkTest bulkTestMapEntrySet() {
return new TestMapEntrySet();
}
public class TestMapEntrySet extends AbstractTestSet {
public TestMapEntrySet() {
super("MapEntrySet");
}
// Have to implement manually; entrySet doesn't support addAll
protected Object[] getFullElements() {
Object[] k = getSampleKeys();
Object[] v = getSampleValues();
return makeEntryArray(k, v);
}
// Have to implement manually; entrySet doesn't support addAll
protected Object[] getOtherElements() {
Object[] k = getOtherKeys();
Object[] v = getOtherValues();
return makeEntryArray(k, v);
}
protected Set makeEmptySet() {
return makeEmptyMap().entrySet();
}
protected Set makeFullSet() {
return makeFullMap().entrySet();
}
protected boolean isAddSupported() {
// Collection views don't support add operations.
return false;
}
protected boolean isRemoveSupported() {
// Entry set should only support remove if map does
return AbstractTestMap.this.isRemoveSupported();
}
protected boolean supportsEmptyCollections() {
return AbstractTestMap.this.supportsEmptyCollections();
}
protected boolean supportsFullCollections() {
return AbstractTestMap.this.supportsFullCollections();
}
protected void resetFull() {
AbstractTestMap.this.resetFull();
collection = map.entrySet();
TestMapEntrySet.this.confirmed = AbstractTestMap.this.confirmed.entrySet();
}
protected void resetEmpty() {
AbstractTestMap.this.resetEmpty();
collection = map.entrySet();
TestMapEntrySet.this.confirmed = AbstractTestMap.this.confirmed.entrySet();
}
public void testMapEntrySetIteratorEntry() {
resetFull();
Iterator it = collection.iterator();
int count = 0;
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
assertEquals(true, AbstractTestMap.this.map.containsKey(entry.getKey()));
assertEquals(true, AbstractTestMap.this.map.containsValue(entry.getValue()));
assertEquals(AbstractTestMap.this.map.get(entry.getKey()), entry.getValue());
count++;
}
assertEquals(collection.size(), count);
}
public void testMapEntrySetIteratorEntrySetValue() {
Object key1 = getSampleKeys()[0];
Object key2 = getSampleKeys()[1];
Object newValue1 = getNewSampleValues()[0];
Object newValue2 = getNewSampleValues()[1];
resetFull();
// explicitly get entries as sample values/keys are connected for some maps
// such as BeanMap
Iterator it = TestMapEntrySet.this.collection.iterator();
Map.Entry entry1 = getEntry(it, key1);
it = TestMapEntrySet.this.collection.iterator();
Map.Entry entry2 = getEntry(it, key2);
Iterator itConfirmed = TestMapEntrySet.this.confirmed.iterator();
Map.Entry entryConfirmed1 = getEntry(itConfirmed, key1);
itConfirmed = TestMapEntrySet.this.confirmed.iterator();
Map.Entry entryConfirmed2 = getEntry(itConfirmed, key2);
verify();
if (isSetValueSupported() == false) {
try {
entry1.setValue(newValue1);
} catch (UnsupportedOperationException ex) {
}
return;
}
entry1.setValue(newValue1);
entryConfirmed1.setValue(newValue1);
assertEquals(newValue1, entry1.getValue());
assertEquals(true, AbstractTestMap.this.map.containsKey(entry1.getKey()));
assertEquals(true, AbstractTestMap.this.map.containsValue(newValue1));
assertEquals(newValue1, AbstractTestMap.this.map.get(entry1.getKey()));
verify();
entry1.setValue(newValue1);
entryConfirmed1.setValue(newValue1);
assertEquals(newValue1, entry1.getValue());
assertEquals(true, AbstractTestMap.this.map.containsKey(entry1.getKey()));
assertEquals(true, AbstractTestMap.this.map.containsValue(newValue1));
assertEquals(newValue1, AbstractTestMap.this.map.get(entry1.getKey()));
verify();
entry2.setValue(newValue2);
entryConfirmed2.setValue(newValue2);
assertEquals(newValue2, entry2.getValue());
assertEquals(true, AbstractTestMap.this.map.containsKey(entry2.getKey()));
assertEquals(true, AbstractTestMap.this.map.containsValue(newValue2));
assertEquals(newValue2, AbstractTestMap.this.map.get(entry2.getKey()));
verify();
}
protected Map.Entry getEntry(Iterator itConfirmed, Object key) {
Map.Entry entry = null;
while (itConfirmed.hasNext()) {
Map.Entry temp = (Map.Entry) itConfirmed.next();
if (temp.getKey() == null) {
if (key == null) {
entry = temp;
break;
}
} else if (temp.getKey().equals(key)) {
entry = temp;
break;
}
}
assertNotNull("No matching entry in map for key '" + key + "'", entry);
return entry;
}
protected void verify() {
super.verify();
AbstractTestMap.this.verify();
}
}
/**
* Bulk test {@link Map#keySet()}. This method runs through all of
* the tests in {@link AbstractTestSet}.
* After modification operations, {@link #verify()} is invoked to ensure
* that the map and the other collection views are still valid.
*
* @return a {@link AbstractTestSet} instance for testing the map's key set
*/
public BulkTest bulkTestMapKeySet() {
return new TestMapKeySet();
}
public class TestMapKeySet extends AbstractTestSet {
public TestMapKeySet() {
super("");
}
protected Object[] getFullElements() {
return getSampleKeys();
}
protected Object[] getOtherElements() {
return getOtherKeys();
}
protected Set makeEmptySet() {
return makeEmptyMap().keySet();
}
protected Set makeFullSet() {
return makeFullMap().keySet();
}
protected boolean isNullSupported() {
return AbstractTestMap.this.isAllowNullKey();
}
protected boolean isAddSupported() {
return false;
}
protected boolean isRemoveSupported() {
return AbstractTestMap.this.isRemoveSupported();
}
protected boolean supportsEmptyCollections() {
return AbstractTestMap.this.supportsEmptyCollections();
}
protected boolean supportsFullCollections() {
return AbstractTestMap.this.supportsFullCollections();
}
protected void resetEmpty() {
AbstractTestMap.this.resetEmpty();
collection = map.keySet();
TestMapKeySet.this.confirmed = AbstractTestMap.this.confirmed.keySet();
}
protected void resetFull() {
AbstractTestMap.this.resetFull();
collection = map.keySet();
TestMapKeySet.this.confirmed = AbstractTestMap.this.confirmed.keySet();
}
protected void verify() {
super.verify();
AbstractTestMap.this.verify();
}
}
/**
* Bulk test {@link Map#values()}. This method runs through all of
* the tests in {@link AbstractTestCollection}.
* After modification operations, {@link #verify()} is invoked to ensure
* that the map and the other collection views are still valid.
*
* @return a {@link AbstractTestCollection} instance for testing the map's
* values collection
*/
public BulkTest bulkTestMapValues() {
return new TestMapValues();
}
public class TestMapValues extends AbstractTestCollection {
public TestMapValues() {
super("");
}
protected Object[] getFullElements() {
return getSampleValues();
}
protected Object[] getOtherElements() {
return getOtherValues();
}
protected Collection makeCollection() {
return makeEmptyMap().values();
}
protected Collection makeFullCollection() {
return makeFullMap().values();
}
protected boolean isNullSupported() {
return AbstractTestMap.this.isAllowNullKey();
}
protected boolean isAddSupported() {
return false;
}
protected boolean isRemoveSupported() {
return AbstractTestMap.this.isRemoveSupported();
}
protected boolean supportsEmptyCollections() {
return AbstractTestMap.this.supportsEmptyCollections();
}
protected boolean supportsFullCollections() {
return AbstractTestMap.this.supportsFullCollections();
}
protected boolean areEqualElementsDistinguishable() {
// equal values are associated with different keys, so they are
// distinguishable.
return true;
}
protected Collection makeConfirmedCollection() {
// never gets called, reset methods are overridden
return null;
}
protected Collection makeConfirmedFullCollection() {
// never gets called, reset methods are overridden
return null;
}
protected void resetFull() {
AbstractTestMap.this.resetFull();
collection = map.values();
TestMapValues.this.confirmed = AbstractTestMap.this.confirmed.values();
}
protected void resetEmpty() {
AbstractTestMap.this.resetEmpty();
collection = map.values();
TestMapValues.this.confirmed = AbstractTestMap.this.confirmed.values();
}
protected void verify() {
super.verify();
AbstractTestMap.this.verify();
}
// TODO: should test that a remove on the values collection view
// removes the proper mapping and not just any mapping that may have
// the value equal to the value returned from the values iterator.
}
/**
* Resets the {@link #map}, {@link #entrySet}, {@link #keySet},
* {@link #values} and {@link #confirmed} fields to empty.
*/
protected void resetEmpty() {
this.map = makeEmptyMap();
views();
this.confirmed = makeConfirmedMap();
}
/**
* Resets the {@link #map}, {@link #entrySet}, {@link #keySet},
* {@link #values} and {@link #confirmed} fields to full.
*/
protected void resetFull() {
this.map = makeFullMap();
views();
this.confirmed = makeConfirmedMap();
Object[] k = getSampleKeys();
Object[] v = getSampleValues();
for (int i = 0; i < k.length; i++) {
confirmed.put(k[i], v[i]);
}
}
/**
* Resets the collection view fields.
*/
private void views() {
this.keySet = map.keySet();
this.values = map.values();
this.entrySet = map.entrySet();
}
/**
* Verifies that {@link #map} is still equal to {@link #confirmed}.
* This method checks that the map is equal to the HashMap,
* <I>and</I> that the map's collection views are still equal to
* the HashMap's collection views. An <Code>equals</Code> test
* is done on the maps and their collection views; their size and
* <Code>isEmpty</Code> results are compared; their hashCodes are
* compared; and <Code>containsAll</Code> tests are run on the
* collection views.
*/
protected void verify() {
verifyMap();
verifyEntrySet();
verifyKeySet();
verifyValues();
}
protected void verifyMap() {
int size = confirmed.size();
boolean empty = confirmed.isEmpty();
assertEquals("Map should be same size as HashMap",
size, map.size());
assertEquals("Map should be empty if HashMap is",
empty, map.isEmpty());
assertEquals("hashCodes should be the same",
confirmed.hashCode(), map.hashCode());
// this fails for LRUMap because confirmed.equals() somehow modifies
// map, causing concurrent modification exceptions.
//assertEquals("Map should still equal HashMap", confirmed, map);
// this works though and performs the same verification:
assertTrue("Map should still equal HashMap", map.equals(confirmed));
// TODO: this should really be reexamined to figure out why LRU map
// behaves like it does (the equals shouldn't modify since all accesses
// by the confirmed collection should be through an iterator, thus not
// causing LRUMap to change).
}
protected void verifyEntrySet() {
int size = confirmed.size();
boolean empty = confirmed.isEmpty();
assertEquals("entrySet should be same size as HashMap's" +
"\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(),
size, entrySet.size());
assertEquals("entrySet should be empty if HashMap is" +
"\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(),
empty, entrySet.isEmpty());
assertTrue("entrySet should contain all HashMap's elements" +
"\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(),
entrySet.containsAll(confirmed.entrySet()));
assertEquals("entrySet hashCodes should be the same" +
"\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(),
confirmed.entrySet().hashCode(), entrySet.hashCode());
assertEquals("Map's entry set should still equal HashMap's" +
"\nTest: " + entrySet + "\nReal: " + confirmed.entrySet(),
confirmed.entrySet(), entrySet);
}
protected void verifyKeySet() {
int size = confirmed.size();
boolean empty = confirmed.isEmpty();
assertEquals("keySet should be same size as HashMap's" +
"\nTest: " + keySet + "\nReal: " + confirmed.keySet(),
size, keySet.size());
assertEquals("keySet should be empty if HashMap is" +
"\nTest: " + keySet + "\nReal: " + confirmed.keySet(),
empty, keySet.isEmpty());
assertTrue("keySet should contain all HashMap's elements" +
"\nTest: " + keySet + "\nReal: " + confirmed.keySet(),
keySet.containsAll(confirmed.keySet()));
assertEquals("keySet hashCodes should be the same" +
"\nTest: " + keySet + "\nReal: " + confirmed.keySet(),
confirmed.keySet().hashCode(), keySet.hashCode());
assertEquals("Map's key set should still equal HashMap's" +
"\nTest: " + keySet + "\nReal: " + confirmed.keySet(),
confirmed.keySet(), keySet);
}
protected void verifyValues() {
List known = new ArrayList(confirmed.values());
List test = new ArrayList(values);
int size = confirmed.size();
boolean empty = confirmed.isEmpty();
assertEquals("values should be same size as HashMap's" +
"\nTest: " + test + "\nReal: " + known,
size, values.size());
assertEquals("values should be empty if HashMap is" +
"\nTest: " + test + "\nReal: " + known,
empty, values.isEmpty());
assertTrue("values should contain all HashMap's elements" +
"\nTest: " + test + "\nReal: " + known,
test.containsAll(known));
assertTrue("values should contain all HashMap's elements" +
"\nTest: " + test + "\nReal: " + known,
known.containsAll(test));
// originally coded to use a HashBag, but now separate jar so...
for (Iterator it = known.iterator(); it.hasNext();) {
boolean removed = test.remove(it.next());
assertTrue("Map's values should still equal HashMap's", removed);
}
assertTrue("Map's values should still equal HashMap's", test.isEmpty());
}
/**
* Erases any leftover instance variables by setting them to null.
*/
protected void tearDown() throws Exception {
map = null;
keySet = null;
entrySet = null;
values = null;
confirmed = null;
}
} |
package org.jastadd.tinytemplate.test;
import static org.junit.Assert.*;
import org.jastadd.tinytemplate.SimpleContext;
import org.jastadd.tinytemplate.TinyTemplate;
import org.jastadd.tinytemplate.TemplateParser.SyntaxError;
import org.junit.Test;
public class TestTinyTemplate {
/**
* Constructor
*/
public TestTinyTemplate() {
TinyTemplate.printWarnings(false);
TinyTemplate.throwExceptions(false);
}
/**
* Tests expanding an undefined template
* @throws SyntaxError
*/
@Test
public void testUndefinedTemplate() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("");
assertEquals("", tt.expand("test"));
}
/**
* Tests expanding a simple template
* @throws SyntaxError
*/
@Test
public void testSimple_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("test [[hello]]");
assertEquals("hello", tt.expand("test"));
}
/**
* Tests expanding an empty template
* @throws SyntaxError
*/
@Test
public void testSimple_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("foo [[]]");
assertEquals("", tt.expand("foo"));
}
/**
* Multiple templates in one "file"
* @throws SyntaxError
*/
@Test
public void testSimple_3() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo [[ baa ]] bar [[ faa ]]");
assertEquals(" baa ", tt.expand("foo"));
assertEquals(" faa ", tt.expand("bar"));
}
/**
* Very many special characters can be used in template names
* @throws SyntaxError
*/
@Test
public void testSimple_4() throws SyntaxError {
TinyTemplate tt = new TinyTemplate("$(%)!}@{ [[=)]]");
assertEquals("=)", tt.expand("$(%)!}@{"));
}
/**
* Newlines in template body
* @throws SyntaxError
*/
@Test
public void testSimple_5() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"x= [[\n" +
"z\r" +
"\r\n" +
"]]");
String nl = System.getProperty("line.separator");
assertEquals("z" + nl + nl, tt.expand("x"));
}
/**
* Newlines in template body
* @throws SyntaxError
*/
@Test
public void testSimple_6() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo =\n" +
"[[void a() {\n" +
" baa;\n" +
"}\n" +
"\n" +
"void b() {\n" +
" boo(hoo);\n" +
"}]]");
String nl = System.getProperty("line.separator");
assertEquals(
"void a() {" + nl +
" baa;" + nl +
"}" + nl +
nl +
"void b() {" + nl +
" boo(hoo);" + nl +
"}", tt.expand("foo"));
}
/**
* Missing template name
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_1() throws SyntaxError {
new TinyTemplate("[[]]");
}
/**
* Missing template name
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_2() throws SyntaxError {
new TinyTemplate(" = [[]]");
}
/**
* Missing end of template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_3() throws SyntaxError {
new TinyTemplate("x = [[ ");
}
/**
* Missing end of template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_4() throws SyntaxError {
new TinyTemplate("x = [[ ]");
}
/**
* Missing start of template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_5() throws SyntaxError {
new TinyTemplate("x = ]]");
}
/**
* Missing start of template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_6() throws SyntaxError {
new TinyTemplate("x = [ ]]");
}
/**
* Double brackets not allowed inside template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_7() throws SyntaxError {
new TinyTemplate("x = [[ [[ ]]");
}
/**
* Double brackets not allowed inside template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_8() throws SyntaxError {
new TinyTemplate("x = [[ ]] ]]");
}
/**
* Missing template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_9() throws SyntaxError {
new TinyTemplate("x = ");
}
/**
* Missing template body
* @throws SyntaxError
*/
@Test(expected=SyntaxError.class)
public void testSyntaxError_10() throws SyntaxError {
new TinyTemplate("x");
}
/**
* Multiple assign are allowed between template name and template body
* @throws SyntaxError
*/
@Test
public void testMultiAssign_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"test == \n" +
"== ==== = ===== [[$hello]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("hello", "hej");
assertEquals("hej", tc.expand("test"));
}
/**
* Multiple template names are allowed for each template
* @throws SyntaxError
*/
@Test
public void testSynonyms_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"test == foo = = = bar [[$hello]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("hello", "hej");
assertEquals("hej", tc.expand("test"));
assertEquals("hej", tc.expand("foo"));
assertEquals("hej", tc.expand("bar"));
}
/**
* Multiple template names are allowed for each template
* @throws SyntaxError
*/
@Test
public void testSynonyms_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"test foo bar [[$hello]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("hello", "hej");
assertEquals("hej", tc.expand("test"));
assertEquals("hej", tc.expand("foo"));
assertEquals("hej", tc.expand("bar"));
}
/**
* Tests a template comment
* @throws SyntaxError
*/
@Test
public void testComment_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"# line comment\n" +
"test = [[$hello]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("hello", "hej");
assertEquals("hej", tc.expand("test"));
}
/**
* Tests a template comment
* @throws SyntaxError
*/
@Test
public void testComment_2() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo=[[x]]# comment\n" +
"# test = [[y]]");
assertEquals("", tt.expand("test"));
assertEquals("x", tt.expand("foo"));
}
/**
* Tests a template comment
* @throws SyntaxError
*/
@Test
public void testComment_3() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo=[[## not a comment]]");
assertEquals("hash signs inside a template body are not comments",
"# not a comment", tt.expand("foo"));
}
/**
* Tests that indentation is replaced correctly
* @throws SyntaxError
*/
@Test
public void testIndentation_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo = \n" +
"[[void m() {\n" +
" \n" +
" 2 \n" +
" ]]");
tt.setIndentation("\t");
String nl = System.getProperty("line.separator");
assertEquals(
"void m() {" + nl +
"\t" + nl +
"\t\t2 " + nl +
"\t\t\t\t", tt.expand("foo"));
}
/**
* Expansions can be correctly indented, but the indentation inside the
* expansion is not touched.
* @throws SyntaxError
*/
@Test
public void testIndentationExpansion_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo = \n" +
"[[ $block]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("block",
"{\n" +
" hello\n" +
" you\n" +
"}");
tt.setIndentation(" ");
String nl = System.getProperty("line.separator");
assertEquals(
" {" + nl +
" hello" + nl +
" you" + nl +
" }", tc.expand("foo"));
}
/**
* Line splicing is not enabled
* @throws SyntaxError
*/
@Test
public void testLineSplicing_1() throws SyntaxError {
TinyTemplate tt = new TinyTemplate(
"foo[[ \\\n" +
"$boo\\\n" +
"\n" +
"]]");
SimpleContext tc = new SimpleContext(tt, new Object());
tc.bind("boo",
"{\n" +
" hello\\\n" +
" you\n" +
"}");
tt.setIndentation(" ");
String nl = System.getProperty("line.separator");
assertEquals(
" \\" + nl +
"{\n" +
" hello\\\n" +
" you\n" +
"}\\" + nl + nl, tc.expand("foo"));
}
} |
package com.atul.JavaOpenCV;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
//import java.io.ByteArrayInputStream;
//import java.io.InputStream;
//import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
//import javax.swing.plaf.ButtonUI;
import javax.swing.WindowConstants;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
public class Imshow {
public JFrame Window;
private ImageIcon image;
private JLabel label;
//private MatOfByte matOfByte;
private Boolean SizeCustom;
private int Height, Width;
public Imshow(String title) {
Window = new JFrame();
image = new ImageIcon();
label = new JLabel();
//matOfByte = new MatOfByte();
label.setIcon(image);
Window.getContentPane().add(label);
Window.setResizable(false);
Window.setTitle(title);
SizeCustom = false;
setCloseOption(0);
}
public Imshow(String title, int height, int width) {
SizeCustom = true;
Height = height;
Width = width;
Window = new JFrame();
image = new ImageIcon();
label = new JLabel();
//matOfByte = new MatOfByte();
label.setIcon(image);
Window.getContentPane().add(label);
Window.setResizable(false);
Window.setTitle(title);
setCloseOption(0);
}
public void showImage(Mat img) {
if (SizeCustom) {
Imgproc.resize(img, img, new Size(Height, Width));
}
//Highgui.imencode(".jpg", img, matOfByte);
// byte[] byteArray = matOfByte.toArray();
BufferedImage bufImage = null;
try {
// InputStream in = new ByteArrayInputStream(byteArray);
// bufImage = ImageIO.read(in);
bufImage = toBufferedImage(img);
image.setImage(bufImage);
Window.pack();
label.updateUI();
Window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
// version !
public BufferedImage toBufferedImage(Mat m) {
int type = BufferedImage.TYPE_BYTE_GRAY;
if (m.channels() > 1) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels() * m.cols() * m.rows();
byte[] b = new byte[bufferSize];
m.get(0, 0, b); // get all the pixels
BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster()
.getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return image;
}
public void setCloseOption(int option) {
switch (option) {
case 0:
Window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
break;
case 1:
Window.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
break;
default:
Window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
} |
package matlab;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
import org.antlr.runtime.ANTLRReaderStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.Token;
/**
* Parent class of the generated MatlabScannerTests class.
* Provides helper methods to keep MatlabScannerTests short.
*/
class ScannerTestBase extends TestCase {
private static final Pattern SYMBOL_PATTERN = Pattern.compile("^\\s*([_A-Z]+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*(?:\\s(\\d+))?\\s*(?:\\s=(.*))?$");
/* Compare the output of the scanner with a list of expected symbols and an optional exception. */
@SuppressWarnings("unchecked")
static void checkScan(MatlabLexer lexer, List<Symbol> symbols, TextPosition exceptionPos) throws IOException {
CommonTokenStream tokens = new CommonTokenStream(lexer);
List<Token> actualTokens = tokens.getTokens(); //prefetch all tokens
int tokenNum = 0;
for(Symbol expected : symbols) {
Token actual = actualTokens.get(tokenNum);
assertEquals("Token #" + tokenNum, actual, expected);
tokenNum++;
if(lexer.hasProblem()) {
TranslationProblem prob = lexer.getProblems().get(0);
assertEquals(prob.getMessage(), new TextPosition(prob.getLine(), prob.getColumn()), exceptionPos);
return;
}
}
if(tokenNum < actualTokens.size()) {
int actualType = tokens.get(tokenNum).getType();
int expectedType = MatlabParser.EOF;
fail("Token #" + tokenNum + ": incorrect token type - " +
"expected: " + expectedType + " (" + MatlabParser.tokenNames[expectedType] + ") " +
"but was: " + actualType + " (" + MatlabParser.tokenNames[actualType] + ")");
}
if(lexer.hasProblem()) {
TranslationProblem prob = lexer.getProblems().get(0);
assertEquals(prob.getMessage(), new TextPosition(prob.getLine(), prob.getColumn()), exceptionPos);
return;
}
}
/* Construct a scanner that will read from the specified file. */
static MatlabLexer getLexer(String filename) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(filename));
MatlabLexer lexer = new MatlabLexer(new ANTLRReaderStream(in));
return lexer;
}
/*
* Read symbols from the .out file.
* Returns a position if there is an exception line and null otherwise.
*/
static TextPosition parseSymbols(String filename, /*OUT*/ List<Symbol> symbols)
throws IOException, IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
BufferedReader in = new BufferedReader(new FileReader(filename));
while(in.ready()) {
String line = in.readLine();
if(isExceptionLine(line)) {
return getExceptionPosition(line);
}
symbols.add(parseSymbol(line));
}
in.close();
return null;
}
/* Returns true if the line should be treated as an exception line. */
private static boolean isExceptionLine(String line) {
return line.charAt(0) == '~';
}
/*
* Constructs a TextPosition from a line of text.
* Format:
* ~ start_line start_col
*/
private static TextPosition getExceptionPosition(String line) {
StringTokenizer tokenizer = new StringTokenizer(line.substring(1));
assertEquals("Number of tokens in exception line: " + line, 2, tokenizer.countTokens());
int lineNum = Integer.parseInt(tokenizer.nextToken());
int colNum = Integer.parseInt(tokenizer.nextToken());
return new TextPosition(lineNum, colNum);
}
/*
* Constructs a Symbol from a line of text.
* Format:
* TYPE start_line start_col length [=value]
* e.g. FOR 2 1 3
* IDENTIFIER 3 2 1 =x
*/
private static Symbol parseSymbol(String line)
throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
Matcher matcher = SYMBOL_PATTERN.matcher(line);
if(!matcher.matches()) {
fail("Invalid line: " + line);
}
String idString = matcher.group(1);
int id = MatlabParser.class.getField(idString).getInt(null); //null since the field is static
int startLine = Integer.parseInt(matcher.group(2));
int startCol = Integer.parseInt(matcher.group(3));
String value = matcher.group(6);
if(matcher.group(5) == null) {
int length = Integer.parseInt(matcher.group(4));
return new Symbol(id, startLine, startCol, startLine, startCol + length - 1, value);
} else {
int endLine = Integer.parseInt(matcher.group(4));
int endCol = Integer.parseInt(matcher.group(5));
return new Symbol(id, startLine, startCol, endLine, endCol, value);
}
}
/* Checks deep equality of two Symbols (complexity comes from giving nice error messages). */
public static void assertEquals(String msg, Token actual, Symbol expected) throws IOException {
final int expectedId = expected.getType();
final int actualId = actual.getType();
if(actualId != expectedId) {
fail(msg + ": incorrect token type - " +
"expected: " + expectedId + " (" + MatlabParser.tokenNames[expectedId] + ") " +
"but was: " + actualId + " (" + MatlabParser.tokenNames[actualId] + ")");
}
final String expectedValue = expected.getText();
final String actualValue = ScannerTestTool.stringifyValue(actual.getText());
if(((actualValue == null || expectedValue == null) && (actualValue != expectedValue)) ||
(actualValue != null && !actualValue.equals(expectedValue))) {
fail(msg + " - " + MatlabParser.tokenNames[actualId] + ": incorrect token value - " +
"expected: " + expectedValue + " " +
"but was: " + actualValue);
}
final int expectedStartLine = expected.getStartLine();
final int expectedStartCol = expected.getStartCol();
final int actualStartLine = actual.getLine();
final int actualStartCol = actual.getCharPositionInLine() + 1;
if(expectedStartLine != actualStartLine || expectedStartCol != actualStartCol) {
fail(msg + " - " + getTokenString(actual) + ": incorrect start position - " +
"expected: line " + expectedStartLine + " col " + expectedStartCol + " " +
"but was: line " + actualStartLine + " col " + actualStartCol);
}
final int expectedEndLine = expected.getEndLine();
final int expectedEndCol = expected.getEndCol();
TextPosition lastPos = ScannerTestTool.getLastPosition(actual.getText());
final int actualEndLine = actualStartLine + lastPos.getLine() - 1;
final int actualEndCol = actualStartCol + lastPos.getColumn() - 1;
if(expectedEndLine != actualEndLine || expectedEndCol != actualEndCol) {
fail(msg + " - " + getTokenString(actual) + ": incorrect end position - " +
"expected: line " + expectedEndLine + " col " + expectedEndCol + " " +
"but was: line " + actualEndLine + " col " + actualEndCol);
}
}
/* Checks deep equality of two error TextPositions. */
public static void assertEquals(String msg, TextPosition actual, TextPosition expected) {
if(actual == null) {
if(expected == null) {
return;
} else {
fail("Actual exception was unexpectedly null (expected: [" + actual.getLine() + ", " + actual.getColumn() + "] " + expected + ")");
}
} else if(expected == null) {
fail("Unexpected exception: [" + actual.getLine() + ", " + actual.getColumn() + "] " + actual);
}
assertEquals(msg + " - exception line number", actual.getLine(), expected.getLine());
assertEquals(msg + " - exception column number", actual.getColumn(), expected.getColumn());
}
/* Returns a pretty-printed version of a Symbol. */
protected static String getTokenString(Token tok) {
return MatlabParser.tokenNames[tok.getType()] + "(" + tok.getText() + ")";
}
static class Symbol {
private final int startLine;
private final int startCol;
private final int endLine;
private final int endCol;
private final int type;
private final String text;
Symbol(int type, int startLine, int startCol, int endLine, int endCol, String text) {
this.startLine = startLine;
this.startCol = startCol;
this.endLine = endLine;
this.endCol = endCol;
this.type = type;
this.text = text;
}
public int getStartLine() {
return startLine;
}
public int getStartCol() {
return startCol;
}
public int getEndLine() {
return endLine;
}
public int getEndCol() {
return endCol;
}
public int getType() {
return type;
}
public String getText() {
return text;
}
public String toString() {
return MatlabParser.tokenNames[type] + "[" + type + "] - (" + startLine + ", " + startCol + ") to (" + endLine + ", " + endCol + ") = " + text;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.