answer
stringlengths 17
10.2M
|
|---|
package org.intermine.api.bag;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.intermine.InterMineException;
import org.intermine.api.profile.BagValue;
import org.intermine.api.profile.InterMineBag;
/**
* @author Daniela
*/
public class BagQueryUpgrade
{
private static final Logger LOG = Logger.getLogger(BagQueryUpgrade.class);
BagQueryRunner bagQueryRunner;
private InterMineBag bag;
/**
* @param bagQueryRunner the bag query runner
* @param bag list to upgrade
*/
public BagQueryUpgrade(BagQueryRunner bagQueryRunner, InterMineBag bag) {
this.bagQueryRunner = bagQueryRunner;
this.bag = bag;
}
/**
* @return type of bag
*/
public String getType() {
return bag.getType();
}
/**
* @return results of list upgrade
*/
public BagQueryResult getBagQueryResult() {
BagQueryResult bagQueryResult = null;
List<BagValue> bagValueList = bag.getContentsOrderByExtraValue();
List<BagQueryResult> bagQueryResultList = new ArrayList<BagQueryResult>();
List<String> primaryIdentifiersList = new ArrayList<String>();
String extra;
String prevExtra = "";
try {
for (BagValue bagValue : bagValueList) {
extra = (bagValue.getExtra() != null) ? bagValue.getExtra() : "";
if ("".equals(extra)) {
primaryIdentifiersList.add(bagValue.getValue());
prevExtra = extra;
} else {
if ("".equals(prevExtra)) {
primaryIdentifiersList.add(bagValue.getValue());
prevExtra = extra;
} else {
if (prevExtra.equals(extra)) {
primaryIdentifiersList.add(bagValue.getValue());
} else {
bagQueryResultList.add(bagQueryRunner.searchForBag(bag.getType(),
primaryIdentifiersList, prevExtra, false));
prevExtra = extra;
primaryIdentifiersList = new ArrayList<String>();
primaryIdentifiersList.add(bagValue.getValue());
}
}
}
}
bagQueryResultList.add(bagQueryRunner.searchForBag(bag.getType(),
primaryIdentifiersList, prevExtra, false));
bagQueryResult = combineBagQueryResult(bagQueryResultList);
} catch (ClassNotFoundException cnfe) {
LOG.warn("The type " + bag.getType() + "isn't in the model."
+ "Impossible upgrade the bag list " + bag.getTitle(), cnfe);
} catch (InterMineException ie) {
LOG.warn("Cannot upgrade the list " + bag.getTitle(), ie);
}
return bagQueryResult;
}
private static BagQueryResult combineBagQueryResult(List<BagQueryResult> bagQueryResultList) {
BagQueryResult bagQueryResult = new BagQueryResult();
for (BagQueryResult bqr : bagQueryResultList) {
bagQueryResult.getMatches().putAll(bqr.getMatches());
bagQueryResult.getIssues().putAll(bqr.getIssues());
bagQueryResult.getUnresolved().putAll(bqr.getUnresolved());
}
return bagQueryResult;
}
}
|
/*
* This snippet shows how to set and get properties.
*
* For more information, read "Le guide de survie Java" (chap. 2)
* (by Timothy Fisher, ed. CampusPress)
*
* Usage:
* - compile: javac Properties.java
* - execute: java Properties
*/
public class Properties {
public static void main(String [] args) {
// Set the timezone property
System.setProperty("timezone", "EsternStandardTime");
// Get the timezone property
String timezone = System.getProperty("timezone");
System.out.println(timezone);
// Get all properties
java.util.Properties properties = System.getProperties();
for (String key : properties.stringPropertyNames()) {
System.out.println(key + " = " + properties.getProperty(key));
}
}
}
|
package fr.broeglin.camel.musings.activemq;
import static java.util.Arrays.asList;
import static org.apache.activemq.command.ActiveMQDestination.QUEUE_TYPE;
import static org.apache.activemq.command.ActiveMQDestination.createDestination;
import static org.apache.camel.LoggingLevel.INFO;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.camel.component.ActiveMQComponent;
import org.apache.activemq.camel.component.ActiveMQConfiguration;
import org.apache.activemq.network.NetworkConnector;
import org.apache.camel.Endpoint;
import org.apache.camel.EndpointInject;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NetworkOfBrokersTest extends CamelTestSupport {
public static final Logger log = LoggerFactory.getLogger(NetworkOfBrokersTest.class);
private static final String REMOTE_BROKER_URL = "tcp://127.0.0.1:51616";
private static final String LOCAL_BROKER_URL = "tcp://127.0.0.1:61616";
@EndpointInject(uri = "direct:in")
Endpoint in;
@EndpointInject(uri = "mock:out")
MockEndpoint out;
private void setUpLocalBroker() throws Exception {
BrokerService broker = createActivemqBroker("local", LOCAL_BROKER_URL);
NetworkConnector connector = broker.addNetworkConnector("static:
+ REMOTE_BROKER_URL);
connector.setDuplex(true);
connector.setStaticBridge(true);
connector.setStaticallyIncludedDestinations(asList(
createDestination("TEST", QUEUE_TYPE),
createDestination("TEST_REPLY_TO", QUEUE_TYPE)));
broker.start();
}
private void setUpRemoteBroker() throws Exception {
createActivemqBroker("remote", REMOTE_BROKER_URL).start();
}
private BrokerService createActivemqBroker(String brokerName, String bindAddress)
throws Exception {
log.debug("Setting up ActiveMQ broker {}: {}", brokerName, bindAddress);
BrokerService broker = new BrokerService();
broker.setBrokerName(brokerName);
broker.setUseShutdownHook(false);
broker.setPersistent(false);
broker.setManagementContext(null);
broker.setUseJmx(false);
broker.addConnector(bindAddress);
return broker;
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
setUpRemoteBroker();
setUpLocalBroker();
addActivemqComponent("activemqRemote", REMOTE_BROKER_URL);
addActivemqComponent("activemqLocal", LOCAL_BROKER_URL);
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from(in)
.to("activemqRemote:queue:TEST?requestTimeout=2000&replyTo=TEST_REPLY_TO")
.log(INFO, "About to send message ${body}...")
.to(out);
from("activemqLocal:queue:TEST")
.log(INFO, "About to transform message ${body}...")
.transform(simple("${body} X"));
}
};
}
private void addActivemqComponent(String scheme, String brokerURL) {
ActiveMQConfiguration confRemote = new ActiveMQConfiguration();
confRemote.setBrokerURL(brokerURL);
ActiveMQComponent component = new ActiveMQComponent(confRemote);
context().addComponent(scheme, component);
}
@Test
public void should_forward_message() throws Exception {
out.expectedMessageCount(1);
template.requestBody(in, "test message");
out.message(0).body().isEqualTo("test message X");
out.assertIsSatisfied();
}
}
|
package ru.stqa.pft.addressbook;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import java.util.concurrent.TimeUnit;
import java.util.Date;
import java.io.File;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.*;
import static org.openqa.selenium.OutputType.*;
public class GroupCreationTests {
FirefoxDriver wd;
@BeforeMethod
public void setUp() throws Exception {
wd = new FirefoxDriver();
wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); wd.get("http://localhost/addressbook/");
wd.findElement(By.name("user")).click();
wd.findElement(By.name("user")).clear();
wd.findElement(By.name("user")).sendKeys("admin");
wd.findElement(By.name("pass")).click();
wd.findElement(By.name("pass")).sendKeys("\\undefined");
wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click();
}
@Test
public void testGroupCreation() {
wd.findElement(By.linkText("groups")).click();
wd.findElement(By.name("new")).click();
wd.findElement(By.name("group_name")).click();
wd.findElement(By.name("group_name")).clear();
wd.findElement(By.name("group_name")).sendKeys("test1");
wd.findElement(By.name("group_header")).click();
wd.findElement(By.name("group_header")).clear();
wd.findElement(By.name("group_header")).sendKeys("test2");
wd.findElement(By.name("group_footer")).click();
wd.findElement(By.name("group_footer")).clear();
wd.findElement(By.name("group_footer")).sendKeys("test3");
wd.findElement(By.name("submit")).click();
wd.findElement(By.linkText("group page")).click();
}
@AfterMethod
public void tearDown() {
wd.quit();
}
public static boolean isAlertPresent(FirefoxDriver wd) {
try {
wd.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
}
|
package host.exp.exponent.utils;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.WindowManager;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import host.exp.exponent.ABIVersion;
import host.exp.exponent.ExponentManifest;
import host.exp.exponent.analytics.EXL;
import org.json.JSONObject;
public class ExperienceActivityUtils {
private static final String TAG = ExperienceActivityUtils.class.getSimpleName();
public static void updateOrientation(JSONObject manifest, Activity activity) {
if (manifest == null) {
return;
}
String orientation = manifest.optString(ExponentManifest.MANIFEST_ORIENTATION_KEY, null);
if (orientation == null) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
return;
}
switch (orientation) {
case "default":
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
break;
case "portrait":
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case "landscape":
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
}
}
// region user interface style - light/dark/automatic mode
public static void overrideUserInterfaceStyle(JSONObject manifest, AppCompatActivity activity) {
String userInterfaceStyle = readUserInterfaceStyleFromManifest(manifest);
int mode = nightModeFromString(userInterfaceStyle);
activity.getDelegate().setLocalNightMode(mode);
}
private static int nightModeFromString(@Nullable String userInterfaceStyle) {
if (userInterfaceStyle == null) {
return AppCompatDelegate.MODE_NIGHT_NO;
}
switch (userInterfaceStyle) {
case "automatic":
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY;
}
return AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
case "dark":
return AppCompatDelegate.MODE_NIGHT_YES;
case "light":
default:
return AppCompatDelegate.MODE_NIGHT_NO;
}
}
@Nullable
private static String readUserInterfaceStyleFromManifest(JSONObject manifest) {
if (manifest.has("android") && manifest.optJSONObject("android").has("userInterfaceStyle")) {
return manifest.optJSONObject("android").optString("userInterfaceStyle");
}
return manifest.optString("userInterfaceStyle", "light");
}
// endregion
public static void setWindowTransparency(final String sdkVersion, final JSONObject manifest, final Activity activity) {
JSONObject statusBarOptions = manifest.optJSONObject(ExponentManifest.MANIFEST_STATUS_BAR_KEY);
String statusBarColor;
if (statusBarOptions != null) {
statusBarColor = statusBarOptions.optString(ExponentManifest.MANIFEST_STATUS_BAR_BACKGROUND_COLOR);
} else {
statusBarColor = manifest.optString(ExponentManifest.MANIFEST_STATUS_BAR_COLOR);
}
if (statusBarColor != null && ColorParser.isValid(statusBarColor)) {
try {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().setStatusBarColor(Color.parseColor(statusBarColor));
} catch (Throwable e) {
EXL.e(TAG, e);
}
}
if (statusBarOptions == null) {
return;
}
String statusBarAppearance = statusBarOptions.optString(ExponentManifest.MANIFEST_STATUS_BAR_APPEARANCE);
if (statusBarAppearance != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (statusBarAppearance.equals("dark-content")) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
} catch (Throwable e) {
EXL.e(TAG, e);
}
}
}
public static void setTaskDescription(final ExponentManifest exponentManifest, final JSONObject manifest, final Activity activity) {
final String iconUrl = manifest.optString(ExponentManifest.MANIFEST_ICON_URL_KEY);
final int color = exponentManifest.getColorFromManifest(manifest);
exponentManifest.loadIconBitmap(iconUrl, new ExponentManifest.BitmapListener() {
@Override
public void onLoadBitmap(Bitmap bitmap) {
// This if statement is only needed so the compiler doesn't show an error.
try {
activity.setTaskDescription(new ActivityManager.TaskDescription(
manifest.optString(ExponentManifest.MANIFEST_NAME_KEY),
bitmap,
color
));
} catch (Throwable e) {
EXL.e(TAG, e);
}
}
});
}
public static void setNavigationBar(final JSONObject manifest, final Activity activity) {
JSONObject navBarOptions = manifest.optJSONObject(ExponentManifest.MANIFEST_NAVIGATION_BAR_KEY);
if (navBarOptions == null) {
return;
}
String navBarColor = navBarOptions.optString(ExponentManifest.MANIFEST_NAVIGATION_BAR_BACKGROUND_COLOR);
// Set background color of navigation bar
if (navBarColor != null && ColorParser.isValid(navBarColor)) {
try {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
activity.getWindow().setNavigationBarColor(Color.parseColor(navBarColor));
} catch (Throwable e) {
EXL.e(TAG, e);
}
}
// Set icon color of navigation bar
String navBarAppearance = navBarOptions.optString(ExponentManifest.MANIFEST_NAVIGATION_BAR_APPEARANCE);
if (navBarAppearance != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (navBarAppearance.equals("dark-content")) {
View decorView = activity.getWindow().getDecorView();
int flags = decorView.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
decorView.setSystemUiVisibility(flags);
}
} catch (Throwable e) {
EXL.e(TAG, e);
}
}
// Set visibility of navigation bar
if (navBarOptions.has(ExponentManifest.MANIFEST_NAVIGATION_BAR_VISIBLILITY)) {
Boolean visible = navBarOptions.optBoolean(ExponentManifest.MANIFEST_NAVIGATION_BAR_VISIBLILITY);
if (!visible) {
// Hide both the navigation bar and the status bar. The Android docs recommend, "you should
// design your app to hide the status bar whenever you hide the navigation bar."
View decorView = activity.getWindow().getDecorView();
int flags = decorView.getSystemUiVisibility();
flags |= (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
decorView.setSystemUiVisibility(flags);
}
}
}
}
|
package com.jme3.system.lwjgl;
import com.jme3.input.lwjgl.GlfwJoystickInput;
import com.jme3.input.lwjgl.GlfwKeyInput;
import com.jme3.input.lwjgl.GlfwMouseInput;
import com.jme3.renderer.Renderer;
import com.jme3.renderer.RendererException;
import com.jme3.renderer.lwjgl.LwjglGL;
import com.jme3.renderer.lwjgl.LwjglGLExt;
import com.jme3.renderer.lwjgl.LwjglGLFboEXT;
import com.jme3.renderer.lwjgl.LwjglGLFboGL3;
import com.jme3.renderer.opengl.*;
import com.jme3.renderer.opengl.GL;
import com.jme3.system.*;
import org.lwjgl.Sys;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.opengl.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.lwjgl.opengl.GL.createCapabilities;
import static org.lwjgl.opengl.GL11.GL_TRUE;
import static org.lwjgl.opengl.GL11.glGetInteger;
/**
* A LWJGL implementation of a graphics context.
*/
public abstract class LwjglContext implements JmeContext {
private static final Logger logger = Logger.getLogger(LwjglContext.class.getName());
protected static final String THREAD_NAME = "jME3 Main";
protected AtomicBoolean created = new AtomicBoolean(false);
protected AtomicBoolean renderable = new AtomicBoolean(false);
protected final Object createdLock = new Object();
protected AppSettings settings = new AppSettings(true);
protected Renderer renderer;
protected GlfwKeyInput keyInput;
protected GlfwMouseInput mouseInput;
protected GlfwJoystickInput joyInput;
protected Timer timer;
protected SystemListener listener;
public void setSystemListener(SystemListener listener) {
this.listener = listener;
}
protected void printContextInitInfo() {
logger.log(Level.INFO, "LWJGL {0} context running on thread {1}\n" +
" * Graphics Adapter: GLFW {2}",
new Object[]{Sys.getVersion(), Thread.currentThread().getName(), GLFW.glfwGetVersionString()});
}
protected int determineMaxSamples() {
// If we already have a valid context, determine samples using current context.
if (GLFW.glfwExtensionSupported("GL_ARB_framebuffer_object") == GL_TRUE) {
return glGetInteger(ARBFramebufferObject.GL_MAX_SAMPLES);
} else if (GLFW.glfwExtensionSupported("GL_EXT_framebuffer_multisample") == GL_TRUE) {
return glGetInteger(EXTFramebufferMultisample.GL_MAX_SAMPLES_EXT);
}
return Integer.MAX_VALUE;
}
protected void loadNatives() {
if (JmeSystem.isLowPermissions()) {
return;
}
if ("LWJGL".equals(settings.getAudioRenderer())) {
NativeLibraryLoader.loadNativeLibrary("openal-lwjgl3", true);
}
if (NativeLibraryLoader.isUsingNativeBullet()) {
NativeLibraryLoader.loadNativeLibrary("bulletjme", true);
}
NativeLibraryLoader.loadNativeLibrary("lwjgl3", true);
}
protected int getNumSamplesToUse() {
int samples = 0;
if (settings.getSamples() > 1) {
samples = settings.getSamples();
final int supportedSamples = determineMaxSamples();
if (supportedSamples < samples) {
logger.log(Level.WARNING,
"Couldn't satisfy antialiasing samples requirement: x{0}. "
+ "Video hardware only supports: x{1}",
new Object[]{samples, supportedSamples});
samples = supportedSamples;
}
}
return samples;
}
protected void initContextFirstTime() {
GLContext.createFromCurrent();
final ContextCapabilities capabilities = createCapabilities(settings.getRenderer().equals(AppSettings.LWJGL_OPENGL3));
if (!capabilities.OpenGL20) {
throw new RendererException("OpenGL 2.0 or higher is required for jMonkeyEngine");
}
if (settings.getRenderer().equals(AppSettings.LWJGL_OPENGL2)
|| settings.getRenderer().equals(AppSettings.LWJGL_OPENGL3)) {
GL gl = new LwjglGL();
GLExt glext = new LwjglGLExt();
GLFbo glfbo;
if (capabilities.OpenGL30) {
glfbo = new LwjglGLFboGL3();
} else {
glfbo = new LwjglGLFboEXT();
}
if (settings.getBoolean("GraphicsDebug")) {
gl = new GLDebugDesktop(gl, glext, glfbo);
glext = (GLExt) gl;
glfbo = (GLFbo) gl;
}
if (settings.getBoolean("GraphicsTiming")) {
GLTimingState timingState = new GLTimingState();
gl = (GL) GLTiming.createGLTiming(gl, timingState, GL.class, GL2.class, GL3.class, GL4.class);
glext = (GLExt) GLTiming.createGLTiming(glext, timingState, GLExt.class);
glfbo = (GLFbo) GLTiming.createGLTiming(glfbo, timingState, GLFbo.class);
}
if (settings.getBoolean("GraphicsTrace")) {
gl = (GL) GLTracer.createDesktopGlTracer(gl, GL.class, GL2.class, GL3.class, GL4.class);
glext = (GLExt) GLTracer.createDesktopGlTracer(glext, GLExt.class);
glfbo = (GLFbo) GLTracer.createDesktopGlTracer(glfbo, GLFbo.class);
}
renderer = new GLRenderer(gl, glext, glfbo);
renderer.initialize();
} else {
throw new UnsupportedOperationException("Unsupported renderer: " + settings.getRenderer());
}
if (capabilities.GL_ARB_debug_output && settings.getBoolean("GraphicsDebug")) {
ARBDebugOutput.glDebugMessageCallbackARB(new LwjglGLDebugOutputHandler(), 0); // User param is zero. Not sure what we could use that for.
}
renderer.setMainFrameBufferSrgb(settings.getGammaCorrection());
renderer.setLinearizeSrgbImages(settings.getGammaCorrection());
// Init input
if (keyInput != null) {
keyInput.initialize();
}
if (mouseInput != null) {
mouseInput.initialize();
}
if (joyInput != null) {
joyInput.initialize();
}
renderable.set(true);
}
public void internalDestroy() {
renderer = null;
timer = null;
renderable.set(false);
synchronized (createdLock) {
created.set(false);
createdLock.notifyAll();
}
}
public void internalCreate() {
synchronized (createdLock) {
created.set(true);
createdLock.notifyAll();
}
initContextFirstTime();
}
public void create() {
create(false);
}
public void destroy() {
destroy(false);
}
protected void waitFor(boolean createdVal) {
synchronized (createdLock) {
while (created.get() != createdVal) {
try {
createdLock.wait();
} catch (InterruptedException ignored) {
}
}
}
}
public boolean isCreated() {
return created.get();
}
public boolean isRenderable() {
return renderable.get();
}
public void setSettings(AppSettings settings) {
this.settings.copyFrom(settings);
}
public AppSettings getSettings() {
return settings;
}
public Renderer getRenderer() {
return renderer;
}
public Timer getTimer() {
return timer;
}
}
|
package jshellsession;
class TimedThreadLock {
private final Object mLock;
private volatile boolean mLockReleased;
TimedThreadLock() {
mLock = new Object();
mLockReleased = false;
}
private void lockIndefinitely() {
synchronized (mLock) {
while (!mLockReleased) {
try {
mLock.wait();
} catch (InterruptedException ignored) {
}
}
}
}
void lock(long duration /* in millis */) {
if (duration < 0) {
throw new IllegalStateException("duration is less than 0");
} else if (duration == 0) {
lockIndefinitely();
} else {
synchronized (mLock) {
final long startTime = System.currentTimeMillis();
while (duration > 0) {
try {
mLock.wait(duration);
} catch (InterruptedException ignored) {
}
// handle interruptions
if (mLockReleased) {
break;
} else {
final long elapsedTime = System.currentTimeMillis() - startTime;
duration = Math.max(duration - elapsedTime, 0);
}
}
mLockReleased = false;
}
}
}
void unlock() {
synchronized (mLock) {
mLockReleased = true;
mLock.notify();
}
}
}
|
package com.developgmail.mitroshin.criminalintent;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DatePickerFragment extends DialogFragment {
private static final String ARG_DATE = "date";
public static final String EXTRA_DATE = "com.developgmail.mitroshin.criminalintent.date";
private DatePicker mDatePicker;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(ARG_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Date date = (Date) getArguments().getSerializable(ARG_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date, null);
mDatePicker = (DatePicker) v.findViewById(R.id.dialog_date_picker);
mDatePicker.init(year, month, day, null);
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int year = mDatePicker.getYear();
int month = mDatePicker.getMonth();
int day = mDatePicker.getDayOfMonth();
Date date = new GregorianCalendar(year, month, day).getTime();
sendResult(Activity.RESULT_OK, date);
}
})
.create();
}
private void sendResult(int resultCode, Date date) {
if (getTargetFragment() == null) {
return;
}
Intent intent = new Intent();
intent.putExtra(EXTRA_DATE, date);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}
}
|
package org.lenskit.util.io;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import javax.annotation.WillClose;
import javax.annotation.WillCloseWhenClosed;
import java.util.*;
import java.util.stream.Stream;
/**
* Utility methods for streams.
*
* @compat Public
* @deprecated Use {@link Stream} methods instead of this class's methods.
*/
@Deprecated
public final class ObjectStreams {
private ObjectStreams() {
}
/**
* Wrap an iterator in an object stream.
*
* The iterator may not contain `null`. This property is checked lazily; the object stream will not fail
* until the `null` would be returned.
*
* @param <T> The type of data to return.
* @param iterator An iterator to wrap
* @return An object stream returning the elements of the iterator.
*/
public static <T> ObjectStream<T> wrap(Iterator<? extends T> iterator) {
return new IteratorObjectStream<>(iterator);
}
/**
* Wrap a Java stream in an object stream.
*
* The stream may not contain `null`. This property is checked lazily; the object stream will not fail
* until the `null` would be returned.
*
* @param <T> The type of data to return.
* @param stream A stream to wrap
* @return An object stream returning the elements of the stream.
*/
public static <T> ObjectStream<T> wrap(Stream<? extends T> stream) {
return new IteratorObjectStream<>(stream.iterator());
}
/**
* Wrap a collection in an object stream.
*
* The iterator may not contain `null`. This property is checked lazily; the object stream will not fail
* until the `null` would be returned.
*
* @param <T> The type of data to return.
* @param collection A collection to wrap
* @return An object stream returning the elements of the collection.
*/
public static <T> ObjectStream<T> wrap(Collection<? extends T> collection) {
return new IteratorObjectStream<>(collection);
}
/**
* Filter an object stream.
*
* @param <T> The type of object stream rows.
* @param stream The source stream.
* @param predicate A predicate indicating which rows to return.
* @return An object stream returning all rows for which <var>predicate</var> returns
* {@code true}.
*/
public static <T> ObjectStream<T> filter(@WillCloseWhenClosed ObjectStream<T> stream, Predicate<? super T> predicate) {
return new FilteredObjectStream<>(stream, predicate);
}
/**
* Filter an object stream to only contain elements of type <var>type</var>. Unlike
* {@link #filter(ObjectStream, Predicate)} with a predicate from
* {@link Predicates#instanceOf(Class)}, this method also transforms the
* stream to be of the target type.
*
* @param <T> The type of value in the stream.
* @param source The source stream.
* @param type The type to filter.
* @return An object stream returning all elements in <var>stream</var> which are
* instances of type <var>type</var>.
*/
public static <T> ObjectStream<T> filter(@WillCloseWhenClosed final ObjectStream<?> source, final Class<T> type) {
return new AbstractObjectStream<T>() {
@SuppressWarnings("unchecked")
@Override
public T readObject() {
Object obj = source.readObject();
while (obj != null && !type.isInstance(obj)) {
obj = source.readObject();
}
return type.cast(obj);
}
@Override
public void close() {
source.close();
}
};
}
/**
* Consume and discard the first {@code n} elements from an object stream.
* @param n The number of elements to drop.
* @param stream The stream.
* @param <T> The stream's element type.
* @return The passed-in stream, for convenience and functional-looking code. This method immediately consumes the
* elements, however, so {@code stream} is modified.
*/
public static <T> ObjectStream<T> consume(int n, ObjectStream<T> stream) {
Preconditions.checkArgument(n >= 0, "number to skip must be non-negative");
boolean wasNull = false;
for (int i = 0; i < n && !wasNull; i++) {
T obj = stream.readObject();
wasNull = obj == null;
}
return stream;
}
/**
* Transform an object stream's values.
*
* @param <S> The type of source stream rows
* @param <T> The type of output stream rows
* @param objectStream The source stream
* @param function A function to apply to each row in the stream. It will be applied to each value at most once.
* @return A new stream iterating the results of <var>function</var>.
*/
public static <S, T> ObjectStream<T> transform(@WillCloseWhenClosed ObjectStream<S> objectStream, Function<? super S, ? extends T> function) {
return new TransformedObjectStream<>(objectStream, function);
}
/**
* Create an empty object stream.
*
* @param <T> The type of value in the object stream.
* @return An empty object stream.
*/
public static <T> ObjectStream<T> empty() {
return wrap(Collections.<T>emptyList());
}
/**
* Read an object stream into a list, closing when it is finished.
*
* @param <T> The type of item in the object stream.
* @param objectStream The object stream.
* @return A new list containing the elements of the object stream.
*/
@SuppressWarnings("PMD.LooseCoupling")
public static <T> List<T> makeList(@WillClose ObjectStream<? extends T> objectStream) {
List<T> result = null;
try {
if (objectStream instanceof IteratorObjectStream) {
result = ((IteratorObjectStream) objectStream).getList();
}
if (result == null) {
ImmutableList.Builder<T> builder = ImmutableList.builder();
builder.addAll(objectStream);
result = builder.build();
}
} finally {
objectStream.close();
}
return result;
}
/**
* Count the items in a stream.
*
* @param objectStream The object stream.
* @return The number of items in the stream.
*/
@SuppressWarnings("PMD.LooseCoupling")
public static int count(@WillClose ObjectStream<?> objectStream) {
try {
if (objectStream instanceof IteratorObjectStream) {
List<?> list = ((IteratorObjectStream) objectStream).getList();
if (list != null) {
return list.size();
}
}
int n = 0;
Object obj = objectStream.readObject();
while (obj != null) {
n++;
obj = objectStream.readObject();
}
return n;
} finally {
objectStream.close();
}
}
/**
* Sort an object stream. This reads the original object stream into a list, sorts it, and
* returns a new object stream backed by the list (after closing the original object stream).
*
* @param <T> The type of value in the object stream.
* @param objectStream The object stream to sort.
* @param comp The comparator to use to sort the object stream.
* @return An object stream iterating over the sorted results.
*/
public static <T> ObjectStream<T> sort(@WillClose ObjectStream<T> objectStream,
Comparator<? super T> comp) {
ArrayList<T> list;
try {
list = Lists.newArrayList(objectStream);
} finally {
objectStream.close();
}
Collections.sort(list, comp);
return wrap(list);
}
/**
* Create an object stream over a fixed set of elements. This is mostly useful for testing.
* @param contents The contents.
* @param <T> The data type.
* @return The object stream.
*/
@SafeVarargs
@SuppressWarnings("varargs") // method is safe MDE 2015-05-08
public static <T> ObjectStream<T> of(T... contents) {
return wrap(Arrays.asList(contents));
}
/**
* Concatenate object streams. Each object stream is closed as closed as it is consumed.
* @param streams The object streams to concatenate.
* @param <T> The type of data.
* @return The concatenated object stream.
*/
public static <T> ObjectStream<T> concat(Iterable<? extends ObjectStream<? extends T>> streams) {
return new SequencedObjectStream<>(streams);
}
/**
* Concatenate object streams.
* @see #concat(Iterable)
*/
@SafeVarargs
@SuppressWarnings("varargs") // method is safe MDE 2015-05-08
public static <T> ObjectStream<T> concat(ObjectStream<? extends T>... objectStreams) {
return concat(Arrays.asList(objectStreams));
}
}
|
package com.lzh.mdzhihudaily_mvp.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.lzh.mdzhihudaily_mvp.R;
import com.lzh.mdzhihudaily_mvp.base.BaseActivity;
import com.lzh.mdzhihudaily_mvp.model.DataRepository;
import com.lzh.mdzhihudaily_mvp.model.Entity.NewsDetail;
import com.lzh.mdzhihudaily_mvp.utils.HtmlUtil;
import butterknife.BindView;
import rx.Subscriber;
import rx.Subscription;
public class ThemeNewsDetailActivity extends BaseActivity {
private static final String STORY_ID = "story_id";
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.webview)
WebView webview;
@BindView(R.id.cpb_loading)
ContentLoadingProgressBar cpbLoading;
private Subscription subscription;
public static void startActivity(Context context, long storyId) {
Intent intent = new Intent(context, ThemeNewsDetailActivity.class);
intent.putExtra(STORY_ID, storyId);
context.startActivity(intent);
}
@Override
protected int getLayoutId() {
return R.layout.activity_theme_news_detail;
}
@Override
protected void initView() {
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
webview.setOverScrollMode(View.OVER_SCROLL_NEVER);
webview.getSettings().setLoadsImagesAutomatically(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
// DOM storage API
webview.getSettings().setDomStorageEnabled(true);
}
@Override
protected void initData() {
cpbLoading.setVisibility(View.VISIBLE);
Intent intent =getIntent();
long storyId = intent.getLongExtra(STORY_ID, 0);
subscription = DataRepository.getInstance()
.getNewsDetail(storyId)
.subscribe(new Subscriber<NewsDetail>() {
@Override
public void onCompleted() {
cpbLoading.setVisibility(View.GONE);
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
cpbLoading.setVisibility(View.GONE);
}
@Override
public void onNext(NewsDetail newsDetail) {
String htmlData = HtmlUtil.createHtmlData(newsDetail);
webview.loadData(htmlData, HtmlUtil.MIME_TYPE, HtmlUtil.ENCODING);
}
});
}
private void unsubscript() {
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unsubscript();
}
}
|
package fr.leomoldo.android.bunkerwar.activity;
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import fr.leomoldo.android.bunkerwar.BombshellAnimatorAsyncTask;
import fr.leomoldo.android.bunkerwar.BombshellPathComputer;
import fr.leomoldo.android.bunkerwar.GameSequencer;
import fr.leomoldo.android.bunkerwar.R;
import fr.leomoldo.android.bunkerwar.drawer.Bunker;
import fr.leomoldo.android.bunkerwar.drawer.Landscape;
import fr.leomoldo.android.bunkerwar.sdk.Drawer;
import fr.leomoldo.android.bunkerwar.sdk.GameView;
import fr.leomoldo.android.bunkerwar.sdk.ViewCoordinates;
import fr.leomoldo.android.bunkerwar.view.AbstractPrecisionSliderLayout;
import fr.leomoldo.android.bunkerwar.view.AnglePrecisionSliderLayout;
import fr.leomoldo.android.bunkerwar.view.PowerPrecisionSliderLayout;
public class TwoPlayerGameActivity extends AppCompatActivity implements BombshellAnimatorAsyncTask.CollisionListener, AbstractPrecisionSliderLayout.PrecisionSliderLayoutListener {
private final static String LOG_TAG = TwoPlayerGameActivity.class.getSimpleName();
private final static String BUNDLE_KEY_GAME_SEQUENCER = TwoPlayerGameActivity.class.getName() + ".gameSequencer";
private final static String BUNDLE_KEY_BUNKER_ONE = TwoPlayerGameActivity.class.getName() + ".bunkerOne";
private final static String BUNDLE_KEY_BUNKER_TWO = TwoPlayerGameActivity.class.getName() + ".bunkerTwo";
private final static String BUNDLE_KEY_LANDSCAPE = TwoPlayerGameActivity.class.getName() + ".landscape";
// Model :
private GameSequencer mGameSequencer;
private Bunker mPlayerOneBunker;
private Bunker mPlayerTwoBunker;
private Landscape mLandscape;
private BombshellAnimatorAsyncTask mBombshellAnimatorAsyncTask;
// Views :
private GameView mGameView;
private LinearLayout mLinearLayoutControls;
private TextView mTextViewPlayersName;
private AnglePrecisionSliderLayout mAnglePrecisionSliderLayout;
private PowerPrecisionSliderLayout mPowerPrecisionSliderLayout;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two_player_game);
// Retrieve useful views.
mLinearLayoutControls = (LinearLayout) findViewById(R.id.linearLayoutControls);
mTextViewPlayersName = (TextView) findViewById(R.id.textView_playersName);
mAnglePrecisionSliderLayout = (AnglePrecisionSliderLayout) findViewById(R.id.anglePrecisionSliderLayout);
mPowerPrecisionSliderLayout = (PowerPrecisionSliderLayout) findViewById(R.id.powerPrecisionSliderLayout);
mGameView = (GameView) findViewById(R.id.gameView);
mAnglePrecisionSliderLayout.setListener(this);
mPowerPrecisionSliderLayout.setListener(this);
final View rootView = getWindow().getDecorView().getRootView();
rootView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Clean :
/*
mGameView.unregisterDrawer(mLandscape);
mGameView.unregisterDrawer(mPlayerOneBunker);
mGameView.unregisterDrawer(mPlayerTwoBunker);
*/
// Define layout animation.
// TODO Debug and clean.
ObjectAnimator animatorAppearing = ObjectAnimator.ofFloat(mLinearLayoutControls, "translationY", -mLinearLayoutControls.getHeight(), 0f);
ObjectAnimator animatorDisappearing = ObjectAnimator.ofFloat(mLinearLayoutControls, "translationY", 0f, mLinearLayoutControls.getHeight());
/*
TranslateAnimation animationAppearing = new TranslateAnimation(0f, 0f, -mLinearLayoutControls.getHeight(), 0f);
TranslateAnimation animationDisappearing = new TranslateAnimation(0f, 0f, 0f, mLinearLayoutControls.getHeight());
*/
LayoutTransition layoutTransition = new LayoutTransition();
layoutTransition.setAnimator(LayoutTransition.APPEARING, animatorAppearing);
layoutTransition.setAnimator(LayoutTransition.DISAPPEARING, animatorDisappearing);
// LayoutAnimationController layoutAnimationController = new LayoutAnimationController(animation);
((RelativeLayout) findViewById(R.id.mainRelativeLayout)).setLayoutTransition(layoutTransition);
// Initialize or restore game model.
if (savedInstanceState != null) {
mGameSequencer = savedInstanceState.getParcelable(BUNDLE_KEY_GAME_SEQUENCER);
mLandscape = savedInstanceState.getParcelable(BUNDLE_KEY_LANDSCAPE);
if (mGameSequencer.getGameState() != GameSequencer.GameState.PLAYER_TWO_WON) {
mPlayerOneBunker = savedInstanceState.getParcelable(BUNDLE_KEY_BUNKER_ONE);
}
if (mGameSequencer.getGameState() != GameSequencer.GameState.PLAYER_ONE_WON) {
mPlayerTwoBunker = savedInstanceState.getParcelable(BUNDLE_KEY_BUNKER_TWO);
}
} else {
mGameSequencer = new GameSequencer();
mLandscape = new Landscape(getResources().getColor(R.color.green_land_slice));
mPlayerOneBunker = new Bunker(true, getResources().getColor(R.color.red_bunker), getBunkerOneCoordinates());
mPlayerTwoBunker = new Bunker(false, getResources().getColor(R.color.yellow_bunker), getBunkerTwoCoordinates());
}
if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_ONE_PLAYING) {
mTextViewPlayersName.setText(getString(R.string.player_one));
mAnglePrecisionSliderLayout.setValue(mPlayerOneBunker.getAbsoluteCanonAngleDegrees());
mPowerPrecisionSliderLayout.setValue(mPlayerOneBunker.getCanonPower());
} else if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_TWO_PLAYING) {
mTextViewPlayersName.setText(getString(R.string.player_two));
mAnglePrecisionSliderLayout.setValue(mPlayerTwoBunker.getAbsoluteCanonAngleDegrees());
mPowerPrecisionSliderLayout.setValue(mPlayerTwoBunker.getCanonPower());
} else {
mLinearLayoutControls.setVisibility(View.GONE);
}
// Initialize GameView.
if (mPlayerOneBunker != null) {
mGameView.registerDrawer(mPlayerOneBunker);
}
if (mPlayerTwoBunker != null) {
mGameView.registerDrawer(mPlayerTwoBunker);
}
mGameView.registerDrawer(mLandscape);
mGameView.invalidate();
if (Build.VERSION.SDK_INT < 16) {
rootView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
mGameSequencer.cancelFiring();
outState.putParcelable(BUNDLE_KEY_GAME_SEQUENCER, mGameSequencer);
outState.putParcelable(BUNDLE_KEY_LANDSCAPE, mLandscape);
if (mGameSequencer.getGameState() != GameSequencer.GameState.PLAYER_TWO_WON) {
outState.putParcelable(BUNDLE_KEY_BUNKER_ONE, mPlayerOneBunker);
}
if (mGameSequencer.getGameState() != GameSequencer.GameState.PLAYER_ONE_WON) {
outState.putParcelable(BUNDLE_KEY_BUNKER_TWO, mPlayerTwoBunker);
}
super.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
if (mBombshellAnimatorAsyncTask != null) {
mBombshellAnimatorAsyncTask.cancel(true);
}
super.onDestroy();
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.confirm_abondon_game));
builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
TwoPlayerGameActivity.super.onBackPressed();
}
});
builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
@Override
public void onValueChanged(AbstractPrecisionSliderLayout sliderLayout, int newValue) {
if (sliderLayout.equals(mAnglePrecisionSliderLayout)) {
if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_ONE_PLAYING) {
mPlayerOneBunker.setAbsoluteCanonAngle(newValue);
mGameView.invalidate();
} else if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_TWO_PLAYING) {
mPlayerTwoBunker.setAbsoluteCanonAngle(newValue);
mGameView.invalidate();
}
} else if (sliderLayout.equals(mPowerPrecisionSliderLayout)) {
if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_ONE_PLAYING) {
mPlayerOneBunker.setCanonPower(newValue);
mGameView.invalidate();
} else if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_TWO_PLAYING) {
mPlayerTwoBunker.setCanonPower(newValue);
mGameView.invalidate();
}
}
}
public void onButtonClickedFire(View view) {
if (mBombshellAnimatorAsyncTask != null) {
Log.d(LOG_TAG, "There is a Bombshell flying already");
return;
}
mLinearLayoutControls.setVisibility(View.GONE);
// Update GameSequencer.
mGameSequencer.fireButtonPressed();
BombshellPathComputer bombshellPathComputer;
ArrayList<Drawer> collidableDrawers = new ArrayList<Drawer>();
collidableDrawers.add(mLandscape);
// Update UI.
if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_ONE_FIRING) {
bombshellPathComputer = new BombshellPathComputer(mPlayerOneBunker.getCanonPower(), mPlayerOneBunker.getGeometricalCanonAngleRadian(), mPlayerOneBunker.getViewCoordinates());
collidableDrawers.add(mPlayerTwoBunker);
} else if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_TWO_FIRING) {
bombshellPathComputer = new BombshellPathComputer(mPlayerTwoBunker.getCanonPower(), mPlayerTwoBunker.getGeometricalCanonAngleRadian(), mPlayerTwoBunker.getViewCoordinates());
collidableDrawers.add(mPlayerOneBunker);
} else {
// Issue...
return;
}
mBombshellAnimatorAsyncTask = new BombshellAnimatorAsyncTask(mGameView, collidableDrawers, this);
mBombshellAnimatorAsyncTask.execute(bombshellPathComputer);
}
@Override
public void onDrawerHit(Drawer drawer) {
mBombshellAnimatorAsyncTask = null;
if (drawer == null || drawer.equals(mLandscape)) {
Toast.makeText(this, R.string.target_missed, Toast.LENGTH_SHORT).show();
mGameSequencer.bombshellMissedTarget();
if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_ONE_PLAYING) {
mTextViewPlayersName.setText(getString(R.string.player_one));
mAnglePrecisionSliderLayout.setValue(mPlayerOneBunker.getAbsoluteCanonAngleDegrees());
mPowerPrecisionSliderLayout.setValue(mPlayerOneBunker.getCanonPower());
} else if (mGameSequencer.getGameState() == GameSequencer.GameState.PLAYER_TWO_PLAYING) {
mTextViewPlayersName.setText(getString(R.string.player_two));
mAnglePrecisionSliderLayout.setValue(mPlayerTwoBunker.getAbsoluteCanonAngleDegrees());
mPowerPrecisionSliderLayout.setValue(mPlayerTwoBunker.getCanonPower());
} else {
// Issue...
}
mLinearLayoutControls.setVisibility(View.VISIBLE);
} else if (drawer.equals(mPlayerTwoBunker)) {
Toast.makeText(this, getString(R.string.player_won) + " " + mGameSequencer.getRoundsCountPlayerOne() + " " + getString(R.string.player_rounds_count), Toast.LENGTH_LONG).show();
mGameView.unregisterDrawer(mPlayerTwoBunker);
mPlayerTwoBunker = null;
mGameSequencer.bombshellDitHitBunker(false);
} else if (drawer.equals(mPlayerOneBunker)) {
Toast.makeText(this, getString(R.string.player_won) + " " + mGameSequencer.getRoundsCountPlayerTwo() + " " + getString(R.string.player_rounds_count), Toast.LENGTH_LONG).show();
mGameView.unregisterDrawer(mPlayerOneBunker);
mPlayerOneBunker = null;
mGameSequencer.bombshellDitHitBunker(true);
}
}
private ViewCoordinates getBunkerOneCoordinates() {
float landSliceWidth = mGameView.getWidth() / mLandscape.getNumberOfLandscapeSlices();
return new ViewCoordinates(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER * landSliceWidth,
mGameView.getHeight()
- mGameView.getHeight() * Landscape.MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER)
- Bunker.BUNKER_RADIUS);
}
private ViewCoordinates getBunkerTwoCoordinates() {
float landSliceWidth = mGameView.getWidth() / mLandscape.getNumberOfLandscapeSlices();
return new ViewCoordinates(mGameView.getWidth() - landSliceWidth * Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER,
mGameView.getHeight()
- mGameView.getHeight() * Landscape.MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(mLandscape.getNumberOfLandscapeSlices() - 1 - Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER)
- Bunker.BUNKER_RADIUS);
}
}
|
package info.nightscout.androidaps.plugins.OpenAPSMA;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSMAUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSMAUpdateResultGui;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round;
import info.nightscout.utils.SafeParse;
public class OpenAPSMAPlugin implements PluginBase, APSInterface {
private static Logger log = LoggerFactory.getLogger(OpenAPSMAPlugin.class);
// last values
DetermineBasalAdapterJS lastDetermineBasalAdapterJS = null;
Date lastAPSRun = null;
DetermineBasalResult lastAPSResult = null;
boolean fragmentEnabled = false;
boolean fragmentVisible = true;
@Override
public String getName() {
return MainApp.instance().getString(R.string.openapsma);
}
@Override
public boolean isEnabled(int type) {
return fragmentEnabled;
}
@Override
public boolean isVisibleInTabs(int type) {
return fragmentVisible;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
this.fragmentVisible = fragmentVisible;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
this.fragmentEnabled = fragmentEnabled;
}
@Override
public int getType() {
return PluginBase.APS;
}
@Override
public String getFragmentClass() {
return OpenAPSMAFragment.class.getName();
}
@Override
public APSResult getLastAPSResult() {
return lastAPSResult;
}
@Override
public Date getLastAPSRun() {
return lastAPSRun;
}
@Override
public void invoke() {
DetermineBasalAdapterJS determineBasalAdapterJS = null;
try {
determineBasalAdapterJS = new DetermineBasalAdapterJS(new ScriptReader(MainApp.instance().getBaseContext()));
} catch (IOException e) {
log.error(e.getMessage(), e);
return;
}
DatabaseHelper.GlucoseStatus glucoseStatus = MainApp.getDbHelper().getGlucoseStatusData();
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
PumpInterface pump = MainApp.getConfigBuilder();
if (!isEnabled(PluginBase.APS)) {
MainApp.bus().post(new EventOpenAPSMAUpdateResultGui(MainApp.instance().getString(R.string.openapsma_disabled)));
if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
MainApp.bus().post(new EventOpenAPSMAUpdateResultGui(MainApp.instance().getString(R.string.openapsma_noglucosedata)));
if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_noglucosedata));
return;
}
if (profile == null) {
MainApp.bus().post(new EventOpenAPSMAUpdateResultGui(MainApp.instance().getString(R.string.openapsma_noprofile)));
if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_noprofile));
return;
}
if (pump == null) {
MainApp.bus().post(new EventOpenAPSMAUpdateResultGui(MainApp.instance().getString(R.string.openapsma_nopump)));
if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_nopump));
return;
}
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
String units = profile.getUnits();
String maxBgDefault = "180";
String minBgDefault = "100";
String targetBgDefault = "150";
if (!units.equals(Constants.MGDL)) {
maxBgDefault = "10";
minBgDefault = "5";
targetBgDefault = "7";
}
Date now = new Date();
double maxIob = SafeParse.stringToDouble(SP.getString("openapsma_max_iob", "1.5"));
double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
double minBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_min_bg", minBgDefault)), units);
double maxBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_max_bg", maxBgDefault)), units);
double targetBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_target_bg", targetBgDefault)), units);
minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d);
TreatmentsInterface treatments = MainApp.getConfigBuilder().getActiveTreatments();
TempBasalsInterface tempBasals = MainApp.getConfigBuilder().getActiveTempBasals();
treatments.updateTotalIOB();
tempBasals.updateTotalIOB();
IobTotal bolusIob = treatments.getLastCalculation();
IobTotal basalIob = tempBasals.getLastCalculation();
IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round();
TreatmentsPlugin.MealData mealData = treatments.getMealData();
maxIob = MainApp.getConfigBuilder().applyMaxIOBConstraints(maxIob);
determineBasalAdapterJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, pump, iobTotal, glucoseStatus, mealData);
DetermineBasalResult determineBasalResult = determineBasalAdapterJS.invoke();
// Fix bug determine basal
if (determineBasalResult.rate == 0d && determineBasalResult.duration == 0 && !MainApp.getConfigBuilder().isTempBasalInProgress()) determineBasalResult.changeRequested = false;
// limit requests on openloop mode
if (!MainApp.getConfigBuilder().isClosedModeEnabled()) {
if (MainApp.getConfigBuilder().isTempBasalInProgress() && Math.abs(determineBasalResult.rate - MainApp.getConfigBuilder().getTempBasalAbsoluteRate()) < 0.1)
determineBasalResult.changeRequested = false;
if (!MainApp.getConfigBuilder().isTempBasalInProgress() && Math.abs(determineBasalResult.rate - MainApp.getConfigBuilder().getBaseBasalRate()) < 0.1)
determineBasalResult.changeRequested = false;
}
determineBasalResult.iob = iobTotal;
determineBasalAdapterJS.release();
try {
determineBasalResult.json.put("timestamp", DateUtil.toISOString(now));
} catch (JSONException e) {
e.printStackTrace();
}
lastDetermineBasalAdapterJS = determineBasalAdapterJS;
lastAPSResult = determineBasalResult;
lastAPSRun = now;
MainApp.bus().post(new EventOpenAPSMAUpdateGui());
//deviceStatus.suggested = determineBasalResult.json;
}
}
|
package info.nightscout.androidaps.plugins.Overview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.jjoe64.graphview.GraphView;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.QuickWizardEntry;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAckAlarm;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewTreatmentDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.WizardDialog;
import info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventSetWakeLock;
import info.nightscout.androidaps.plugins.Overview.graphData.GraphData;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileViewerDialog;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.OKDialog;
import info.nightscout.utils.Profiler;
import info.nightscout.utils.SP;
import info.nightscout.utils.SingleClickButton;
import info.nightscout.utils.ToastUtils;
public class OverviewFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, View.OnLongClickListener {
private static Logger log = LoggerFactory.getLogger(OverviewFragment.class);
TextView timeView;
TextView bgView;
TextView arrowView;
TextView timeAgoView;
TextView deltaView;
TextView avgdeltaView;
TextView baseBasalView;
TextView extendedBolusView;
TextView activeProfileView;
TextView iobView;
TextView cobView;
TextView apsModeView;
TextView tempTargetView;
TextView pumpStatusView;
TextView pumpDeviceStatusView;
TextView openapsDeviceStatusView;
TextView uploaderDeviceStatusView;
LinearLayout loopStatusLayout;
LinearLayout pumpStatusLayout;
GraphView bgGraph;
GraphView iobGraph;
TextView iage;
TextView cage;
TextView sage;
TextView pbage;
CheckBox showPredictionView;
CheckBox showBasalsView;
CheckBox showIobView;
CheckBox showCobView;
CheckBox showDeviationsView;
CheckBox showRatiosView;
RecyclerView notificationsView;
LinearLayoutManager llm;
LinearLayout acceptTempLayout;
SingleClickButton treatmentButton;
SingleClickButton wizardButton;
SingleClickButton calibrationButton;
SingleClickButton acceptTempButton;
SingleClickButton quickWizardButton;
CheckBox lockScreen;
boolean smallWidth;
boolean smallHeight;
public static boolean shorttextmode = false;
private boolean accepted;
private int rangeToDisplay = 6; // for graph
Handler sLoopHandler = new Handler();
Runnable sRefreshLoop = null;
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledUpdate = null;
public OverviewFragment() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
//check screen width
final DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
int screen_width = dm.widthPixels;
int screen_height = dm.heightPixels;
smallWidth = screen_width <= Constants.SMALL_WIDTH;
smallHeight = screen_height <= Constants.SMALL_HEIGHT;
boolean landscape = screen_height < screen_width;
View view;
if (MainApp.sResources.getBoolean(R.bool.isTablet) && (Config.NSCLIENT || Config.G5UPLOADER)) {
view = inflater.inflate(R.layout.overview_fragment_nsclient_tablet, container, false);
} else if (Config.NSCLIENT || Config.G5UPLOADER) {
view = inflater.inflate(R.layout.overview_fragment_nsclient, container, false);
shorttextmode = true;
} else if (smallHeight || landscape) {
view = inflater.inflate(R.layout.overview_fragment_smallheight, container, false);
} else {
view = inflater.inflate(R.layout.overview_fragment, container, false);
}
timeView = (TextView) view.findViewById(R.id.overview_time);
bgView = (TextView) view.findViewById(R.id.overview_bg);
arrowView = (TextView) view.findViewById(R.id.overview_arrow);
if (smallWidth) {
arrowView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35);
}
timeAgoView = (TextView) view.findViewById(R.id.overview_timeago);
deltaView = (TextView) view.findViewById(R.id.overview_delta);
avgdeltaView = (TextView) view.findViewById(R.id.overview_avgdelta);
baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal);
extendedBolusView = (TextView) view.findViewById(R.id.overview_extendedbolus);
activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile);
pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus);
pumpDeviceStatusView = (TextView) view.findViewById(R.id.overview_pump);
openapsDeviceStatusView = (TextView) view.findViewById(R.id.overview_openaps);
uploaderDeviceStatusView = (TextView) view.findViewById(R.id.overview_uploader);
loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout);
pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout);
pumpStatusView.setBackgroundColor(MainApp.sResources.getColor(R.color.colorInitializingBorder));
iobView = (TextView) view.findViewById(R.id.overview_iob);
cobView = (TextView) view.findViewById(R.id.overview_cob);
apsModeView = (TextView) view.findViewById(R.id.overview_apsmode);
tempTargetView = (TextView) view.findViewById(R.id.overview_temptarget);
iage = (TextView) view.findViewById(R.id.careportal_insulinage);
cage = (TextView) view.findViewById(R.id.careportal_canulaage);
sage = (TextView) view.findViewById(R.id.careportal_sensorage);
pbage = (TextView) view.findViewById(R.id.careportal_pbage);
bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph);
iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph);
treatmentButton = (SingleClickButton) view.findViewById(R.id.overview_treatmentbutton);
treatmentButton.setOnClickListener(this);
wizardButton = (SingleClickButton) view.findViewById(R.id.overview_wizardbutton);
wizardButton.setOnClickListener(this);
acceptTempButton = (SingleClickButton) view.findViewById(R.id.overview_accepttempbutton);
if (acceptTempButton != null)
acceptTempButton.setOnClickListener(this);
quickWizardButton = (SingleClickButton) view.findViewById(R.id.overview_quickwizardbutton);
quickWizardButton.setOnClickListener(this);
quickWizardButton.setOnLongClickListener(this);
calibrationButton = (SingleClickButton) view.findViewById(R.id.overview_calibrationbutton);
if (calibrationButton != null)
calibrationButton.setOnClickListener(this);
acceptTempLayout = (LinearLayout) view.findViewById(R.id.overview_accepttemplayout);
showPredictionView = (CheckBox) view.findViewById(R.id.overview_showprediction);
showBasalsView = (CheckBox) view.findViewById(R.id.overview_showbasals);
showIobView = (CheckBox) view.findViewById(R.id.overview_showiob);
showCobView = (CheckBox) view.findViewById(R.id.overview_showcob);
showDeviationsView = (CheckBox) view.findViewById(R.id.overview_showdeviations);
showRatiosView = (CheckBox) view.findViewById(R.id.overview_showratios);
showPredictionView.setChecked(SP.getBoolean("showprediction", false));
showBasalsView.setChecked(SP.getBoolean("showbasals", true));
showIobView.setChecked(SP.getBoolean("showiob", false));
showCobView.setChecked(SP.getBoolean("showcob", false));
showDeviationsView.setChecked(SP.getBoolean("showdeviations", false));
showRatiosView.setChecked(SP.getBoolean("showratios", false));
showPredictionView.setOnCheckedChangeListener(this);
showBasalsView.setOnCheckedChangeListener(this);
showIobView.setOnCheckedChangeListener(this);
showCobView.setOnCheckedChangeListener(this);
showDeviationsView.setOnCheckedChangeListener(this);
showRatiosView.setOnCheckedChangeListener(this);
notificationsView = (RecyclerView) view.findViewById(R.id.overview_notifications);
notificationsView.setHasFixedSize(true);
llm = new LinearLayoutManager(view.getContext());
notificationsView.setLayoutManager(llm);
bgGraph.getGridLabelRenderer().setGridColor(MainApp.sResources.getColor(R.color.graphgrid));
bgGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setGridColor(MainApp.sResources.getColor(R.color.graphgrid));
iobGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false);
bgGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
iobGraph.getGridLabelRenderer().setLabelVerticalWidth(50);
iobGraph.getGridLabelRenderer().setNumVerticalLabels(5);
rangeToDisplay = SP.getInt(R.string.key_rangetodisplay, 6);
bgGraph.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
rangeToDisplay += 6;
rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay;
SP.putInt(R.string.key_rangetodisplay, rangeToDisplay);
updateGUI("rangeChange");
return false;
}
});
lockScreen = (CheckBox) view.findViewById(R.id.overview_lockscreen);
if (lockScreen != null) {
lockScreen.setChecked(SP.getBoolean("lockscreen", false));
lockScreen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SP.putBoolean("lockscreen", isChecked);
MainApp.bus().post(new EventSetWakeLock(isChecked));
}
});
}
return view;
} catch (Exception e) {
Crashlytics.logException(e);
log.debug("Runtime Exception", e);
}
return null;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v == apsModeView) {
final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
final PumpDescription pumpDescription = ConfigBuilderPlugin.getActivePump().getPumpDescription();
if (activeloop == null)
return;
menu.setHeaderTitle(MainApp.sResources.getString(R.string.loop));
if (activeloop.isEnabled(PluginBase.LOOP)) {
menu.add(MainApp.sResources.getString(R.string.disableloop));
if (!activeloop.isSuspended()) {
menu.add(MainApp.sResources.getString(R.string.suspendloopfor1h));
menu.add(MainApp.sResources.getString(R.string.suspendloopfor2h));
menu.add(MainApp.sResources.getString(R.string.suspendloopfor3h));
menu.add(MainApp.sResources.getString(R.string.suspendloopfor10h));
if (pumpDescription.tempDurationStep <= 30)
menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor30m));
menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor1h));
menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor2h));
menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor3h));
} else {
menu.add(MainApp.sResources.getString(R.string.resume));
}
}
if (!activeloop.isEnabled(PluginBase.LOOP))
menu.add(MainApp.sResources.getString(R.string.enableloop));
} else if (v == activeProfileView) {
menu.setHeaderTitle(MainApp.sResources.getString(R.string.profile));
menu.add(MainApp.sResources.getString(R.string.danar_viewprofile));
menu.add(MainApp.sResources.getString(R.string.careportal_profileswitch));
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.overview_showprediction:
case R.id.overview_showbasals:
case R.id.overview_showiob:
break;
case R.id.overview_showcob:
showDeviationsView.setOnCheckedChangeListener(null);
showDeviationsView.setChecked(false);
showDeviationsView.setOnCheckedChangeListener(this);
break;
case R.id.overview_showdeviations:
showCobView.setOnCheckedChangeListener(null);
showCobView.setChecked(false);
showCobView.setOnCheckedChangeListener(this);
break;
case R.id.overview_showratios:
break;
}
SP.putBoolean("showiob", showIobView.isChecked());
SP.putBoolean("showprediction", showPredictionView.isChecked());
SP.putBoolean("showbasals", showBasalsView.isChecked());
SP.putBoolean("showcob", showCobView.isChecked());
SP.putBoolean("showdeviations", showDeviationsView.isChecked());
SP.putBoolean("showratios", showRatiosView.isChecked());
scheduleUpdateGUI("onGraphCheckboxesCheckedChanged");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
if (item.getTitle().equals(MainApp.sResources.getString(R.string.disableloop))) {
activeloop.setFragmentEnabled(PluginBase.LOOP, false);
activeloop.setFragmentVisible(PluginBase.LOOP, false);
MainApp.getConfigBuilder().storeSettings();
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(60); // upload 60 min, we don;t know real duration
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.enableloop))) {
activeloop.setFragmentEnabled(PluginBase.LOOP, true);
activeloop.setFragmentVisible(PluginBase.LOOP, true);
MainApp.getConfigBuilder().storeSettings();
updateGUI("suspendmenu");
NSUpload.uploadOpenAPSOffline(0);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.resume))) {
activeloop.suspendTo(0L);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(0);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor1h))) {
activeloop.suspendTo(System.currentTimeMillis() + 60L * 60 * 1000);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(60);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor2h))) {
activeloop.suspendTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(120);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor3h))) {
activeloop.suspendTo(System.currentTimeMillis() + 3 * 60L * 60 * 1000);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(180);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor10h))) {
activeloop.suspendTo(System.currentTimeMillis() + 10 * 60L * 60 * 1000);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(600);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor30m))) {
activeloop.disconnectTo(System.currentTimeMillis() + 30L * 60 * 1000);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 30, true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(30);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor1h))) {
activeloop.disconnectTo(System.currentTimeMillis() + 1 * 60L * 60 * 1000);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 60, true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(60);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor2h))) {
activeloop.disconnectTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 2 * 60, true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(120);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor3h))) {
activeloop.disconnectTo(System.currentTimeMillis() + 3 * 60L * 60 * 1000);
updateGUI("suspendmenu");
ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 3 * 60, true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(180);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.careportal_profileswitch))) {
NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCHDIRECT;
profileswitch.executeProfileSwitch = true;
newDialog.setOptions(profileswitch, R.string.careportal_profileswitch);
newDialog.show(getFragmentManager(), "NewNSTreatmentDialog");
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.danar_viewprofile))) {
ProfileViewerDialog pvd = ProfileViewerDialog.newInstance(System.currentTimeMillis());
FragmentManager manager = getFragmentManager();
pvd.show(manager, "ProfileViewDialog");
}
return super.onContextItemSelected(item);
}
@Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
switch (v.getId()) {
case R.id.overview_accepttempbutton:
onClickAcceptTemp();
break;
case R.id.overview_quickwizardbutton:
onClickQuickwizard();
break;
case R.id.overview_wizardbutton:
WizardDialog wizardDialog = new WizardDialog();
wizardDialog.show(manager, "WizardDialog");
break;
case R.id.overview_calibrationbutton:
CalibrationDialog calibrationDialog = new CalibrationDialog();
calibrationDialog.show(manager, "CalibrationDialog");
break;
case R.id.overview_treatmentbutton:
NewTreatmentDialog treatmentDialogFragment = new NewTreatmentDialog();
treatmentDialogFragment.show(manager, "TreatmentDialog");
break;
case R.id.overview_pumpstatus:
if (ConfigBuilderPlugin.getActivePump().isSuspended() || !ConfigBuilderPlugin.getActivePump().isInitialized())
ConfigBuilderPlugin.getCommandQueue().readStatus("RefreshClicked", null);
break;
}
}
@Override
public boolean onLongClick(View v) {
switch (v.getId()) {
case R.id.overview_quickwizardbutton:
Intent i = new Intent(v.getContext(), QuickWizardListActivity.class);
startActivity(i);
return true;
}
return false;
}
private void onClickAcceptTemp() {
if (ConfigBuilderPlugin.getActiveLoop() != null) {
ConfigBuilderPlugin.getActiveLoop().invoke("Accept temp button", false);
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (finalLastRun != null && finalLastRun.lastAPSRun != null && finalLastRun.constraintsProcessed.changeRequested) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getContext().getString(R.string.confirmation));
builder.setMessage(getContext().getString(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
builder.setPositiveButton(getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
hideTempRecommendation();
clearNotification();
MainApp.getConfigBuilder().applyAPSRequest(finalLastRun.constraintsProcessed, new Callback() {
@Override
public void run() {
if (result.enacted) {
finalLastRun.setByPump = result;
finalLastRun.lastEnact = new Date();
finalLastRun.lastOpenModeAccept = new Date();
NSUpload.uploadDeviceStatus();
ObjectivesPlugin objectivesPlugin = MainApp.getSpecificPlugin(ObjectivesPlugin.class);
if (objectivesPlugin != null) {
ObjectivesPlugin.manualEnacts++;
ObjectivesPlugin.saveProgress();
}
}
scheduleUpdateGUI("onClickAcceptTemp");
}
});
Answers.getInstance().logCustom(new CustomEvent("AcceptTemp"));
}
});
builder.setNegativeButton(getContext().getString(R.string.cancel), null);
builder.show();
}
}
}
void onClickQuickwizard() {
final BgReading actualBg = DatabaseHelper.actualBg();
final Profile profile = MainApp.getConfigBuilder().getProfile();
final TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory();
final QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive();
if (quickWizardEntry != null && actualBg != null) {
quickWizardButton.setVisibility(View.VISIBLE);
final BolusWizard wizard = quickWizardEntry.doCalc(profile, tempTarget, actualBg);
final JSONObject boluscalcJSON = new JSONObject();
try {
boluscalcJSON.put("eventTime", DateUtil.toISOString(new Date()));
boluscalcJSON.put("targetBGLow", wizard.targetBGLow);
boluscalcJSON.put("targetBGHigh", wizard.targetBGHigh);
boluscalcJSON.put("isf", wizard.sens);
boluscalcJSON.put("ic", wizard.ic);
boluscalcJSON.put("iob", -(wizard.insulingFromBolusIOB + wizard.insulingFromBasalsIOB));
boluscalcJSON.put("bolusiobused", true);
boluscalcJSON.put("basaliobused", true);
boluscalcJSON.put("bg", actualBg.valueToUnits(profile.getUnits()));
boluscalcJSON.put("insulinbg", wizard.insulinFromBG);
boluscalcJSON.put("insulinbgused", true);
boluscalcJSON.put("bgdiff", wizard.bgDiff);
boluscalcJSON.put("insulincarbs", wizard.insulinFromCarbs);
boluscalcJSON.put("carbs", quickWizardEntry.carbs());
boluscalcJSON.put("othercorrection", 0d);
boluscalcJSON.put("insulintrend", wizard.insulinFromTrend);
boluscalcJSON.put("insulin", wizard.calculatedTotalInsulin);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
if (wizard.calculatedTotalInsulin > 0d && quickWizardEntry.carbs() > 0d) {
DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
String confirmMessage = getString(R.string.entertreatmentquestion);
Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(wizard.calculatedTotalInsulin);
Integer carbsAfterConstraints = MainApp.getConfigBuilder().applyCarbsConstraints(quickWizardEntry.carbs());
confirmMessage += "\n" + getString(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g";
if (!insulinAfterConstraints.equals(wizard.calculatedTotalInsulin) || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror));
builder.setMessage(getString(R.string.constraints_violation) + "\n" + getString(R.string.changeyourinput));
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null);
builder.show();
return;
}
final Double finalInsulinAfterConstraints = insulinAfterConstraints;
final Integer finalCarbsAfterConstraints = carbsAfterConstraints;
final Context context = getContext();
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
accepted = false;
builder.setTitle(MainApp.sResources.getString(R.string.confirmation));
builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
synchronized (builder) {
if (accepted) {
log.debug("guarding: already accepted");
return;
}
accepted = true;
if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) {
if (wizard.superBolus) {
final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
if (activeloop != null) {
activeloop.superBolusTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000);
MainApp.bus().post(new EventRefreshOverview("WizardDialog"));
}
ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 120, true, new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
}
});
}
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.eventType = CareportalEvent.BOLUSWIZARD;
detailedBolusInfo.insulin = finalInsulinAfterConstraints;
detailedBolusInfo.carbs = finalCarbsAfterConstraints;
detailedBolusInfo.context = context;
detailedBolusInfo.boluscalc = boluscalcJSON;
detailedBolusInfo.source = Source.USER;
ConfigBuilderPlugin.getCommandQueue().bolus(detailedBolusInfo, new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.treatmentdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
}
});
Answers.getInstance().logCustom(new CustomEvent("QuickWizard"));
}
}
}
});
builder.setNegativeButton(getString(R.string.cancel), null);
builder.show();
}
}
}
@Override
public void onPause() {
super.onPause();
MainApp.bus().unregister(this);
sLoopHandler.removeCallbacksAndMessages(null);
unregisterForContextMenu(apsModeView);
unregisterForContextMenu(activeProfileView);
}
@Override
public void onResume() {
super.onResume();
MainApp.bus().register(this);
sRefreshLoop = new Runnable() {
@Override
public void run() {
scheduleUpdateGUI("refreshLoop");
sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
}
};
sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
registerForContextMenu(apsModeView);
registerForContextMenu(activeProfileView);
updateGUI("onResume");
}
@Subscribe
public void onStatusEvent(final EventInitializationChanged ev) {
scheduleUpdateGUI("EventInitializationChanged");
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange ev) {
scheduleUpdateGUI("EventPreferenceChange");
}
@Subscribe
public void onStatusEvent(final EventRefreshOverview ev) {
scheduleUpdateGUI(ev.from);
}
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) {
scheduleUpdateGUI("EventAutosensCalculationFinished");
}
@Subscribe
public void onStatusEvent(final EventTreatmentChange ev) {
scheduleUpdateGUI("EventTreatmentChange");
}
@Subscribe
public void onStatusEvent(final EventCareportalEventChange ev) {
scheduleUpdateGUI("EventCareportalEventChange");
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange ev) {
scheduleUpdateGUI("EventTempBasalChange");
}
@Subscribe
public void onStatusEvent(final EventExtendedBolusChange ev) {
scheduleUpdateGUI("EventExtendedBolusChange");
}
// Handled by EventAutosensCalculationFinished
// @Subscribe
// public void onStatusEvent(final EventNewBG ev) {
// scheduleUpdateGUI("EventNewBG");
@Subscribe
public void onStatusEvent(final EventNewOpenLoopNotification ev) {
scheduleUpdateGUI("EventNewOpenLoopNotification");
}
// Handled by EventAutosensCalculationFinished
// @Subscribe
// public void onStatusEvent(final EventNewBasalProfile ev) {
// scheduleUpdateGUI("EventNewBasalProfile");
@Subscribe
public void onStatusEvent(final EventTempTargetChange ev) {
scheduleUpdateGUI("EventTempTargetChange");
}
@Subscribe
public void onStatusEvent(final EventPumpStatusChanged s) {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
updatePumpStatus(s.textStatus());
}
});
}
private void hideTempRecommendation() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (acceptTempLayout != null)
acceptTempLayout.setVisibility(View.GONE);
}
});
}
private void clearNotification() {
NotificationManager notificationManager =
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
}
private void updatePumpStatus(String status) {
if (!status.equals("")) {
pumpStatusView.setText(status);
pumpStatusLayout.setVisibility(View.VISIBLE);
loopStatusLayout.setVisibility(View.GONE);
} else {
pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.VISIBLE);
}
}
public void scheduleUpdateGUI(final String from) {
class UpdateRunnable implements Runnable {
public void run() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
updateGUI(from);
scheduledUpdate = null;
}
});
}
}
// prepare task for execution in 400 msec
// cancel waiting task to prevent multiple updates
if (scheduledUpdate != null)
scheduledUpdate.cancel(false);
Runnable task = new UpdateRunnable();
final int msec = 500;
scheduledUpdate = worker.schedule(task, msec, TimeUnit.MILLISECONDS);
}
@SuppressLint("SetTextI18n")
public void updateGUI(String from) {
log.debug("updateGUI entered from: " + from);
Date updateGUIStart = new Date();
if (getActivity() == null)
return;
if (timeView != null) { //must not exists
timeView.setText(DateUtil.timeString(new Date()));
}
if (MainApp.getConfigBuilder().getProfile() == null) {// app not initialized yet
pumpStatusView.setText(R.string.noprofileset);
pumpStatusLayout.setVisibility(View.VISIBLE);
loopStatusLayout.setVisibility(View.GONE);
return;
}
pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.VISIBLE);
updateNotifications();
CareportalFragment.updateAge(getActivity(), sage, iage, cage, pbage);
BgReading actualBG = DatabaseHelper.actualBg();
BgReading lastBG = DatabaseHelper.lastBg();
PumpInterface pump = ConfigBuilderPlugin.getActivePump();
Profile profile = MainApp.getConfigBuilder().getProfile();
String units = profile.getUnits();
if (units == null) {
pumpStatusView.setText(R.string.noprofileset);
pumpStatusLayout.setVisibility(View.VISIBLE);
loopStatusLayout.setVisibility(View.GONE);
return;
}
double lowLine = SP.getDouble("low_mark", 0d);
double highLine = SP.getDouble("high_mark", 0d);
//Start with updating the BG as it is unaffected by loop.
if (lastBG != null) {
int color = MainApp.sResources.getColor(R.color.inrange);
if (lastBG.valueToUnits(units) < lowLine)
color = MainApp.sResources.getColor(R.color.low);
else if (lastBG.valueToUnits(units) > highLine)
color = MainApp.sResources.getColor(R.color.high);
bgView.setText(lastBG.valueToUnitsToString(units));
arrowView.setText(lastBG.directionToSymbol());
bgView.setTextColor(color);
arrowView.setTextColor(color);
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (glucoseStatus != null) {
deltaView.setText("Δ " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units);
if (avgdeltaView != null)
avgdeltaView.setText("øΔ15m: " + Profile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units) +
" øΔ40m: " + Profile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units));
} else {
deltaView.setText("Δ " + MainApp.sResources.getString(R.string.notavailable));
if (avgdeltaView != null)
avgdeltaView.setText("");
}
}
// open loop mode
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (Config.APS && pump.getPumpDescription().isTempBasalCapable) {
apsModeView.setVisibility(View.VISIBLE);
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.loopenabled));
apsModeView.setTextColor(Color.BLACK);
final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
if (activeloop != null && activeloop.isEnabled(activeloop.getType()) && activeloop.isSuperBolus()) {
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.looppumpsuspended));
apsModeView.setText(String.format(MainApp.sResources.getString(R.string.loopsuperbolusfor), activeloop.minutesToEndOfSuspend()));
apsModeView.setTextColor(Color.WHITE);
} else if (activeloop != null && activeloop.isEnabled(activeloop.getType()) && activeloop.isSuspended()) {
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.looppumpsuspended));
apsModeView.setText(String.format(MainApp.sResources.getString(R.string.loopsuspendedfor), activeloop.minutesToEndOfSuspend()));
apsModeView.setTextColor(Color.WHITE);
} else if (pump.isSuspended()) {
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.looppumpsuspended));
apsModeView.setText(MainApp.sResources.getString(R.string.pumpsuspended));
apsModeView.setTextColor(Color.WHITE);
} else if (activeloop != null && activeloop.isEnabled(activeloop.getType())) {
if (MainApp.getConfigBuilder().isClosedModeEnabled()) {
apsModeView.setText(MainApp.sResources.getString(R.string.closedloop));
} else {
apsModeView.setText(MainApp.sResources.getString(R.string.openloop));
}
} else {
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.loopdisabled));
apsModeView.setText(MainApp.sResources.getString(R.string.disabledloop));
apsModeView.setTextColor(Color.WHITE);
}
} else {
apsModeView.setVisibility(View.GONE);
}
// temp target
TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory();
if (tempTarget != null) {
tempTargetView.setTextColor(Color.BLACK);
tempTargetView.setBackgroundColor(MainApp.sResources.getColor(R.color.tempTargetBackground));
tempTargetView.setVisibility(View.VISIBLE);
tempTargetView.setText(Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.end()));
} else {
tempTargetView.setTextColor(Color.WHITE);
tempTargetView.setBackgroundColor(MainApp.sResources.getColor(R.color.tempTargetDisabledBackground));
tempTargetView.setText(Profile.toTargetRangeString(profile.getTargetLow(), profile.getTargetHigh(), units, units));
tempTargetView.setVisibility(View.VISIBLE);
}
if (acceptTempLayout != null) {
boolean showAcceptButton = !MainApp.getConfigBuilder().isClosedModeEnabled(); // Open mode needed
showAcceptButton = showAcceptButton && finalLastRun != null && finalLastRun.lastAPSRun != null; // aps result must exist
showAcceptButton = showAcceptButton && (finalLastRun.lastOpenModeAccept == null || finalLastRun.lastOpenModeAccept.getTime() < finalLastRun.lastAPSRun.getTime()); // never accepted or before last result
showAcceptButton = showAcceptButton && finalLastRun.constraintsProcessed.changeRequested; // change is requested
if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && ConfigBuilderPlugin.getActiveLoop() != null) {
acceptTempLayout.setVisibility(View.VISIBLE);
acceptTempButton.setText(getContext().getString(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
} else {
acceptTempLayout.setVisibility(View.GONE);
}
}
if (calibrationButton != null) {
if (MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginBase.BGSOURCE) && profile != null && DatabaseHelper.actualBg() != null) {
calibrationButton.setVisibility(View.VISIBLE);
} else {
calibrationButton.setVisibility(View.GONE);
}
}
final TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
String basalText = "";
if (shorttextmode) {
if (activeTemp != null) {
basalText = "T: " + activeTemp.toStringVeryShort();
} else {
basalText = DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getProfile().getBasal()) + "U/h";
}
baseBasalView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String fullText = MainApp.sResources.getString(R.string.pump_basebasalrate_label) + ": " + DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getProfile().getBasal()) + "U/h\n";
if (activeTemp != null) {
fullText += MainApp.sResources.getString(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull();
}
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.basal), fullText, null);
}
});
} else {
if (activeTemp != null) {
basalText = activeTemp.toStringFull() + " ";
}
if (Config.NSCLIENT || Config.G5UPLOADER)
basalText += "(" + DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getProfile().getBasal()) + " U/h)";
else if (pump.getPumpDescription().isTempBasalCapable) {
basalText += "(" + DecimalFormatter.to2Decimal(pump.getBaseBasalRate()) + "U/h)";
}
}
if (activeTemp != null) {
baseBasalView.setTextColor(MainApp.sResources.getColor(R.color.basal));
} else {
baseBasalView.setTextColor(Color.WHITE);
}
baseBasalView.setText(basalText);
final ExtendedBolus extendedBolus = MainApp.getConfigBuilder().getExtendedBolusFromHistory(System.currentTimeMillis());
String extendedBolusText = "";
if (extendedBolusView != null) { // must not exists in all layouts
if (shorttextmode) {
if (extendedBolus != null && !pump.isFakingTempsByExtendedBoluses()) {
extendedBolusText = DecimalFormatter.to2Decimal(extendedBolus.absoluteRate()) + "U/h";
}
extendedBolusView.setText(extendedBolusText);
extendedBolusView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.extendedbolus), extendedBolus.toString(), null);
}
});
} else {
if (extendedBolus != null && !pump.isFakingTempsByExtendedBoluses()) {
extendedBolusText = extendedBolus.toString();
}
extendedBolusView.setText(extendedBolusText);
}
if (extendedBolusText.equals(""))
extendedBolusView.setVisibility(View.GONE);
else
extendedBolusView.setVisibility(View.VISIBLE);
}
activeProfileView.setText(MainApp.getConfigBuilder().getProfileName());
activeProfileView.setBackgroundColor(Color.GRAY);
tempTargetView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
NewNSTreatmentDialog newTTDialog = new NewNSTreatmentDialog();
final OptionsToShow temptarget = CareportalFragment.TEMPTARGET;
temptarget.executeTempTarget = true;
newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget);
newTTDialog.show(getFragmentManager(), "NewNSTreatmentDialog");
return true;
}
});
tempTargetView.setLongClickable(true);
// QuickWizard button
QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive();
if (quickWizardEntry != null && lastBG != null && pump.isInitialized() && !pump.isSuspended()) {
quickWizardButton.setVisibility(View.VISIBLE);
String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g";
BolusWizard wizard = quickWizardEntry.doCalc(profile, tempTarget, lastBG);
text += " " + DecimalFormatter.to2Decimal(wizard.calculatedTotalInsulin) + "U";
quickWizardButton.setText(text);
if (wizard.calculatedTotalInsulin <= 0)
quickWizardButton.setVisibility(View.GONE);
} else
quickWizardButton.setVisibility(View.GONE);
// Bolus and calc button
if (pump.isInitialized() && !pump.isSuspended()) {
wizardButton.setVisibility(View.VISIBLE);
treatmentButton.setVisibility(View.VISIBLE);
} else {
wizardButton.setVisibility(View.GONE);
treatmentButton.setVisibility(View.GONE);
}
if (lowLine < 1) {
lowLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units);
}
if (highLine < 1) {
highLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units);
}
if (lastBG == null) { //left this here as it seems you want to exit at this point if it is null...
return;
}
Integer flag = bgView.getPaintFlags();
if (actualBG == null) {
flag |= Paint.STRIKE_THRU_TEXT_FLAG;
} else
flag &= ~Paint.STRIKE_THRU_TEXT_FLAG;
bgView.setPaintFlags(flag);
timeAgoView.setText(DateUtil.minAgo(lastBG.date));
// iob
MainApp.getConfigBuilder().updateTotalIOBTreatments();
MainApp.getConfigBuilder().updateTotalIOBTempBasals();
final IobTotal bolusIob = MainApp.getConfigBuilder().getLastCalculationTreatments().round();
final IobTotal basalIob = MainApp.getConfigBuilder().getLastCalculationTempBasals().round();
if (shorttextmode) {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U";
iobView.setText(iobtext);
iobView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U\n"
+ getString(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U\n"
+ getString(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U\n";
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.iob), iobtext, null);
}
});
} else if (MainApp.sResources.getBoolean(R.bool.isTablet)) {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ getString(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ getString(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)";
iobView.setText(iobtext);
} else {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ DecimalFormatter.to2Decimal(bolusIob.iob) + "/"
+ DecimalFormatter.to2Decimal(basalIob.basaliob) + ")";
iobView.setText(iobtext);
}
// cob
if (cobView != null) { // view must not exists
String cobText = "";
AutosensData autosensData = IobCobCalculatorPlugin.getLastAutosensData();
if (autosensData != null)
cobText = (int) autosensData.cob + " g";
cobView.setText(cobText);
}
boolean showPrediction = showPredictionView.isChecked() && finalLastRun != null && finalLastRun.constraintsProcessed.getClass().equals(DetermineBasalResultAMA.class);
if (MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class) != null && MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class).isEnabled(PluginBase.APS)) {
showPredictionView.setVisibility(View.VISIBLE);
getActivity().findViewById(R.id.overview_showprediction_label).setVisibility(View.VISIBLE);
} else {
showPredictionView.setVisibility(View.GONE);
getActivity().findViewById(R.id.overview_showprediction_label).setVisibility(View.GONE);
}
// pump status from ns
if (pumpDeviceStatusView != null) {
pumpDeviceStatusView.setText(NSDeviceStatus.getInstance().getPumpStatus());
pumpDeviceStatusView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.pump), NSDeviceStatus.getInstance().getExtendedPumpStatus(), null);
}
});
}
// OpenAPS status from ns
if (openapsDeviceStatusView != null) {
openapsDeviceStatusView.setText(NSDeviceStatus.getInstance().getOpenApsStatus());
openapsDeviceStatusView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.openaps), NSDeviceStatus.getInstance().getExtendedOpenApsStatus(), null);
}
});
}
// Uploader status from ns
if (uploaderDeviceStatusView != null) {
uploaderDeviceStatusView.setText(NSDeviceStatus.getInstance().getUploaderStatus());
uploaderDeviceStatusView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.uploader), NSDeviceStatus.getInstance().getExtendedUploaderStatus(), null);
}
});
}
// allign to hours
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.add(Calendar.HOUR, 1);
int hoursToFetch;
long toTime;
long fromTime;
long endTime;
if (showPrediction) {
int predHours = (int) (Math.ceil(((DetermineBasalResultAMA) finalLastRun.constraintsProcessed).getLatestPredictionsTime() - System.currentTimeMillis()) / (60 * 60 * 1000));
predHours = Math.min(2, predHours);
predHours = Math.max(0, predHours);
hoursToFetch = rangeToDisplay - predHours;
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
endTime = toTime + predHours * 60 * 60 * 1000L;
} else {
hoursToFetch = rangeToDisplay;
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
endTime = toTime;
}
long now = System.currentTimeMillis();
// 2nd graph
// remove old data
iobGraph.getSeries().clear();
GraphData secondGraphData = new GraphData();
boolean useIobForScale = false;
boolean useCobForScale = false;
boolean useDevForScale = false;
boolean useRatioForScale = false;
if (showIobView.isChecked()) {
useIobForScale = true;
} else if (showCobView.isChecked()) {
useCobForScale = true;
} else if (showDeviationsView.isChecked()) {
useDevForScale = true;
} else if (showRatiosView.isChecked()) {
useRatioForScale = true;
}
if (showIobView.isChecked())
secondGraphData.addIob(iobGraph, fromTime, now, useIobForScale, 1d);
if (showCobView.isChecked())
secondGraphData.addCob(iobGraph, fromTime, now, useCobForScale, useCobForScale ? 1d : 0.5d);
if (showDeviationsView.isChecked())
secondGraphData.addDeviations(iobGraph, fromTime, now, useDevForScale, 1d);
if (showRatiosView.isChecked())
secondGraphData.addRatio(iobGraph, fromTime, now, useRatioForScale, 1d);
if (showIobView.isChecked() || showCobView.isChecked() || showDeviationsView.isChecked() || showRatiosView.isChecked()) {
iobGraph.setVisibility(View.VISIBLE);
} else {
iobGraph.setVisibility(View.GONE);
}
// remove old data from graph
bgGraph.getSeries().clear();
GraphData graphData = new GraphData();
graphData.addInRangeArea(bgGraph, fromTime, endTime, lowLine, highLine);
if (showPrediction)
graphData.addBgReadings(bgGraph, fromTime, toTime, lowLine, highLine, (DetermineBasalResultAMA) finalLastRun.constraintsProcessed);
else
graphData.addBgReadings(bgGraph, fromTime, toTime, lowLine, highLine, null);
// set manual x bounds to have nice steps
graphData.formatAxis(bgGraph, fromTime, endTime);
secondGraphData.formatAxis(iobGraph, fromTime, endTime);
// Treatments
graphData.addTreatments(bgGraph, fromTime, endTime);
// add basal data
if (pump.getPumpDescription().isTempBasalCapable && showBasalsView.isChecked()) {
graphData.addBasals(bgGraph, fromTime, now, lowLine / graphData.maxY / 1.2d);
}
graphData.addNowLine(bgGraph, now);
secondGraphData.addNowLine(iobGraph, now);
// finaly enforce drawing of graphs
bgGraph.onDataChanged(false, false);
iobGraph.onDataChanged(false, false);
Profiler.log(log, from, updateGUIStart);
}
//Notifications
static class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.NotificationsViewHolder> {
List<Notification> notificationsList;
RecyclerViewAdapter(List<Notification> notificationsList) {
this.notificationsList = notificationsList;
}
@Override
public NotificationsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.overview_notification_item, viewGroup, false);
return new NotificationsViewHolder(v);
}
@Override
public void onBindViewHolder(NotificationsViewHolder holder, int position) {
Notification notification = notificationsList.get(position);
holder.dismiss.setTag(notification);
if (Objects.equals(notification.text, MainApp.sResources.getString(R.string.nsalarm_staledata)))
holder.dismiss.setText("snooze");
holder.text.setText(notification.text);
holder.time.setText(DateUtil.timeString(notification.date));
if (notification.level == Notification.URGENT)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationUrgent));
else if (notification.level == Notification.NORMAL)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationNormal));
else if (notification.level == Notification.LOW)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationLow));
else if (notification.level == Notification.INFO)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationInfo));
else if (notification.level == Notification.ANNOUNCEMENT)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationAnnouncement));
}
@Override
public int getItemCount() {
return notificationsList.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
static class NotificationsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView time;
TextView text;
Button dismiss;
NotificationsViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.notification_cardview);
time = (TextView) itemView.findViewById(R.id.notification_time);
text = (TextView) itemView.findViewById(R.id.notification_text);
dismiss = (Button) itemView.findViewById(R.id.notification_dismiss);
dismiss.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Notification notification = (Notification) v.getTag();
switch (v.getId()) {
case R.id.notification_dismiss:
MainApp.bus().post(new EventDismissNotification(notification.id));
if (notification.nsAlarm != null) {
BroadcastAckAlarm.handleClearAlarm(notification.nsAlarm, MainApp.instance().getApplicationContext(), 60 * 60 * 1000L);
}
// Adding current time to snooze if we got staleData
log.debug("Notification text is: " + notification.text);
if (notification.text.equals(MainApp.sResources.getString(R.string.nsalarm_staledata))) {
NotificationStore nstore = OverviewPlugin.getPlugin().notificationStore;
long msToSnooze = SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L;
log.debug("snooze nsalarm_staledatavalue in minutes is " + SP.getInt("nsalarm_staledatavalue", 15) + "\n in ms is: " + msToSnooze + " currentTimeMillis is: " + System.currentTimeMillis());
nstore.snoozeTo(System.currentTimeMillis() + (SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L));
}
break;
}
}
}
}
void updateNotifications() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
NotificationStore nstore = OverviewPlugin.getPlugin().notificationStore;
nstore.removeExpired();
nstore.unSnooze();
if (nstore.store.size() > 0) {
RecyclerViewAdapter adapter = new RecyclerViewAdapter(nstore.store);
notificationsView.setAdapter(adapter);
notificationsView.setVisibility(View.VISIBLE);
} else {
notificationsView.setVisibility(View.GONE);
}
}
});
}
}
|
package info.nightscout.androidaps.plugins.Overview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.HapticFeedbackConstants;
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 android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.crashlytics.android.answers.CustomEvent;
import com.jjoe64.graphview.GraphView;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.QuickWizardEntry;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAckAlarm;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewCarbsDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewInsulinDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewTreatmentDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.WizardDialog;
import info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventSetWakeLock;
import info.nightscout.androidaps.plugins.Overview.graphData.GraphData;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore;
import info.nightscout.androidaps.plugins.SourceDexcomG5.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileViewerDialog;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.OKDialog;
import info.nightscout.utils.Profiler;
import info.nightscout.utils.SP;
import info.nightscout.utils.SingleClickButton;
import info.nightscout.utils.ToastUtils;
public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener {
private static Logger log = LoggerFactory.getLogger(OverviewFragment.class);
TextView timeView;
TextView bgView;
TextView arrowView;
TextView timeAgoView;
TextView deltaView;
TextView avgdeltaView;
TextView baseBasalView;
TextView extendedBolusView;
TextView activeProfileView;
TextView iobView;
TextView cobView;
TextView apsModeView;
TextView tempTargetView;
TextView pumpStatusView;
TextView pumpDeviceStatusView;
TextView openapsDeviceStatusView;
TextView uploaderDeviceStatusView;
LinearLayout loopStatusLayout;
LinearLayout pumpStatusLayout;
GraphView bgGraph;
GraphView iobGraph;
ImageButton chartButton;
TextView iage;
TextView cage;
TextView sage;
TextView pbage;
RecyclerView notificationsView;
LinearLayoutManager llm;
LinearLayout acceptTempLayout;
SingleClickButton acceptTempButton;
SingleClickButton treatmentButton;
SingleClickButton wizardButton;
SingleClickButton calibrationButton;
SingleClickButton insulinButton;
SingleClickButton carbsButton;
SingleClickButton cgmButton;
SingleClickButton quickWizardButton;
CheckBox lockScreen;
boolean smallWidth;
boolean smallHeight;
public static boolean shorttextmode = false;
private boolean accepted;
private int rangeToDisplay = 6; // for graph
Handler sLoopHandler = new Handler();
Runnable sRefreshLoop = null;
final Object updateSync = new Object();
public enum CHARTTYPE {PRE, BAS, IOB, COB, DEV, SEN};
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledUpdate = null;
public OverviewFragment() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
//check screen width
final DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
int screen_width = dm.widthPixels;
int screen_height = dm.heightPixels;
smallWidth = screen_width <= Constants.SMALL_WIDTH;
smallHeight = screen_height <= Constants.SMALL_HEIGHT;
boolean landscape = screen_height < screen_width;
View view;
if (MainApp.sResources.getBoolean(R.bool.isTablet) && (Config.NSCLIENT || Config.G5UPLOADER)) {
view = inflater.inflate(R.layout.overview_fragment_nsclient_tablet, container, false);
} else if (Config.NSCLIENT || Config.G5UPLOADER) {
view = inflater.inflate(R.layout.overview_fragment_nsclient, container, false);
shorttextmode = true;
} else if (smallHeight || landscape) {
view = inflater.inflate(R.layout.overview_fragment_smallheight, container, false);
} else {
view = inflater.inflate(R.layout.overview_fragment, container, false);
}
timeView = (TextView) view.findViewById(R.id.overview_time);
bgView = (TextView) view.findViewById(R.id.overview_bg);
arrowView = (TextView) view.findViewById(R.id.overview_arrow);
if (smallWidth) {
arrowView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35);
}
timeAgoView = (TextView) view.findViewById(R.id.overview_timeago);
deltaView = (TextView) view.findViewById(R.id.overview_delta);
avgdeltaView = (TextView) view.findViewById(R.id.overview_avgdelta);
baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal);
extendedBolusView = (TextView) view.findViewById(R.id.overview_extendedbolus);
activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile);
pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus);
pumpDeviceStatusView = (TextView) view.findViewById(R.id.overview_pump);
openapsDeviceStatusView = (TextView) view.findViewById(R.id.overview_openaps);
uploaderDeviceStatusView = (TextView) view.findViewById(R.id.overview_uploader);
loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout);
pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout);
pumpStatusView.setBackgroundColor(MainApp.sResources.getColor(R.color.colorInitializingBorder));
iobView = (TextView) view.findViewById(R.id.overview_iob);
cobView = (TextView) view.findViewById(R.id.overview_cob);
apsModeView = (TextView) view.findViewById(R.id.overview_apsmode);
tempTargetView = (TextView) view.findViewById(R.id.overview_temptarget);
iage = (TextView) view.findViewById(R.id.careportal_insulinage);
cage = (TextView) view.findViewById(R.id.careportal_canulaage);
sage = (TextView) view.findViewById(R.id.careportal_sensorage);
pbage = (TextView) view.findViewById(R.id.careportal_pbage);
bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph);
iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph);
treatmentButton = (SingleClickButton) view.findViewById(R.id.overview_treatmentbutton);
treatmentButton.setOnClickListener(this);
wizardButton = (SingleClickButton) view.findViewById(R.id.overview_wizardbutton);
wizardButton.setOnClickListener(this);
insulinButton = (SingleClickButton) view.findViewById(R.id.overview_insulinbutton);
if (insulinButton != null)
insulinButton.setOnClickListener(this);
carbsButton = (SingleClickButton) view.findViewById(R.id.overview_carbsbutton);
if (carbsButton != null)
carbsButton.setOnClickListener(this);
acceptTempButton = (SingleClickButton) view.findViewById(R.id.overview_accepttempbutton);
if (acceptTempButton != null)
acceptTempButton.setOnClickListener(this);
quickWizardButton = (SingleClickButton) view.findViewById(R.id.overview_quickwizardbutton);
quickWizardButton.setOnClickListener(this);
quickWizardButton.setOnLongClickListener(this);
calibrationButton = (SingleClickButton) view.findViewById(R.id.overview_calibrationbutton);
if (calibrationButton != null)
calibrationButton.setOnClickListener(this);
cgmButton = (SingleClickButton) view.findViewById(R.id.overview_cgmbutton);
if (cgmButton != null)
cgmButton.setOnClickListener(this);
acceptTempLayout = (LinearLayout) view.findViewById(R.id.overview_accepttemplayout);
notificationsView = (RecyclerView) view.findViewById(R.id.overview_notifications);
notificationsView.setHasFixedSize(true);
llm = new LinearLayoutManager(view.getContext());
notificationsView.setLayoutManager(llm);
int axisWidth = 50;
if (dm.densityDpi <= 120)
axisWidth = 3;
else if (dm.densityDpi <= 160)
axisWidth = 10;
else if (dm.densityDpi <= 320)
axisWidth = 35;
else if (dm.densityDpi <= 420)
axisWidth = 50;
else if (dm.densityDpi <= 560)
axisWidth = 70;
else
axisWidth = 80;
bgGraph.getGridLabelRenderer().setGridColor(MainApp.sResources.getColor(R.color.graphgrid));
bgGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setGridColor(MainApp.sResources.getColor(R.color.graphgrid));
iobGraph.getGridLabelRenderer().reloadStyles();
iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false);
bgGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth);
iobGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth);
iobGraph.getGridLabelRenderer().setNumVerticalLabels(5);
rangeToDisplay = SP.getInt(R.string.key_rangetodisplay, 6);
bgGraph.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
rangeToDisplay += 6;
rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay;
SP.putInt(R.string.key_rangetodisplay, rangeToDisplay);
updateGUI("rangeChange");
return false;
}
});
setupChartMenu(view);
lockScreen = (CheckBox) view.findViewById(R.id.overview_lockscreen);
if (lockScreen != null) {
lockScreen.setChecked(SP.getBoolean("lockscreen", false));
lockScreen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SP.putBoolean("lockscreen", isChecked);
MainApp.bus().post(new EventSetWakeLock(isChecked));
}
});
}
return view;
} catch (Exception e) {
FabricPrivacy.logException(e);
log.debug("Runtime Exception", e);
}
return null;
}
private void setupChartMenu(View view) {
chartButton = (ImageButton) view.findViewById(R.id.overview_chartMenuButton);
chartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
final boolean predictionsAvailable = finalLastRun != null && finalLastRun.request.hasPredictions;
MenuItem item;
CharSequence title;
SpannableString s;
PopupMenu popup = new PopupMenu(v.getContext(), v);
if (predictionsAvailable) {
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.PRE.ordinal(), Menu.NONE, "Predictions");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.prediction, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showprediction", true));
}
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showbasals", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showiob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showcob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdeviations", false));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showratios", false));
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == CHARTTYPE.PRE.ordinal()) {
SP.putBoolean("showprediction", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.BAS.ordinal()) {
SP.putBoolean("showbasals", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.IOB.ordinal()) {
SP.putBoolean("showiob", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.COB.ordinal()) {
SP.putBoolean("showcob", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.DEV.ordinal()) {
SP.putBoolean("showdeviations", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.SEN.ordinal()) {
SP.putBoolean("showratios", !item.isChecked());
}
scheduleUpdateGUI("onGraphCheckboxesCheckedChanged");
return true;
}
});
chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp);
popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu menu) {
chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
}
});
popup.show();
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v == apsModeView) {
final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
final PumpDescription pumpDescription = ConfigBuilderPlugin.getActivePump().getPumpDescription();
if (activeloop == null || !MainApp.getConfigBuilder().isProfileValid("ContexMenuCreation"))
return;
menu.setHeaderTitle(MainApp.sResources.getString(R.string.loop));
if (activeloop.isEnabled(PluginBase.LOOP)) {
menu.add(MainApp.sResources.getString(R.string.disableloop));
if (!activeloop.isSuspended()) {
menu.add(MainApp.sResources.getString(R.string.suspendloopfor1h));
menu.add(MainApp.sResources.getString(R.string.suspendloopfor2h));
menu.add(MainApp.sResources.getString(R.string.suspendloopfor3h));
menu.add(MainApp.sResources.getString(R.string.suspendloopfor10h));
if (pumpDescription.tempDurationStep15mAllowed)
menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor15m));
if (pumpDescription.tempDurationStep30mAllowed)
menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor30m));
menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor1h));
menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor2h));
menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor3h));
} else {
menu.add(MainApp.sResources.getString(R.string.resume));
}
}
if (!activeloop.isEnabled(PluginBase.LOOP))
menu.add(MainApp.sResources.getString(R.string.enableloop));
} else if (v == activeProfileView) {
menu.setHeaderTitle(MainApp.sResources.getString(R.string.profile));
menu.add(MainApp.sResources.getString(R.string.danar_viewprofile));
if (MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() != null) {
menu.add(MainApp.sResources.getString(R.string.careportal_profileswitch));
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null)
return true;
final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
if (item.getTitle().equals(MainApp.sResources.getString(R.string.disableloop))) {
activeloop.setPluginEnabled(PluginBase.LOOP, false);
activeloop.setFragmentVisible(PluginBase.LOOP, false);
MainApp.getConfigBuilder().storeSettings();
updateGUI("suspendmenu");
MainApp.getConfigBuilder().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(24 * 60); // upload 24h, we don't know real duration
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.enableloop))) {
activeloop.setPluginEnabled(PluginBase.LOOP, true);
activeloop.setFragmentVisible(PluginBase.LOOP, true);
MainApp.getConfigBuilder().storeSettings();
updateGUI("suspendmenu");
NSUpload.uploadOpenAPSOffline(0);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.resume))) {
activeloop.suspendTo(0L);
updateGUI("suspendmenu");
MainApp.getConfigBuilder().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(0);
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor1h))) {
MainApp.getConfigBuilder().suspendLoop(60);
updateGUI("suspendmenu");
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor2h))) {
MainApp.getConfigBuilder().suspendLoop(120);
updateGUI("suspendmenu");
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor3h))) {
MainApp.getConfigBuilder().suspendLoop(180);
updateGUI("suspendmenu");
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor10h))) {
MainApp.getConfigBuilder().suspendLoop(600);
updateGUI("suspendmenu");
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor15m))) {
MainApp.getConfigBuilder().disconnectPump(15, profile);
updateGUI("suspendmenu");
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor30m))) {
MainApp.getConfigBuilder().disconnectPump(30, profile);
updateGUI("suspendmenu");
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor1h))) {
MainApp.getConfigBuilder().disconnectPump(60, profile);
updateGUI("suspendmenu");
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor2h))) {
MainApp.getConfigBuilder().disconnectPump(120, profile);
updateGUI("suspendmenu");
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor3h))) {
MainApp.getConfigBuilder().disconnectPump(180, profile);
updateGUI("suspendmenu");
return true;
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.careportal_profileswitch))) {
NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCHDIRECT;
profileswitch.executeProfileSwitch = true;
newDialog.setOptions(profileswitch, R.string.careportal_profileswitch);
newDialog.show(getFragmentManager(), "NewNSTreatmentDialog");
} else if (item.getTitle().equals(MainApp.sResources.getString(R.string.danar_viewprofile))) {
ProfileViewerDialog pvd = ProfileViewerDialog.newInstance(System.currentTimeMillis());
FragmentManager manager = getFragmentManager();
pvd.show(manager, "ProfileViewDialog");
}
return super.onContextItemSelected(item);
}
@Override
public void onClick(View v) {
boolean xdrip = MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginBase.BGSOURCE);
boolean g5 = MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class) != null && MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class).isEnabled(PluginBase.BGSOURCE);
String units = MainApp.getConfigBuilder().getProfileUnits();
FragmentManager manager = getFragmentManager();
switch (v.getId()) {
case R.id.overview_accepttempbutton:
onClickAcceptTemp();
break;
case R.id.overview_quickwizardbutton:
onClickQuickwizard();
break;
case R.id.overview_wizardbutton:
WizardDialog wizardDialog = new WizardDialog();
wizardDialog.show(manager, "WizardDialog");
break;
case R.id.overview_calibrationbutton:
if (xdrip) {
CalibrationDialog calibrationDialog = new CalibrationDialog();
calibrationDialog.show(manager, "CalibrationDialog");
} else if (g5) {
try {
Intent i = new Intent("com.dexcom.cgm.activities.MeterEntryActivity");
startActivity(i);
} catch (ActivityNotFoundException e) {
ToastUtils.showToastInUiThread(getActivity(), MainApp.gs(R.string.g5appnotdetected));
}
}
break;
case R.id.overview_cgmbutton:
if (xdrip)
openCgmApp("com.eveningoutpost.dexdrip");
else if (g5 && units.equals(Constants.MGDL))
openCgmApp("com.dexcom.cgm.region5.mgdl");
else if (g5 && units.equals(Constants.MMOL))
openCgmApp("com.dexcom.cgm.region5.mmol");
break;
case R.id.overview_treatmentbutton:
NewTreatmentDialog treatmentDialogFragment = new NewTreatmentDialog();
treatmentDialogFragment.show(manager, "TreatmentDialog");
break;
case R.id.overview_insulinbutton:
new NewInsulinDialog().show(manager, "InsulinDialog");
break;
case R.id.overview_carbsbutton:
new NewCarbsDialog().show(manager, "CarbsDialog");
break;
case R.id.overview_pumpstatus:
if (ConfigBuilderPlugin.getActivePump().isSuspended() || !ConfigBuilderPlugin.getActivePump().isInitialized())
ConfigBuilderPlugin.getCommandQueue().readStatus("RefreshClicked", null);
break;
}
}
public boolean openCgmApp(String packageName) {
PackageManager packageManager = getContext().getPackageManager();
try {
Intent intent = packageManager.getLaunchIntentForPackage(packageName);
if (intent == null) {
throw new ActivityNotFoundException();
}
intent.addCategory(Intent.CATEGORY_LAUNCHER);
getContext().startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
new AlertDialog.Builder(getContext())
.setMessage(R.string.error_starting_cgm)
.setPositiveButton("OK", null)
.show();
return false;
}
}
@Override
public boolean onLongClick(View v) {
switch (v.getId()) {
case R.id.overview_quickwizardbutton:
Intent i = new Intent(v.getContext(), QuickWizardListActivity.class);
startActivity(i);
return true;
}
return false;
}
private void onClickAcceptTemp() {
Profile profile = MainApp.getConfigBuilder().getProfile();
if (ConfigBuilderPlugin.getActiveLoop() != null && profile != null) {
ConfigBuilderPlugin.getActiveLoop().invoke("Accept temp button", false);
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (finalLastRun != null && finalLastRun.lastAPSRun != null && finalLastRun.constraintsProcessed.isChangeRequested()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getContext().getString(R.string.confirmation));
builder.setMessage(getContext().getString(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
builder.setPositiveButton(getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
hideTempRecommendation();
clearNotification();
MainApp.getConfigBuilder().applyTBRRequest(finalLastRun.constraintsProcessed, profile, new Callback() {
@Override
public void run() {
if (result.enacted) {
finalLastRun.tbrSetByPump = result;
finalLastRun.lastEnact = new Date();
finalLastRun.lastOpenModeAccept = new Date();
NSUpload.uploadDeviceStatus();
ObjectivesPlugin objectivesPlugin = MainApp.getSpecificPlugin(ObjectivesPlugin.class);
if (objectivesPlugin != null) {
ObjectivesPlugin.manualEnacts++;
ObjectivesPlugin.saveProgress();
}
}
scheduleUpdateGUI("onClickAcceptTemp");
}
});
FabricPrivacy.getInstance().logCustom(new CustomEvent("AcceptTemp"));
}
});
builder.setNegativeButton(getContext().getString(R.string.cancel), null);
builder.show();
}
}
}
void onClickQuickwizard() {
final BgReading actualBg = DatabaseHelper.actualBg();
final Profile profile = MainApp.getConfigBuilder().getProfile();
final TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory();
final QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive();
if (quickWizardEntry != null && actualBg != null && profile != null) {
quickWizardButton.setVisibility(View.VISIBLE);
final BolusWizard wizard = quickWizardEntry.doCalc(profile, tempTarget, actualBg, true);
final JSONObject boluscalcJSON = new JSONObject();
try {
boluscalcJSON.put("eventTime", DateUtil.toISOString(new Date()));
boluscalcJSON.put("targetBGLow", wizard.targetBGLow);
boluscalcJSON.put("targetBGHigh", wizard.targetBGHigh);
boluscalcJSON.put("isf", wizard.sens);
boluscalcJSON.put("ic", wizard.ic);
boluscalcJSON.put("iob", -(wizard.insulingFromBolusIOB + wizard.insulingFromBasalsIOB));
boluscalcJSON.put("bolusiobused", true);
boluscalcJSON.put("basaliobused", true);
boluscalcJSON.put("bg", actualBg.valueToUnits(profile.getUnits()));
boluscalcJSON.put("insulinbg", wizard.insulinFromBG);
boluscalcJSON.put("insulinbgused", true);
boluscalcJSON.put("bgdiff", wizard.bgDiff);
boluscalcJSON.put("insulincarbs", wizard.insulinFromCarbs);
boluscalcJSON.put("carbs", quickWizardEntry.carbs());
boluscalcJSON.put("othercorrection", 0d);
boluscalcJSON.put("insulintrend", wizard.insulinFromTrend);
boluscalcJSON.put("insulin", wizard.calculatedTotalInsulin);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
if (wizard.calculatedTotalInsulin > 0d && quickWizardEntry.carbs() > 0d) {
DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
String confirmMessage = getString(R.string.entertreatmentquestion);
Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(wizard.calculatedTotalInsulin)).value();
Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value();
confirmMessage += "\n" + getString(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g";
if (!insulinAfterConstraints.equals(wizard.calculatedTotalInsulin) || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror));
builder.setMessage(getString(R.string.constraints_violation) + "\n" + getString(R.string.changeyourinput));
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null);
builder.show();
return;
}
final Double finalInsulinAfterConstraints = insulinAfterConstraints;
final Integer finalCarbsAfterConstraints = carbsAfterConstraints;
final Context context = getContext();
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
accepted = false;
builder.setTitle(MainApp.sResources.getString(R.string.confirmation));
builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
synchronized (builder) {
if (accepted) {
log.debug("guarding: already accepted");
return;
}
accepted = true;
if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) {
if (wizard.superBolus) {
final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
if (activeloop != null) {
activeloop.superBolusTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000);
MainApp.bus().post(new EventRefreshOverview("WizardDialog"));
}
ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 120, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
}
});
}
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.eventType = CareportalEvent.BOLUSWIZARD;
detailedBolusInfo.insulin = finalInsulinAfterConstraints;
detailedBolusInfo.carbs = finalCarbsAfterConstraints;
detailedBolusInfo.context = context;
detailedBolusInfo.boluscalc = boluscalcJSON;
detailedBolusInfo.source = Source.USER;
ConfigBuilderPlugin.getCommandQueue().bolus(detailedBolusInfo, new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.treatmentdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
}
});
FabricPrivacy.getInstance().logCustom(new CustomEvent("QuickWizard"));
}
}
}
});
builder.setNegativeButton(getString(R.string.cancel), null);
builder.show();
}
}
}
@Override
public void onPause() {
super.onPause();
MainApp.bus().unregister(this);
sLoopHandler.removeCallbacksAndMessages(null);
unregisterForContextMenu(apsModeView);
unregisterForContextMenu(activeProfileView);
}
@Override
public void onResume() {
super.onResume();
MainApp.bus().register(this);
sRefreshLoop = new Runnable() {
@Override
public void run() {
scheduleUpdateGUI("refreshLoop");
sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
}
};
sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
registerForContextMenu(apsModeView);
registerForContextMenu(activeProfileView);
updateGUI("onResume");
}
@Subscribe
public void onStatusEvent(final EventInitializationChanged ev) {
scheduleUpdateGUI("EventInitializationChanged");
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange ev) {
scheduleUpdateGUI("EventPreferenceChange");
}
@Subscribe
public void onStatusEvent(final EventRefreshOverview ev) {
scheduleUpdateGUI(ev.from);
}
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) {
scheduleUpdateGUI("EventAutosensCalculationFinished");
}
@Subscribe
public void onStatusEvent(final EventTreatmentChange ev) {
scheduleUpdateGUI("EventTreatmentChange");
}
@Subscribe
public void onStatusEvent(final EventCareportalEventChange ev) {
scheduleUpdateGUI("EventCareportalEventChange");
}
@Subscribe
public void onStatusEvent(final EventTempBasalChange ev) {
scheduleUpdateGUI("EventTempBasalChange");
}
@Subscribe
public void onStatusEvent(final EventExtendedBolusChange ev) {
scheduleUpdateGUI("EventExtendedBolusChange");
}
// Handled by EventAutosensCalculationFinished
// @Subscribe
// public void onStatusEvent(final EventNewBG ev) {
// scheduleUpdateGUI("EventNewBG");
@Subscribe
public void onStatusEvent(final EventNewOpenLoopNotification ev) {
scheduleUpdateGUI("EventNewOpenLoopNotification");
}
// Handled by EventAutosensCalculationFinished
// @Subscribe
// public void onStatusEvent(final EventNewBasalProfile ev) {
// scheduleUpdateGUI("EventNewBasalProfile");
@Subscribe
public void onStatusEvent(final EventTempTargetChange ev) {
scheduleUpdateGUI("EventTempTargetChange");
}
@Subscribe
public void onStatusEvent(final EventPumpStatusChanged s) {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
updatePumpStatus(s.textStatus());
}
});
}
private void hideTempRecommendation() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (acceptTempLayout != null)
acceptTempLayout.setVisibility(View.GONE);
}
});
}
private void clearNotification() {
NotificationManager notificationManager =
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
}
private void updatePumpStatus(String status) {
if (!status.equals("")) {
pumpStatusView.setText(status);
pumpStatusLayout.setVisibility(View.VISIBLE);
loopStatusLayout.setVisibility(View.GONE);
} else {
pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.VISIBLE);
}
}
public void scheduleUpdateGUI(final String from) {
class UpdateRunnable implements Runnable {
public void run() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
updateGUI(from);
scheduledUpdate = null;
}
});
}
}
// prepare task for execution in 400 msec
// cancel waiting task to prevent multiple updates
if (scheduledUpdate != null)
scheduledUpdate.cancel(false);
Runnable task = new UpdateRunnable();
final int msec = 500;
scheduledUpdate = worker.schedule(task, msec, TimeUnit.MILLISECONDS);
}
@SuppressLint("SetTextI18n")
public void updateGUI(final String from) {
log.debug("updateGUI entered from: " + from);
final Date updateGUIStart = new Date();
if (getActivity() == null)
return;
if (timeView != null) { //must not exists
timeView.setText(DateUtil.timeString(new Date()));
}
if (!MainApp.getConfigBuilder().isProfileValid("Overview")) {
pumpStatusView.setText(R.string.noprofileset);
pumpStatusLayout.setVisibility(View.VISIBLE);
loopStatusLayout.setVisibility(View.GONE);
return;
}
pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.VISIBLE);
updateNotifications();
CareportalFragment.updateAge(getActivity(), sage, iage, cage, pbage);
BgReading actualBG = DatabaseHelper.actualBg();
BgReading lastBG = DatabaseHelper.lastBg();
final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
final Profile profile = MainApp.getConfigBuilder().getProfile();
final String units = profile.getUnits();
final double lowLine = OverviewPlugin.getPlugin().determineLowLine(units);
final double highLine = OverviewPlugin.getPlugin().determineHighLine(units);
//Start with updating the BG as it is unaffected by loop.
if (lastBG != null) {
int color = MainApp.sResources.getColor(R.color.inrange);
if (lastBG.valueToUnits(units) < lowLine)
color = MainApp.sResources.getColor(R.color.low);
else if (lastBG.valueToUnits(units) > highLine)
color = MainApp.sResources.getColor(R.color.high);
bgView.setText(lastBG.valueToUnitsToString(units));
arrowView.setText(lastBG.directionToSymbol());
bgView.setTextColor(color);
arrowView.setTextColor(color);
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (glucoseStatus != null) {
deltaView.setText("Δ " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units);
if (avgdeltaView != null)
avgdeltaView.setText("øΔ15m: " + Profile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units) +
" øΔ40m: " + Profile.toUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units));
} else {
deltaView.setText("Δ " + MainApp.sResources.getString(R.string.notavailable));
if (avgdeltaView != null)
avgdeltaView.setText("");
}
}
Constraint<Boolean> closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed();
// open loop mode
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (Config.APS && pump.getPumpDescription().isTempBasalCapable) {
apsModeView.setVisibility(View.VISIBLE);
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.loopenabled));
apsModeView.setTextColor(Color.BLACK);
final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop();
if (activeloop != null && activeloop.isEnabled(activeloop.getType()) && activeloop.isSuperBolus()) {
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.looppumpsuspended));
apsModeView.setText(String.format(MainApp.sResources.getString(R.string.loopsuperbolusfor), activeloop.minutesToEndOfSuspend()));
apsModeView.setTextColor(Color.WHITE);
} else if (activeloop != null && activeloop.isEnabled(activeloop.getType()) && activeloop.isSuspended()) {
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.looppumpsuspended));
apsModeView.setText(String.format(MainApp.sResources.getString(R.string.loopsuspendedfor), activeloop.minutesToEndOfSuspend()));
apsModeView.setTextColor(Color.WHITE);
} else if (pump.isSuspended()) {
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.looppumpsuspended));
apsModeView.setText(MainApp.sResources.getString(R.string.pumpsuspended));
apsModeView.setTextColor(Color.WHITE);
} else if (activeloop != null && activeloop.isEnabled(activeloop.getType())) {
if (closedLoopEnabled.value()) {
apsModeView.setText(MainApp.sResources.getString(R.string.closedloop));
} else {
apsModeView.setText(MainApp.sResources.getString(R.string.openloop));
}
} else {
apsModeView.setBackgroundColor(MainApp.sResources.getColor(R.color.loopdisabled));
apsModeView.setText(MainApp.sResources.getString(R.string.disabledloop));
apsModeView.setTextColor(Color.WHITE);
}
} else {
apsModeView.setVisibility(View.GONE);
}
// temp target
TempTarget tempTarget = MainApp.getConfigBuilder().getTempTargetFromHistory();
if (tempTarget != null) {
tempTargetView.setTextColor(Color.BLACK);
tempTargetView.setBackgroundColor(MainApp.sResources.getColor(R.color.tempTargetBackground));
tempTargetView.setVisibility(View.VISIBLE);
tempTargetView.setText(Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.end()));
} else {
tempTargetView.setTextColor(Color.WHITE);
tempTargetView.setBackgroundColor(MainApp.sResources.getColor(R.color.tempTargetDisabledBackground));
tempTargetView.setText(Profile.toTargetRangeString(profile.getTargetLow(), profile.getTargetHigh(), units, units));
tempTargetView.setVisibility(View.VISIBLE);
}
if (acceptTempLayout != null) {
boolean showAcceptButton = !closedLoopEnabled.value(); // Open mode needed
showAcceptButton = showAcceptButton && finalLastRun != null && finalLastRun.lastAPSRun != null; // aps result must exist
showAcceptButton = showAcceptButton && (finalLastRun.lastOpenModeAccept == null || finalLastRun.lastOpenModeAccept.getTime() < finalLastRun.lastAPSRun.getTime()); // never accepted or before last result
showAcceptButton = showAcceptButton && finalLastRun.constraintsProcessed.isChangeRequested(); // change is requested
if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && ConfigBuilderPlugin.getActiveLoop() != null) {
acceptTempLayout.setVisibility(View.VISIBLE);
acceptTempButton.setText(getContext().getString(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
} else {
acceptTempLayout.setVisibility(View.GONE);
}
}
boolean xDripIsBgSource = MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginBase.BGSOURCE);
boolean g5IsBgSource = MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class) != null && MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class).isEnabled(PluginBase.BGSOURCE);
boolean bgAvailable = DatabaseHelper.actualBg() != null;
if (calibrationButton != null) {
if ((xDripIsBgSource || g5IsBgSource) && bgAvailable && SP.getBoolean(R.string.key_show_calibration_button, true)) {
calibrationButton.setVisibility(View.VISIBLE);
} else {
calibrationButton.setVisibility(View.GONE);
}
}
if (cgmButton != null) {
if (xDripIsBgSource && SP.getBoolean(R.string.key_show_cgm_button, false)) {
cgmButton.setVisibility(View.VISIBLE);
} else if (g5IsBgSource && SP.getBoolean(R.string.key_show_cgm_button, false)) {
cgmButton.setVisibility(View.VISIBLE);
} else {
cgmButton.setVisibility(View.GONE);
}
}
final TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
String basalText = "";
if (shorttextmode) {
if (activeTemp != null) {
basalText = "T: " + activeTemp.toStringVeryShort();
} else {
basalText = DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h";
}
baseBasalView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String fullText = MainApp.sResources.getString(R.string.pump_basebasalrate_label) + ": " + DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h\n";
if (activeTemp != null) {
fullText += MainApp.sResources.getString(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull();
}
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.basal), fullText, null);
}
});
} else {
if (activeTemp != null) {
basalText = activeTemp.toStringFull() + " ";
}
if (Config.NSCLIENT || Config.G5UPLOADER)
basalText += "(" + DecimalFormatter.to2Decimal(profile.getBasal()) + " U/h)";
else if (pump.getPumpDescription().isTempBasalCapable) {
basalText += "(" + DecimalFormatter.to2Decimal(pump.getBaseBasalRate()) + "U/h)";
}
}
if (activeTemp != null) {
baseBasalView.setTextColor(MainApp.sResources.getColor(R.color.basal));
} else {
baseBasalView.setTextColor(Color.WHITE);
}
baseBasalView.setText(basalText);
final ExtendedBolus extendedBolus = MainApp.getConfigBuilder().getExtendedBolusFromHistory(System.currentTimeMillis());
String extendedBolusText = "";
if (extendedBolusView != null) { // must not exists in all layouts
if (shorttextmode) {
if (extendedBolus != null && !pump.isFakingTempsByExtendedBoluses()) {
extendedBolusText = DecimalFormatter.to2Decimal(extendedBolus.absoluteRate()) + "U/h";
}
extendedBolusView.setText(extendedBolusText);
extendedBolusView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.extendedbolus), extendedBolus.toString(), null);
}
});
} else {
if (extendedBolus != null && !pump.isFakingTempsByExtendedBoluses()) {
extendedBolusText = extendedBolus.toString();
}
extendedBolusView.setText(extendedBolusText);
}
if (extendedBolusText.equals(""))
extendedBolusView.setVisibility(View.INVISIBLE);
else
extendedBolusView.setVisibility(View.VISIBLE);
}
activeProfileView.setText(MainApp.getConfigBuilder().getProfileName());
activeProfileView.setBackgroundColor(Color.GRAY);
tempTargetView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
NewNSTreatmentDialog newTTDialog = new NewNSTreatmentDialog();
final OptionsToShow temptarget = CareportalFragment.TEMPTARGET;
temptarget.executeTempTarget = true;
newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget);
newTTDialog.show(getFragmentManager(), "NewNSTreatmentDialog");
return true;
}
});
tempTargetView.setLongClickable(true);
// QuickWizard button
QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive();
if (quickWizardEntry != null && lastBG != null && pump.isInitialized() && !pump.isSuspended()) {
quickWizardButton.setVisibility(View.VISIBLE);
String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g";
BolusWizard wizard = quickWizardEntry.doCalc(profile, tempTarget, lastBG, false);
text += " " + DecimalFormatter.toPumpSupportedBolus(wizard.calculatedTotalInsulin) + "U";
quickWizardButton.setText(text);
if (wizard.calculatedTotalInsulin <= 0)
quickWizardButton.setVisibility(View.GONE);
} else
quickWizardButton.setVisibility(View.GONE);
if (carbsButton != null) {
if (SP.getBoolean(R.string.key_show_carbs_button, true)
&& (!ConfigBuilderPlugin.getActivePump().getPumpDescription().storesCarbInfo ||
(pump.isInitialized() && !pump.isSuspended()))) {
carbsButton.setVisibility(View.VISIBLE);
} else {
carbsButton.setVisibility(View.GONE);
}
}
if (pump.isInitialized() && !pump.isSuspended()) {
if (treatmentButton != null) {
if (SP.getBoolean(R.string.key_show_treatment_button, false)) {
treatmentButton.setVisibility(View.VISIBLE);
} else {
treatmentButton.setVisibility(View.GONE);
}
}
if (wizardButton != null) {
if (SP.getBoolean(R.string.key_show_wizard_button, true)) {
wizardButton.setVisibility(View.VISIBLE);
} else {
wizardButton.setVisibility(View.GONE);
}
}
if (insulinButton != null) {
if (SP.getBoolean(R.string.key_show_insulin_button, true)) {
insulinButton.setVisibility(View.VISIBLE);
} else {
insulinButton.setVisibility(View.GONE);
}
}
}
if (lastBG == null) { //left this here as it seems you want to exit at this point if it is null...
return;
}
Integer flag = bgView.getPaintFlags();
if (actualBG == null) {
flag |= Paint.STRIKE_THRU_TEXT_FLAG;
} else
flag &= ~Paint.STRIKE_THRU_TEXT_FLAG;
bgView.setPaintFlags(flag);
timeAgoView.setText(DateUtil.minAgo(lastBG.date));
// iob
MainApp.getConfigBuilder().updateTotalIOBTreatments();
MainApp.getConfigBuilder().updateTotalIOBTempBasals();
final IobTotal bolusIob = MainApp.getConfigBuilder().getLastCalculationTreatments().round();
final IobTotal basalIob = MainApp.getConfigBuilder().getLastCalculationTempBasals().round();
if (shorttextmode) {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U";
iobView.setText(iobtext);
iobView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U\n"
+ getString(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U\n"
+ getString(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U\n";
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.iob), iobtext, null);
}
});
} else if (MainApp.sResources.getBoolean(R.bool.isTablet)) {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ getString(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ getString(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)";
iobView.setText(iobtext);
} else {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ DecimalFormatter.to2Decimal(bolusIob.iob) + "/"
+ DecimalFormatter.to2Decimal(basalIob.basaliob) + ")";
iobView.setText(iobtext);
}
// cob
if (cobView != null) { // view must not exists
String cobText = "";
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensData("Overview COB");
if (autosensData != null)
cobText = (int) autosensData.cob + " g";
cobView.setText(cobText);
}
final boolean predictionsAvailable = finalLastRun != null && finalLastRun.request.hasPredictions;
// pump status from ns
if (pumpDeviceStatusView != null) {
pumpDeviceStatusView.setText(NSDeviceStatus.getInstance().getPumpStatus());
pumpDeviceStatusView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.pump), NSDeviceStatus.getInstance().getExtendedPumpStatus(), null);
}
});
}
// OpenAPS status from ns
if (openapsDeviceStatusView != null) {
openapsDeviceStatusView.setText(NSDeviceStatus.getInstance().getOpenApsStatus());
openapsDeviceStatusView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.openaps), NSDeviceStatus.getInstance().getExtendedOpenApsStatus(), null);
}
});
}
// Uploader status from ns
if (uploaderDeviceStatusView != null) {
uploaderDeviceStatusView.setText(NSDeviceStatus.getInstance().getUploaderStatus());
uploaderDeviceStatusView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OKDialog.show(getActivity(), MainApp.sResources.getString(R.string.uploader), NSDeviceStatus.getInstance().getExtendedUploaderStatus(), null);
}
});
}
new Thread(new Runnable() {
@Override
public void run() {
// allign to hours
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.add(Calendar.HOUR, 1);
int hoursToFetch;
final long toTime;
final long fromTime;
final long endTime;
if (predictionsAvailable && SP.getBoolean("showprediction", false)) {
int predHours = (int) (Math.ceil(finalLastRun.constraintsProcessed.getLatestPredictionsTime() - System.currentTimeMillis()) / (60 * 60 * 1000));
predHours = Math.min(2, predHours);
predHours = Math.max(0, predHours);
hoursToFetch = rangeToDisplay - predHours;
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
endTime = toTime + predHours * 60 * 60 * 1000L;
} else {
hoursToFetch = rangeToDisplay;
toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific
fromTime = toTime - hoursToFetch * 60 * 60 * 1000L;
endTime = toTime;
}
final long now = System.currentTimeMillis();
Profiler.log(log, from + " - 1st graph - START", updateGUIStart);
final GraphData graphData = new GraphData(bgGraph, IobCobCalculatorPlugin.getPlugin());
graphData.addInRangeArea(fromTime, endTime, lowLine, highLine);
if (predictionsAvailable && SP.getBoolean("showprediction", false))
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, finalLastRun.constraintsProcessed);
else
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null);
// set manual x bounds to have nice steps
graphData.formatAxis(fromTime, endTime);
// Treatments
graphData.addTreatments(fromTime, endTime);
// add basal data
if (pump.getPumpDescription().isTempBasalCapable && SP.getBoolean("showbasals", true)) {
graphData.addBasals(fromTime, now, lowLine / graphData.maxY / 1.2d);
}
// add target line
graphData.addTargetLine(fromTime, toTime, profile);
graphData.addNowLine(now);
Profiler.log(log, from + " - 2nd graph - START", updateGUIStart);
final GraphData secondGraphData = new GraphData(iobGraph, IobCobCalculatorPlugin.getPlugin());
boolean useIobForScale = false;
boolean useCobForScale = false;
boolean useDevForScale = false;
boolean useRatioForScale = false;
boolean useDSForScale = false;
if (SP.getBoolean("showiob", true)) {
useIobForScale = true;
} else if (SP.getBoolean("showcob", true)) {
useCobForScale = true;
} else if (SP.getBoolean("showdeviations", false)) {
useDevForScale = true;
} else if (SP.getBoolean("showratios", false)) {
useRatioForScale = true;
} else if (Config.displayDeviationSlope) {
useDSForScale = true;
}
if (SP.getBoolean("showiob", true))
secondGraphData.addIob(fromTime, now, useIobForScale, 1d);
if (SP.getBoolean("showcob", true))
secondGraphData.addCob(fromTime, now, useCobForScale, useCobForScale ? 1d : 0.5d);
if (SP.getBoolean("showdeviations", false))
secondGraphData.addDeviations(fromTime, now, useDevForScale, 1d);
if (SP.getBoolean("showratios", false))
secondGraphData.addRatio(fromTime, now, useRatioForScale, 1d);
if (Config.displayDeviationSlope)
secondGraphData.addDeviationSlope(fromTime, now, useDSForScale, 1d);
// set manual x bounds to have nice steps
secondGraphData.formatAxis(fromTime, endTime);
secondGraphData.addNowLine(now);
// do GUI update
FragmentActivity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (SP.getBoolean("showiob", true) || SP.getBoolean("showcob", true) || SP.getBoolean("showdeviations", false) || SP.getBoolean("showratios", false) || Config.displayDeviationSlope) {
iobGraph.setVisibility(View.VISIBLE);
} else {
iobGraph.setVisibility(View.GONE);
}
// finally enforce drawing of graphs
graphData.performUpdate();
secondGraphData.performUpdate();
Profiler.log(log, from + " - onDataChanged", updateGUIStart);
}
});
}
}
}).start();
Profiler.log(log, from, updateGUIStart);
}
//Notifications
static class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.NotificationsViewHolder> {
List<Notification> notificationsList;
RecyclerViewAdapter(List<Notification> notificationsList) {
this.notificationsList = notificationsList;
}
@Override
public NotificationsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.overview_notification_item, viewGroup, false);
return new NotificationsViewHolder(v);
}
@Override
public void onBindViewHolder(NotificationsViewHolder holder, int position) {
Notification notification = notificationsList.get(position);
holder.dismiss.setTag(notification);
if (Objects.equals(notification.text, MainApp.sResources.getString(R.string.nsalarm_staledata)))
holder.dismiss.setText("snooze");
holder.text.setText(notification.text);
holder.time.setText(DateUtil.timeString(notification.date));
if (notification.level == Notification.URGENT)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationUrgent));
else if (notification.level == Notification.NORMAL)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationNormal));
else if (notification.level == Notification.LOW)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationLow));
else if (notification.level == Notification.INFO)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationInfo));
else if (notification.level == Notification.ANNOUNCEMENT)
holder.cv.setBackgroundColor(ContextCompat.getColor(MainApp.instance(), R.color.notificationAnnouncement));
}
@Override
public int getItemCount() {
return notificationsList.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
static class NotificationsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView time;
TextView text;
Button dismiss;
NotificationsViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.notification_cardview);
time = (TextView) itemView.findViewById(R.id.notification_time);
text = (TextView) itemView.findViewById(R.id.notification_text);
dismiss = (Button) itemView.findViewById(R.id.notification_dismiss);
dismiss.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Notification notification = (Notification) v.getTag();
switch (v.getId()) {
case R.id.notification_dismiss:
MainApp.bus().post(new EventDismissNotification(notification.id));
if (notification.nsAlarm != null) {
BroadcastAckAlarm.handleClearAlarm(notification.nsAlarm, MainApp.instance().getApplicationContext(), 60 * 60 * 1000L);
}
// Adding current time to snooze if we got staleData
log.debug("Notification text is: " + notification.text);
if (notification.text.equals(MainApp.sResources.getString(R.string.nsalarm_staledata))) {
NotificationStore nstore = OverviewPlugin.getPlugin().notificationStore;
long msToSnooze = SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L;
log.debug("snooze nsalarm_staledatavalue in minutes is " + SP.getInt("nsalarm_staledatavalue", 15) + "\n in ms is: " + msToSnooze + " currentTimeMillis is: " + System.currentTimeMillis());
nstore.snoozeTo(System.currentTimeMillis() + (SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L));
}
break;
}
}
}
}
void updateNotifications() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
NotificationStore nstore = OverviewPlugin.getPlugin().notificationStore;
nstore.removeExpired();
nstore.unSnooze();
if (nstore.store.size() > 0) {
RecyclerViewAdapter adapter = new RecyclerViewAdapter(nstore.store);
notificationsView.setAdapter(adapter);
notificationsView.setVisibility(View.VISIBLE);
} else {
notificationsView.setVisibility(View.GONE);
}
}
});
}
}
|
package org.fraunhofer.cese.funf_sensor.Probe;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import edu.mit.media.funf.probe.Probe;
public class NetworkConnectionProbe extends Probe.Base implements Probe.PassiveProbe {
private BroadcastReceiver receiver;
private static final String TAG = "NetworkProbe: ";
@Override
protected void onEnable() {
super.onStart();
receiver = new ConnectionInfoReceiver(this);
IntentFilter intentFilter = new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
// intentFilter.addAction("android.net.wifi.RSSI_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGED");
intentFilter.addAction("android.net.wifi.NETWORK_STATE_CHANGED_ACTION");
intentFilter.addAction("android.net.wifi.supplicant.STATE_CHANGED");
getContext().registerReceiver(receiver, intentFilter);
Log.i(TAG, "enabled.");
sendInitialProbe();
}
@Override
protected void onDisable() {
super.onStop();
getContext().unregisterReceiver(receiver);
}
private void sendData(Intent intent) {
sendData(getGson().toJsonTree(intent).getAsJsonObject());
}
private void sendInitialProbe() {
Intent intent = new Intent();
intent.putExtra("Initial cellular data network state: ", getCellDataState());
intent.putExtra("Initial WifiState: ", getWifiState(intent));
intent.putExtra("Initial connection quality: ", intent.getIntExtra(WifiManager.EXTRA_NEW_RSSI, 0));
sendData(intent);
Log.i(TAG, "initial probe sent.");
}
private class ConnectionInfoReceiver extends BroadcastReceiver {
private final String STATE = "new Connection State: ";
private final String PREVIOUS_STATE = "previous Connection State: ";
public NetworkConnectionProbe callback;
public ConnectionInfoReceiver(NetworkConnectionProbe callback) {
this.callback = callback;
}
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case WifiManager.WIFI_STATE_CHANGED_ACTION:
intent.putExtra("New Wifi State: ", getWifiState(intent));
intent.putExtra("Previous Wifi State: ", getPreviousWifiState(intent));
intent.putExtra("cellular data network state: ", getCellDataState());
callback.sendData(intent);
break;
case WifiManager.RSSI_CHANGED_ACTION:
intent.putExtra("new connection quality: ", intent.getIntExtra(WifiManager.EXTRA_NEW_RSSI, 0));
intent.putExtra("cellular data network state: ", getCellDataState());
callback.sendData(intent);
break;
case WifiManager.NETWORK_STATE_CHANGED_ACTION:
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
intent.putExtra("new network state: ", networkInfo.toString());
intent.putExtra("cellular data network state: ", getCellDataState());
callback.sendData(intent);
break;
case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION:
SupplicantState supplicantState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
intent.putExtra("new supplicant state: ", supplicantState.toString());
intent.putExtra("cellular data network state: ", getCellDataState());
if (supplicantState.toString().equals("COMPLETED")){
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
intent.putExtra("WifiInfo: ", wifiInfo.toString());
int ipAdress = wifiInfo.getIpAddress();
String sSID = wifiInfo.getSSID();
intent.putExtra("IP-Adress: ", ipAdress);
intent.putExtra("SSID: ", sSID);
}
callback.sendData(intent);
break;
default:
intent.putExtra(TAG, "something went wrong.");
callback.sendData(intent);
break;
}
Log.i(TAG, "NetworkConnectionProbe sent");
}
}
private String getCellDataState(){
String result;
TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
switch(telephonyManager.getDataState()){
case TelephonyManager.DATA_CONNECTED:
result = "connected.";
break;
case TelephonyManager.DATA_DISCONNECTED:
result = "disconnected.";
break;
case TelephonyManager.DATA_CONNECTING:
result = "connecting.";
break;
case TelephonyManager.DATA_SUSPENDED:
result = "suspended.";
break;
default:
result = "Something went wrong.";
break;
}
return result;
}
private String getWifiState(Intent intent){
String result;
switch (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0)) {
case WifiManager.WIFI_STATE_ENABLED:
result = "enabled.";
break;
case WifiManager.WIFI_STATE_DISABLED:
result = "disabled.";
break;
case WifiManager.WIFI_STATE_ENABLING:
result = "enabling.";
break;
case WifiManager.WIFI_STATE_DISABLING:
result = "disabling";
break;
case WifiManager.WIFI_STATE_UNKNOWN:
result = "unknown.";
break;
default:
result = "Something went wrong";
break;
}
return result;
}
private String getPreviousWifiState(Intent intent){
String result;
switch (intent.getIntExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, 0)) {
case WifiManager.WIFI_STATE_ENABLED:
result = "enabled.";
break;
case WifiManager.WIFI_STATE_DISABLED:
result = "disabled.";
break;
case WifiManager.WIFI_STATE_ENABLING:
result = "enabling.";
break;
case WifiManager.WIFI_STATE_DISABLING:
result = "disabling";
break;
case WifiManager.WIFI_STATE_UNKNOWN:
result = "unknown.";
break;
default:
result = "Something went wrong";
break;
}
return result;
}
}
|
package org.worshipsongs.page.component.fragment;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import org.worshipsongs.activity.MainActivity;
import org.worshipsongs.utils.PropertyUtils;
import org.worshipsongs.worship.R;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
public class ServiceListFragment extends Fragment
{
private LinearLayout linearLayout;
private FragmentActivity FragmentActivity;
private ListView serviceListView;
private File serviceFile = null;
private ArrayAdapter<String> adapter;
List<String> service = new ArrayList<String>();
String serviceName;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
FragmentActivity = (FragmentActivity) super.getActivity();
linearLayout = (LinearLayout) inflater.inflate(R.layout.service_list_activity, container, false);
serviceListView = (ListView) linearLayout.findViewById(R.id.list_view);
loadService();
final Vibrator vibrator = (Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
serviceListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int position, long arg3)
{
vibrator.vibrate(15);
serviceName = serviceListView.getItemAtPosition(position).toString();
System.out.println("Selected Song for Service:"+service);
LayoutInflater li = LayoutInflater.from(getActivity());
View promptsView = li.inflate(R.layout.service_delete_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setView(promptsView);
alertDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
serviceFile = PropertyUtils.getServicePropertyFile(getActivity());
PropertyUtils.removeService(serviceName, serviceFile);
Toast.makeText(getActivity(), "Service " +serviceName + " Deleted...!", Toast.LENGTH_LONG).show();
service.clear();
loadService();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
});
serviceListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick (AdapterView < ? > parent, View view, int position, long id)
{
serviceName = serviceListView.getItemAtPosition(position).toString();
System.out.println("Selected Service:"+serviceName);
Bundle bundle=new Bundle();
bundle.putString("serviceName", serviceName);
Fragment fragment=new ServiceSongListFragment();
fragment.setArguments(bundle);
getFragmentManager().beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
});
return linearLayout;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.main, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
}
public void loadService()
{
readServiceName();
if(service.size() <= 0)
service.add("You haven't created any service yet!\n" +
"Services are a great way to organize selected songs for events. To add a song to the service, go the Songs screen and long press a song.");
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, service);
serviceListView.setAdapter(adapter);
}
public List readServiceName()
{
Properties property = new Properties();
InputStream inputStream = null;
try
{
serviceFile = PropertyUtils.getServicePropertyFile(getActivity());
inputStream = new FileInputStream(serviceFile);
property.load(inputStream);
Enumeration<?> e = property.propertyNames();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
//String value = property.getProperty(key);
service.add(key);
}
inputStream.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
return service;
}
}
|
package com.google.appinventor.shared.rpc.project;
import com.google.gwt.user.client.rpc.IsSerializable;
import java.util.ArrayList;
import java.util.logging.Logger;
public class GalleryApp implements IsSerializable {
/**
* Default constructor. This constructor is required by GWT.
*/
@SuppressWarnings("unused")
public GalleryApp() {
}
public static final String GALLERYURL = "http://gallery.appinventor.mit.edu/rpc?";
public GalleryApp(String title, String developerName, String description,
long creationDate, long updateDate, String imageURL, String sourceFileName,
int downloads, int views, int likes, int comments,
String imageBlobId, String sourceBlobId, String galleryAppId,
ArrayList<String> tags) {
super();
this.title = title;
this.developerName = developerName;
this.description = description;
this.creationDate = creationDate;
this.updateDate = updateDate;
this.imageURL = imageURL;
// the source file name we get from gallery can have some bad characters in it...
// e.g., name (2).zip. We need to cleanse this and probably deal with url as
// well.
if (sourceFileName.contains(".")) {
String[] splitName = sourceFileName.split("\\.");
projectName = splitName[0];
} else {
projectName = sourceFileName;
}
this.downloads = downloads;
this.views = views;
this.likes = likes;
this.comments = comments;
this.imageBlobId= imageBlobId;
this.sourceBlobId= sourceBlobId;
this.galleryAppId= galleryAppId;
this.tags = tags;
}
/* this constructor is called when we are creating a new gallery app but don't have
the stuff yet */
public GalleryApp(String title, long projectId) {
super();
this.title=title;
this.downloads=0;
this.views=0;
this.likes=0;
this.comments=0;
this.projectId=projectId;
}
private String title;
private String developerName;
private String description;
private long creationDate;
private long updateDate;
private String projectName;
private String imageURL;
private int downloads;
private int views;
private int likes;
private int comments;
private String imageBlobId;
private String sourceBlobId;
private String galleryAppId;
private ArrayList<String> tags;
private long projectId; // when we edit a newly published app, we need the ai proj id.
public long getProjectId() {
return projectId;
}
public void setProjectId(long projectId) {
this.projectId=projectId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDeveloperName() {
return developerName;
}
public void setDeveloperName(String developerName) {
this.developerName = developerName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getCreationDate() {
return this.creationDate;
}
public void setCreationDate(long creationDate) {
this.creationDate = creationDate;
}
public long getUpdateDate() {
return this.updateDate;
}
public void setUpdateDate(long updateDate) {
this.updateDate = updateDate;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public int getDownloads() {
return downloads;
}
public void setDownloads(int downloads) {
this.downloads = downloads;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public int getComments() {
return comments;
}
public void setComments(int comments) {
this.comments = comments;
}
public void setImageBlobId(String imageBlobId) {
this.imageBlobId = imageBlobId;
}
public String getImageBlobId() {
return this.imageBlobId;
}
public void setSourceBlobId(String sourceBlobId) {
this.sourceBlobId = sourceBlobId;
}
public String getSourceBlobId() {
return this.sourceBlobId;
}
public void setGalleryAppId(String galleryAppId) {
this.galleryAppId = galleryAppId;
}
public String getGalleryAppId() {
return this.galleryAppId;
}
// url is of form:
// gallery.appinventor.mit.edu/rpc?getblob=<sourceBlob>:<appid>
public String getSourceURL() {
return GALLERYURL+"getblob="+getSourceBlobId()+":"+getGalleryAppId();
}
public ArrayList<String> getTags() {
return this.tags;
}
public void setTags(ArrayList<String> tags) {
this.tags = tags;
}
@Override
public String toString() {
return title + " ||| " + description + " ||| " + imageURL;
}
}
|
package edu.jhu.hlt.rebar.ballast.tools;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import edu.jhu.hlt.concrete.Communication;
import edu.jhu.hlt.concrete.SentenceSegmentation;
import edu.jhu.hlt.concrete.SituationMention;
import edu.jhu.hlt.concrete.SituationMentionSet;
import edu.jhu.hlt.concrete.util.ConcreteException;
import edu.jhu.hlt.concrete.util.SuperCommunication;
import edu.jhu.hlt.rebar.ballast.AnnotationException;
/**
* @author max
*
*/
public class BasicSituationTaggerTest {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
/**
* Test method for {@link edu.jhu.hlt.rebar.ballast.tools.BasicSituationTagger#annotate(edu.jhu.hlt.concrete.Communication)}.
* @throws IOException
* @throws TException
* @throws ConcreteException
* @throws AnnotationException
*/
@Test
public void testAnnotate() throws IOException, TException, ConcreteException, AnnotationException {
Communication c = new Communication();
byte[] bytes = Files.readAllBytes(Paths.get("src/test/resources" + File.separator + "130596359.concrete"));
new TDeserializer(new TBinaryProtocol.Factory()).deserialize(c, bytes);
SuperCommunication sc = new SuperCommunication(c);
SentenceSegmentation firstSentSeg = sc.firstSentenceSegmentation();
String idOne = firstSentSeg.getSentenceList().get(0).getTokenizationList().get(0).getUuid();
String idTwo = firstSentSeg.getSentenceList().get(1).getTokenizationList().get(0).getUuid();
SituationMentionSet ems = new BasicSituationTagger().annotate(c);
List<SituationMention> emList = ems.getMentionList();
assertEquals(2, emList.size());
SituationMention first = emList.get(0);
assertEquals(idOne, first.getTokens().getTokenizationId());
assertEquals(Integer.valueOf(3), first.getTokens().getTokenIndexList().get(0));
SituationMention second = emList.get(1);
assertEquals(idTwo, second.getTokens().getTokenizationId());
}
}
|
package org.wildfly.clustering.server.group;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.infinispan.Cache;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.notifications.cachelistener.annotation.TopologyChanged;
import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent;
import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged;
import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent;
import org.infinispan.remoting.transport.Address;
import org.wildfly.clustering.group.Group;
import org.wildfly.clustering.group.Node;
/**
* {@link Group} implementation based on the topology of a cache.
* @author Paul Ferraro
*/
@org.infinispan.notifications.Listener(sync = false)
public class CacheGroup implements Group, AutoCloseable {
private final List<Listener> listeners = new CopyOnWriteArrayList<>();
private final Cache<?, ?> cache;
private final InfinispanNodeFactory factory;
private final SortedMap<Integer, Boolean> views = Collections.synchronizedSortedMap(new TreeMap<>());
public CacheGroup(CacheGroupConfiguration config) {
this.cache = config.getCache();
this.factory = config.getNodeFactory();
this.cache.getCacheManager().addListener(this);
this.cache.addListener(this);
}
@Override
public void close() {
this.cache.removeListener(this);
this.cache.getCacheManager().removeListener(this);
}
@Override
public String getName() {
return this.cache.getCacheManager().getClusterName();
}
@Override
public boolean isCoordinator() {
return this.cache.getCacheManager().getAddress().equals(this.getCoordinator());
}
@Override
public Node getLocalNode() {
return this.factory.createNode(this.cache.getCacheManager().getAddress());
}
@Override
public Node getCoordinatorNode() {
return this.factory.createNode(this.getCoordinator());
}
private Address getCoordinator() {
DistributionManager dist = this.cache.getAdvancedCache().getDistributionManager();
return (dist != null) ? dist.getConsistentHash().getMembers().get(0) : this.cache.getCacheManager().getCoordinator();
}
@Override
public List<Node> getNodes() {
List<Address> addresses = this.getAddresses();
List<Node> nodes = new ArrayList<>(addresses.size());
for (Address address: addresses) {
nodes.add(this.factory.createNode(address));
}
return nodes;
}
@ViewChanged
public void viewChanged(ViewChangedEvent event) {
// Record view status for use by @TopologyChanged event
this.views.put(event.getViewId(), event.isMergeView());
}
@TopologyChanged
public void topologyChanged(TopologyChangedEvent<?, ?> event) {
if (event.isPre()) return;
List<Address> oldAddresses = event.getConsistentHashAtStart().getMembers();
List<Node> oldNodes = this.getNodes(oldAddresses);
List<Address> newAddresses = event.getConsistentHashAtEnd().getMembers();
List<Node> newNodes = this.getNodes(newAddresses);
Set<Address> obsolete = new HashSet<>(oldAddresses);
obsolete.removeAll(newAddresses);
this.factory.invalidate(obsolete);
int viewId = event.getCache().getCacheManager().getTransport().getViewId();
Boolean status = this.views.get(viewId);
boolean merged = (status != null) ? status.booleanValue() : false;
for (Listener listener: this.listeners) {
listener.membershipChanged(oldNodes, newNodes, merged);
}
// Purge obsolete views
this.views.headMap(viewId).clear();
}
private List<Node> getNodes(List<Address> addresses) {
List<Node> nodes = new ArrayList<>(addresses.size());
for (Address address: addresses) {
nodes.add(this.factory.createNode(address));
}
return nodes;
}
@Override
public void addListener(Listener listener) {
this.listeners.add(listener);
}
@Override
public void removeListener(Listener listener) {
this.listeners.remove(listener);
}
private List<Address> getAddresses() {
DistributionManager dist = this.cache.getAdvancedCache().getDistributionManager();
return (dist != null) ? dist.getConsistentHash().getMembers() : this.cache.getCacheManager().getMembers();
}
}
|
package org.neo4j.kernel.impl.api.index;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.schema.IndexDefinition;
import org.neo4j.graphdb.schema.Schema;
import org.neo4j.kernel.GraphDatabaseAPI;
import org.neo4j.kernel.ThreadToStatementContextBridge;
import org.neo4j.kernel.api.Statement;
import org.neo4j.kernel.api.index.IndexAccessor;
import org.neo4j.kernel.api.index.IndexConfiguration;
import org.neo4j.kernel.api.index.IndexPopulator;
import org.neo4j.kernel.api.index.InternalIndexState;
import org.neo4j.kernel.api.index.NodePropertyUpdate;
import org.neo4j.kernel.api.index.SchemaIndexProvider;
import org.neo4j.kernel.extension.KernelExtensionFactory;
import org.neo4j.kernel.impl.transaction.XaDataSourceManager;
import org.neo4j.test.EphemeralFileSystemRule;
import org.neo4j.test.TestGraphDatabaseFactory;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.neo4j.graphdb.DynamicLabel.label;
import static org.neo4j.graphdb.Neo4jMatchers.getIndexes;
import static org.neo4j.graphdb.Neo4jMatchers.hasSize;
import static org.neo4j.graphdb.Neo4jMatchers.haveState;
import static org.neo4j.graphdb.Neo4jMatchers.inTx;
import static org.neo4j.helpers.collection.IteratorUtil.asCollection;
import static org.neo4j.kernel.impl.api.index.SchemaIndexTestHelper.singleInstanceSchemaIndexProviderFactory;
public class IndexRecoveryIT
{
@Test
public void shouldBeAbleToRecoverInTheMiddleOfPopulatingAnIndex() throws Exception
{
// Given
startDb();
CountDownLatch latch = new CountDownLatch( 1 );
when( mockedIndexProvider.getPopulator( anyLong(), any( IndexConfiguration.class ) ) )
.thenReturn( indexPopulatorWithControlledCompletionTiming( latch ) );
createIndex( myLabel );
// And Given
Future<Void> killFuture = killDbInSeparateThread();
latch.countDown();
killFuture.get();
// When
when( mockedIndexProvider.getInitialState( anyLong() ) ).thenReturn( InternalIndexState.POPULATING );
latch = new CountDownLatch( 1 );
when( mockedIndexProvider.getPopulator( anyLong(), any( IndexConfiguration.class ) ) )
.thenReturn( indexPopulatorWithControlledCompletionTiming( latch ) );
startDb();
// Then
assertThat( getIndexes( db, myLabel ), inTx( db, hasSize( 1 ) ) );
assertThat( getIndexes( db, myLabel ), inTx( db, haveState( db, Schema.IndexState.POPULATING ) ) );
verify( mockedIndexProvider, times( 2 ) ).getPopulator( anyLong(), any( IndexConfiguration.class ) );
verify( mockedIndexProvider, times( 0 ) ).getOnlineAccessor( anyLong(), any( IndexConfiguration.class ) );
latch.countDown();
}
@Test
public void shouldBeAbleToRecoverInTheMiddleOfPopulatingAnIndexWhereLogHasRotated() throws Exception
{
// Given
startDb();
CountDownLatch latch = new CountDownLatch( 1 );
when( mockedIndexProvider.getPopulator( anyLong(), any( IndexConfiguration.class ) ) )
.thenReturn( indexPopulatorWithControlledCompletionTiming( latch ) );
createIndex( myLabel );
rotateLogs();
// And Given
Future<Void> killFuture = killDbInSeparateThread();
latch.countDown();
killFuture.get();
latch = new CountDownLatch( 1 );
when( mockedIndexProvider.getPopulator( anyLong(), any( IndexConfiguration.class ) ) )
.thenReturn( indexPopulatorWithControlledCompletionTiming( latch ) );
when( mockedIndexProvider.getInitialState( anyLong() ) ).thenReturn( InternalIndexState.POPULATING );
// When
startDb();
// Then
assertThat( getIndexes( db, myLabel ), inTx( db, hasSize( 1 ) ) );
assertThat( getIndexes( db, myLabel ), inTx( db, haveState( db, Schema.IndexState.POPULATING ) ) );
verify( mockedIndexProvider, times( 2 ) ).getPopulator( anyLong(), any( IndexConfiguration.class ) );
verify( mockedIndexProvider, times( 0 ) ).getOnlineAccessor( anyLong(), any( IndexConfiguration.class ) );
latch.countDown();
}
@Test
public void shouldBeAbleToRecoverAndUpdateOnlineIndex() throws Exception
{
// Given
startDb();
when( mockedIndexProvider.getPopulator( anyLong(), any( IndexConfiguration.class ) ) )
.thenReturn( mock( IndexPopulator.class ) );
when( mockedIndexProvider.getOnlineAccessor( anyLong(), any( IndexConfiguration.class ) ) )
.thenReturn( mock( IndexAccessor.class ) );
createIndexAndAwaitPopulation( myLabel );
Set<NodePropertyUpdate> expectedUpdates = createSomeBananas( myLabel );
// And Given
killDb();
when( mockedIndexProvider.getInitialState( anyLong() ) ).thenReturn( InternalIndexState.ONLINE );
GatheringIndexWriter writer = new GatheringIndexWriter();
when( mockedIndexProvider.getOnlineAccessor( anyLong(), any( IndexConfiguration.class ) ) )
.thenReturn( writer );
// When
startDb();
// Then
assertThat( getIndexes( db, myLabel ), inTx( db, hasSize( 1 ) ) );
assertThat( getIndexes( db, myLabel ), inTx( db, haveState( db, Schema.IndexState.ONLINE ) ) );
verify( mockedIndexProvider, times( 1 ) ).getPopulator( anyLong(), any( IndexConfiguration.class ) );
int onlineAccessorInvocationCount = 2; // once when we create the index, and once when we restart the db
verify( mockedIndexProvider, times( onlineAccessorInvocationCount ) )
.getOnlineAccessor( anyLong(), any( IndexConfiguration.class ) );
assertEquals( expectedUpdates, writer.recoveredUpdates );
}
@Test
public void shouldKeepFailedIndexesAsFailedAfterRestart() throws Exception
{
// Given
when( mockedIndexProvider.getPopulator( anyLong(), any( IndexConfiguration.class ) ) )
.thenReturn( mock( IndexPopulator.class ) );
when( mockedIndexProvider.getOnlineAccessor( anyLong(), any( IndexConfiguration.class ) ) )
.thenReturn( mock( IndexAccessor.class ) );
startDb();
createIndex( myLabel );
// And Given
killDb();
when( mockedIndexProvider.getInitialState( anyLong() ) ).thenReturn( InternalIndexState.FAILED );
// When
startDb();
// Then
assertThat( getIndexes( db, myLabel ), inTx( db, hasSize( 1 ) ) );
assertThat( getIndexes( db, myLabel ), inTx( db, haveState( db, Schema.IndexState.FAILED ) ) );
verify( mockedIndexProvider, times( 2 ) ).getPopulator( anyLong(), any( IndexConfiguration.class ) );
}
private GraphDatabaseAPI db;
@Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule();
private final SchemaIndexProvider mockedIndexProvider = mock( SchemaIndexProvider.class );
private final KernelExtensionFactory<?> mockedIndexProviderFactory =
singleInstanceSchemaIndexProviderFactory( TestSchemaIndexProviderDescriptor.PROVIDER_DESCRIPTOR.getKey(),
mockedIndexProvider );
private final String key = "number_of_bananas_owned";
private final Label myLabel = label( "MyLabel" );
@Before
public void setUp()
{
when( mockedIndexProvider.getProviderDescriptor() )
.thenReturn( TestSchemaIndexProviderDescriptor.PROVIDER_DESCRIPTOR );
when( mockedIndexProvider.compareTo( any( SchemaIndexProvider.class ) ) )
.thenReturn( 1 ); // always pretend to have highest priority
}
private void startDb()
{
if ( db != null )
{
db.shutdown();
}
TestGraphDatabaseFactory factory = new TestGraphDatabaseFactory();
factory.setFileSystem( fs.get() );
factory.addKernelExtensions( Arrays.<KernelExtensionFactory<?>>asList( mockedIndexProviderFactory ) );
db = (GraphDatabaseAPI) factory.newImpermanentDatabase();
}
private void killDb()
{
if ( db != null )
{
fs.snapshot( new Runnable()
{
@Override
public void run()
{
db.shutdown();
db = null;
}
} );
}
}
private Future<Void> killDbInSeparateThread()
{
ExecutorService executor = newSingleThreadExecutor();
Future<Void> result = executor.submit( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
killDb();
return null;
}
} );
executor.shutdown();
return result;
}
@After
public void after()
{
if ( db != null )
{
db.shutdown();
}
}
private void rotateLogs()
{
db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).rotateLogicalLogs();
}
private void createIndexAndAwaitPopulation( Label label )
{
IndexDefinition index = createIndex( label );
try ( Transaction tx = db.beginTx() )
{
db.schema().awaitIndexOnline( index, 10, SECONDS );
tx.success();
}
}
private IndexDefinition createIndex( Label label )
{
try ( Transaction tx = db.beginTx() )
{
IndexDefinition index = db.schema().indexFor( label ).on( key ).create();
tx.success();
return index;
}
}
private Set<NodePropertyUpdate> createSomeBananas( Label label )
{
Set<NodePropertyUpdate> updates = new HashSet<>();
try ( Transaction tx = db.beginTx() )
{
ThreadToStatementContextBridge ctxProvider = db.getDependencyResolver().resolveDependency(
ThreadToStatementContextBridge.class );
try ( Statement statement = ctxProvider.statement() )
{
for ( int number : new int[] {4, 10} )
{
Node node = db.createNode( label );
node.setProperty( key, number );
updates.add( NodePropertyUpdate.add( node.getId(),
statement.readOperations().propertyKeyGetForName( key ), number,
new long[]{statement.readOperations().labelGetForName( label.name() )} ) );
}
}
tx.success();
return updates;
}
}
private static class GatheringIndexWriter extends IndexAccessor.Adapter
{
private final Set<NodePropertyUpdate> updates = new HashSet<>();
private final Set<NodePropertyUpdate> recoveredUpdates = new HashSet<>();
@Override
public void updateAndCommit( Iterable<NodePropertyUpdate> updates )
{
this.updates.addAll( asCollection( updates ) );
}
@Override
public void recover( Iterable<NodePropertyUpdate> updates ) throws IOException
{
this.recoveredUpdates.addAll( asCollection( updates ) );
}
}
private IndexPopulator indexPopulatorWithControlledCompletionTiming( final CountDownLatch latch )
{
return new IndexPopulator.Adapter()
{
@Override
public void create()
{
try
{
latch.await();
}
catch ( InterruptedException e )
{
// fall through and return early
}
throw new RuntimeException( "this is expected" );
}
};
}
}
|
package com.yahoo.container.jdisc.component;
import com.yahoo.component.AbstractComponent;
import com.yahoo.component.Deconstructable;
import com.yahoo.concurrent.ThreadFactoryFactory;
import com.yahoo.container.di.ComponentDeconstructor;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.jdisc.SharedResource;
import com.yahoo.yolean.UncheckedInterruptedException;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.INFO;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Level.WARNING;
/**
* @author Tony Vaagenes
* @author gv
*/
public class Deconstructor implements ComponentDeconstructor {
private static final Logger log = Logger.getLogger(Deconstructor.class.getName());
private final ExecutorService executor =
Executors.newFixedThreadPool(1, ThreadFactoryFactory.getThreadFactory("component-deconstructor"));
// This must be smaller than the shutdownDeadlineExecutor delay in ConfiguredApplication
private final Duration shutdownTimeout;
public Deconstructor(Duration shutdownTimeout) {
this.shutdownTimeout = shutdownTimeout;
}
public Deconstructor() { this(Duration.ofSeconds(45)); }
@Override
public void deconstruct(long generation, List<Object> components, Collection<Bundle> bundles) {
Collection<Deconstructable> destructibleComponents = new ArrayList<>();
for (var component : components) {
if (component instanceof AbstractComponent) {
AbstractComponent abstractComponent = (AbstractComponent) component;
if (abstractComponent.isDeconstructable()) {
destructibleComponents.add(abstractComponent);
}
} else if (component instanceof Provider) {
destructibleComponents.add((Deconstructable) component);
} else if (component instanceof SharedResource) {
// Release shared resources in same order as other components in case of usage without reference counting
destructibleComponents.add(new SharedResourceReleaser(component));
}
}
if (!destructibleComponents.isEmpty() || !bundles.isEmpty()) {
executor.execute(new DestructComponentTask(generation, destructibleComponents, bundles));
}
}
@Override
public void shutdown() {
executor.shutdown();
try {
log.info("Waiting up to " + shutdownTimeout.toSeconds() + " seconds for all previous components graphs to deconstruct.");
if (!executor.awaitTermination(shutdownTimeout.getSeconds(), TimeUnit.SECONDS)) {
log.warning("Waiting for deconstruction timed out.");
}
} catch (InterruptedException e) {
log.info("Interrupted while waiting for component deconstruction to finish.");
throw new UncheckedInterruptedException(e, true);
}
}
private static class SharedResourceReleaser implements Deconstructable {
final SharedResource resource;
private SharedResourceReleaser(Object resource) { this.resource = (SharedResource) resource; }
@Override public void deconstruct() { resource.release(); }
}
private static class DestructComponentTask implements Runnable {
private final Random random = new Random(System.nanoTime());
private final long generation;
private final Collection<Deconstructable> components;
private final Collection<Bundle> bundles;
DestructComponentTask(long generation, Collection<Deconstructable> components, Collection<Bundle> bundles) {
this.generation = generation;
this.components = components;
this.bundles = bundles;
}
/**
* Returns a random delay between 0 and 10 minutes which will be different across identical containers invoking this at the same time.
* Used to randomize restart to avoid simultaneous cluster restarts.
*/
private Duration getRandomizedShutdownDelay() {
long seconds = (long) (random.nextDouble() * 60 * 10);
return Duration.ofSeconds(seconds);
}
@Override
public void run() {
long start = System.currentTimeMillis();
log.info(String.format("Starting deconstruction of %d old components from graph generation %d",
components.size(), generation));
for (var component : components) {
log.log(FINE, () -> "Starting deconstruction of " + component);
try {
component.deconstruct();
log.log(FINE, () -> "Finished deconstructing of " + component);
} catch (Exception | NoClassDefFoundError e) { // May get class not found due to it being already unloaded
log.log(WARNING, "Exception thrown when deconstructing component " + component, e);
} catch (Error e) {
try {
Duration shutdownDelay = getRandomizedShutdownDelay();
log.log(Level.SEVERE, "Error when deconstructing component " + component + ". Will sleep for " +
shutdownDelay.getSeconds() + " seconds then restart", e);
Thread.sleep(shutdownDelay.toMillis());
} catch (InterruptedException exception) {
log.log(WARNING, "Randomized wait before dying disrupted. Dying now.");
}
com.yahoo.protect.Process.logAndDie("Shutting down due to error when deconstructing component " + component);
} catch (Throwable e) {
log.log(WARNING, "Non-error not exception throwable thrown when deconstructing component " + component, e);
}
}
log.info(String.format("Completed deconstruction in %.3f seconds", (System.currentTimeMillis() - start) / 1000D));
// It should now be safe to uninstall the old bundles.
for (var bundle : bundles) {
try {
log.log(INFO, "Uninstalling bundle " + bundle);
bundle.uninstall();
} catch (BundleException e) {
log.log(SEVERE, "Could not uninstall bundle " + bundle);
}
}
// NOTE: It could be tempting to refresh packages here, but if active bundles were using any of
// the removed ones, they would switch wiring in the middle of a generation's lifespan.
// This would happen if the dependent active bundle has not been rebuilt with a new version
// of its dependency(ies).
}
}
}
|
package com.yahoo.vespa.hosted.controller.api.role;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.TenantName;
import java.net.URI;
import java.util.Set;
/**
* Policies for REST APIs in the controller. A policy is only considered when defined in a {@link Role}.
*
* - A policy describes a set of {@link Privilege}s, which are valid for a set of {@link SystemName}s.
* - A policy is evaluated by an {@link Enforcer}, which holds the {@link SystemName} the evaluation is done in.
* - A policy is evaluated in a {@link Context}, which may limit it to a specific {@link TenantName} or
* {@link ApplicationName}.
*
* @author mpolden
*/
enum Policy {
/** Full access to everything. */
operator(Privilege.grant(Action.all())
.on(PathGroup.allExcept(PathGroup.operatorRestrictedPaths()))
.in(SystemName.all()),
Privilege.grant(Action.read)
.on(PathGroup.billingPathsNoToken())
.in(SystemName.all()),
Privilege.grant(Action.read)
.on(PathGroup.billingToken)
.in(SystemName.PublicCd)),
/** Full access to everything. */
supporter(Privilege.grant(Action.read)
.on(PathGroup.all())
.in(SystemName.all())),
/** Full access to user management for a tenant in select systems. */
tenantManager(Privilege.grant(Action.all())
.on(PathGroup.tenantUsers)
.in(SystemName.all())),
/** Full access to user management for an application in select systems. */
applicationManager(Privilege.grant(Action.all())
.on(PathGroup.applicationUsers)
.in(SystemName.all())),
/** Access to create a user tenant in select systems. */
user(Privilege.grant(Action.create, Action.update)
.on(PathGroup.user)
.in(SystemName.main, SystemName.cd)),
/** Access to create a tenant. */
tenantCreate(Privilege.grant(Action.create)
.on(PathGroup.tenant)
.in(SystemName.all())),
/** Full access to tenant information and settings. */
tenantDelete(Privilege.grant(Action.delete)
.on(PathGroup.tenant)
.in(SystemName.all())),
/** Full access to tenant information and settings. */
tenantUpdate(Privilege.grant(Action.update)
.on(PathGroup.tenantInfo)
.on(PathGroup.tenant)
.in(SystemName.all())),
/** Read access to tenant information and settings. */
tenantRead(Privilege.grant(Action.read)
.on(PathGroup.tenant, PathGroup.tenantInfo, PathGroup.tenantUsers, PathGroup.applicationUsers)
.in(SystemName.all())),
/** Access to set and unset archive access role under a tenant. */
tenantArchiveAccessManagement(Privilege.grant(Action.update, Action.delete)
.on(PathGroup.tenantArchiveAccess)
.in(SystemName.all())),
/** Access to create application under a certain tenant. */
applicationCreate(Privilege.grant(Action.create)
.on(PathGroup.application)
.in(SystemName.all())),
/** Read access to application information and settings. */
applicationRead(Privilege.grant(Action.read)
.on(PathGroup.application, PathGroup.applicationInfo, PathGroup.reindexing, PathGroup.serviceDump)
.in(SystemName.all())),
/** Read access to application information and settings. */
applicationUpdate(Privilege.grant(Action.update)
.on(PathGroup.application, PathGroup.applicationInfo)
.in(SystemName.all())),
/** Access to delete a certain application. */
applicationDelete(Privilege.grant(Action.delete)
.on(PathGroup.application)
.in(SystemName.all())),
/** Full access to application information and settings. */
applicationOperations(Privilege.grant(Action.write())
.on(PathGroup.applicationInfo, PathGroup.productionRestart, PathGroup.reindexing, PathGroup.serviceDump)
.in(SystemName.all())),
/** Access to create and delete developer and deploy keys under a tenant. */
keyManagement(Privilege.grant(Action.write())
.on(PathGroup.tenantKeys, PathGroup.applicationKeys)
.in(SystemName.all())),
/** Access to revoke keys from the tenant */
keyRevokal(Privilege.grant(Action.delete)
.on(PathGroup.tenantKeys, PathGroup.applicationKeys)
.in(SystemName.all())),
/** Full access to application development deployments. */
developmentDeployment(Privilege.grant(Action.all())
.on(PathGroup.developmentDeployment, PathGroup.developmentRestart)
.in(SystemName.all())),
/** Read access to all application deployments. */
deploymentRead(Privilege.grant(Action.read)
.on(PathGroup.developmentDeployment, PathGroup.productionDeployment)
.in(SystemName.all())),
/** Full access to submissions for continuous deployment. */
submission(Privilege.grant(Action.all())
.on(PathGroup.submission)
.in(SystemName.all())),
/** Read access to all information in select systems. */
classifiedRead(Privilege.grant(Action.read)
.on(PathGroup.allExcept(PathGroup.classifiedOperator))
.in(SystemName.main, SystemName.cd)),
/** Read access to public info. */
publicRead(Privilege.grant(Action.read)
.on(PathGroup.publicInfo)
.in(SystemName.all())),
/** Access to /system-flags/v1/deploy. */
systemFlagsDeploy(Privilege.grant(Action.update)
.on(PathGroup.systemFlagsDeploy)
.in(SystemName.all())),
/** Access to /system-flags/v1/dryrun. */
systemFlagsDryrun(Privilege.grant(Action.update)
.on(PathGroup.systemFlagsDryrun)
.in(SystemName.all())),
/** Access to /payment/notification */
paymentProcessor(Privilege.grant(Action.create)
.on(PathGroup.paymentProcessor)
.in(SystemName.PublicCd)),
/** Read your own instrument information */
paymentInstrumentRead(Privilege.grant(Action.read)
.on(PathGroup.billingInstrument)
.in(SystemName.PublicCd, SystemName.Public)),
/** Ability to update tenant payment instrument */
paymentInstrumentUpdate(Privilege.grant(Action.update)
.on(PathGroup.billingInstrument)
.in(SystemName.PublicCd, SystemName.Public)),
/** Ability to remove your own payment instrument */
paymentInstrumentDelete(Privilege.grant(Action.delete)
.on(PathGroup.billingInstrument)
.in(SystemName.PublicCd, SystemName.Public)),
/** Get the token to view instrument form */
paymentInstrumentCreate(Privilege.grant(Action.read)
.on(PathGroup.billingToken)
.in(SystemName.PublicCd, SystemName.Public)),
/** Ability to update tenant payment instrument */
planUpdate(Privilege.grant(Action.update)
.on(PathGroup.billingPlan, PathGroup.billing)
.in(SystemName.PublicCd, SystemName.Public)),
/** Ability to update tenant collection method */
collectionMethodUpdate(Privilege.grant(Action.update)
.on(PathGroup.billingCollection)
.in(SystemName.PublicCd, SystemName.Public)),
/** Read the generated bills */
billingInformationRead(Privilege.grant(Action.read)
.on(PathGroup.billingList, PathGroup.billing)
.in(SystemName.PublicCd, SystemName.Public)),
accessRequests(Privilege.grant(Action.all())
.on(PathGroup.accessRequests, PathGroup.accessRequestApproval)
.in(SystemName.PublicCd, SystemName.Public)),
/** Invoice management */
hostedAccountant(Privilege.grant(Action.all())
.on(PathGroup.hostedAccountant, PathGroup.accountant)
.in(SystemName.PublicCd, SystemName.Public)),
/** Listing endpoint certificate request info */
endpointCertificateRequestInfo(Privilege.grant(Action.read)
.on(PathGroup.endpointCertificateRequestInfo)
.in(SystemName.all())),
/** Secret store operations */
secretStoreOperations(Privilege.grant(Action.all())
.on(PathGroup.secretStore)
.in(SystemName.PublicCd, SystemName.Public)),
horizonProxyOperations(Privilege.grant(Action.all())
.on(PathGroup.horizonProxy)
.in(SystemName.PublicCd, SystemName.Public));
private final Set<Privilege> privileges;
Policy(Privilege... privileges) {
this.privileges = Set.of(privileges);
}
/** Returns whether action is allowed on path in given context */
boolean evaluate(Action action, URI uri, Context context, SystemName system) {
return privileges.stream().anyMatch(privilege -> privilege.actions().contains(action) &&
privilege.systems().contains(system) &&
privilege.pathGroups().stream()
.anyMatch(pg -> pg.matches(uri, context)));
}
}
|
package alluxio.worker.block.allocator;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.worker.WorkerContext;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.Reflection;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This is the class to test the "contract" of different kinds of allocators,
* i.e., the general properties the allocators need to follow.
*/
public class AllocatorContractTest extends BaseAllocatorTest {
protected List<String> mStrategies;
/**
* Try to find all implementation classes of {@link Allocator} in the same package.
*
* @throws Exception if setting up the dependencies fails
*/
@Before
@Override
public void before() throws Exception {
super.before();
mStrategies = new ArrayList<>();
try {
String packageName = Reflection.getPackageName(Allocator.class);
ClassPath path = ClassPath.from(Thread.currentThread().getContextClassLoader());
List<ClassPath.ClassInfo> clazzInPackage =
new ArrayList<>(path.getTopLevelClassesRecursive(packageName));
for (ClassPath.ClassInfo clazz : clazzInPackage) {
Set<Class<?>> interfaces =
new HashSet<>(Arrays.asList(clazz.load().getInterfaces()));
if (interfaces.size() > 0 && interfaces.contains(Allocator.class)) {
mStrategies.add(clazz.getName());
}
}
} catch (Exception e) {
Assert.fail("Failed to find implementation of allocate strategy");
}
}
/**
* Tests that no allocation happens when the RAM, SSD and HDD size is more than the default one.
*
* @throws Exception if a block cannot be allocated
*/
@Test
public void shouldNotAllocateTest() throws Exception {
Configuration conf = WorkerContext.getConf();
for (String strategyName : mStrategies) {
conf.set(Constants.WORKER_ALLOCATOR_CLASS, strategyName);
resetManagerView();
Allocator allocator = Allocator.Factory.create(conf, getManagerView());
assertTempBlockMeta(allocator, mAnyDirInTierLoc1, DEFAULT_RAM_SIZE + 1, false);
assertTempBlockMeta(allocator, mAnyDirInTierLoc2, DEFAULT_SSD_SIZE + 1, false);
assertTempBlockMeta(allocator, mAnyDirInTierLoc3, DEFAULT_HDD_SIZE + 1, false);
assertTempBlockMeta(allocator, mAnyTierLoc, DEFAULT_HDD_SIZE + 1, false);
assertTempBlockMeta(allocator, mAnyTierLoc, DEFAULT_SSD_SIZE + 1, true);
}
}
/**
* Tests that allocation happens when the RAM, SSD and HDD size is lower than the default size.
*
* @throws Exception if a block cannot be allocated
*/
@Test
public void shouldAllocateTest() throws Exception {
Configuration conf = WorkerContext.getConf();
for (String strategyName : mStrategies) {
conf.set(Constants.WORKER_ALLOCATOR_CLASS, strategyName);
resetManagerView();
Allocator tierAllocator = Allocator.Factory.create(conf, getManagerView());
for (int i = 0; i < DEFAULT_RAM_NUM; i++) {
assertTempBlockMeta(tierAllocator, mAnyDirInTierLoc1, DEFAULT_RAM_SIZE - 1, true);
}
for (int i = 0; i < DEFAULT_SSD_NUM; i++) {
assertTempBlockMeta(tierAllocator, mAnyDirInTierLoc2, DEFAULT_SSD_SIZE - 1, true);
}
for (int i = 0; i < DEFAULT_HDD_NUM; i++) {
assertTempBlockMeta(tierAllocator, mAnyDirInTierLoc3, DEFAULT_HDD_SIZE - 1, true);
}
resetManagerView();
Allocator anyAllocator = Allocator.Factory.create(conf, getManagerView());
for (int i = 0; i < DEFAULT_RAM_NUM; i++) {
assertTempBlockMeta(anyAllocator, mAnyTierLoc, DEFAULT_RAM_SIZE - 1, true);
}
for (int i = 0; i < DEFAULT_SSD_NUM; i++) {
assertTempBlockMeta(anyAllocator, mAnyTierLoc, DEFAULT_SSD_SIZE - 1, true);
}
for (int i = 0; i < DEFAULT_HDD_NUM; i++) {
assertTempBlockMeta(anyAllocator, mAnyTierLoc, DEFAULT_HDD_SIZE - 1, true);
}
}
}
}
|
package org.togglz.core.repository.cache;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.togglz.core.Feature;
import org.togglz.core.repository.FeatureState;
import org.togglz.core.repository.StateRepository;
import org.togglz.core.util.NamedFeature;
/**
*
* Unit test for {@link CachingStateRepository}.
*
* @author Christian Kaltepoth
*
*/
public class CachingStateRepositoryTest {
private StateRepository delegate;
@Before
public void setup() {
delegate = Mockito.mock(StateRepository.class);
// the mock supports the ENUM
Mockito.when(delegate.getFeatureState(DummyFeature.TEST))
.thenReturn(new FeatureState(DummyFeature.TEST, true));
// and NamedFeature
Mockito.when(delegate.getFeatureState(new NamedFeature("TEST")))
.thenReturn(new FeatureState(DummyFeature.TEST, true));
}
public void tearDown() {
delegate = null;
}
@Test
public void testCachingOfReadOperationsWithTimeToLife() throws InterruptedException {
StateRepository repository = new CachingStateRepository(delegate, 10000);
// do some lookups
for (int i = 0; i < 10; i++) {
assertTrue(repository.getFeatureState(DummyFeature.TEST).isEnabled());
Thread.sleep(10);
}
// delegate only called once
Mockito.verify(delegate).getFeatureState(DummyFeature.TEST);
Mockito.verifyNoMoreInteractions(delegate);
}
@Test
public void testCacheWithDifferentFeatureImplementations() throws InterruptedException {
StateRepository repository = new CachingStateRepository(delegate, 0);
// do some lookups
for (int i = 0; i < 10; i++) {
Feature feature = (i % 2 == 0) ? DummyFeature.TEST :
new NamedFeature(DummyFeature.TEST.name());
assertTrue(repository.getFeatureState(feature).isEnabled());
Thread.sleep(10);
}
// delegate only called once
Mockito.verify(delegate).getFeatureState(DummyFeature.TEST);
Mockito.verifyNoMoreInteractions(delegate);
}
@Test
public void testCachingOfReadOperationsWithoutTimeToLife() throws InterruptedException {
StateRepository repository = new CachingStateRepository(delegate, 0);
// do some lookups
for (int i = 0; i < 10; i++) {
assertTrue(repository.getFeatureState(DummyFeature.TEST).isEnabled());
Thread.sleep(10);
}
// delegate only called once
Mockito.verify(delegate).getFeatureState(DummyFeature.TEST);
Mockito.verifyNoMoreInteractions(delegate);
}
@Test
public void testCacheExpiryBecauseOfTimeToLife() throws InterruptedException {
long ttl = 5;
StateRepository repository = new CachingStateRepository(delegate, ttl);
// do some lookups
for (int i = 0; i < 5; i++) {
assertTrue(repository.getFeatureState(DummyFeature.TEST).isEnabled());
Thread.sleep(ttl + 30); // wait some small amount of time to let the cache expire
}
// delegate called 5 times
Mockito.verify(delegate, Mockito.times(5)).getFeatureState(DummyFeature.TEST);
Mockito.verifyNoMoreInteractions(delegate);
}
@Test
public void testStateModifyExpiresCache() throws InterruptedException {
StateRepository repository = new CachingStateRepository(delegate, 10000);
// do some lookups
for (int i = 0; i < 5; i++) {
assertTrue(repository.getFeatureState(DummyFeature.TEST).isEnabled());
Thread.sleep(10);
}
// now modify the feature state
repository.setFeatureState(new FeatureState(DummyFeature.TEST, true));
// do some lookups
for (int i = 0; i < 5; i++) {
assertTrue(repository.getFeatureState(DummyFeature.TEST).isEnabled());
Thread.sleep(10);
}
// Check for the correct number of invocations
Mockito.verify(delegate, Mockito.times(2)).getFeatureState(DummyFeature.TEST);
Mockito.verify(delegate).setFeatureState(Mockito.any(FeatureState.class));
Mockito.verifyNoMoreInteractions(delegate);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailForNegativeTtl() {
new CachingStateRepository(delegate, -1);
}
private enum DummyFeature implements Feature {
TEST;
}
}
|
package ru.job4j.loop;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;
public class PaintTest {
@Test
public void whenPiramidWithHeightTwoThenStringWithTwoRows() {
Paint paint = new Paint();
String result = paint.piramid(2);
String linesep = System.getProperty("line.separator");
String expected = String.format(" ^ %s^^^%s", linesep, linesep);
assertThat(result, is(expected));
}
@Test
public void whenPiramidWithHeightThreeThenStringWithThreeRows() {
Paint paint = new Paint();
String result = paint.piramid(3);
String linesep = System.getProperty("line.separator");
// String expected = String.format(" ^ %s ^^^ %s^^^^^%s", linesep, linesep, linesep);
String expected = String.format(" ^ %s ^^^ %<s^^^^^%<s", linesep);
assertThat(result, is(expected));
}
}
|
package ru.job4j;
import java.util.*;
public class TwoSameObjects {
public void createTO() {
Calendar calendar = new GregorianCalendar();
UserM user1 = new UserM("Игорь",0, calendar);
UserM user2 = new UserM("Игорь",0, calendar);
Map<UserM,Object> userObjectMap = new HashMap<>();
userObjectMap.put(user1,1);
userObjectMap.put(user2,2);
System.out.print(userObjectMap);
}
}
|
package org.gbif.crawler.pipelines.indexing;
import java.io.IOException;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.gbif.api.model.pipelines.StepRunner;
import org.gbif.api.model.pipelines.StepType;
import org.gbif.api.model.registry.Dataset;
import org.gbif.api.service.registry.DatasetService;
import org.gbif.common.messaging.AbstractMessageCallback;
import org.gbif.common.messaging.api.MessagePublisher;
import org.gbif.common.messaging.api.messages.PipelinesIndexedMessage;
import org.gbif.common.messaging.api.messages.PipelinesInterpretedMessage;
import org.gbif.crawler.pipelines.HdfsUtils;
import org.gbif.crawler.pipelines.PipelineCallback;
import org.gbif.crawler.pipelines.dwca.DwcaToAvroConfiguration;
import org.gbif.pipelines.common.PipelinesVariables.Metrics;
import org.gbif.pipelines.common.PipelinesVariables.Pipeline.Interpretation;
import org.gbif.pipelines.common.PipelinesVariables.Pipeline.Interpretation.RecordType;
import org.gbif.registry.ws.client.pipelines.PipelinesHistoryWsClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.slf4j.MDC.MDCCloseable;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Callback which is called when the {@link PipelinesInterpretedMessage} is received.
* <p>
* The main method is {@link IndexingCallback#handleMessage}
*/
public class IndexingCallback extends AbstractMessageCallback<PipelinesInterpretedMessage> {
private static final Logger LOG = LoggerFactory.getLogger(IndexingCallback.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private final IndexingConfiguration config;
private final MessagePublisher publisher;
private final DatasetService datasetService;
private final CuratorFramework curator;
private final HttpClient httpClient;
private final PipelinesHistoryWsClient historyWsClient;
IndexingCallback(IndexingConfiguration config, MessagePublisher publisher, DatasetService datasetService,
CuratorFramework curator, HttpClient httpClient, PipelinesHistoryWsClient historyWsClient) {
this.curator = checkNotNull(curator, "curator cannot be null");
this.config = checkNotNull(config, "config cannot be null");
this.datasetService = checkNotNull(datasetService, "config cannot be null");
this.publisher = publisher;
this.httpClient = httpClient;
this.historyWsClient = historyWsClient;
}
/**
* Handles a MQ {@link PipelinesInterpretedMessage} message
*/
@Override
public void handleMessage(PipelinesInterpretedMessage message) {
UUID datasetId = message.getDatasetUuid();
Integer attempt = message.getAttempt();
try (MDCCloseable mdc1 = MDC.putCloseable("datasetId", datasetId.toString());
MDCCloseable mdc2 = MDC.putCloseable("attempt", attempt.toString());
MDCCloseable mdc3 = MDC.putCloseable("step", StepType.INTERPRETED_TO_INDEX.name())) {
if (!isMessageCorrect(message)) {
LOG.info("Skip the message, cause the runner is different or it wasn't modified, exit from handler");
return;
}
LOG.info("Message handler began - {}", message);
Set<String> steps = message.getPipelineSteps();
Runnable runnable = createRunnable(message);
// Message callback handler, updates zookeeper info, runs process logic and sends next MQ message
PipelineCallback.create()
.incomingMessage(message)
.outgoingMessage(new PipelinesIndexedMessage(datasetId, attempt, steps))
.curator(curator)
.zkRootElementPath(StepType.INTERPRETED_TO_INDEX.getLabel())
.pipelinesStepName(StepType.INTERPRETED_TO_INDEX)
.publisher(publisher)
.runnable(runnable)
.historyWsClient(historyWsClient)
.build()
.handleMessage();
LOG.info("Message handler ended - {}", message);
}
}
/**
* Only correct messages can be handled, by now is only messages with the same runner as runner in service config
* {@link IndexingConfiguration#processRunner}
*/
private boolean isMessageCorrect(PipelinesInterpretedMessage message) {
if (Strings.isNullOrEmpty(message.getRunner())) {
throw new IllegalArgumentException("Runner can't be null or empty " + message.toString());
}
return config.processRunner.equals(message.getRunner());
}
/**
* Main message processing logic, creates a terminal java process, which runs interpreted-to-index pipeline
*/
private Runnable createRunnable(PipelinesInterpretedMessage message) {
return () -> {
try {
String datasetId = message.getDatasetUuid().toString();
String attempt = Integer.toString(message.getAttempt());
long recordsNumber = getRecordNumber(message);
String indexName = computeIndexName(message, recordsNumber);
int numberOfShards = computeNumberOfShards(indexName, recordsNumber);
ProcessRunnerBuilder builder = ProcessRunnerBuilder.create()
.config(config)
.message(message)
.esIndexName(indexName)
.esAlias(config.indexAlias)
.esShardsNumber(numberOfShards);
if (config.processRunner.equalsIgnoreCase(StepRunner.DISTRIBUTED.name())) {
int sparkExecutorNumbers = computeSparkExecutorNumbers(recordsNumber);
builder.sparkParallelism(computeSparkParallelism(datasetId, attempt))
.sparkExecutorMemory(computeSparkExecutorMemory(sparkExecutorNumbers))
.sparkExecutorNumbers(sparkExecutorNumbers);
}
// Assembles a terminal java process and runs it
int exitValue = builder.build().start().waitFor();
if (exitValue != 0) {
throw new RuntimeException("Process has been finished with exit value - " + exitValue);
} else {
LOG.info("Process has been finished with exit value - {}", exitValue);
}
} catch (InterruptedException | IOException ex) {
LOG.error(ex.getMessage(), ex);
throw new IllegalStateException("Failed indexing on " + message.getDatasetUuid(), ex);
}
};
}
/**
* Computes the number of thread for spark.default.parallelism, top limit is config.sparkParallelismMax
*/
private int computeSparkParallelism(String datasetId, String attempt) throws IOException {
// Chooses a runner type by calculating number of files
String basic = RecordType.BASIC.name().toLowerCase();
String directoryName = Interpretation.DIRECTORY_NAME;
String basicPath = String.join("/", config.repositoryPath, datasetId, attempt, directoryName, basic);
int count = HdfsUtils.getFileCount(basicPath, config.hdfsSiteConfig);
count *= 2; // 2 Times more threads than files
if (count < config.sparkParallelismMin) {
return config.sparkParallelismMin;
}
if (count > config.sparkParallelismMax) {
return config.sparkParallelismMax;
}
return count;
}
/**
* Computes the memory for executor in Gb, where min is config.sparkExecutorMemoryGbMin and
* max is config.sparkExecutorMemoryGbMax
* <p>
* 65_536d is found empirically salt
*/
private String computeSparkExecutorMemory(int sparkExecutorNumbers) {
if (sparkExecutorNumbers < config.sparkExecutorMemoryGbMin) {
return config.sparkExecutorMemoryGbMin + "G";
}
if (sparkExecutorNumbers > config.sparkExecutorMemoryGbMax) {
return config.sparkExecutorMemoryGbMax + "G";
}
return sparkExecutorNumbers + "G";
}
/**
* Computes the numbers of executors, where min is config.sparkExecutorNumbersMin and
* max is config.sparkExecutorNumbersMax
* <p>
* 500_000d is records per executor
*/
private int computeSparkExecutorNumbers(long recordsNumber) {
int sparkExecutorNumbers = (int) Math.ceil(recordsNumber / (config.sparkExecutorCores * config.sparkRecordsPerThread));
if (sparkExecutorNumbers < config.sparkExecutorNumbersMin) {
return config.sparkExecutorNumbersMin;
}
if (sparkExecutorNumbers > config.sparkExecutorNumbersMax) {
return config.sparkExecutorNumbersMax;
}
return sparkExecutorNumbers;
}
/**
* Computes the name for ES index:
* Case 1 - Independent index for datasets where number of records more than config.indexIndepRecord
* Case 2 - Default static index name for datasets where last changed date more than
* config.indexDefStaticDateDurationDd
* Case 3 - Default dynamic index name for all other datasets
*/
private String computeIndexName(PipelinesInterpretedMessage message, long recordsNumber) throws IOException {
String datasetId = message.getDatasetUuid().toString();
String prefix = message.getResetPrefix();
// Independent index for datasets where number of records more than config.indexIndepRecord
String idxName;
if (recordsNumber >= config.indexIndepRecord) {
idxName = datasetId + "_" + message.getAttempt();
idxName = prefix == null ? idxName : idxName + "_" + prefix;
idxName = message.isRepeatAttempt() ? idxName + "_" + Instant.now().toEpochMilli() : idxName;
LOG.info("ES Index name - {}, recordsNumber - {}", idxName, recordsNumber);
return idxName;
}
// Default static index name for datasets where last changed date more than config.indexDefStaticDateDurationDd
Date lastChangedDate = getLastChangedDate(datasetId);
long diffInMillies = Math.abs(new Date().getTime() - lastChangedDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
if (diff >= config.indexDefStaticDateDurationDd) {
String esPr = prefix == null ? config.indexDefStaticPrefixName : config.indexDefStaticPrefixName + "_" + prefix;
idxName = getIndexName(esPr).orElse(esPr + "_" + Instant.now().toEpochMilli());
LOG.info("ES Index name - {}, lastChangedDate - {}, diff days - {}", idxName, lastChangedDate, diff);
return idxName;
}
// Default dynamic index name for all other datasets
String esPr = prefix == null ? config.indexDefDynamicPrefixName : config.indexDefDynamicPrefixName + "_" + prefix;
idxName = getIndexName(esPr).orElse(esPr + "_" + Instant.now().toEpochMilli());
LOG.info("ES Index name - {}, lastChangedDate - {}, diff days - {}", idxName, lastChangedDate, diff);
return idxName;
}
/**
* Computes number of index shards:
* 1) in case of default index -> config.indexDefSize / config.indexRecordsPerShard
* 2) in case of independent index -> recordsNumber / config.indexRecordsPerShard
*/
private int computeNumberOfShards(String indexName, long recordsNumber) {
if (indexName.startsWith(config.indexDefDynamicPrefixName) || indexName.startsWith(config.indexDefStaticPrefixName)) {
return (int) Math.ceil((double) config.indexDefSize / (double) config.indexRecordsPerShard);
}
return (int) Math.ceil((double) recordsNumber / (double) config.indexRecordsPerShard);
}
/**
* Uses Registry to ask the last changed date for a dataset
*/
private Date getLastChangedDate(String datasetId) {
Dataset dataset = datasetService.get(UUID.fromString(datasetId));
return dataset.getModified();
}
/**
* Reads number of records from a archive-to-avro metadata file, verbatim-to-interpreted contains attempted records
* count, which is not accurate enough
*/
private long getRecordNumber(PipelinesInterpretedMessage message) throws IOException {
String datasetId = message.getDatasetUuid().toString();
String attempt = Integer.toString(message.getAttempt());
String metaFileName = new DwcaToAvroConfiguration().metaFileName;
String metaPath = String.join("/", config.repositoryPath, datasetId, attempt, metaFileName);
String recordsNumber = HdfsUtils.getValueByKey(config.hdfsSiteConfig, metaPath, Metrics.ARCHIVE_TO_ER_COUNT);
if (recordsNumber == null || recordsNumber.isEmpty()) {
if (message.getNumberOfRecords() != null) {
return message.getNumberOfRecords();
} else {
throw new IllegalArgumentException(
"Please check archive-to-avro metadata yaml file or message records number, recordsNumber can't be null or empty!");
}
}
return Long.parseLong(recordsNumber);
}
/**
* Returns index name by index prefix where number of records is less than configured
*/
private Optional<String> getIndexName(String prefix) throws IOException {
String url = String.format(config.esIndexCatUrl, prefix);
HttpUriRequest httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
throw new IOException("ES _cat API exception " + response.getStatusLine().getReasonPhrase());
}
List<EsCatIndex> indices = MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<EsCatIndex>>() {});
if (indices.size() != 0 && indices.get(0).getCount() <= config.indexDefNewIfSize) {
return Optional.of(indices.get(0).getName());
}
return Optional.empty();
}
}
|
package de.alpharogroup.crypto.key.reader;
import static org.testng.AssertJUnit.assertEquals;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import org.bouncycastle.util.io.pem.PemObject;
import org.meanbean.test.BeanTestException;
import org.meanbean.test.BeanTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import de.alpharogroup.file.search.PathFinder;
/**
* Test class for the class {@link PemObjectReader}.
*/
public class PemObjectReaderTest
{
/** The LOGGER. */
static final Logger logger = LoggerFactory.getLogger(PemObjectReaderTest.class.getName());
/**
* Test method for {@link PemObjectReader#getPemObject(File)}.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testGetPemObject() throws IOException
{
final File privatekeyPemDir = new File(PathFinder.getSrcTestResourcesDir(), "pem");
final File privatekeyPemFile = new File(privatekeyPemDir, "private.pem");
final PemObject pemObject = PemObjectReader.getPemObject(privatekeyPemFile);
final String actual = pemObject.getType();
final String expected = "RSA PRIVATE KEY";
assertEquals(expected, actual);
}
/**
* Test method for {@link PemObjectReader#toPemFormat(PemObject)}.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testToPemFormat() throws IOException
{
final File privatekeyPemDir = new File(PathFinder.getSrcTestResourcesDir(), "pem");
final File privatekeyPemFile = new File(privatekeyPemDir, "private.pem");
final PemObject pemObject = PemObjectReader.getPemObject(privatekeyPemFile);
final String foo = PemObjectReader.toPemFormat(pemObject);
logger.debug("\n" + foo);
}
/**
* Test method for {@link PemObjectReader} with {@link BeanTester}
*/
@Test(expectedExceptions = { BeanTestException.class, InvocationTargetException.class,
UnsupportedOperationException.class })
public void testWithBeanTester()
{
final BeanTester beanTester = new BeanTester();
beanTester.testBean(PemObjectReader.class);
}
/**
* Test method for {@link PemObjectReader#readPemPrivateKey(File, String)}.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testReadPemPrivateKey() throws IOException
{
final File privatekeyPemDir = new File(PathFinder.getSrcTestResourcesDir(), "pem");
final File privatekeyPemFile = new File(privatekeyPemDir, "id_rsa");
PrivateKey privateKey = PemObjectReader.readPemPrivateKey(privatekeyPemFile, "secret");
assertNotNull(privateKey);
}
}
|
package io.cloudslang.content.tesseract.services;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static io.cloudslang.content.tesseract.utils.Constants.FILE_NOT_EXISTS;
import static java.util.Objects.requireNonNull;
public class PdfService {
private static StringBuffer result = new StringBuffer();
public static String imageConvert(String sourcePath, String dataPath, String lang, String dpi) throws Exception {
List<File> fileList = null;
String destination = sourcePath.substring(0, sourcePath.lastIndexOf(File.separator)) + File.separator;
try {
if (!sourcePath.equals("")) {
File pdf = new File(sourcePath);
fileList = requireNonNull(convertPdfToImage(pdf, destination, Integer.parseInt(dpi)));
for (File image : fileList) {
result.append(OcrService.extractText(image.getAbsolutePath(), dataPath, lang));
FileUtils.forceDelete(image);
}
}
return result.toString();
} finally {
if (fileList != null) {
for (File image : fileList) {
if (image.exists())
FileUtils.forceDelete(image);
}
}
}
}
private static List<File> convertPdfToImage(File file, String destination, Integer dpi) throws Exception {
if (file.exists()) {
PDDocument doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
List<File> fileList = new ArrayList<>();
String fileName = file.getName().replace(".pdf", "");
for (int i = 0; i < doc.getNumberOfPages(); i++) {
// default image files path: original file path
// if necessary, file.getParent() + "/" => another path
File fileTemp = new File(destination + fileName + "_" + RandomStringUtils.randomAlphanumeric(15).toUpperCase() + ".png"); // jpg or png
BufferedImage image = renderer.renderImageWithDPI(i, dpi);
// if necessary, change 200 into another integer.
ImageIO.write(image, "PNG", fileTemp); // JPEG or PNG
fileList.add(fileTemp);
}
doc.close();
return fileList;
}
throw new RuntimeException(FILE_NOT_EXISTS);
}
}
|
package edu.nyu.vida.data_polygamy.ctdata;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.math3.exception.ConvergenceException;
import org.apache.commons.math3.ml.clustering.CentroidCluster;
import org.apache.commons.math3.ml.clustering.DoublePoint;
import org.apache.commons.math3.ml.clustering.KMeansPlusPlusClusterer;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import edu.nyu.vida.data_polygamy.ct.Function;
import edu.nyu.vida.data_polygamy.ct.GraphInput;
import edu.nyu.vida.data_polygamy.ct.MergeTrees;
import edu.nyu.vida.data_polygamy.ct.MergeTrees.TreeType;
import edu.nyu.vida.data_polygamy.ct.MyIntList;
import edu.nyu.vida.data_polygamy.ct.Persistence;
import edu.nyu.vida.data_polygamy.ct.ReebGraphData;
import edu.nyu.vida.data_polygamy.ct.SimplifyFeatures;
import edu.nyu.vida.data_polygamy.ct.SimplifyFeatures.Feature;
import edu.nyu.vida.data_polygamy.utils.FrameworkUtils;
import edu.nyu.vida.data_polygamy.utils.Utilities;
public class TopologicalIndex implements Serializable {
private static final long serialVersionUID = 1L;
//private static final double thresholdRatio = 0.2;
public static class Attribute implements Serializable {
private static final long serialVersionUID = 1L;
public int id;
public Int2ObjectOpenHashMap<ArrayList<SpatioTemporalVal>> data =
new Int2ObjectOpenHashMap<ArrayList<SpatioTemporalVal>>();
public Int2ObjectOpenHashMap<Integer> thresholdStTime =
new Int2ObjectOpenHashMap<Integer>();
public Int2ObjectOpenHashMap<Integer> thresholdEnTime =
new Int2ObjectOpenHashMap<Integer>();
public Int2ObjectOpenHashMap<Float> minThreshold =
new Int2ObjectOpenHashMap<Float>();
public Int2ObjectOpenHashMap<Float> maxThreshold =
new Int2ObjectOpenHashMap<Float>();
public IntOpenHashSet nodeSet = new IntOpenHashSet();
public void copy(Attribute att) {
this.id = att.id;
data.putAll(att.data);
nodeSet.addAll(att.nodeSet);
}
}
public static class Event implements Comparable<Event>, Serializable {
private static final long serialVersionUID = 1L;
public int time;
public boolean positive;
public int id;
@Override
public int compareTo(Event o) {
return time - o.time;
}
@Override
public boolean equals(Object obj) {
Event r = (Event) obj;
return r.time == time && r.id == id && positive == r.positive;
}
@Override
public int hashCode() {
return (time + " " + id + " " + positive).hashCode();
}
}
public static class PersistencePoints implements Serializable {
private static final long serialVersionUID = 1L;
public DoubleArrayList ex = new DoubleArrayList();
public DoubleArrayList sad = new DoubleArrayList();
public void addPersistencePoint(Feature f, TreeType tree) {
double pt = f.exFn;
double s = f.sadFn;
if(pt < 100) {
pt *= 1;
}
if (tree == TreeType.JoinTree && f.sadFn < f.exFn) {
pt = f.sadFn;
s = f.exFn;
}
ex.add(pt);
sad.add(s);
}
}
static TreeType [] types = {TreeType.JoinTree, TreeType.SplitTree};
int attribute;
int spatialRes, tempRes;
boolean is2D = false;
public boolean empty = true;
public int stTime = Integer.MAX_VALUE;
public int enTime = 0;
public int nv;
Int2ObjectOpenHashMap<GraphInput> functions = new Int2ObjectOpenHashMap<GraphInput>();
Int2ObjectOpenHashMap<Feature[]> minIndex = new Int2ObjectOpenHashMap<Feature[]>();
Int2ObjectOpenHashMap<Feature[]> maxIndex = new Int2ObjectOpenHashMap<Feature[]>();
public TopologicalIndex() {}
public TopologicalIndex(int spatialRes, int tempRes, int nv) {
this.empty = false;
this.nv = nv;
this.tempRes = tempRes;
this.spatialRes = spatialRes;
if (spatialRes != FrameworkUtils.CITY)
is2D = true;
}
public Int2ObjectOpenHashMap<Feature[]> getIndex(boolean min) {
if (min)
return minIndex;
else
return maxIndex;
}
public int createIndex(Attribute att, int[][] edges2D) {
this.attribute = att.id;
//if (att.data.size() == 0) return 1;
for (int t = 0; t < types.length; t++) {
TreeType tree = types[t];
boolean min = true;
if (tree == TreeType.SplitTree) {
min = false;
}
try {
for (int tempBin : att.data.keySet()) {
//System.out.println("Time: " + tempBin);
ArrayList<SpatioTemporalVal> stArr = att.data.get(tempBin);
int actualVertices = stArr.size();
//if (actualVertices == 0) continue;
int localSt = stArr.get(0).getTemporal();
int localEnd = stArr.get(stArr.size() - 1).getTemporal();
stTime = Math.min(stTime, localSt);
enTime = Math.max(enTime, localEnd);
att.thresholdStTime.put(tempBin, new Integer(stTime));
att.thresholdEnTime.put(tempBin, new Integer(enTime));
GraphInput tf = functions.get(tempBin);
if (tf == null) {
if (is2D) {
tf = new TimeSeries2DFunction(stArr, att.nodeSet, edges2D,
this.nv, this.tempRes, localSt, localEnd);
}
else
tf = new TimeSeriesFunction(stArr);
functions.put(tempBin, tf);
}
MergeTrees ct = new MergeTrees();
ct.computeTree(tf, tree);
ReebGraphData data = ct.output(tree);
if (data.noArcs == 0) {
System.err.println("Empty Attribute: " + att.id);
return 1;
}
Function fn = new Persistence(data);
SimplifyFeatures sim = new SimplifyFeatures();
sim.simplify(data, null, fn, 0.01f);
Feature[] f = sim.brFeatures;
if (min) {
if(f[0].sadFn != data.nodes[0].fn) {
Utilities.er("I have no idea what is happening!!!!! Version 3");
}
f[0].v = data.nodes[0].v;
} else {
if(is2D) {
actualVertices = tf.getFnVertices().length;
} else if(tf.getFnVertices().length != actualVertices) {
Utilities.er("Its time you quit!!");
}
if(f[0].v == actualVertices) {
// new root added
int to = data.arcs[data.noArcs - 1].to;
int from = data.arcs[data.noArcs - 1].from;
if(data.nodes[from].v != actualVertices) {
Utilities.er("I have no idea what is happening!!!!!");
}
f[0].v = data.nodes[to].v;
if(data.nodes[to].fn != f[0].exFn) {
Utilities.er("I have no idea what is happening!!!!! Version 2");
}
}
}
//System.out.println("creating contour tree for " + tempBin);
if (min) {
minIndex.put(tempBin, f);
} else {
maxIndex.put(tempBin, f);
}
}
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
return 0;
}
public ArrayList<byte[]> queryEvents(float th, boolean outlier, Attribute att, String threshold) {
return queryEvents(th, outlier, att, threshold, false);
}
public ArrayList<byte[]> queryEvents(float th, boolean outlier, Attribute att, String threshold, boolean print) {
att.minThreshold.clear();
att.maxThreshold.clear();
int timeSteps = FrameworkUtils.getTimeSteps(this.tempRes, this.stTime, this.enTime);
ArrayList<byte[]> results = new ArrayList<byte[]>();
if (timeSteps == 0) return results;
for (int i = 0; i < this.nv; i++) {
byte[] data = new byte[timeSteps];
Arrays.fill(data, FrameworkUtils.nonEvent);
results.add(data);
}
for(int t = 0;t < types.length;t ++) {
TreeType tree = types[t];
boolean min = true;
if (tree == TreeType.SplitTree) {
min = false;
}
Int2ObjectOpenHashMap<Feature[]> index = getIndex(min);
PersistencePoints perVals = new PersistencePoints();
for (int tempBin : att.data.keySet()) {
Feature []f = index.get(tempBin);
if (f.length == 0) continue;
double pth = th * f[0].wt;
if (!outlier) {
try {
if (threshold.isEmpty()) {
pth = getThreshold(f);
} else {
pth = Double.parseDouble(threshold);
}
} catch (ConvergenceException e) {
continue;
}
}
for (int i = 0; i < f.length; i++) {
if(f[i].wt >= pth) {
perVals.addPersistencePoint(f[i], tree);
} else {
break;
}
}
if (!outlier) {
Collections.sort(perVals.ex);
int no = perVals.ex.size();
double[] vals = new double[no];
for (int i = 0; i < vals.length; i++) {
vals[i] = perVals.ex.get(i);
}
if(vals.length == 0) {
continue;
}
double eventTh = min?vals[vals.length - 1]:vals[0];
getEvents(results, functions.get(tempBin), index.get(tempBin), min, eventTh, print);
perVals = new PersistencePoints();
if (min) {
att.minThreshold.put(tempBin, new Float(eventTh));
} else {
att.maxThreshold.put(tempBin, new Float(eventTh));
}
}
}
if (outlier) {
Collections.sort(perVals.ex);
int no = perVals.ex.size();
double[] vals = new double[no];
for (int i = 0; i < vals.length; i++) {
vals[i] = perVals.ex.get(i);
}
if(vals.length == 0) {
continue;
}
double eventTh = min?vals[vals.length - 1]:vals[0];
if (threshold.isEmpty()) {
eventTh = iqOutlierTh(vals, min);
} else {
eventTh = Double.parseDouble(threshold);
}
getEvents(results, eventTh, index, min, att);
}
}
return results;
}
public static double epsilon = 0.00001;
private double iqOutlierTh(double[] vals, boolean min) {
DescriptiveStatistics ds = new DescriptiveStatistics(vals);
double fq = ds.getPercentile(25);
double tq = ds.getPercentile(75);
double iqr = tq - fq;
if(min) {
double th = fq - 1.5 * iqr;
return (th - epsilon);
} else {
double th = tq + 1.5 * iqr;
return (th + epsilon);
}
}
void getEvents(ArrayList<byte[]> events, double eventTh,
Int2ObjectOpenHashMap<Feature[] > featureMap, boolean min, Attribute att) {
// getting events using merge tree
for (int tempBin : att.data.keySet()) {
Feature[] features = featureMap.get(tempBin);
GraphInput tf = functions.get(tempBin);
getEvents(events, tf, features, min, eventTh, false);
if (min) {
att.minThreshold.put(tempBin, new Float(eventTh));
} else {
att.maxThreshold.put(tempBin, new Float(eventTh));
}
}
}
private void getEvents(ArrayList<byte[]> events, GraphInput tf, Feature[] features, boolean min, double eventTh, boolean print) {
float[] fnVertices = tf.getFnVertices();
// nv = 1;
// if (is2D) {
// nv = ((TimeSeries2DFunction)tf).nv;
IntOpenHashSet set = new IntOpenHashSet();
/*int numberThresholdValues = 0;
for (Feature f: features) {
double pt = f.exFn;
if (min) {
if (f.sadFn < f.exFn) {
pt = f.sadFn;
}
}
if (pt == eventTh) {
numberThresholdValues++;
}
}
double ratio = numberThresholdValues / (double) features.length;*/
for(Feature f: features) {
float pt = f.exFn;
if (min) {
if (f.sadFn < f.exFn) {
pt = f.sadFn;
}
//if (ratio >= thresholdRatio && pt == eventTh) {
// continue;
if (pt > eventTh) {
continue;
}
int exv = f.v;
IntArrayList queue = new IntArrayList();
queue.add(exv);
while(queue.size() > 0) {
int vin = queue.remove(0);
if(set.contains(vin)) {
continue;
}
set.add(vin);
pt = fnVertices[vin];
if(pt <= eventTh) {
int tid = vin / nv;
int time = tf.getTime(tid);
int spatial = vin % nv;
int index = FrameworkUtils.getTimeSteps(this.tempRes,
this.stTime, time);
byte[] spatialEvents = events.get(spatial);
spatialEvents[index-1] = FrameworkUtils.negativeEvent;
events.set(spatial, spatialEvents);
if (print) {
// October 15th, 2011 to October 31st, 2011
if ((time >= 1318636800) && (time <= 1320105599)) {
System.out.print(FrameworkUtils.getTemporalStr(FrameworkUtils.HOUR, time) + "\t");
System.out.print(eventTh + ", " + pt);
System.out.println("");
}
}
MyIntList star = tf.getStar(vin);
for(int i = 0;i < star.length;i ++) {
if(!set.contains(star.array[i])) {
queue.add(star.array[i]);
}
}
}
}
} else {
//if (ratio >= thresholdRatio && pt == eventTh) {
// continue;
if (pt < eventTh) {
continue;
}
int exv = f.v;
IntArrayList queue = new IntArrayList();
queue.add(exv);
while(queue.size() > 0) {
int vin = queue.remove(0);
if(set.contains(vin)) {
continue;
}
set.add(vin);
pt = fnVertices[vin];
if(pt >= eventTh) {
int tid = vin / nv;
int time = tf.getTime(tid);
int spatial = vin % nv;
int index = FrameworkUtils.getTimeSteps(this.tempRes,
this.stTime, time);
byte[] spatialEvents = events.get(spatial);
spatialEvents[index-1] = FrameworkUtils.positiveEvent;
events.set(spatial, spatialEvents);
if (print) {
// October 15th, 2011 to October 31st, 2011
if ((time >= 1318636800) && (time <= 1320105599)) {
System.out.print(FrameworkUtils.getTemporalStr(FrameworkUtils.HOUR, time) + "\t");
System.out.print(eventTh + ", " + pt);
System.out.println("");
}
}
MyIntList star = tf.getStar(vin);
for(int i = 0;i < star.length;i ++) {
if(!set.contains(star.array[i])) {
queue.add(star.array[i]);
}
}
}
}
}
}
}
public double getThreshold(Feature []f) {
KMeansPlusPlusClusterer<DoublePoint> kmeans = new KMeansPlusPlusClusterer<DoublePoint>(2,1000);
ArrayList<DoublePoint> pts = new ArrayList<DoublePoint>();
if(f.length < 2) {
return f[0].wt * 0.4;
}
for (int i = 0; i < f.length; i++) {
DoublePoint dpt = new DoublePoint(new double[] {f[i].wt});
pts.add(dpt);
}
List<CentroidCluster<DoublePoint>> clusters = kmeans.cluster(pts);
double maxp = 0;
double minp = 0;
int ct = 0;
for(CentroidCluster<DoublePoint> c: clusters) {
double mp = 0;
double mnp = Double.MAX_VALUE;
for(DoublePoint dpt: c.getPoints()) {
double [] pt = dpt.getPoint();
mp = Math.max(mp,pt[0]);
mnp = Math.min(mnp,pt[0]);
}
if(mp > maxp) {
maxp = mp;
minp = mnp;
}
ct ++;
}
if(ct > 2) {
Utilities.er("Can there be > 2 clusters?");
}
return minp;
}
}
|
package org.eclipse.birt.data.engine.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.script.ScriptContext;
import org.eclipse.birt.data.engine.api.DataEngineContext;
import org.eclipse.birt.data.engine.api.IBaseDataSetDesign;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBaseQueryDefinition;
import org.eclipse.birt.data.engine.api.IBaseQueryResults;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IColumnDefinition;
import org.eclipse.birt.data.engine.api.IComputedColumn;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IDataScriptEngine;
import org.eclipse.birt.data.engine.api.IFilterDefinition;
import org.eclipse.birt.data.engine.api.IGroupDefinition;
import org.eclipse.birt.data.engine.api.IQueryDefinition;
import org.eclipse.birt.data.engine.api.IResultMetaData;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.api.ISortDefinition;
import org.eclipse.birt.data.engine.api.IFilterDefinition.FilterTarget;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.ComputedColumn;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.api.script.IDataSourceInstanceHandle;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.executor.BaseQuery;
import org.eclipse.birt.data.engine.executor.JointDataSetQuery;
import org.eclipse.birt.data.engine.expression.CompareHints;
import org.eclipse.birt.data.engine.expression.ExpressionCompilerUtil;
import org.eclipse.birt.data.engine.expression.ExpressionProcessor;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.aggregation.AggregateTable;
import org.eclipse.birt.data.engine.impl.group.GroupCalculatorFactory;
import org.eclipse.birt.data.engine.odi.ICandidateQuery;
import org.eclipse.birt.data.engine.odi.IDataSource;
import org.eclipse.birt.data.engine.odi.IEventHandler;
import org.eclipse.birt.data.engine.odi.IPreparedDSQuery;
import org.eclipse.birt.data.engine.odi.IQuery;
import org.eclipse.birt.data.engine.odi.IResultClass;
import org.eclipse.birt.data.engine.odi.IResultIterator;
import org.eclipse.birt.data.engine.odi.IResultObjectEvent;
import org.eclipse.birt.data.engine.olap.api.ICubeQueryResults;
import org.eclipse.birt.data.engine.olap.script.JSCubeBindingObject;
import org.eclipse.birt.data.engine.script.OnFetchScriptHelper;
import org.eclipse.birt.data.engine.script.ScriptConstants;
import org.mozilla.javascript.Scriptable;
import com.ibm.icu.text.Collator;
public abstract class QueryExecutor implements IQueryExecutor
{
protected IBaseQueryDefinition baseQueryDefn;
private AggregateTable aggrTable;
// from PreparedQuery->PreparedDataSourceQuery->DataEngineImpl
private Scriptable sharedScope;
/** Externally provided query scope; can be null */
// from PreparedQuery->PreparedDataSourceQuery
private Scriptable parentScope;
// for query execution
private Scriptable queryScope;
private boolean isPrepared = false;
private boolean isExecuted = false;
protected boolean loadFromCache;
protected boolean ignoreDataSetFilter = false;
private Map queryAppContext;
/** Query nesting level, 1 - outermost query */
private int nestedLevel = 1;
/** Runtime data source and data set used by this instance of executor */
protected DataSourceRuntime dataSource;
protected DataSetRuntime dataSet;
protected IDataSource odiDataSource;
protected IQuery odiQuery;
/** Outer query's results; null if this query is not nested */
protected IQueryService tabularOuterResults;
private IResultIterator odiResult;
private IExecutorHelper parentHelper;
private DataEngineSession session;
protected List temporaryComputedColumns = new ArrayList( );
private static Logger logger = Logger.getLogger( QueryExecutor.class.getName( ) );
protected IQueryContextVisitor contextVisitor;
/**
* @param sharedScope
* @param baseQueryDefn
* @param aggrTable
*/
QueryExecutor( Scriptable sharedScope, IBaseQueryDefinition baseQueryDefn,
AggregateTable aggrTable, DataEngineSession session, IQueryContextVisitor contextVisitor )
{
Object[] params = {
sharedScope, baseQueryDefn, aggrTable, session
};
logger.entering( QueryExecutor.class.getName( ),
"QueryExecutor",
params );
this.sharedScope = sharedScope;
this.baseQueryDefn = baseQueryDefn;
this.aggrTable = aggrTable;
this.session = session;
this.contextVisitor = contextVisitor;
logger.exiting( QueryExecutor.class.getName( ), "QueryExecutor" );
}
public IQueryContextVisitor getQueryContextVisitor()
{
return this.contextVisitor;
}
/**
* Provide the actual DataSourceRuntime used for the query.
*
* @return
*/
abstract protected DataSourceRuntime findDataSource( ) throws DataException;
/**
* Create a new instance of data set runtime
*
* @return
*/
abstract protected DataSetRuntime newDataSetRuntime( ) throws DataException;
/**
* Create a new unopened odiDataSource given the data source runtime
* definition
*
* @return
*/
abstract protected IDataSource createOdiDataSource( ) throws DataException;
/**
* Create an empty instance of odi query
*
* @return
*/
abstract protected IQuery createOdiQuery( ) throws DataException;
/**
* Prepares the ODI query
*/
protected void prepareOdiQuery( ) throws DataException
{
}
/**
*
* @throws DataException
*/
protected void dataSourceBeforeOpen( ) throws DataException
{
if ( !this.loadFromCache )
{
this.dataSource.beforeOpen( );
}
}
/**
*
* @throws DataException
*/
protected void dataSourceAfterOpen( ) throws DataException
{
if ( !this.loadFromCache )
{
this.dataSource.afterOpen( );
}
}
/**
*
* @throws DataException
*/
protected void dataSetBeforeOpen( ) throws DataException
{
if ( !this.loadFromCache )
{
this.dataSet.beforeOpen( );
}
}
/**
*
* @throws DataException
*/
protected void dataSetAfterOpen( ) throws DataException
{
if ( !this.loadFromCache )
{
this.dataSet.afterOpen( );
}
}
/**
*
* @throws DataException
*/
protected void dataSetBeforeClose( ) throws DataException
{
if ( !this.loadFromCache )
{
dataSet.beforeClose( );
}
}
/**
*
* @throws DataException
*/
protected void dataSetAfterClose( ) throws DataException
{
if ( !this.loadFromCache )
{
this.dataSet.afterClose( );
}
}
/**
* Executes the ODI query to reproduce a ODI result set
* @param eventHandler
* @param stopSign
* @return
*/
abstract protected IResultIterator executeOdiQuery(
IEventHandler eventHandler ) throws DataException;
/**
* @param context
*/
void setAppContext( Map context )
{
queryAppContext = context;
}
/**
* Prepare Executor so that it is ready to execute the query
*
* @param outerRts
* @param targetScope
* @throws DataException
*/
void prepareExecution( IBaseQueryResults outerRts, Scriptable targetScope )
throws DataException
{
if ( isPrepared )
return;
this.parentScope = targetScope;
dataSource = findDataSource( );
if ( outerRts != null && ( outerRts instanceof IQueryService || outerRts instanceof ICubeQueryResults ))
{
if ( outerRts instanceof IQueryService )
{
tabularOuterResults = ( (IQueryService) outerRts );
if ( tabularOuterResults.isClosed( ) )
{
// Outer result is closed; invalid
throw new DataException( ResourceConstants.RESULT_CLOSED );
}
this.nestedLevel = tabularOuterResults.getNestedLevel( );
// TODO: check helper is null
IExecutorHelper helper = tabularOuterResults.getExecutorHelper( );
this.setParentExecutorHelper( helper );
}
else if( outerRts instanceof ICubeQueryResults )
{
ExecutorHelper helper = new ExecutorHelper( null );
helper.setScriptable( new JSCubeBindingObject( ( (ICubeQueryResults) outerRts ).getCubeCursor( ) ) );
this.setParentExecutorHelper( helper );
}
}
// Create the data set runtime
// Since data set runtime contains the execution result, a new data set
// runtime is needed for each execute
dataSet = newDataSetRuntime( );
assert dataSet != null;
initializeCollator( );
//For cached data set, we need not execute any scripts.
loadFromCache = loadFromCache( );
dataSet.setFromCache( loadFromCache );
openDataSource( );
// Run beforeOpen script now so the script can modify the
// DataSetRuntime properties
dataSetBeforeOpen( );
// Let subclass create a new and empty intance of the appropriate
// odi IQuery
odiQuery = createOdiQuery( );
odiQuery.setDistinctValueFlag( dataSet.needDistinctValue( ) );
odiQuery.setQueryDefinition( this.baseQueryDefn );
odiQuery.setExprProcessor( new ExpressionProcessor( dataSet ) );
//Set the row fetch limit for the IQuery instance.The row fetch limit
//is the number of rows that a data set can fetch from data source.
if( dataSet.getDesign( ) != null )
{
//When it is not a subquery, the property "row fetch limit" should be applied
//to the query.
odiQuery.setRowFetchLimit( dataSet.getDesign( ).getRowFetchLimit( ) );
}
populateOdiQuery( );
try
{
prepareOdiQuery( );
}
catch ( DataException e )
{
throw new DataException( ResourceConstants.FAIL_PREPARE_EXECUTION,
e,
dataSet.getName( ) );
}
isPrepared = true;
}
abstract protected String getDataSetName( );
private void initializeCollator( ) throws DataException
{
if ( session != null )
{
IBaseDataSetDesign design = ( (DataEngineImpl) this.session.getEngine( ) ).getDataSetDesign( getDataSetName( ) );
if ( design != null )
{
String nullOrdering = design.getNullsOrdering( );
Collator collator = design.getCompareLocale( ) == null ? null
: Collator.getInstance( design.getCompareLocale( ) );
dataSet.setCompareLocale( collator );
dataSet.setNullest( nullOrdering );
dataSet.getScriptScope( ).put( "compare_locale",
dataSet.getScriptScope( ),
collator );
}
}
}
/**
*
* @return
* @throws DataException
*/
private boolean loadFromCache( ) throws DataException
{
if( this.dataSource == null )
return false;
if ( !( this.baseQueryDefn instanceof IQueryDefinition ) )
return false;
return this.session.getDataSetCacheManager( )
.doesLoadFromCache( ((DataEngineImpl)session.getEngine( )).getDataSourceDesign( this.dataSet.getDesign( ).getDataSourceName( ) ),
this.dataSet.getDesign( ),
new ParameterUtil( this.tabularOuterResults == null
? null
: this.tabularOuterResults.getQueryScope( ),
this.dataSet,
( IQueryDefinition )this.baseQueryDefn,
this.getQueryScope( ),
session.getEngineContext( ).getScriptContext( )).resolveDataSetParameters( true ),
this.queryAppContext );
}
/**
* Open the required DataSource. This method should be called after
* "dataSource" is initialized by findDataSource() method.
*
* @throws DataException
*/
protected void openDataSource( ) throws DataException
{
assert odiDataSource == null;
// Open the underlying data source
// dataSource = findDataSource( );
if ( dataSource != null )
{
// TODO: potential bug
if ( !dataSource.isOpen( )
|| session.getDataSetCacheManager( ).needsToCache( ))
{
// Data source is not open; create an Odi Data Source and open it
// We should run the beforeOpen script now to give it a chance to modify
// runtime data source properties
dataSourceBeforeOpen( );
// Let subclass create a new unopened odi data source
odiDataSource = createOdiDataSource( );
// Passes thru the prepared query executor's
// context to the new odi data source
odiDataSource.setAppContext( queryAppContext );
// Open the odi data source
dataSource.openOdiDataSource( odiDataSource );
dataSourceAfterOpen( );
}
else
{
// Use existing odiDataSource created for the data source runtime
odiDataSource = dataSource.getOdiDataSource( );
// Passes thru the prepared query executor's
// current context to existing data source
odiDataSource.setAppContext( queryAppContext );
}
}
}
/**
* Populates odiQuery with this query's definitions
*
* @throws DataException
*/
protected void populateOdiQuery( ) throws DataException
{
assert odiQuery != null;
assert this.baseQueryDefn != null;
SortingOptimizer opt = new SortingOptimizer( this.dataSet.getDesign( ), this.baseQueryDefn );
// Set grouping
populateGrouping( session.getEngineContext( ).getScriptContext( ), opt );
// Set sorting
populateSorting( opt );
// set fetch event
populateFetchEvent( session.getEngineContext( ).getScriptContext( ) );
// specify max rows the query should fetch
odiQuery.setMaxRows( this.baseQueryDefn.getMaxRows( ) );
prepareCacheQuery( this.odiQuery );
}
/**
* TODO: enhance me, this is only a temp logic
* Set temporary computed columns to DataSourceQuery where cache is used
*/
protected void prepareCacheQuery( IQuery odiQuery )
{
if ( temporaryComputedColumns != null
&& temporaryComputedColumns.size( ) > 0 )
{
if ( odiQuery instanceof org.eclipse.birt.data.engine.executor.dscache.DataSourceQuery )
{
( (org.eclipse.birt.data.engine.executor.dscache.DataSourceQuery) odiQuery ).setTempComputedColumn( this.temporaryComputedColumns );
}
else if ( odiQuery instanceof org.eclipse.birt.data.engine.executor.dscache.CandidateQuery )
{
( (org.eclipse.birt.data.engine.executor.dscache.CandidateQuery) odiQuery ).setTempComputedColumn( this.temporaryComputedColumns );
}
}
}
/**
* Populate grouping to the query.
*
* @param cx
* @throws DataException
*/
private void populateGrouping( ScriptContext cx, SortingOptimizer opt ) throws DataException
{
List groups = this.baseQueryDefn.getGroups( );
if ( groups != null && !groups.isEmpty( ) )
{
IQuery.GroupSpec[] groupSpecs = new IQuery.GroupSpec[groups.size( )];
Iterator it = groups.iterator( );
for ( int i = 0; it.hasNext( ); i++ )
{
IGroupDefinition src = (IGroupDefinition) it.next( );
validateGroupExpression( src );
String expr = getDataSetGroupKeyExpression( src );
String groupName = populateGroupName( i, expr );
int dataType = getColumnDataType( cx, getGroupKeyExpression( src ) );
boolean doGroupSorting = false;
if ( this.session.getEngineContext( ).getMode( ) == DataEngineContext.MODE_UPDATE )
{
doGroupSorting = true;
}
else if ( src.getSortDirection( ) == IGroupDefinition.NO_SORT )
{
doGroupSorting = false;
}
else
{
doGroupSorting = this.baseQueryDefn.getQueryExecutionHints( )
.doSortBeforeGrouping( );
}
IQuery.GroupSpec dest = QueryExecutorUtil.groupDefnToSpec( cx,
src,
expr,
groupName,
-1,
dataType,
doGroupSorting );
groupSpecs[i] = dest;
this.temporaryComputedColumns.add( getComputedColumnInstance( cx,
groupSpecs[i].getInterval( ),
src,
expr,
groupName,
dest,
dataType) );
}
if ( opt.acceptGroupSorting( ) )
{
for ( int i = 0; i < groupSpecs.length; i++ )
{
IQuery.GroupSpec spec = groupSpecs[i];
spec.setSortDirection( IGroupDefinition.NO_SORT );
}
}
odiQuery.setGrouping( Arrays.asList( groupSpecs ) );
}
}
/**
* Validating the group expression.
*
* @param src
* @throws DataException
*/
private void validateGroupExpression( IGroupDefinition src ) throws DataException
{
if ( ( src.getKeyColumn( ) == null || src.getKeyColumn( )
.trim( )
.length( ) == 0 )
&& ( src.getKeyExpression( ) == null || src.getKeyExpression( )
.trim( )
.length( ) == 0 ) )
throw new DataException( ResourceConstants.BAD_GROUP_EXPRESSION );
}
/**
* Populate the group name according to the given expression.
*
* @param i
* @param expr
* @return
*/
private String populateGroupName( int i, String expr )
{
String groupName;
if ( expr.trim( ).equalsIgnoreCase( "row[0]" )
|| expr.trim( ).equalsIgnoreCase( "row._rowPosition" )
|| expr.trim( ).equalsIgnoreCase( "dataSetRow[0]" )
|| expr.trim( )
.equalsIgnoreCase( "dataSetRow._rowPosition" ) )
{
groupName = "_{$TEMP_GROUP_" + i + "ROWID$}_";
}
else
{
groupName = "_{$TEMP_GROUP_" + i + "$}_";
}
return groupName;
}
/**
* Get the computed column instance according to the group type.If group has
* interval, return GroupComputedColumn, otherwise return normal computed
* column.
*
* @param cx
* @param groupSpecs
* @param i
* @param src
* @param expr
* @param groupName
* @param dest
* @return
* @throws DataException
*/
private IComputedColumn getComputedColumnInstance( ScriptContext cx,
int interval, IGroupDefinition src,
String expr, String groupName, IQuery.GroupSpec dest,
int dataType)
throws DataException
{
if ( dest.getInterval( ) != IGroupDefinition.NO_INTERVAL )
{
return new GroupComputedColumn( groupName,
expr,
dataType == DataType.DECIMAL_TYPE ? dataType : QueryExecutorUtil.getTempComputedColumnType( interval ),
GroupCalculatorFactory.getGroupCalculator( src.getInterval( ),
src.getIntervalStart( ),
src.getIntervalRange( ),
dataType,
session.getEngineContext( ).getLocale( ),
session.getEngineContext( ).getTimeZone( )) );
}
else
{
return new ComputedColumn( groupName,
expr,
dataType );
}
}
/**
* Populate the sortings in a query.
*
* @throws DataException
*/
private void populateSorting( SortingOptimizer opt ) throws DataException
{
if ( opt.acceptQuerySorting( ) )
return;
populateQuerySorting( );
}
private void populateQuerySorting( ) throws DataException
{
List<?> sorts = this.baseQueryDefn.getSorts( );
if ( sorts != null && !sorts.isEmpty( ) )
{
IQuery.SortSpec[] sortSpecs = new IQuery.SortSpec[sorts.size( )];
Iterator<?> it = sorts.iterator( );
for ( int i = 0; it.hasNext( ); i++ )
{
ISortDefinition src = (ISortDefinition) it.next( );
int sortIndex = -1;
String sortKey = src.getColumn( );
if ( sortKey == null )
{
sortKey = src.getExpression( ).getText( );
}
else
{
sortKey = getColumnRefExpression( sortKey );
}
String dataSetExpr = getDataSetExpr(sortKey);
temporaryComputedColumns.add( new ComputedColumn( "_{$TEMP_SORT_"
+ i + "$}_",
dataSetExpr == null ? sortKey : dataSetExpr,
getExpressionDataType( sortKey ) ) );
sortIndex = -1;
sortKey = String.valueOf( "_{$TEMP_SORT_" + i + "$}_" );
IQuery.SortSpec dest = new IQuery.SortSpec( sortIndex,
sortKey,
src.getSortDirection( ) == ISortDefinition.SORT_ASC,
createCollator( src )
);
sortSpecs[i] = dest;
}
odiQuery.setOrdering( Arrays.asList( sortSpecs ) );
}
}
private Collator createCollator( ISortDefinition sd )
{
if ( sd.getSortStrength( ) != -1 )
{
Collator c = Collator.getInstance( sd.getSortLocale( ) == null
? session.getEngineContext( ).getLocale( )
: sd.getSortLocale( ) );
c.setStrength( sd.getSortStrength( ) );
return c;
}
return null;
}
private String getDataSetExpr( String rowExpr ) throws DataException
{
String dataSetExpr = null ;
try
{
String bindingName = ExpressionUtil.getColumnBindingName( rowExpr );
Object binding = this.baseQueryDefn.getBindings( ).get( bindingName );
if( binding != null )
{
IBaseExpression expr = ( (IBinding) binding ).getExpression( );
if( expr != null && expr instanceof IScriptExpression )
{
dataSetExpr = ( ( IScriptExpression )expr ).getText( );
}
}
return dataSetExpr;
}
catch ( BirtException e )
{
throw DataException.wrap( e );
}
}
/**
*
* @param expression
* @return
* @throws DataException
*/
private int getExpressionDataType( String expression ) throws DataException
{
try
{
if( expression == null )
return DataType.ANY_TYPE;
String bindingName = ExpressionUtil.getColumnBindingName( expression );
if( bindingName == null )
return DataType.ANY_TYPE;
if ( bindingName.equals( ScriptConstants.ROW_NUM_KEYWORD ) )
return DataType.INTEGER_TYPE;
Object binding = this.baseQueryDefn.getBindings( ).get( bindingName );
if( binding == null )
return DataType.ANY_TYPE;
int dataType = ( (IBinding) binding ).getDataType( );
if( dataType != DataType.UNKNOWN_TYPE )
return dataType;
else
return DataType.ANY_TYPE;
}
catch ( BirtException e )
{
throw DataException.wrap( e );
}
}
/**
*
* @param cx
* @throws DataException
*/
private void populateFetchEvent( ScriptContext cx ) throws DataException
{
List<IFilterDefinition> dataSetFilters = new ArrayList<IFilterDefinition>( );
List<IFilterDefinition> queryFilters = new ArrayList<IFilterDefinition>( );
List<IFilterDefinition> aggrFilters = new ArrayList<IFilterDefinition>( );
List<IFilterDefinition> aggrNoUpdateFilters = new ArrayList<IFilterDefinition>( );
List<IFilterDefinition> dataSetAggrFilters = new ArrayList<IFilterDefinition>( );
if ( dataSet.getFilters( ) != null && !ignoreDataSetFilter )
{
Map bindings = createBindingFromComputedColumn( dataSet.getComputedColumns( ));
for ( int i = 0; i < dataSet.getFilters( ).size( ); i++ )
{
if ( !( (IFilterDefinition) dataSet.getFilters( ).get( i ) ).updateAggregation( ) )
continue;
if ( QueryExecutorUtil.isAggrFilter( (IFilterDefinition) dataSet.getFilters( )
.get( i ),
bindings ) )
{
dataSetAggrFilters.add( (IFilterDefinition) dataSet.getFilters( ).get( i ) );
}
else
{
dataSetFilters.add( (IFilterDefinition) dataSet.getFilters( ).get( i ) );
}
}
}
@SuppressWarnings("unchecked")
List<IFilterDefinition> filters = this.baseQueryDefn.getFilters( );
if ( filters != null )
{
@SuppressWarnings("unchecked")
Map<String, IBinding> bindings = this.baseQueryDefn.getBindings( );
for ( int i = 0; i < filters.size( ); i++ )
{
IFilterDefinition filter = filters.get( i );
if( ignoreDataSetFilter && FilterTarget.DATASET.equals( filter.getFilterTarget( ) ) )
{
continue;
}
if ( !QueryExecutorUtil.isValidFilterExpression( filter.getExpression( ),
bindings,
this.session.getEngineContext( ).getScriptContext( ) ) )
{
String expression = filter.getExpression( ).toString( );
if ( filter.getExpression( ) instanceof IScriptExpression )
expression = ( (IScriptExpression) filter.getExpression( ) ).getText( );
else if ( filter.getExpression( ) instanceof IConditionalExpression )
expression = ( (IConditionalExpression) filter.getExpression( ) ).getExpression( )
.getText( );
throw new DataException( ResourceConstants.INVALID_DEFINITION_IN_FILTER,
new Object[]{
expression
} );
}
if ( !filter.updateAggregation( ) )
{
aggrNoUpdateFilters.add( filter );
}
else if ( QueryExecutorUtil.isAggrFilter( filter, bindings ) )
{
aggrFilters.add( filter );
}
else
{
queryFilters.add( filter );
}
}
}
//When prepare filters, the temporaryComputedColumns would also be effect.
List multipassFilters = prepareFilters( cx,
dataSetFilters,
queryFilters,
temporaryComputedColumns );
/
List computedColumns = null;
// set computed column event
computedColumns = this.dataSet.getComputedColumns( );
if ( computedColumns == null )
computedColumns = new ArrayList( );
if ( computedColumns.size( ) > 0
&& this.getAppContext( ) != null
&& getAppContext( ).containsKey( IQueryOptimizeHints.QUERY_OPTIMIZE_HINT ) )
{
List<IColumnDefinition> trimmedColumns = ( (IQueryOptimizeHints) getAppContext( ).get( IQueryOptimizeHints.QUERY_OPTIMIZE_HINT ) ).getTrimmedColumns( )
.get( dataSet.getName( ) );
if ( trimmedColumns != null )
{
Set<String> trimmedNames = new HashSet<String>( );
for ( IColumnDefinition col : trimmedColumns )
{
trimmedNames.add( col.getColumnName( ) );
}
List toBeRemovedComputedColumns = new ArrayList( );
for ( int i = 0; i < computedColumns.size( ); i++ )
{
if ( trimmedNames.contains( ( (IComputedColumn) computedColumns.get( i ) ).getName( ) ) )
{
toBeRemovedComputedColumns.add( computedColumns.get( i ) );
}
}
computedColumns.removeAll( toBeRemovedComputedColumns );
}
}
if ( computedColumns.size( ) > 0
|| temporaryComputedColumns.size( ) > 0 )
{
IResultObjectEvent objectEvent = new ComputedColumnHelper( this.dataSet,
computedColumns,
temporaryComputedColumns, cx );
odiQuery.addOnFetchEvent( objectEvent );
this.dataSet.getComputedColumns( )
.addAll( temporaryComputedColumns );
}
if ( dataSet.getEventHandler( ) != null )
{
OnFetchScriptHelper event = new OnFetchScriptHelper( dataSet );
odiQuery.addOnFetchEvent( event );
}
if ( dataSetFilters.size( )
+ queryFilters.size( ) + multipassFilters.size( ) + aggrFilters.size( ) + dataSetAggrFilters.size( ) + aggrNoUpdateFilters.size( ) > 0 )
{
IResultObjectEvent objectEvent = new FilterByRow( dataSetFilters,
queryFilters,
multipassFilters,
aggrFilters,
dataSetAggrFilters,
aggrNoUpdateFilters,
dataSet );
odiQuery.addOnFetchEvent( objectEvent );
}
}
/**
*
* @param computedColumns
* @return
* @throws DataException
*/
private Map<String, IBinding> createBindingFromComputedColumn( List computedColumns ) throws DataException
{
Map<String, IBinding> result = new HashMap<String, IBinding>();
if( computedColumns == null || computedColumns.size( ) == 0 )
return result;
for( Object computedColumn: computedColumns )
{
IComputedColumn cc = (IComputedColumn)computedColumn;
IBinding binding = new Binding( cc.getName( ) );
binding.setExpression( cc.getExpression( ) );
binding.setAggrFunction( cc.getAggregateFunction( ) );
result.put( cc.getName( ), binding );
}
return result;
}
/**
* get the data type of a expression
* @param cx
* @param expr
* @return
* @throws DataException
*/
private int getColumnDataType( ScriptContext cx, String expr ) throws DataException
{
String columnName = QueryExecutorUtil.getColInfoFromJSExpr( cx, expr )
.getColumnName( );
if ( columnName == null )
{
return DataType.UNKNOWN_TYPE;
}
if ( columnName.equals( ScriptConstants.ROW_NUM_KEYWORD ) )
{
return DataType.INTEGER_TYPE;
}
Object baseExpr = ( this.baseQueryDefn.getBindings( ).get( columnName ) );
if ( baseExpr == null )
{
return DataType.UNKNOWN_TYPE;
}
int dataType = ( (IBinding) baseExpr ).getDataType( );
if( dataType == DataType.UNKNOWN_TYPE )
return DataType.ANY_TYPE;
return dataType;
}
/**
* @param src
* @return
* @throws DataException
*/
private String getDataSetGroupKeyExpression( IGroupDefinition src )
{
String expr = getGroupKeyExpression(src);
String dataSetExpr;
try
{
dataSetExpr = getDataSetExpr( expr );
}
catch (DataException e)
{
dataSetExpr = null;
}
try
{
if( "dataSetRow._rowPosition".equals( dataSetExpr ) )
return expr;
if( dataSetExpr != null && ExpressionUtil.getColumnName( dataSetExpr ) != null )
return dataSetExpr;
}
catch (BirtException e)
{
}
return expr;
}
private String getGroupKeyExpression(IGroupDefinition src) {
String expr = src.getKeyColumn( );
if ( expr == null )
{
expr = src.getKeyExpression( );
}
else
{
expr = getColumnRefExpression( expr );
}
return expr;
}
/**
*
* @param expr
* @return
*/
private String getColumnRefExpression( String expr )
{
return ExpressionUtil.createJSRowExpression( expr );
}
void setParentExecutorHelper( IExecutorHelper helper )
{
this.parentHelper = helper;
}
/**
*
* @param cx
* @param dataSetFilters
* @param queryFilters
* @param temporaryComputedColumns
* @return
* @throws DataException
*/
private List prepareFilters( ScriptContext cx, List dataSetFilters,
List queryFilters, List temporaryComputedColumns ) throws DataException
{
List result = new ArrayList( );
/*List allFilter = new ArrayList();
allFilter.addAll( dataSetFilters );
allFilter.addAll( queryFilters );
prepareFilter( cx, allFilter, temporaryComputedColumns, result );
*/
prepareFilter( cx, dataSetFilters,temporaryComputedColumns, result );
prepareFilter( cx, queryFilters,temporaryComputedColumns, result );
return result;
}
/**
*
* @param cx
* @param dataSetFilters
* @param temporaryComputedColumns
* @param result
* @throws DataException
*/
private void prepareFilter( ScriptContext cx, List dataSetFilters,
List temporaryComputedColumns, List result ) throws DataException
{
if ( dataSetFilters != null && !dataSetFilters.isEmpty( ) )
{
Iterator it = dataSetFilters.iterator( );
for ( int i = 0; it.hasNext( ); i++ )
{
IFilterDefinition src = (IFilterDefinition) it.next( );
IBaseExpression expr = src.getExpression( );
if ( isGroupFilter( src ) )
{
ConditionalExpression ce = ( (ConditionalExpression) expr );
String exprText = ce.getExpression( ).getText( );
ColumnInfo columnInfo = QueryExecutorUtil.getColInfoFromJSExpr( cx,
exprText );
int index = columnInfo.getColumnIndex( );
String name = columnInfo.getColumnName( );
if ( name == null && index < 0 )
{
int currentIndex = result.size( );
// If failed to treate filter key as a column reference
// expression
// then treat it as a computed column expression
temporaryComputedColumns.add( new ComputedColumn( "_{$TEMP_FILTER_"
+ currentIndex + "$}_",
exprText,
DataType.ANY_TYPE ) );
it.remove( );
result.add( new FilterDefinition( new ConditionalExpression( new ScriptExpression( String.valueOf( "dataSetRow[\"_{$TEMP_FILTER_"
+ currentIndex + "$}_\"]" ) ),
ce.getOperator( ),
ce.getOperand1( ),
ce.getOperand2( ) ) ) );
}
}
}
}
}
/**
*
* @param filter
* @return
* @throws DataException
*/
private boolean isGroupFilter( IFilterDefinition filter ) throws DataException
{
IBaseExpression expr = filter.getExpression( );
if ( expr instanceof IConditionalExpression )
{
if ( !ExpressionCompilerUtil.isValidExpressionInQueryFilter( expr,
session.getEngineContext( ).getScriptContext( )) )
throw new DataException( ResourceConstants.INVALID_DEFINITION_IN_FILTER,
new Object[]{
( (IConditionalExpression) expr ).getExpression( )
.getText( )
} );
try
{
if ( odiQuery instanceof BaseQuery )
{
return ( (BaseQuery) odiQuery ).getExprProcessor( )
.hasAggregation( expr );
}
}
catch ( DataException e )
{
return true;
}
}
return false;
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getResultMetaData()
*/
public IResultMetaData getResultMetaData( ) throws DataException
{
assert odiQuery instanceof IPreparedDSQuery
|| odiQuery instanceof ICandidateQuery
|| odiQuery instanceof JointDataSetQuery;
if ( odiQuery instanceof IPreparedDSQuery )
{
if ( ( (IPreparedDSQuery) odiQuery ).getResultClass( ) != null )
return new ColumnBindingMetaData( baseQueryDefn,
( (IPreparedDSQuery) odiQuery ).getResultClass( ) );
else
return null;
}
else if ( odiQuery instanceof JointDataSetQuery )
{
return new ColumnBindingMetaData( baseQueryDefn,
( (JointDataSetQuery) odiQuery ).getResultClass( ) );
}
else
{
IResultMetaData meta = DataSetDesignHelper.getResultMetaData( baseQueryDefn,
odiQuery );
if ( meta == null )
return new ColumnBindingMetaData( baseQueryDefn,
( (ICandidateQuery) odiQuery ).getResultClass( ) );
else
return meta;
}
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getOdiResultClass()
*/
public IResultClass getOdiResultClass( ) throws DataException
{
assert odiQuery instanceof IPreparedDSQuery
|| odiQuery instanceof ICandidateQuery
|| odiQuery instanceof JointDataSetQuery;
if ( odiQuery instanceof IPreparedDSQuery )
{
return ( (IPreparedDSQuery) odiQuery ).getResultClass( );
}
else if ( odiQuery instanceof JointDataSetQuery )
{
return ( (JointDataSetQuery) odiQuery ).getResultClass( );
}
else
{
IResultClass resultClass = DataSetDesignHelper.getResultClass( odiQuery );
if ( resultClass != null )
return resultClass;
else
return ( (ICandidateQuery) odiQuery ).getResultClass( );
}
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#execute()
*/
public void execute( IEventHandler eventHandler ) throws DataException
{
logger.logp( Level.FINER,
QueryExecutor.class.getName( ),
"execute",
"Start to execute" );
if ( this.isExecuted )
return;
ExecutorHelper helper = new ExecutorHelper( this.parentHelper );
eventHandler.setExecutorHelper( helper );
if ( eventHandler.getAppContext( ) != null && this.dataSet.getDesign( ) != null && dataSet.getSession( ) != null)
{
String nullOrdering = this.dataSet.getDesign( ).getNullsOrdering( );
Collator collator = this.dataSet.getDesign( ).getCompareLocale( ) == null
? null : Collator.getInstance( this.dataSet.getDesign( )
.getCompareLocale( ) );
eventHandler.getAppContext( )
.put( "org.eclipse.birt.data.engine.expression.compareHints",
new CompareHints( collator, nullOrdering ) );
}
// Execute the query
odiResult = executeOdiQuery( eventHandler );
helper.setScriptable( this.dataSet.getJSResultRowObject( ) );
resetComputedColumns( );
// Bind the row object to the odi result set
this.dataSet.setResultSet( odiResult, false );
// Calculate aggregate values
//this.aggrTable.calculate( odiResult, getQueryScope( ) );
this.isExecuted = true;
logger.logp( Level.FINER,
QueryExecutor.class.getName( ),
"execute",
"Finish executing" );
}
/**
* reset computed columns
*/
private void resetComputedColumns( )
{
List l = this.getDataSet( ).getComputedColumns( );
if ( l != null )
l.removeAll( this.temporaryComputedColumns );
}
/*
* Closes the executor; release all odi resources
*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#close()
*/
public void close( )
{
if ( odiQuery == null )
{
// already closed
logger.logp( Level.FINER,
QueryExecutor.class.getName( ),
"close",
"executor closed " );
return;
}
// Close the data set and associated odi query
try
{
dataSetBeforeClose( );
}
catch ( DataException e )
{
logger.logp( Level.FINE,
QueryExecutor.class.getName( ),
"close",
e.getMessage( ),
e );
}
if ( odiResult != null )
{
try
{
odiResult.close( );
}
catch ( DataException e1 )
{
// TODO Auto-generated catch block
e1.printStackTrace( );
}
}
odiQuery.close( );
try
{
dataSet.close( );
}
catch ( DataException e )
{
logger.logp( Level.FINE,
QueryExecutor.class.getName( ),
"close",
e.getMessage( ),
e );
}
odiQuery = null;
odiDataSource = null;
odiResult = null;
queryScope = null;
isPrepared = false;
isExecuted = false;
// Note: reset dataSet and dataSource only after afterClose() is executed, since
// the script may access these two objects
try
{
dataSetAfterClose( );
}
catch ( DataException e )
{
logger.logp( Level.FINE,
QueryExecutor.class.getName( ),
"close",
e.getMessage( ),
e );
}
dataSet = null;
dataSource = null;
logger.logp( Level.FINER,
QueryExecutor.class.getName( ),
"close",
"executor closed " );
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getDataSet()
*/
public DataSetRuntime getDataSet( )
{
return dataSet;
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getSharedScope()
*/
public Scriptable getSharedScope( )
{
return this.sharedScope;
}
/**
* Gets the Javascript scope for evaluating expressions for this query
*
* @return
* @throws DataException
*/
public Scriptable getQueryScope( ) throws DataException
{
try
{
if ( queryScope == null )
{
// Set up a query scope. All expressions are evaluated against
// the
// Data set JS object as the prototype (so that it has access to
// all
// data set properties). It uses a subscope of the externally
// provided
// parent scope, or the global shared scope
queryScope = newSubScope( parentScope );
queryScope.setPrototype( dataSet.getJSDataSetObject( ) );
}
return queryScope;
}
catch ( BirtException e )
{
throw DataException.wrap( e );
}
}
/**
* Creates a subscope within parent scope
* @param parentAndProtoScope parent scope. If null, the shared top-level scope is used as parent
* @throws BirtException
*/
private Scriptable newSubScope( Scriptable parentAndProtoScope ) throws BirtException
{
if ( parentAndProtoScope == null )
parentAndProtoScope = sharedScope;
Scriptable scope = ((IDataScriptEngine)session.getEngineContext( ).getScriptContext( ).getScriptEngine( IDataScriptEngine.ENGINE_NAME )).getJSContext( session.getEngineContext( ).getScriptContext( ) )
.newObject( parentAndProtoScope );
scope.setParentScope( parentAndProtoScope );
scope.setPrototype( parentAndProtoScope );
return scope;
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getNestedLevel()
*/
public int getNestedLevel( )
{
return this.nestedLevel;
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getDataSourceInstanceHandle()
*/
public IDataSourceInstanceHandle getDataSourceInstanceHandle( )
{
return this.dataSource;
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getJSAggrValueObject()
*/
public Scriptable getJSAggrValueObject( )
{
return this.aggrTable.getJSAggrValueObject( );
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getNestedDataSets(int)
*/
public DataSetRuntime[] getNestedDataSets( int nestedCount )
{
return tabularOuterResults == null ? null
: tabularOuterResults.getDataSetRuntime( nestedCount );
}
/*
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getOdiResultSet()
*/
public IResultIterator getOdiResultSet( )
{
return this.odiResult;
}
/**
* @param evaluateValue
* @return
* @throws DataException
*/
protected Collection resolveDataSetParameters( boolean evaluateValue )
throws DataException
{
return new ParameterUtil( this.tabularOuterResults == null ? null:this.tabularOuterResults.getQueryScope( ),
this.getDataSet( ),
(IQueryDefinition) this.baseQueryDefn,
this.getQueryScope( ),
session.getEngineContext( ).getScriptContext( )).resolveDataSetParameters( evaluateValue );
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.impl.IQueryExecutor#getAppContext()
*/
public Map getAppContext()
{
return this.queryAppContext;
}
public DataEngineSession getSession()
{
return this.session;
}
}
|
/* Print half pyramid using java */
public class Main {
public static void main(String[] args) {
int ros = 5;
for (int i = 0; i <= ros; i++) {
for (int j = 0; j <= i ; j++) {
String str = "*";
// create a string made up of n copies of s
// String repeated = String.format(String.format("%%%ds", 2), " ").replace(" ",str);
System.out.print(str );
}
System.out.print("\n");
}
}
}
|
//$HeadURL$
package org.deegree.services.resources;
import static org.h2.util.IOUtils.copyAndClose;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.deegree.commons.utils.log.LoggingNotes;
import org.deegree.services.controller.OGCFrontController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides access to service-related stored resources, e.g. XML schema files.
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
@LoggingNotes(debug = "logs resource requests")
public class ResourcesServlet extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger( ResourcesServlet.class );
private static final long serialVersionUID = -2072170206703402474L;
/**
* Returns the HTTP URL for retrieving the specified resource.
* <p>
* NOTE: This method will only return a correct result if the calling thread originated in the
* {@link #doGet(HttpServletRequest, HttpServletResponse)} or
* {@link #doPost(HttpServletRequest, HttpServletResponse)} of this class (or has been spawned as a child thread by
* such a thread).
* </p>
*
* @param resourcePath
*
* @return the HTTP URL (for GET requests)
*/
public static String getHttpGetURL( String resourcePath ) {
String url = OGCFrontController.getHttpGetURL();
url = url.substring( 0, url.lastIndexOf( '/' ) );
// TODO retrieve from config (web.xml)
return url + "/resources/" + resourcePath;
}
@Override
protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
String resourcePath = request.getPathInfo();
if ( !resourcePath.startsWith( "/" ) ) {
throw new ServletException( "Requested resource path does not start with '/'." );
}
if ( !resourcePath.toLowerCase().endsWith( ".xsd" ) ) {
throw new ServletException( "Requested resource path does not end with '.xsd'." );
}
resourcePath = resourcePath.substring( 1 );
LOG.debug( "Requested resource: " + resourcePath );
File wsDir = OGCFrontController.getServiceWorkspace().getLocation();
File resource = new File( wsDir, resourcePath );
if ( !resource.exists() ) {
throw new ServletException( "Resource " + resourcePath + " does not exist." );
}
if ( !resource.isFile() ) {
throw new ServletException( "Resource " + resourcePath + " does not denote a file." );
}
sendResource( resource, response );
}
private void sendResource( File resource, HttpServletResponse response )
throws IOException {
response.setContentLength( (int) resource.length() );
String mimeType = determineMimeType( resource );
response.setContentType( mimeType );
copyAndClose( new FileInputStream( resource ), response.getOutputStream() );
}
private String determineMimeType( File resource ) {
// TODO
return "text/xml";
}
}
|
package com.github.aureliano.edocs.domain.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.github.aureliano.edocs.common.exception.EDocsException;
import com.github.aureliano.edocs.common.persistence.DataPagination;
import com.github.aureliano.edocs.domain.entity.Attachment;
import com.github.aureliano.edocs.domain.entity.Document;
import com.github.aureliano.edocs.domain.helper.DataTypeHelper;
public class AttachmentDao extends AbstractDao<Attachment> {
private static final Logger logger = Logger.getLogger(AttachmentDao.class.getName());
public AttachmentDao() {}
@Override
public Attachment save(Attachment entity) {
return super.saveEntity(entity);
}
@Override
public void delete(Attachment entity) {
this.delete(entity.getId());
}
@Override
public void delete(Integer id) {
String sql = "delete from attachments where id = ?";
super.delete(sql, id);
}
@Override
public Attachment find(Integer id) {
String sql = "select * from attachments where id = ?";
return super.findEntity(sql, id);
}
@Override
public List<Attachment> search(DataPagination<Attachment> dataPagination) {
StringBuilder sql = new StringBuilder("select * from attachments where");
Attachment entity = dataPagination.getEntity();
if (entity.getId() != null) {
sql.append(" id = " + entity.getId());
return this.search(sql.toString());
}
if (entity.getTemp() != null) {
sql.append(" temp = " + entity.getTemp());
}
if (entity.getDocument() != null) {
if (!sql.toString().endsWith("where")) {
sql.append(" and");
}
sql.append(" document_fk = " + entity.getDocument().getId());
}
super.setPaginationParams(dataPagination, sql);
return this.search(sql.toString());
}
@Override
public List<Attachment> search(String query) {
return super.searchEntities(query);
}
@Override
protected PreparedStatement createPreparedStatement(Attachment attachment) {
String sql = this.getSaveQuery(attachment);
logger.fine("Save user SQL: " + sql);
try {
PreparedStatement ps = super.connection.prepareStatement(sql, new String[] {"ID"});
ps.setString(1, attachment.getName());
ps.setDate(2, DataTypeHelper.toSqlDate(attachment.getUploadTime()));
ps.setBoolean(3, attachment.getTemp());
Integer documentId = (attachment.getDocument() != null) ? attachment.getDocument().getId() : null;
ps.setObject(4, documentId);
if (attachment.getId() != null) {
ps.setInt(5, attachment.getId());
}
return ps;
} catch (SQLException ex) {
logger.log(Level.SEVERE, ex.getMessage(), ex);
throw new EDocsException(ex);
}
}
@Override
protected Attachment fillEntity(ResultSet rs) throws SQLException {
List<Attachment> data = this.fillEntities(rs);
return (data.isEmpty()) ? null : data.get(0);
}
@Override
protected List<Attachment> fillEntities(ResultSet rs) throws SQLException {
List<Attachment> data = new ArrayList<>();
while (rs.next()) {
Attachment e = new Attachment()
.withId(rs.getInt("id"))
.withName(rs.getString("name"))
.withUploadTime(DataTypeHelper.toJavaDate(rs.getDate("upload_time")))
.withTemp(rs.getBoolean("temp"))
.withDocument(new Document().withId(rs.getInt("document_fk")));
data.add(e);
}
logger.fine("Found " + data.size() + " entities.");
return data;
}
@Override
protected Logger getLogger() {
return logger;
}
private String getSaveQuery(Attachment attachment) {
if (attachment.getId() == null) {
return "insert into attachments(name, upload_time, temp, document_fk) values(?, ?, ?, ?)";
} else {
return "update attachments set name = ?, upload_time = ?, temp = ?, document_fk = ? where id = ?";
}
}
}
|
package com.yahoo.vespa.flags;
import com.yahoo.component.Vtag;
import com.yahoo.vespa.defaults.Defaults;
import com.yahoo.vespa.flags.custom.PreprovisionCapacity;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
/**
* Definitions of feature flags.
*
* <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag}
* or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p>
*
* <ol>
* <li>The unbound flag</li>
* <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding
* an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li>
* <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should
* declare this in the unbound flag definition in this file (referring to
* {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g.
* {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li>
* </ol>
*
* <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically
* there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p>
*
* @author hakonhall
*/
public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
public static final UnboundIntFlag DROP_CACHES = defineIntFlag("drop-caches", 3,
"The int value to write into /proc/sys/vm/drop_caches for each tick. " +
"1 is page cache, 2 is dentries inodes, 3 is both page cache and dentries inodes, etc.",
"Takes effect on next tick.",
HOSTNAME);
public static final UnboundBooleanFlag ENABLE_CROWDSTRIKE = defineFeatureFlag(
"enable-crowdstrike", true,
"Whether to enable CrowdStrike.", "Takes effect on next host admin tick",
HOSTNAME);
public static final UnboundBooleanFlag ENABLE_NESSUS = defineFeatureFlag(
"enable-nessus", true,
"Whether to enable Nessus.", "Takes effect on next host admin tick",
HOSTNAME);
public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag(
"disabled-host-admin-tasks", List.of(), String.class,
"List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask) that should be skipped",
"Takes effect on next host admin tick",
HOSTNAME, NODE_TYPE);
public static final UnboundStringFlag DOCKER_VERSION = defineStringFlag(
"docker-version", "1.13.1-91.git07f3374",
"The version of the docker to use of the format VERSION-REL: The YUM package to be installed will be " +
"2:docker-VERSION-REL.el7.centos.x86_64 in AWS (and without '.centos' otherwise). " +
"If docker-version is not of this format, it must be parseable by YumPackageName::fromString.",
"Takes effect on next tick.",
HOSTNAME);
public static final UnboundLongFlag THIN_POOL_GB = defineLongFlag(
"thin-pool-gb", -1,
"The size of the disk reserved for the thin pool with dynamic provisioning in AWS, in base-2 GB. " +
"If <0, the default is used (which may depend on the zone and node type).",
"Takes effect immediately (but used only during provisioning).",
NODE_TYPE);
public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag(
"container-cpu-cap", 0,
"Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " +
"to cap CPU at 200%, set this to 2, etc.",
"Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart",
HOSTNAME, APPLICATION_ID);
public static final UnboundBooleanFlag INCLUDE_SIS_IN_TRUSTSTORE = defineFeatureFlag(
"include-sis-in-truststore", false,
"Whether to use the trust store backed by Athenz and (in public) Service Identity certificates in " +
"host-admin and/or Docker containers",
"Takes effect on restart of host-admin (for host-admin), and restart of Docker container.",
// For host-admin, HOSTNAME and NODE_TYPE is available
// For Docker containers, HOSTNAME and APPLICATION_ID is available
// WARNING: Having different sets of dimensions is DISCOURAGED in general, but needed for here since
// trust store for host-admin is determined before having access to application ID from node repo.
HOSTNAME, NODE_TYPE, APPLICATION_ID);
public static final UnboundStringFlag TLS_INSECURE_MIXED_MODE = defineStringFlag(
"tls-insecure-mixed-mode", "tls_client_mixed_server",
"TLS insecure mixed mode. Allowed values: ['plaintext_client_mixed_server', 'tls_client_mixed_server', 'tls_client_tls_server']",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundStringFlag TLS_INSECURE_AUTHORIZATION_MODE = defineStringFlag(
"tls-insecure-authorization-mode", "log_only",
"TLS insecure authorization mode. Allowed values: ['disable', 'log_only', 'enforce']",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundBooleanFlag USE_ADAPTIVE_DISPATCH = defineFeatureFlag(
"use-adaptive-dispatch", false,
"Should adaptive dispatch be used over round robin",
"Takes effect at redeployment",
APPLICATION_ID);
public static final UnboundIntFlag REBOOT_INTERVAL_IN_DAYS = defineIntFlag(
"reboot-interval-in-days", 30,
"No reboots are scheduled 0x-1x reboot intervals after the previous reboot, while reboot is " +
"scheduled evenly distributed in the 1x-2x range (and naturally guaranteed at the 2x boundary).",
"Takes effect on next run of NodeRebooter");
public static final UnboundBooleanFlag ENABLE_DYNAMIC_PROVISIONING = defineFeatureFlag(
"enable-dynamic-provisioning", false,
"Provision a new docker host when we otherwise can't allocate a docker node",
"Takes effect on next deployment",
APPLICATION_ID);
public static final UnboundListFlag<PreprovisionCapacity> PREPROVISION_CAPACITY = defineListFlag(
"preprovision-capacity", List.of(), PreprovisionCapacity.class,
"List of node resources and their count that should be present in zone to receive new deployments. When a " +
"preprovisioned is taken, new will be provisioned within next iteration of maintainer.",
"Takes effect on next iteration of HostProvisionMaintainer.");
public static final UnboundBooleanFlag USE_ADVERTISED_RESOURCES = defineFeatureFlag(
"use-advertised-resources", true,
"When enabled, will use advertised host resources rather than actual host resources, ignore host resource " +
"reservation, and fail with exception unless requested resource match advertised host resources exactly.",
"Takes effect on next iteration of HostProvisionMaintainer.",
APPLICATION_ID);
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
"Node resource memory in Gb for admin cluster nodes",
"Takes effect at redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag HOST_HARDENING = defineFeatureFlag(
"host-hardening", false,
"Whether to enable host hardening Linux baseline.",
"Takes effect on next tick or on host-admin restart (may vary where used).",
HOSTNAME);
public static final UnboundStringFlag ZOOKEEPER_SERVER_MAJOR_MINOR_VERSION = defineStringFlag(
"zookeeper-server-version", "3.5",
"The version of ZooKeeper server to use (major.minor, not full version)",
"Takes effect on restart of Docker container",
NODE_TYPE, APPLICATION_ID, HOSTNAME);
public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_QUORUM_COMMUNICATION = defineStringFlag(
"tls-for-zookeeper-quorum-communication", "PORT_UNIFICATION",
"How to setup TLS for ZooKeeper quorum communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY",
"Takes effect on restart of config server",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag USE_OLD_METRICS_CHECKS = defineFeatureFlag(
"use-old-metrics-checks", true,
"Whether to use old metrics checks",
"Takes effect on restart of Docker container",
NODE_TYPE, HOSTNAME, APPLICATION_ID);
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundBooleanFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundStringFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundIntFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundLongFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundDoubleFlag::new, flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass),
flagId, defaultValue, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass,
String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec),
flagId, defaultValue, description, modificationEffect, dimensions);
}
@FunctionalInterface
private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> {
U create(FlagId id, T defaultVale, FetchVector defaultFetchVector);
}
/**
* Defines a Flag.
*
* @param factory Factory for creating unbound flag of type U
* @param flagId The globally unique FlagId.
* @param defaultValue The default value if none is present after resolution.
* @param description Description of how the flag is used.
* @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc.
* @param dimensions What dimensions will be set in the {@link FetchVector} when fetching
* the flag value in
* {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}.
* For instance, if APPLICATION is one of the dimensions here, you should make sure
* APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag
* from the FlagSource.
* @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features.
* @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag.
* @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and
* {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment
* is typically implicit.
*/
private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory,
String flagId,
T defaultValue,
String description,
String modificationEffect,
FetchVector.Dimension[] dimensions) {
FlagId id = new FlagId(flagId);
FetchVector vector = new FetchVector()
.with(HOSTNAME, Defaults.getDefaults().vespaHostname())
// Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0
// (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0.
.with(VESPA_VERSION, Vtag.currentVersion.toFullString());
U unboundFlag = factory.create(id, defaultValue, vector);
FlagDefinition definition = new FlagDefinition(unboundFlag, description, modificationEffect, dimensions);
flags.put(id, definition);
return unboundFlag;
}
public static List<FlagDefinition> getAllFlags() {
return List.copyOf(flags.values());
}
public static Optional<FlagDefinition> getFlag(FlagId flagId) {
return Optional.ofNullable(flags.get(flagId));
}
/**
* Allows the statically defined flags to be controlled in a test.
*
* <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block,
* the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from
* before the block is reinserted.
*
* <p>NOT thread-safe. Tests using this cannot run in parallel.
*/
public static Replacer clearFlagsForTesting() {
return new Replacer();
}
public static class Replacer implements AutoCloseable {
private static volatile boolean flagsCleared = false;
private final TreeMap<FlagId, FlagDefinition> savedFlags;
private Replacer() {
verifyAndSetFlagsCleared(true);
this.savedFlags = Flags.flags;
Flags.flags = new TreeMap<>();
}
@Override
public void close() {
verifyAndSetFlagsCleared(false);
Flags.flags = savedFlags;
}
/**
* Used to implement a simple verification that Replacer is not used by multiple threads.
* For instance two different tests running in parallel cannot both use Replacer.
*/
private static void verifyAndSetFlagsCleared(boolean newValue) {
if (flagsCleared == newValue) {
throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?");
}
flagsCleared = newValue;
}
}
}
|
package com.yahoo.vespa.flags;
import com.yahoo.component.Vtag;
import com.yahoo.vespa.defaults.Defaults;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
/**
* Definitions of feature flags.
*
* <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag}
* or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p>
*
* <ol>
* <li>The unbound flag</li>
* <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding
* an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li>
* <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should
* declare this in the unbound flag definition in this file (referring to
* {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g.
* {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li>
* </ol>
*
* <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically
* there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p>
*
* @author hakonhall
*/
public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Default limit for when to apply termwise query evaluation",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag(
"feed-sequencer-type", "LATENCY",
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Selects type of sequenced executor used for feeding, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag(
"response-sequencer-type", "ADAPTIVE",
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag(
"response-num-threads", 2,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Number of threads used for mbus responses, default is 2, negative number = numcores/4",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag(
"skip-communicationmanager-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the communicationmanager thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag(
"skip-mbus-request-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus request thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag(
"skip-mbus-reply-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus reply thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag(
"use-three-phase-updates", false,
List.of("vekterli"), "2020-12-02", "2021-09-01",
"Whether to enable the use of three-phase updates when bucket replicas are out of sync.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag(
"hide-shared-routing-endpoint", false,
List.of("tokle", "bjormel"), "2020-12-02", "2021-09-01",
"Whether the controller should hide shared routing layer endpoint",
"Takes effect immediately",
APPLICATION_ID
);
public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag(
"async-message-handling-on-schedule", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Optionally deliver async messages in own thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag(
"feed-concurrency", 0.5,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"How much concurrency should be allowed for feed",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag ORCHESTRATE_MISSING_PROXIES = defineFeatureFlag(
"orchestrate-missing-proxies", false,
List.of("hakonhall"), "2020-08-05", "2020-10-05",
"Whether the Orchestrator can assume any missing proxy services are down.",
"Takes effect on first (re)start of config server");
public static final UnboundBooleanFlag GROUP_SUSPENSION = defineFeatureFlag(
"group-suspension", true,
List.of("hakon"), "2021-01-22", "2021-08-22",
"Allow all content nodes in a hierarchical group to suspend at the same time",
"Takes effect on the next suspension request to the Orchestrator.",
APPLICATION_ID);
public static final UnboundBooleanFlag ENCRYPT_DIRTY_DISK = defineFeatureFlag(
"encrypt-dirty-disk", false,
List.of("hakonhall"), "2021-05-14", "2021-10-05",
"Allow migrating an unencrypted data partition to being encrypted when (de)provisioned.",
"Takes effect on next host-admin tick.");
public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag(
"enable-feed-block-in-distributor", true,
List.of("geirst"), "2021-01-27", "2021-09-01",
"Enables blocking of feed in the distributor if resource usage is above limit on at least one content node",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag DEDICATED_CLUSTER_CONTROLLER_FLAVOR = defineStringFlag(
"dedicated-cluster-controller-flavor", "", List.of("jonmv"), "2021-02-25", "2021-08-25",
"Flavor as <vpu>-<memgb>-<diskgb> to use for dedicated cluster controller nodes",
"Takes effect immediately, for subsequent provisioning",
APPLICATION_ID);
public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag(
"allowed-athenz-proxy-identities", List.of(), String.class,
List.of("bjorncs", "tokle"), "2021-02-10", "2021-12-01",
"Allowed Athenz proxy identities",
"takes effect at redeployment");
public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag(
"generate-non-mtls-endpoint", true,
List.of("tokle"), "2021-02-18", "2021-10-01",
"Whether to generate the non-mtls endpoint",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag(
"max-activation-inhibited-out-of-sync-groups", 0,
List.of("vekterli"), "2021-02-19", "2021-09-01",
"Allows replicas in up to N content groups to not be activated " +
"for query visibility if they are out of sync with a majority of other replicas",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag ENABLE_CUSTOM_ACL_MAPPING = defineFeatureFlag(
"enable-custom-acl-mapping", false,
List.of("mortent","bjorncs"), "2021-04-13", "2021-09-01",
"Whether access control filters should read acl request mapping from handler or use default",
"Takes effect at redeployment",
APPLICATION_ID);
public static final UnboundIntFlag NUM_DISTRIBUTOR_STRIPES = defineIntFlag(
"num-distributor-stripes", 0,
List.of("geirst", "vekterli"), "2021-04-20", "2021-09-01",
"Specifies the number of stripes used by the distributor. When 0, legacy single stripe behavior is used.",
"Takes effect after distributor restart",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag(
"max-concurrent-merges-per-node", 16,
List.of("balder", "vekterli"), "2021-06-06", "2021-09-01",
"Specifies max concurrent merges per content node.",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag(
"max-merge-queue-size", 1024,
List.of("balder", "vekterli"), "2021-06-06", "2021-09-01",
"Specifies max size of merge queue.",
"Takes effect at redeploy",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_EXTERNAL_RANK_EXPRESSION = defineFeatureFlag(
"use-external-rank-expression", false,
List.of("baldersheim"), "2021-05-24", "2021-09-01",
"Whether to use distributed external rank expression or inline in rankproperties",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag DISTRIBUTE_EXTERNAL_RANK_EXPRESSION = defineFeatureFlag(
"distribute-external-rank-expression", false,
List.of("baldersheim"), "2021-05-27", "2021-09-01",
"Whether to use distributed external rank expression files by filedistribution",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundIntFlag LARGE_RANK_EXPRESSION_LIMIT = defineIntFlag(
"large-rank-expression-limit", 0x10000,
List.of("baldersheim"), "2021-06-09", "2021-09-01",
"Limit for size of rank expressions distributed by filedistribution",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag CFG_DEPLOY_MULTIPART = defineFeatureFlag(
"cfg-deploy-multipart", false,
List.of("tokle"), "2021-05-19", "2021-09-01",
"Whether to deploy applications using multipart form data (instead of url params)",
"Takes effect immediately",
APPLICATION_ID);
public static final UnboundIntFlag MAX_ENCRYPTING_HOSTS = defineIntFlag(
"max-encrypting-hosts", 0,
List.of("mpolden", "hakonhall"), "2021-05-27", "2021-10-01",
"The maximum number of hosts allowed to encrypt their disk concurrently",
"Takes effect on next run of HostEncrypter, but any currently encrypting hosts will not be cancelled when reducing the limit");
public static final UnboundBooleanFlag REQUIRE_CONNECTIVITY_CHECK = defineFeatureFlag(
"require-connectivity-check", true,
List.of("arnej"), "2021-06-03", "2021-09-01",
"Require that config-sentinel connectivity check passes with good quality before starting services",
"Takes effect on next restart",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag THROW_EXCEPTION_IF_RESOURCE_LIMITS_SPECIFIED = defineFeatureFlag(
"throw-exception-if-resource-limits-specified", false,
List.of("hmusum"), "2021-06-07", "2021-09-07",
"Whether to throw an exception in hosted Vespa if the application specifies resource limits in services.xml",
"Takes effect on next deployment through controller",
APPLICATION_ID);
public static final UnboundBooleanFlag DRY_RUN_ONNX_ON_SETUP = defineFeatureFlag(
"dry-run-onnx-on-setup", false,
List.of("baldersheim"), "2021-06-23", "2021-09-01",
"Whether to dry run onnx models on setup for better error checking",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundListFlag<String> DEFER_APPLICATION_ENCRYPTION = defineListFlag(
"defer-application-encryption", List.of(), String.class,
List.of("mpolden", "hakonhall"), "2021-06-23", "2021-10-01",
"List of applications where encryption of their host should be deferred",
"Takes effect on next run of HostEncrypter");
public static final UnboundBooleanFlag PODMAN3 = defineFeatureFlag(
"podman3", true,
List.of("mpolden"), "2021-07-05", "2021-09-01",
"Whether to use Podman 3 on supported hosts",
"Takes effect on host-admin restart");
public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag(
"min-node-ratio-per-group", 0.0,
List.of("geirst", "vekterli"), "2021-07-16", "2021-10-01",
"Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass,
List<String> owners, String createdAt, String expiresAt,
String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
@FunctionalInterface
private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> {
U create(FlagId id, T defaultVale, FetchVector defaultFetchVector);
}
/**
* Defines a Flag.
*
* @param factory Factory for creating unbound flag of type U
* @param flagId The globally unique FlagId.
* @param defaultValue The default value if none is present after resolution.
* @param description Description of how the flag is used.
* @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc.
* @param dimensions What dimensions will be set in the {@link FetchVector} when fetching
* the flag value in
* {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}.
* For instance, if APPLICATION is one of the dimensions here, you should make sure
* APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag
* from the FlagSource.
* @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features.
* @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag.
* @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and
* {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment
* is typically implicit.
*/
private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory,
String flagId,
T defaultValue,
List<String> owners,
String createdAt,
String expiresAt,
String description,
String modificationEffect,
FetchVector.Dimension[] dimensions) {
FlagId id = new FlagId(flagId);
FetchVector vector = new FetchVector()
.with(HOSTNAME, Defaults.getDefaults().vespaHostname())
// Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0
// (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0.
.with(VESPA_VERSION, Vtag.currentVersion.toFullString());
U unboundFlag = factory.create(id, defaultValue, vector);
FlagDefinition definition = new FlagDefinition(
unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions);
flags.put(id, definition);
return unboundFlag;
}
private static Instant parseDate(String rawDate) {
return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC);
}
public static List<FlagDefinition> getAllFlags() {
return List.copyOf(flags.values());
}
public static Optional<FlagDefinition> getFlag(FlagId flagId) {
return Optional.ofNullable(flags.get(flagId));
}
/**
* Allows the statically defined flags to be controlled in a test.
*
* <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block,
* the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from
* before the block is reinserted.
*
* <p>NOT thread-safe. Tests using this cannot run in parallel.
*/
public static Replacer clearFlagsForTesting() {
return new Replacer();
}
public static class Replacer implements AutoCloseable {
private static volatile boolean flagsCleared = false;
private final TreeMap<FlagId, FlagDefinition> savedFlags;
private Replacer() {
verifyAndSetFlagsCleared(true);
this.savedFlags = Flags.flags;
Flags.flags = new TreeMap<>();
}
@Override
public void close() {
verifyAndSetFlagsCleared(false);
Flags.flags = savedFlags;
}
/**
* Used to implement a simple verification that Replacer is not used by multiple threads.
* For instance two different tests running in parallel cannot both use Replacer.
*/
private static void verifyAndSetFlagsCleared(boolean newValue) {
if (flagsCleared == newValue) {
throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?");
}
flagsCleared = newValue;
}
}
}
|
package com.yahoo.vespa.flags;
import com.yahoo.component.Vtag;
import com.yahoo.vespa.defaults.Defaults;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID;
import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME;
import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE;
import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION;
import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID;
/**
* Definitions of feature flags.
*
* <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag}
* or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p>
*
* <ol>
* <li>The unbound flag</li>
* <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding
* an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li>
* <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should
* declare this in the unbound flag definition in this file (referring to
* {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g.
* {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li>
* </ol>
*
* <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically
* there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p>
*
* @author hakonhall
*/
public class Flags {
private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>();
public static final UnboundStringFlag ALLOCATE_OS_REQUIREMENT = defineStringFlag(
"allocate-os-requirement", "rhel7",
List.of("hakonhall"), "2021-01-26", "2021-07-26",
"Allocations of new nodes are limited to the given host OS. Must be one of 'rhel7', " +
"'rhel8', or 'any'",
"Takes effect on next (re)deployment.",
APPLICATION_ID);
public static final UnboundBooleanFlag RETIRE_WITH_PERMANENTLY_DOWN = defineFeatureFlag(
"retire-with-permanently-down", true,
List.of("hakonhall"), "2020-12-02", "2021-02-01",
"If enabled, retirement will end with setting the host status to PERMANENTLY_DOWN, " +
"instead of ALLOWED_TO_BE_DOWN (old behavior).",
"Takes effect on the next run of RetiredExpirer.",
HOSTNAME);
public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag(
"default-term-wise-limit", 1.0,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Default limit for when to apply termwise query evaluation",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag(
"feed-sequencer-type", "LATENCY",
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Selects type of sequenced executor used for feeding, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag(
"response-sequencer-type", "ADAPTIVE",
List.of("baldersheim"), "2020-12-02", "2021-02-01",
"Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag(
"response-num-threads", 2,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Number of threads used for mbus responses, default is 2, negative number = numcores/4",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag(
"skip-communicatiomanager-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the communicationmanager thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag(
"skip-mbus-request-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus request thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag(
"skip-mbus-reply-thread", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Should we skip the mbus reply thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag(
"use-three-phase-updates", false,
List.of("vekterli"), "2020-12-02", "2021-02-01",
"Whether to enable the use of three-phase updates when bucket replicas are out of sync.",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag USE_FAST_VALUE_TENSOR_IMPLEMENTATION = defineFeatureFlag(
"use-fast-value-tensor-implementation", false,
List.of("geirst"), "2020-12-02", "2021-02-01",
"Whether to use FastValueBuilderFactory as the tensor implementation on all content nodes.",
"Takes effect at restart of content node process",
ZONE_ID, APPLICATION_ID);
public static final UnboundBooleanFlag TCP_ABORT_ON_OVERFLOW = defineFeatureFlag(
"tcp-abort-on-overflow", false,
List.of("andreer"), "2020-12-02", "2021-02-01",
"Whether to set /proc/sys/net/ipv4/tcp_abort_on_overflow to 0 (false) or 1 (true)",
"Takes effect on next host-admin tick.",
HOSTNAME);
public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag(
"tls-for-zookeeper-client-server-communication", "OFF",
List.of("hmusum"), "2020-12-02", "2021-04-01",
"How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY",
"Takes effect on restart of config server",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag(
"use-tls-for-zookeeper-client", false,
List.of("hmusum"), "2020-12-02", "2021-04-01",
"Whether to use TLS for ZooKeeper clients",
"Takes effect on restart of process",
NODE_TYPE, HOSTNAME);
public static final UnboundBooleanFlag VALIDATE_ENDPOINT_CERTIFICATES = defineFeatureFlag(
"validate-endpoint-certificates", false,
List.of("andreer"), "2020-12-02", "2021-02-01",
"Whether endpoint certificates should be validated before use",
"Takes effect on the next deployment of the application");
public static final UnboundBooleanFlag USE_ALTERNATIVE_ENDPOINT_CERTIFICATE_PROVIDER = defineFeatureFlag(
"use-alternative-endpoint-certificate-provider", false,
List.of("andreer"), "2020-12-02", "2021-02-01",
"Whether to use an alternative CA when provisioning new certificates",
"Takes effect only on initial application deployment - not on later certificate refreshes!");
public static final UnboundStringFlag YUM_DIST_HOST = defineStringFlag(
"yum-dist-host", "",
List.of("aressem"), "2020-12-02", "2021-03-01",
"Override the default dist host for yum.",
"Takes effect on next tick or on host-admin restart (may vary where used).");
public static final UnboundBooleanFlag PROVISION_APPLICATION_ROLES = defineFeatureFlag(
"provision-application-roles", false,
List.of("tokle"), "2020-12-02", "2021-04-01",
"Whether application roles should be provisioned",
"Takes effect on next deployment (controller)",
ZONE_ID);
public static final UnboundBooleanFlag APPLICATION_IAM_ROLE = defineFeatureFlag(
"application-iam-roles", false,
List.of("tokle"), "2020-12-02", "2021-04-01",
"Allow separate iam roles when provisioning/assigning hosts",
"Takes effect immediately on new hosts, on next redeploy for applications",
APPLICATION_ID);
public static final UnboundIntFlag MAX_TRIAL_TENANTS = defineIntFlag(
"max-trial-tenants", -1,
List.of("ogronnesby"), "2020-12-03", "2021-04-01",
"The maximum nr. of tenants with trial plan, -1 is unlimited",
"Takes effect immediately"
);
public static final UnboundBooleanFlag CONTROLLER_PROVISION_LB = defineFeatureFlag(
"controller-provision-lb", false,
List.of("mpolden"), "2020-12-02", "2021-02-01",
"Provision load balancer for controller cluster",
"Takes effect when controller application is redeployed",
ZONE_ID
);
public static final UnboundIntFlag TENANT_NODE_QUOTA = defineIntFlag(
"tenant-node-quota", 5,
List.of("andreer"), "2020-12-02", "2021-02-01",
"The number of nodes a tenant is allowed to request per cluster",
"Only takes effect on next deployment, if set to a value other than the default for flag!",
APPLICATION_ID
);
public static final UnboundBooleanFlag ONLY_PUBLIC_ACCESS = defineFeatureFlag(
"enable-public-only", false,
List.of("ogronnesby"), "2020-12-02", "2021-02-01",
"Only access public hosts from container",
"Takes effect on next tick"
);
public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag(
"hide-shared-routing-endpoint", false,
List.of("tokle"), "2020-12-02", "2021-06-01",
"Whether the controller should hide shared routing layer endpoint",
"Takes effect immediately",
APPLICATION_ID
);
public static final UnboundBooleanFlag USE_ACCESS_CONTROL_CLIENT_AUTHENTICATION = defineFeatureFlag(
"use-access-control-client-authentication", false,
List.of("tokle"), "2020-12-02", "2021-03-01",
"Whether application container should set up client authentication on default port based on access control element",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag(
"async-message-handling-on-schedule", false,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"Optionally deliver async messages in own thread",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag(
"feed-concurrency", 0.5,
List.of("baldersheim"), "2020-12-02", "2022-01-01",
"How much concurrency should be allowed for feed",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
public static final UnboundDoubleFlag REINDEXER_WINDOW_SIZE_INCREMENT = defineDoubleFlag(
"reindexer-window-size-increment", 0.2,
List.of("jonmv"), "2020-12-09", "2021-02-07",
"Window size increment for dynamic throttle policy used by reindexer visitor session — more means more aggressive reindexing",
"Takes effect on (re)deployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_BUCKET_EXECUTOR_FOR_LID_SPACE_COMPACT = defineFeatureFlag(
"use-bucket-executor-for-lid-space-compact", false,
List.of("baldersheim"), "2021-01-24", "2021-03-01",
"Wheter to use content-level bucket executor or legacy frozen buckets",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag USE_POWER_OF_TWO_CHOICES_LOAD_BALANCING = defineFeatureFlag(
"use-power-of-two-choices-load-balancing", false,
List.of("tokle"), "2020-12-02", "2021-02-15",
"Whether to use Power of two load balancing algorithm for application",
"Takes effect on next internal redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag GROUP_SUSPENSION = defineFeatureFlag(
"group-suspension", false,
List.of("hakon"), "2021-01-22", "2021-03-22",
"Allow all content nodes in a hierarchical group to suspend at the same time",
"Takes effect on the next suspension request to the Orchestrator.",
APPLICATION_ID);
public static final UnboundBooleanFlag RECONFIGURABLE_ZOOKEEPER_SERVER_FOR_CLUSTER_CONTROLLER = defineFeatureFlag(
"reconfigurable-zookeeper-server-for-cluster-controller", false,
List.of("musum", "mpolden"), "2020-12-16", "2021-02-16",
"Whether to use reconfigurable zookeeper server for cluster controller",
"Takes effect on (re)redeployment",
APPLICATION_ID);
public static final UnboundBooleanFlag ENABLE_JDISC_CONNECTION_LOG = defineFeatureFlag(
"enable-jdisc-connection-log", false,
List.of("bjorncs", "tokle"), "2021-01-12", "2021-04-01",
"Whether to enable jdisc connection log",
"Takes effect on (re)deployment");
public static final UnboundBooleanFlag ENABLE_ZSTD_COMPRESSION_ACCESS_LOG = defineFeatureFlag(
"enable-zstd-compression-access-log", false,
List.of("bjorncs", "tokle", "baldersheim"), "2021-01-19", "2021-04-01",
"Whether to enable zstd compression of jdisc access logs",
"Takes effect on (re)deployment");
public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag(
"enable-feed-block-in-distributor", false,
List.of("geirst"), "2021-01-27", "2021-04-01",
"Enables blocking of feed in the distributor if resource usage is above limit on at least one content node",
"Takes effect at redeployment",
ZONE_ID, APPLICATION_ID);
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners,
String createdAt, String expiresAt, String description,
String modificationEffect, FetchVector.Dimension... dimensions) {
return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
/** WARNING: public for testing: All flags should be defined in {@link Flags}. */
public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass,
List<String> owners, String createdAt, String expiresAt,
String description, String modificationEffect, FetchVector.Dimension... dimensions) {
return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec),
flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions);
}
@FunctionalInterface
private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> {
U create(FlagId id, T defaultVale, FetchVector defaultFetchVector);
}
/**
* Defines a Flag.
*
* @param factory Factory for creating unbound flag of type U
* @param flagId The globally unique FlagId.
* @param defaultValue The default value if none is present after resolution.
* @param description Description of how the flag is used.
* @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc.
* @param dimensions What dimensions will be set in the {@link FetchVector} when fetching
* the flag value in
* {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}.
* For instance, if APPLICATION is one of the dimensions here, you should make sure
* APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag
* from the FlagSource.
* @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features.
* @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag.
* @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and
* {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment
* is typically implicit.
*/
private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory,
String flagId,
T defaultValue,
List<String> owners,
String createdAt,
String expiresAt,
String description,
String modificationEffect,
FetchVector.Dimension[] dimensions) {
FlagId id = new FlagId(flagId);
FetchVector vector = new FetchVector()
.with(HOSTNAME, Defaults.getDefaults().vespaHostname())
// Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0
// (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0.
.with(VESPA_VERSION, Vtag.currentVersion.toFullString());
U unboundFlag = factory.create(id, defaultValue, vector);
FlagDefinition definition = new FlagDefinition(
unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions);
flags.put(id, definition);
return unboundFlag;
}
private static Instant parseDate(String rawDate) {
return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC);
}
public static List<FlagDefinition> getAllFlags() {
return List.copyOf(flags.values());
}
public static Optional<FlagDefinition> getFlag(FlagId flagId) {
return Optional.ofNullable(flags.get(flagId));
}
/**
* Allows the statically defined flags to be controlled in a test.
*
* <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block,
* the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from
* before the block is reinserted.
*
* <p>NOT thread-safe. Tests using this cannot run in parallel.
*/
public static Replacer clearFlagsForTesting() {
return new Replacer();
}
public static class Replacer implements AutoCloseable {
private static volatile boolean flagsCleared = false;
private final TreeMap<FlagId, FlagDefinition> savedFlags;
private Replacer() {
verifyAndSetFlagsCleared(true);
this.savedFlags = Flags.flags;
Flags.flags = new TreeMap<>();
}
@Override
public void close() {
verifyAndSetFlagsCleared(false);
Flags.flags = savedFlags;
}
/**
* Used to implement a simple verification that Replacer is not used by multiple threads.
* For instance two different tests running in parallel cannot both use Replacer.
*/
private static void verifyAndSetFlagsCleared(boolean newValue) {
if (flagsCleared == newValue) {
throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?");
}
flagsCleared = newValue;
}
}
}
|
package logbook.data.context;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
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.TreeMap;
import java.util.concurrent.TimeUnit;
import javax.annotation.CheckForNull;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonValue;
import logbook.config.AppConfig;
import logbook.config.ItemConfig;
import logbook.config.KdockConfig;
import logbook.constants.AppConstants;
import logbook.data.Data;
import logbook.dto.BasicInfoDto;
import logbook.dto.BattleExDto;
import logbook.dto.BattleExDto.Phase;
import logbook.dto.BattlePhaseKind;
import logbook.dto.BattleResultDto;
import logbook.dto.CreateItemDto;
import logbook.dto.DeckMissionDto;
import logbook.dto.DockDto;
import logbook.dto.GetShipDto;
import logbook.dto.ItemDto;
import logbook.dto.ItemInfoDto;
import logbook.dto.KdockDto;
import logbook.dto.LostEntityDto;
import logbook.dto.MapCellDto;
import logbook.dto.MaterialDto;
import logbook.dto.MissionResultDto;
import logbook.dto.NdockDto;
import logbook.dto.PracticeUserDetailDto;
import logbook.dto.PracticeUserDto;
import logbook.dto.QuestDto;
import logbook.dto.ResourceItemDto;
import logbook.dto.ShipDto;
import logbook.dto.ShipInfoDto;
import logbook.gui.ApplicationMain;
import logbook.gui.logic.CreateReportLogic;
import logbook.gui.logic.Sound;
import logbook.internal.BattleResultServer;
import logbook.internal.EnemyData;
import logbook.internal.Item;
import logbook.internal.MasterData;
import logbook.internal.Ship;
import logbook.util.JsonUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.ToolTip;
public final class GlobalContext {
private static final Logger LOG = LogManager.getLogger(GlobalContext.class);
/** Map */
private static Map<Integer, ItemDto> itemMap = new TreeMap<Integer, ItemDto>();
/** Map */
private static Map<Integer, ShipDto> shipMap = new TreeMap<Integer, ShipDto>();
private static ShipDto secretary;
private static List<GetShipDto> getShipList = new ArrayList<GetShipDto>();
private static Map<String, GetShipDto> getShipResource = new HashMap<String, GetShipDto>();
private static List<CreateItemDto> createItemList = new ArrayList<CreateItemDto>();
private static List<BattleResultDto> battleResultList = new ArrayList<BattleResultDto>();
private static List<MissionResultDto> missionResultList = new ArrayList<MissionResultDto>();
private static int hqLevel;
private static int maxChara;
private static int maxSlotitem;
private static String lastBuildKdock;
private static MapCellDto mapCellDto = null;
private static BattleExDto battle = null;
private static DeckMissionDto[] deckMissions = new DeckMissionDto[] { DeckMissionDto.EMPTY, DeckMissionDto.EMPTY,
DeckMissionDto.EMPTY };
private static Map<String, DockDto> dock = new HashMap<String, DockDto>();
private static NdockDto[] ndocks = new NdockDto[] { NdockDto.EMPTY, NdockDto.EMPTY, NdockDto.EMPTY,
NdockDto.EMPTY };
private static KdockDto[] kdocks = new KdockDto[] { KdockDto.EMPTY, KdockDto.EMPTY, KdockDto.EMPTY,
KdockDto.EMPTY };
private static PracticeUserDto[] practiceUser = new PracticeUserDto[] { null, null, null, null, null };
private static Date practiceUserLastUpdate = null;
/** Map */
private static ArrayList<QuestDto> questList = new ArrayList<QuestDto>();
private static Date questLastUpdate;
private static boolean[] isSortie = new boolean[4];
/** (START) */
private static boolean isStart;
private static BasicInfoDto basic;
/** updateContext() */
private static int updateCounter = 0;
private static MaterialDto material = null;
volatile private static Date materialLogLastUpdate = null;
private static boolean combined;
/** 0: 1: 2: 3: */
private static int state = 0;
public static final boolean INIT_COMPLETE;
static {
ItemConfig.load();
INIT_COMPLETE = true;
}
private static enum MATERIAL_DIFF {
NEW_VALUE,
OBTAINED,
CONSUMED,
NONE;
}
/**
* @return Map
*/
public static Map<Integer, ItemDto> getItemMap() {
return itemMap;
}
/**
*
* @param map
*/
public static void setItemMap(Collection<ItemDto> items) {
for (ItemDto item : items) {
int id = item.getSlotitemId();
ItemInfoDto info = Item.get(id);
if (info != null) {
item.setInfo(info);
itemMap.put(item.getId(), item);
}
}
}
/**
* @return Map
*/
public static Map<Integer, ShipDto> getShipMap() {
return shipMap;
}
/**
* @return
*/
public static ShipDto getSecretary() {
return secretary;
}
/**
* @return Lv
*/
public static int hqLevel() {
return hqLevel;
}
/**
* @return
*/
public static int maxChara() {
return maxChara;
}
/**
* @return
*/
public static int maxSlotitem() {
return maxSlotitem;
}
/**
* @return List
*/
public static List<GetShipDto> getGetshipList() {
return getShipList;
}
/**
* @param list List
*/
public static void addGetshipList(List<GetShipDto> list) {
getShipList.addAll(list);
}
/**
* @return List
*/
public static List<CreateItemDto> getCreateItemList() {
return createItemList;
}
/**
* @param list List
*/
public static void addCreateItemList(List<CreateItemDto> list) {
createItemList.addAll(list);
}
/**
* @return List
*/
public static List<BattleResultDto> getBattleResultList() {
return battleResultList;
}
/**
* @return
*/
public static BattleExDto getLastBattleDto() {
return battle;
}
/**
* @return
*/
public static List<MissionResultDto> getMissionResultList() {
return missionResultList;
}
/**
* @param list
*/
public static void addMissionResultList(List<MissionResultDto> list) {
missionResultList.addAll(list);
}
/**
* @return
*/
public static DeckMissionDto[] getDeckMissions() {
return deckMissions;
}
/**
* @return
*/
public static NdockDto[] getNdocks() {
return ndocks;
}
/**
* @return
*/
public static KdockDto[] getKdocks() {
return kdocks;
}
/**
* @return
*/
public static Set<Integer> getMissionShipSet() {
Set<Integer> set = new HashSet<Integer>();
for (DeckMissionDto deckMission : deckMissions) {
if ((deckMission.getMission() != null) && (deckMission.getShips() != null)) {
set.addAll(deckMission.getShips());
}
}
return set;
}
/**
* @return
*/
public static Set<Integer> getNDockShipSet() {
Set<Integer> set = new HashSet<Integer>();
for (NdockDto ndock : ndocks) {
if (ndock.getNdockid() != 0) {
set.add(ndock.getNdockid());
}
}
return set;
}
/**
*
*
* @param ship
* @return true
*/
public static boolean isNdock(ShipDto ship) {
return isNdock(ship.getId());
}
/**
*
* @param ship ID
* @return true
*/
public static boolean isNdock(int ship) {
for (NdockDto ndock : ndocks) {
if (ship == ndock.getNdockid()) {
return true;
}
}
return false;
}
public static PracticeUserDto[] getPracticeUser() {
return practiceUser;
}
public static Date getPracticeUserLastUpdate() {
return practiceUserLastUpdate;
}
/**
*
*
* @param
*/
public static boolean isMission(String idstr) {
int id = Integer.parseInt(idstr);
for (int i = 0; i < deckMissions.length; i++) {
if ((deckMissions[i].getMission() != null) && (deckMissions[i].getFleetid() == id)) {
return true;
}
}
return false;
}
/**
* @return
*/
public static DockDto getDock(String id) {
return dock.get(id);
}
/**
* @return Map
*/
public static Map<String, DockDto> getDock() {
return dock;
}
public static boolean[] getIsSortie() {
return isSortie;
}
public static MapCellDto getSortieMap() {
return mapCellDto;
}
/**
*
* @return
*/
public static List<QuestDto> getQuest() {
return questList;
}
public static Date getQuestLastUpdate() {
return questLastUpdate;
}
/**
*
* @return
*/
public static boolean isSortie(String idstr) {
int id = Integer.parseInt(idstr);
return isSortie[id - 1];
}
/**
*
* @return
*/
@CheckForNull
public static MaterialDto getMaterial() {
return material;
}
/**
*
* @return
*/
@CheckForNull
public static BasicInfoDto getBasicInfo() {
return basic;
}
/**
*
* @return
*/
public static boolean isCombined() {
return combined;
}
/**
*
* @return 0: 1: 2:
*/
public static int getState() {
return state;
}
/**
*
*
* @return true
*/
public static void updateContext(Data data) {
// json
if (AppConfig.get().isStoreJson()) {
doStoreJson(data);
}
switch (data.getDataType()) {
case CHARGE:
doCharge(data);
break;
case CHANGE:
doChange(data);
break;
case PORT:
doPort(data);
break;
case SLOTITEM_MEMBER:
doSlotitemMember(data);
break;
case SHIP3:
doShip3(data);
break;
case SHIP2:
doShip2(data);
break;
case BASIC:
doBasic(data);
break;
case MATERIAL:
doMaterial(data);
break;
case MISSION_RESULT:
doMissionResult(data);
break;
case NDOCK:
doNdock(data);
break;
case CREATE_SHIP:
doCreateship(data);
break;
case KDOCK:
doKdock(data);
break;
case GET_SHIP:
doGetship(data);
break;
case CREATE_ITEM:
doCreateitem(data);
break;
case DESTROY_SHIP:
doDestroyShip(data);
break;
case DESTROY_ITEM2:
doDestroyItem2(data);
break;
case POWERUP:
doPowerup(data);
break;
case LOCK_SHIP:
doLockShip(data);
break;
case LOCK_SLOTITEM:
doLockSlotitem(data);
break;
case REMODEL_SLOT:
doRemodelSlot(data);
break;
case BATTLE:
doBattle(data, BattlePhaseKind.BATTLE);
break;
case BATTLE_MIDNIGHT:
doBattle(data, BattlePhaseKind.MIDNIGHT);
break;
case BATTLE_SP_MIDNIGHT:
doBattle(data, BattlePhaseKind.SP_MIDNIGHT);
break;
case BATTLE_NIGHT_TO_DAY:
doBattle(data, BattlePhaseKind.NIGHT_TO_DAY);
break;
case COMBINED_AIR_BATTLE:
doBattle(data, BattlePhaseKind.COMBINED_AIR);
break;
case COMBINED_BATTLE:
doBattle(data, BattlePhaseKind.COMBINED_BATTLE);
break;
case COMBINED_BATTLE_MIDNIGHT:
doBattle(data, BattlePhaseKind.COMBINED_MIDNIGHT);
break;
case COMBINED_BATTLE_SP_MIDNIGHT:
doBattle(data, BattlePhaseKind.COMBINED_SP_MIDNIGHT);
break;
case COMBINED_BATTLE_WATER:
doBattle(data, BattlePhaseKind.COMBINED_BATTLE_WATER);
break;
case BATTLE_RESULT:
doBattleresult(data);
break;
case COMBINED_BATTLE_RESULT:
doBattleresult(data);
break;
case PRACTICE_BATTLE:
doBattle(data, BattlePhaseKind.PRACTICE_BATTLE);
break;
case PRACTICE_BATTLE_MIDNIGHT:
doBattle(data, BattlePhaseKind.PRACTICE_MIDNIGHT);
break;
case PRACTICE_BATTLE_RESULT:
doBattleresult(data);
break;
case DECK:
doDeck(data);
break;
case START:
doStart(data);
break;
case NEXT:
doNext(data);
break;
case QUEST_LIST:
doQuest(data);
break;
case QUEST_CLEAR:
doQuestClear(data);
break;
case START2:
doStart2(data);
break;
case MAPINFO:
doMapInfo(data);
break;
case MISSION:
doMission(data);
break;
case PRACTICE:
doPractice(data);
break;
case PRACTICE_ENEMYINFO:
doPracticeEnemyinfo(data);
break;
case COMBINED:
doCombined(data);
break;
case NYUKYO_START:
doNyukyoStart(data);
break;
case NYUKYO_SPEEDCHANGE:
doSpeedChange(data);
break;
default:
break;
}
++updateCounter;
}
/**
* @return updateContext()
*/
public static int getUpdateCounter() {
return updateCounter;
}
/**
* JSON
* @param data
*/
private static void doStoreJson(Data data) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HHmmss.SSS");
Date time = Calendar.getInstance().getTime();
String fname = new StringBuilder().append(format.format(time)).append("_").append(data.getDataType())
.append(".json").toString();
File file = new File(FilenameUtils.concat(AppConfig.get().getStoreJsonPath(), fname));
FileUtils.write(file, data.getJsonObject().toString(), Charset.forName("UTF-8"));
} catch (IOException e) {
LOG.warn("JSON", e);
LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doCharge(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
if (apidata != null) {
JsonArray ships = apidata.getJsonArray("api_ship");
for (JsonValue shipval : ships) {
JsonObject shipobj = (JsonObject) shipval;
int shipid = shipobj.getInt("api_id");
int fuel = shipobj.getInt("api_fuel");
int bull = shipobj.getInt("api_bull");
ShipDto ship = shipMap.get(shipid);
if (ship != null) {
ship.setFuel(fuel);
ship.setBull(bull);
String fleetid = ship.getFleetid();
if (fleetid != null) {
DockDto dockdto = dock.get(fleetid);
if (dockdto != null) {
dockdto.setUpdate(true);
}
}
}
}
addUpdateLog("");
}
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doChange(Data data) {
try {
String fleetid = data.getField("api_id");
int shipid = Integer.valueOf(data.getField("api_ship_id"));
int shipidx = Integer.valueOf(data.getField("api_ship_idx"));
DockDto dockdto = dock.get(fleetid);
if (dockdto != null) {
List<ShipDto> ships = dockdto.getShips();
if (shipidx == -1) {
for (int i = 1; i < ships.size(); ++i) {
ships.get(i).setFleetid("");
}
dockdto.removeExceptFlagship();
} else {
// (null)
ShipDto cship = (shipidx < ships.size()) ? ships.get(shipidx) : null;
// (null)
ShipDto rship = shipMap.get(shipid);
// (null)
DockDto rdock = (rship != null) ? dock.get(rship.getFleetid()) : null;
int rdockPos = (rship != null) ? rship.getFleetpos() : 0;
dockdto.removeFleetIdFromShips();
if (rdock != null) {
rdock.removeFleetIdFromShips();
}
if (rdock != null) {
// rship != null
if (cship != null) {
rdock.setShip(rdockPos, cship);
}
else {
rdock.removeShip(rship);
}
}
if (rship == null) {
dockdto.removeShip(cship);
}
else if (cship != null) {
// rship != null && cship != null
dockdto.setShip(shipidx, rship);
}
else {
// rship != null && cship == null
dockdto.addShip(rship);
}
dockdto.updateFleetIdOfShips();
dockdto.setUpdate(true);
if (rdock != null) {
rdock.updateFleetIdOfShips();
rdock.setUpdate(true);
}
}
DockDto firstdock = dock.get("1");
if (firstdock != null) {
setSecretary(firstdock.getShips().get(0));
}
}
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doPort(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
if (apidata != null) {
for (int i = 0; i < isSortie.length; ++i) {
if (isSortie[i]) {
ApplicationMain.main.endSortie();
break;
}
}
Arrays.fill(isSortie, false);
if ((battle != null) && (battle.getDock() != null) && (battle.isPractice() == false)) {
checkBattleDamage(battle.getFriends().get(0).getShips(), battle.getLastPhase().getNowFriendHp());
if (battle.isCombined()) {
checkBattleDamage(battle.getFriends().get(1).getShips(),
battle.getLastPhase().getNowFriendHpCombined());
}
}
mapCellDto = null;
battle = null;
JsonObject apiBasic = apidata.getJsonObject("api_basic");
doBasicSub(apiBasic);
//addConsole("");
JsonArray apiMaterial = apidata.getJsonArray("api_material");
doMaterialSub(apiMaterial);
//addConsole("");
shipMap.clear();
JsonArray apiShip = apidata.getJsonArray("api_ship");
for (int i = 0; i < apiShip.size(); i++) {
ShipDto ship = new ShipDto((JsonObject) apiShip.get(i));
shipMap.put(Integer.valueOf(ship.getId()), ship);
}
JsonArray apiDeckPort = apidata.getJsonArray("api_deck_port");
doDeck(apiDeckPort);
//addConsole("");
JsonArray apiNdock = apidata.getJsonArray("api_ndock");
doNdockSub(apiNdock);
//addConsole("");
//addConsole("");
combined = false;
if (apidata.containsKey("api_combined_flag")) {
switch (apidata.getJsonNumber("api_combined_flag").intValue()) {
case 1:
case 2:
combined = true;
break;
default:
break;
}
//addConsole("");
}
state = checkDataState();
addUpdateLog("");
}
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
* HP
* @param ship
* @param nowhp
* @param sunkShips
*/
private static void checkShipSunk(ShipDto ship, int nowhp, List<ShipDto> sunkShips) {
if (ship.getNowhp() > 0) {
ship.setNowhp(nowhp);
if (ship.getNowhp() == 0) {
sunkShips.add(ship);
CreateReportLogic.storeLostReport(LostEntityDto.make(ship, ""));
}
}
}
/**
*
* @param data
*/
private static void doBattle(Data data, BattlePhaseKind phaseKind) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
if (battle == null) {
battle = new BattleExDto(data.getCreateDate());
battle.setBasicInfo(maxChara - shipMap.size(), maxSlotitem - itemMap.size());
}
BattleExDto.Phase phase = battle.addPhase(apidata, phaseKind);
if (battle.getDock() == null) {
battle = null;
return;
}
List<ShipDto> sunkShips = new ArrayList<ShipDto>();
List<ShipDto> ships = battle.getFriends().get(0).getShips();
int[] nowFriendHp = phase.getNowFriendHp();
if (battle.getDock().getShips().size() != nowFriendHp.length) {
battle = null;
return;
}
if ((phaseKind != BattlePhaseKind.PRACTICE_BATTLE) &&
(phaseKind != BattlePhaseKind.PRACTICE_MIDNIGHT))
{
for (int i = 0; i < ships.size(); ++i) {
checkShipSunk(ships.get(i), nowFriendHp[i], sunkShips);
}
if (battle.isCombined()) {
List<ShipDto> shipsCombined = battle.getFriends().get(1).getShips();
int[] nowFriendHpCombined = phase.getNowFriendHpCombined();
for (int i = 0; i < shipsCombined.size(); ++i) {
checkShipSunk(shipsCombined.get(i), nowFriendHpCombined[i], sunkShips);
}
}
}
addConsole("");
if (AppConfig.get().isPrintSortieLog()) {
addConsole("=" + Arrays.toString(phase.getNowFriendHp()));
if (battle.isCombined()) {
addConsole("=" + Arrays.toString(phase.getNowFriendHpCombined()));
}
addConsole("=" + Arrays.toString(phase.getNowEnemyHp()));
addConsole("→ " + phase.getEstimatedRank().toString());
}
if (AppConfig.get().isPrintSunkLog()) {
for (ShipDto ship : sunkShips) {
addConsole(ship.getName() + "(id:" + ship.getId() + ",lv:" + ship.getLv() + ") ");
}
}
if (mapCellDto == null) {
for (DockDto dock : battle.getFriends()) {
isSortie[Integer.parseInt(dock.getId()) - 1] = true;
}
ApplicationMain.main.startSortie();
}
ApplicationMain.main.updateBattle(battle);
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doBattleresult(Data data) {
try {
if (battle != null) {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
battle.setResult(apidata, mapCellDto);
if (battle.isCompleteResult()) {
BattleResultServer.get().addNewResult(battle);
}
if (battle.isPractice() == false) {
//battleResultList.add(battle);
CreateReportLogic.storeBattleResultReport(battle);
// EnemyData
if (mapCellDto != null) {
int enemyId = mapCellDto.getEnemyId();
EnemyData enemyData = battle.getEnemyData(enemyId, battle.getEnemyName());
if ((mapCellDto.getEnemyData() == null) || (mapCellDto.getEnemyData().getEnemyName() == null)) {
addConsole("eid=" + enemyId + "");
}
EnemyData.set(enemyId, enemyData);
mapCellDto.setEnemyData(enemyData);
}
}
battle.getDock().setUpdate(true);
if (battle.isCombined()) {
battle.getDockCombined().setUpdate(true);
}
Phase lastPhase = battle.getLastPhase();
if (!battle.getRank().equals(lastPhase.getEstimatedRank())) {
LOG.info(": :" + battle.getRank() + " " + lastPhase.getRankCalcInfo(battle));
}
for (int i = 0; i < (battleResultList.size() - AppConstants.MAX_LOG_SIZE); i++) {
battleResultList.remove(0);
}
}
isStart = false;
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
* ()
* @param data
*/
private static void doCreateship(Data data) {
try {
String kdockid = data.getField("api_kdock_id");
ResourceItemDto res = new ResourceItemDto();
res.loadBaseMaterialsFromField(data);
res.setResearchMaterials(Integer.parseInt(data.getField("api_item5")));
GetShipDto resource = new GetShipDto(
Integer.parseInt(data.getField("api_large_flag")) == 1,
res, secretary, hqLevel, -1);
lastBuildKdock = kdockid;
getShipResource.put(kdockid, resource);
KdockConfig.store(kdockid, resource);
updateDetailedMaterial("", res, MATERIAL_DIFF.CONSUMED);
addUpdateLog("()");
} catch (Exception e) {
LOG.warn("()", e);
LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doKdock(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
if (lastBuildKdock != null) {
GetShipDto resource = getShipResource.get(lastBuildKdock);
if (resource != null) {
int freecount = 0;
for (int i = 0; i < apidata.size(); i++) {
int state = ((JsonObject) apidata.get(i)).getJsonNumber("api_state").intValue();
if (state == 0) {
freecount++;
}
}
resource.setFreeDock(freecount);
KdockConfig.store(lastBuildKdock, resource);
}
}
doKdockSub(apidata);
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
private static void doKdockSub(JsonArray apidata) {
kdocks = new KdockDto[] { KdockDto.EMPTY, KdockDto.EMPTY, KdockDto.EMPTY, KdockDto.EMPTY };
for (int i = 0; i < apidata.size(); i++) {
JsonObject object = (JsonObject) apidata.get(i);
int state = object.getJsonNumber("api_state").intValue();
long milis = object.getJsonNumber("api_complete_time").longValue();
Date time = null;
if (milis > 0) {
time = new Date(milis);
kdocks[i] = new KdockDto(true, time);
}
else {
kdocks[i] = new KdockDto(state == 3, null);
}
}
}
/**
* ()
* @param data
*/
private static void doGetship(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
String dock = data.getField("api_kdock_id");
JsonValue slotitem = apidata.get("api_slotitem");
// JsonValue.NULL
if ((slotitem != null) && (slotitem != JsonValue.NULL)) {
JsonArray slotitemArray = (JsonArray) slotitem;
for (int i = 0; i < slotitemArray.size(); i++) {
addSlotitem((JsonObject) slotitemArray.get(i));
}
}
JsonObject apiShip = apidata.getJsonObject("api_ship");
ShipDto ship = new ShipDto(apiShip);
shipMap.put(Integer.valueOf(ship.getId()), ship);
GetShipDto dto = getShipResource.get(dock);
if (dto == null) {
dto = KdockConfig.load(dock);
}
dto.setShip(ship);
getShipList.add(dto);
CreateReportLogic.storeCreateShipReport(dto);
getShipResource.remove(dock);
KdockConfig.remove(dock);
doKdockSub(apidata.getJsonArray("api_kdock"));
state = checkDataState();
addUpdateLog("()");
} catch (Exception e) {
LOG.warn("()", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doCreateitem(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
ResourceItemDto res = new ResourceItemDto();
res.loadBaseMaterialsFromField(data);
CreateItemDto createitem = new CreateItemDto(apidata, res, secretary, hqLevel);
if (createitem.isCreateFlag()) {
ItemDto item = addSlotitem(apidata.getJsonObject("api_slot_item"));
if (item != null) {
createitem.setName(item.getName());
createitem.setType(item.getTypeName());
createItemList.add(createitem);
}
} else {
createItemList.add(createitem);
}
CreateReportLogic.storeCreateItemReport(createitem);
JsonArray newMaterial = apidata.getJsonArray("api_material");
ResourceItemDto items = new ResourceItemDto();
items.loadMaterialFronJson(newMaterial);
updateDetailedMaterial("", items, MATERIAL_DIFF.NEW_VALUE);
state = checkDataState();
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doSlotitemMember(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
itemMap.clear();
for (int i = 0; i < apidata.size(); i++) {
JsonObject object = (JsonObject) apidata.get(i);
addSlotitem(object);
}
state = checkDataState();
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doShip3(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
String shipidstr = data.getField("api_shipid");
JsonArray shipdata = apidata.getJsonArray("api_ship_data");
if (shipidstr != null) {
int shipid = Integer.parseInt(shipidstr);
for (int i = 0; i < shipdata.size(); i++) {
ShipDto ship = new ShipDto((JsonObject) shipdata.get(i));
shipMap.put(shipid, ship);
}
} else {
shipMap.clear();
for (int i = 0; i < shipdata.size(); i++) {
ShipDto ship = new ShipDto((JsonObject) shipdata.get(i));
shipMap.put(ship.getId(), ship);
}
}
doDeck(apidata.getJsonArray("api_deck_data"));
state = checkDataState();
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doShip2(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
shipMap.clear();
for (int i = 0; i < apidata.size(); i++) {
ShipDto ship = new ShipDto((JsonObject) apidata.get(i));
shipMap.put(ship.getId(), ship);
}
if ((battle != null) && (battle.getDock() != null) && (battle.isPractice() == false)) {
checkBattleDamage(battle.getDock().getShips(), battle.getNowFriendHp());
if (battle.isCombined()) {
checkBattleDamage(battle.getDockCombined().getShips(), battle.getNowFriendHpCombined());
}
}
doDeck(data.getJsonObject().getJsonArray("api_data_deck"));
if (battle != null) {
ApplicationMain.main.updateSortieDock();
}
battle = null;
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doDeck(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
for (DockDto dockdto : dock.values()) {
for (ShipDto ship : dockdto.getShips()) {
ship.setFleetid("");
}
}
doDeck(apidata);
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param apidata
*/
private static void doDeck(JsonArray apidata) {
dock.clear();
for (int i = 0; i < apidata.size(); i++) {
JsonObject jsonObject = (JsonObject) apidata.get(i);
int fleetid = jsonObject.getInt("api_id");
String fleetidstr = String.valueOf(fleetid);
String name = jsonObject.getString("api_name");
JsonArray apiship = jsonObject.getJsonArray("api_ship");
DockDto dockdto = new DockDto(fleetidstr, name);
List<Integer> shipIds = new ArrayList<Integer>();
dock.put(fleetidstr, dockdto);
for (int j = 0; j < apiship.size(); j++) {
int shipId = apiship.getInt(j);
shipIds.add(shipId);
ShipDto ship = shipMap.get(shipId);
if (ship != null) {
dockdto.addShip(ship);
if ((i == 0) && (j == 0)) {
setSecretary(ship);
}
ship.setFleetid(fleetidstr);
ship.setFleetpos(j);
}
}
if (i >= 1) {
JsonArray jmission = jsonObject.getJsonArray("api_mission");
int section = ((JsonNumber) jmission.get(1)).intValue();
long milis = ((JsonNumber) jmission.get(2)).longValue();
Date time = null;
if (milis > 0) {
time = new Date(milis);
}
deckMissions[i - 1] = new DeckMissionDto(name, section, time, fleetid, shipIds);
}
}
}
/**
*
*
* @param ship
*/
private static void setSecretary(ShipDto ship) {
if ((secretary == null) || (ship.getId() != secretary.getId())) {
addConsole(ship.getName() + "(Lv" + ship.getLv() + ")" + " ");
}
secretary = ship;
}
/**
*
* @param data
*/
private static void doDestroyShip(Data data) {
try {
int shipid = Integer.valueOf(data.getField("api_ship_id"));
ShipDto ship = shipMap.get(shipid);
if (ship != null) {
CreateReportLogic.storeLostReport(LostEntityDto.make(ship, ""));
for (int item : ship.getItemId()) {
itemMap.remove(item);
}
shipMap.remove(ship.getId());
String fleetid = ship.getFleetid();
if (fleetid != null) {
DockDto dockdto = dock.get(fleetid);
if (dockdto != null) {
dockdto.removeShip(ship);
dockdto.setUpdate(true);
}
}
}
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doDestroyItem2(Data data) {
try {
String itemids = data.getField("api_slotitem_ids");
List<LostEntityDto> dtoList = new ArrayList<LostEntityDto>();
for (String itemid : itemids.split(",")) {
int item = Integer.valueOf(itemid);
ItemDto itemDto = itemMap.get(item);
if (itemDto != null) {
dtoList.add(LostEntityDto.make(item, itemDto));
}
itemMap.remove(item);
}
CreateReportLogic.storeLostReport(dtoList);
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doPowerup(Data data) {
try {
String shipids = data.getField("api_id_items");
for (String shipid : shipids.split(",")) {
ShipDto ship = shipMap.get(Integer.valueOf(shipid));
if (ship != null) {
CreateReportLogic.storeLostReport(LostEntityDto.make(ship, ""));
for (int item : ship.getItemId()) {
itemMap.remove(item);
}
shipMap.remove(ship.getId());
String fleetid = ship.getFleetid();
if (fleetid != null) {
DockDto dockdto = dock.get(fleetid);
if (dockdto != null) {
dockdto.removeShip(ship);
dockdto.setUpdate(true);
dockdto.updateFleetIdOfShips();
}
}
}
}
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
ShipDto ship = new ShipDto(apidata.getJsonObject("api_ship"));
int id = ship.getId();
ShipDto oldShip = shipMap.get(id);
String fleetid = oldShip.getFleetid();
if (fleetid != null) {
DockDto dockdto = dock.get(fleetid);
if (dockdto != null) {
ship.setFleetid(fleetid);
ship.setFleetpos(oldShip.getFleetpos());
dockdto.setShip(ship.getFleetpos(), ship);
}
}
shipMap.put(id, ship);
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doLockShip(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
int shipId = Integer.valueOf(data.getField("api_ship_id"));
boolean locked = apidata.getInt("api_locked") != 0;
ShipDto dto = shipMap.get(shipId);
if (dto != null) {
dto.setLocked(locked);
}
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doLockSlotitem(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
int slotitemId = Integer.valueOf(data.getField("api_slotitem_id"));
boolean locked = apidata.getInt("api_locked") != 0;
ItemDto dto = itemMap.get(slotitemId);
if (dto != null) {
dto.setLocked(locked);
}
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doBasic(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
doBasicSub(apidata);
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param apidata
*/
private static void doBasicSub(JsonObject apidata) {
hqLevel = apidata.getJsonNumber("api_level").intValue();
maxChara = apidata.getJsonNumber("api_max_chara").intValue();
maxSlotitem = apidata.getJsonNumber("api_max_slotitem").intValue();
BasicInfoDto old = basic;
basic = new BasicInfoDto(apidata);
if ((old != null) && (old.getMemberId() != basic.getMemberId())) {
state = 3;
}
}
/**
*
*
* @param data
*/
private static void doMaterial(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
doMaterialSub(apidata);
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param apidata
*/
private static void doMaterialSub(JsonArray apidata) {
Date time = Calendar.getInstance().getTime();
MaterialDto dto = new MaterialDto();
dto.setTime(time);
dto.setEvent("");
for (JsonValue value : apidata) {
JsonObject entry = (JsonObject) value;
switch (entry.getInt("api_id")) {
case AppConstants.MATERIAL_FUEL:
dto.setFuel(entry.getInt("api_value"));
break;
case AppConstants.MATERIAL_AMMO:
dto.setAmmo(entry.getInt("api_value"));
break;
case AppConstants.MATERIAL_METAL:
dto.setMetal(entry.getInt("api_value"));
break;
case AppConstants.MATERIAL_BAUXITE:
dto.setBauxite(entry.getInt("api_value"));
break;
case AppConstants.MATERIAL_BURNER:
dto.setBurner(entry.getInt("api_value"));
break;
case AppConstants.MATERIAL_BUCKET:
dto.setBucket(entry.getInt("api_value"));
break;
case AppConstants.MATERIAL_RESEARCH:
dto.setResearch(entry.getInt("api_value"));
break;
case AppConstants.MATERIAL_SCREW:
dto.setScrew(entry.getInt("api_value"));
break;
default:
break;
}
}
material = dto;
if ((materialLogLastUpdate == null)
|| (TimeUnit.MILLISECONDS.toSeconds(time.getTime() - materialLogLastUpdate.getTime()) >
AppConfig.get().getMaterialLogInterval())) {
CreateReportLogic.storeMaterialReport(material);
materialLogLastUpdate = time;
}
}
/**
* ()
*
* @param data
*/
private static void doMissionResult(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
int clearResult = apidata.getJsonNumber("api_clear_result").intValue();
String questName = apidata.getString("api_quest_name");
ResourceItemDto res = new ResourceItemDto();
if (clearResult != 0) {
res.loadMissionResult(apidata);
updateDetailedMaterial("", res, MATERIAL_DIFF.OBTAINED);
}
MissionResultDto result = new MissionResultDto(clearResult, questName, res);
CreateReportLogic.storeMissionReport(result);
missionResultList.add(result);
state = checkDataState();
addUpdateLog("()");
} catch (Exception e) {
LOG.warn("()", e);
LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doNdock(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
doNdockSub(apidata);
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
private static void ndockFinished(int shipId) {
ShipDto ship = shipMap.get(shipId);
if (ship != null) {
ship.setNowhp(ship.getMaxhp());
ship.setDockTime(0);
}
}
/**
*
* @param apidata
*/
private static void doNdockSub(JsonArray apidata) {
for (int i = 0; i < apidata.size(); i++) {
JsonObject object = (JsonObject) apidata.get(i);
int id = object.getJsonNumber("api_ship_id").intValue();
long milis = object.getJsonNumber("api_complete_time").longValue();
Date time = null;
if (milis > 0) {
time = new Date(milis);
ndocks[i] = new NdockDto(id, time);
}
else if (ndocks[i].getNdocktime() != null) {
ndockFinished(ndocks[i].getNdockid());
ndocks[i] = NdockDto.EMPTY;
}
}
}
/**
*
* @param apidata
*/
private static void doNyukyoStart(Data data) {
try {
int id = Integer.valueOf(data.getField("api_ship_id"));
boolean highspeed = data.getField("api_highspeed").equals("1");
if (highspeed) {
ndockFinished(id);
}
// ndock
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
* @param apidata
*/
private static void doSpeedChange(Data data) {
try {
int id = Integer.valueOf(data.getField("api_ndock_id"));
ndockFinished(ndocks[id - 1].getNdockid());
ndocks[id - 1] = NdockDto.EMPTY;
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doQuest(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
int items_per_page = 5;
int disp_page = apidata.getJsonNumber("api_disp_page").intValue();
int page_count = apidata.getJsonNumber("api_page_count").intValue();
if (page_count == 0) {
questList.clear();
questLastUpdate = new Date();
}
else if ((disp_page > page_count) || apidata.isNull("api_list")) {
}
else {
Date now = new Date();
for (int i = questList.size(); i < (page_count * items_per_page); ++i) {
questList.add(null);
}
for (int i = questList.size() - 1; i >= (page_count * items_per_page); --i) {
questList.remove(i);
}
int pos = 1;
for (JsonValue value : apidata.getJsonArray("api_list")) {
if (value instanceof JsonObject) {
JsonObject questobject = (JsonObject) value;
int index = ((disp_page - 1) * items_per_page) + (pos - 1);
QuestDto quest = new QuestDto();
quest.setTime(now);
quest.setNo(questobject.getInt("api_no"));
quest.setPage(disp_page);
quest.setPos(pos++);
quest.setCategory(questobject.getInt("api_category"));
quest.setType(questobject.getInt("api_type"));
quest.setState(questobject.getInt("api_state"));
quest.setTitle(questobject.getString("api_title"));
quest.setDetail(questobject.getString("api_detail"));
JsonArray material = questobject.getJsonArray("api_get_material");
quest.setFuel(material.getJsonNumber(0).toString());
quest.setAmmo(material.getJsonNumber(1).toString());
quest.setMetal(material.getJsonNumber(2).toString());
quest.setBauxite(material.getJsonNumber(3).toString());
quest.setBonusFlag(questobject.getInt("api_bonus_flag"));
quest.setProgressFlag(questobject.getInt("api_progress_flag"));
questList.set(index, quest);
}
}
if (pos <= items_per_page) {
for (int i = questList.size() - 1; i >= (((disp_page - 1) * items_per_page) + (pos - 1)); --i) {
questList.remove(i);
}
}
if (questList.contains(null) == false) {
Date updateTime = now;
for (QuestDto quest : questList) {
if (updateTime.after(quest.getTime())) {
updateTime = quest.getTime();
}
}
questLastUpdate = updateTime;
}
}
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doQuestClear(Data data) {
try {
/*
String idstr = data.getField("api_quest_id");
if (idstr != null) {
Integer id = Integer.valueOf(idstr);
questMap.remove(id);
}
*/
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
ResourceItemDto items = new ResourceItemDto();
items.loadQuestClear(apidata);
updateDetailedMaterial("", items, MATERIAL_DIFF.OBTAINED);
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doStart(Data data) {
try {
String idstr = data.getField("api_deck_id");
if (idstr != null) {
int id = Integer.parseInt(idstr);
isSortie[id - 1] = true;
if ((id == 1) && combined) {
isSortie[1] = true;
}
}
isStart = true;
JsonObject obj = data.getJsonObject().getJsonObject("api_data");
mapCellDto = new MapCellDto(obj, isStart);
updateDetailedMaterial("", null, MATERIAL_DIFF.NONE);
ApplicationMain.main.startSortie();
ApplicationMain.main.updateMapCell(mapCellDto);
addUpdateLog("");
if (AppConfig.get().isPrintSortieLog())
addConsole(" " + mapCellDto.toString());
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doNext(Data data) {
try {
JsonObject obj = data.getJsonObject().getJsonObject("api_data");
mapCellDto = new MapCellDto(obj, isStart);
ApplicationMain.main.updateMapCell(mapCellDto);
if (AppConfig.get().isPrintSortieLog())
addConsole(" " + mapCellDto.toString());
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doStart2(Data data) {
try {
JsonObject obj = data.getJsonObject().getJsonObject("api_data");
if (obj != null) {
JsonArray apiMstShip = obj.getJsonArray("api_mst_ship");
for (int i = 0; i < apiMstShip.size(); i++) {
JsonObject object = (JsonObject) apiMstShip.get(i);
String id = object.getJsonNumber("api_id").toString();
Ship.set(id, toShipInfoDto(object));
}
addUpdateLog("");
JsonArray apiMstSlotitem = obj.getJsonArray("api_mst_slotitem");
for (int i = 0; i < apiMstSlotitem.size(); i++) {
JsonObject object = (JsonObject) apiMstSlotitem.get(i);
ItemInfoDto item = new ItemInfoDto(object);
int id = object.getJsonNumber("api_id").intValue();
Item.set(id, item);
}
addUpdateLog("");
MasterData.updateMaster(obj);
}
addConsole("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doMapInfo(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
if (apidata != null) {
MasterData.updateMapInfo(apidata);
}
int shipSpace = maxChara - shipMap.size();
int itemSpace = maxSlotitem - itemMap.size();
if (AppConfig.get().isEnableItemFullBalloonNotify() &&
(itemSpace <= AppConfig.get().getItemFullBalloonNotify())) {
ToolTip tip = new ToolTip(ApplicationMain.main.getShell(), SWT.BALLOON
| SWT.ICON_ERROR);
tip.setText("");
tip.setMessage("" + itemSpace + "");
ApplicationMain.main.getTrayItem().setToolTip(tip);
tip.setVisible(true);
Sound.randomWarningPlay();
}
else if (AppConfig.get().isEnableShipFullBalloonNotify() &&
(shipSpace <= AppConfig.get().getShipFullBalloonNotify())) {
ToolTip tip = new ToolTip(ApplicationMain.main.getShell(), SWT.BALLOON
| SWT.ICON_ERROR);
tip.setText("");
tip.setMessage("" + shipSpace + "");
ApplicationMain.main.getTrayItem().setToolTip(tip);
tip.setVisible(true);
Sound.randomWarningPlay();
}
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doMission(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
if (apidata != null) {
MasterData.updateMission(apidata);
}
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doPractice(Data data) {
try {
JsonArray apidata = data.getJsonObject().getJsonArray("api_data");
for (int i = 0; i < apidata.size(); ++i) {
PracticeUserDto dto = new PracticeUserDto((JsonObject) apidata.get(i));
if ((practiceUser[i] == null) || (practiceUser[i].getId() != dto.getId()))
practiceUser[i] = dto;
else
// state
practiceUser[i].setState(dto.getState());
}
practiceUserLastUpdate = new Date();
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
* @param data
*/
private static void doPracticeEnemyinfo(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
PracticeUserDetailDto dto = new PracticeUserDetailDto(apidata);
for (int i = 0; i < 5; ++i) {
if ((practiceUser[i] != null) && (practiceUser[i].getId() == dto.getId())) {
practiceUser[i] = dto;
break;
}
}
ApplicationMain.main.updateCalcPracticeExp(dto);
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
*
* @param data
*/
private static void doCombined(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
combined = (apidata.getInt("api_combined") != 0);
for (int i = 0; i < 2; ++i) {
DockDto dockdto = dock.get(Integer.toString(i + 1));
if (dockdto != null) {
dockdto.setUpdate(true);
}
}
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
private static void doRemodelSlot(Data data) {
try {
JsonObject apidata = data.getJsonObject().getJsonObject("api_data");
if (apidata != null) {
if (apidata.getInt("api_remodel_flag") != 0) {
addSlotitem(apidata.getJsonObject("api_after_slot"));
}
if (JsonUtils.hasKey(apidata, "api_use_slot_id")) {
JsonArray useSlotId = apidata.getJsonArray("api_use_slot_id");
for (int i = 0; i < useSlotId.size(); ++i) {
itemMap.remove(useSlotId.getInt(i));
}
}
JsonArray newMaterial = apidata.getJsonArray("api_after_material");
ResourceItemDto items = new ResourceItemDto();
items.loadMaterialFronJson(newMaterial);
updateDetailedMaterial("", items, MATERIAL_DIFF.NEW_VALUE);
}
addUpdateLog("");
} catch (Exception e) {
LOG.warn("", e);
LOG.warn(data);
}
}
/**
*
* @param dockShips ShipDto
* @param nowhp
*/
private static void checkBattleDamage(List<ShipDto> dockShips, int[] nowhp) {
for (int i = 0; i < dockShips.size(); ++i) {
ShipDto new_ship = shipMap.get(dockShips.get(i).getId());
if (new_ship == null)
continue;
if (new_ship.getNowhp() != nowhp[i]) {
LOG.warn("" + new_ship.getName() + "HP" + new_ship.getNowhp()
+ "" + nowhp[i] + "");
addConsole("");
}
}
}
/**
*
* @returnstate
*/
private static int checkDataState() {
if (state == 3) {
return state;
}
for (ShipDto ship : shipMap.values()) {
if (ship.getShipInfo().getName().length() == 0) {
return 2;
}
}
for (ShipDto ship : shipMap.values()) {
for (int itemId : ship.getItemId()) {
if (itemId != -1) {
if (itemMap.containsKey(itemId) == false) {
return 2;
}
}
}
}
return 1;
}
/** itemMap */
private static ItemDto addSlotitem(JsonObject object) {
int slotitemId = object.getInt("api_slotitem_id");
ItemInfoDto info = Item.get(slotitemId);
if (info != null) {
ItemDto dto = new ItemDto(info, object);
itemMap.put(dto.getId(), dto);
return dto;
}
return null;
}
private static void updateDetailedMaterial(String ev, ResourceItemDto res, MATERIAL_DIFF diff) {
if (material != null) {
switch (diff) {
case NEW_VALUE:
material = res.toMaterialDto();
break;
case OBTAINED:
material = material.clone().obtained(res);
break;
case CONSUMED:
material = material.clone().consumed(res);
break;
default:
break;
}
material.setEvent(ev);
if (AppConfig.get().isMaterialLogDetail()) {
CreateReportLogic.storeMaterialReport(material);
}
}
}
/**
*
*
* @param object
* @return
*/
private static ShipInfoDto toShipInfoDto(JsonObject object) {
String name = object.getString("api_name");
if ("".equals(name)) {
return ShipInfoDto.EMPTY;
}
return new ShipInfoDto(object);
}
private static void addConsole(Object message) {
ApplicationMain.main.printMessage(message.toString());
}
private static void addUpdateLog(Object message) {
if (AppConfig.get().isPrintUpdateLog()) {
addConsole(message);
}
}
}
|
package VASL.build.module.map;
import VASL.build.module.map.boardPicker.*;
import VASSAL.Info;
import VASSAL.build.*;
import VASSAL.build.module.map.BoardPicker;
import VASSAL.build.module.map.GlobalMap;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.build.module.map.boardPicker.BoardSlot;
import VASSAL.build.module.map.boardPicker.board.HexGrid;
import VASSAL.command.Command;
import VASSAL.command.NullCommand;
import VASSAL.configure.DirectoryConfigurer;
import VASSAL.configure.ValidationReport;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.ReadErrorDialog;
import VASSAL.tools.io.IOUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.swing.*;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.text.Collator;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ASLBoardPicker extends BoardPicker implements ActionListener {
private static final Logger logger =
LoggerFactory.getLogger(ASLBoardPicker.class);
/**
* The key for the preferences setting giving the board directory
*/
public static final String BOARD_DIR = "boardURL";
private File boardDir;
protected TerrainEditor terrain;
private SetupControls setupControls;
private boolean enableDeluxe;
public ASLBoardPicker() {
}
protected void initComponents() {
initTerrainEditor();
super.initComponents();
addButton("Add overlays");
addButton("Crop boards");
addButton("Terrain SSR");
}
public Command decode(String command) {
if (command.startsWith("bd\t")) {
List<Board> v = new ArrayList<Board>();
Command comm = new NullCommand();
if (command.length() > 3) {
command = command.substring(3);
for (int index = command.indexOf("bd\t"); index > 0; index = command.indexOf("bd\t")) {
ASLBoard b = new VASLBoard();
String boardDesc = command.substring(0, index);
try {
StringTokenizer st2 = new StringTokenizer(boardDesc, "\t\n");
b.relativePosition().move(Integer.parseInt(st2.nextToken()), Integer.parseInt(st2.nextToken()));
String baseName = st2.nextToken();
this.tileBoard(baseName);
buildBoard(b, boardDesc);
v.add(b);
} catch (final BoardException e) {
ErrorDialog.dataError(new BadDataReport("Board not found", boardDesc, e));
}
command = command.substring(index + 3);
}
ASLBoard b = new VASLBoard();
try {
StringTokenizer st2 = new StringTokenizer(command, "\t\n");
b.relativePosition().move(Integer.parseInt(st2.nextToken()), Integer.parseInt(st2.nextToken()));
String baseName = st2.nextToken();
this.tileBoard(baseName);
buildBoard(b, command);
v.add(b);
} catch (final BoardException e) {
ErrorDialog.dataError(new BadDataReport("Unable to build board", command, e));
}
}
comm = comm.append(new SetBoards(this, v));
return comm;
} else {
return null;
}
}
public String encode(Command c) {
if (c instanceof SetBoards && map != null) {
String s = "bd\t";
for (Iterator it = getSelectedBoards().iterator(); it.hasNext(); ) {
ASLBoard b = (ASLBoard) it.next();
s += b.getState();
if (it.hasNext()) {
s += "bd\t";
}
}
return s;
} else {
return null;
}
}
public void addTo(Buildable b) {
DirectoryConfigurer config = new VASSAL.configure.DirectoryConfigurer(BOARD_DIR, "Board Directory");
final GameModule g = GameModule.getGameModule();
g.getPrefs().addOption(config);
String storedValue = g.getPrefs().getStoredValue(BOARD_DIR);
if (storedValue == null || !new File(storedValue).exists()) {
File archive = new File(g.getDataArchive().getName());
File dir = archive.getParentFile();
File defaultDir = new File(dir, "boards");
if (!defaultDir.exists()) {
defaultDir.mkdir();
}
config.setValue(defaultDir);
}
setBoardDir((File) g.getPrefs().getValue(BOARD_DIR));
g.getPrefs().getOption(BOARD_DIR).addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
setBoardDir((File) evt.getNewValue());
}
});
super.addTo(b);
}
public void setBoardDir(File dir) {
boardDir = dir;
refreshPossibleBoards();
reset();
}
@Override
public void setup(boolean show) {
super.setup(show);
if (show) {
setGlobalMapScale();
}
}
@Override
/**
* This is a hack to prevent setup from being called multiple times when creating a new game.
* When this happens the VASL map gets created twice, which is bad
*/
public void finish() {
currentBoards = new ArrayList<Board>(getBoardsFromControls());
}
public void setGlobalMapScale() {
Collection<Board> bds = getSelectedBoards();
if (bds.iterator().hasNext()) {
double mag = bds.iterator().next().getMagnification();
double globalScale = 0.19444444;
if (mag > 1.0) {
globalScale /= mag;
}
map.getComponentsOf(GlobalMap.class).get(0).setAttribute("scale", globalScale);
}
}
public File getBoardDir() {
return boardDir;
}
public void initTerrainEditor() {
if (terrain == null) {
terrain = new TerrainEditor();
InputStream in = null;
try {
in = GameModule.getGameModule().getDataArchive().getInputStream("boardData/SSRControls");
terrain.readOptions(in);
} catch (IOException ignore) {
} finally {
IOUtils.closeQuietly(in);
}
}
}
/**
* Reads the current board directory and constructs the list of available boards
*/
public void refreshPossibleBoards() {
String files[] = boardDir == null ? new String[0] : boardDir.list();
List<String> sorted = new ArrayList<String>();
for (int i = 0; i < files.length; ++i) {
if (files[i].startsWith("bd") && !(new File(boardDir, files[i])).isDirectory()) {
String name = files[i].substring(2);
if (name.endsWith(".gif")) {
name = name.substring(0, name.indexOf(".gif"));
} else if (name.indexOf(".") >= 0) {
name = null;
}
if (name != null && !sorted.contains(name)) {
sorted.add(name);
}
}
}
// * Strings with leading zeros sort ahead of those without.
// * Strings with leading integer parts sort ahead of those without.
// * Strings with lesser leading integer parts sort ahead of those with
// greater leading integer parts.
// * Strings which are otherwise equal are sorted lexicographically by
// their trailing noninteger parts.
final Comparator<Object> alpha = Collator.getInstance();
final Pattern pat = Pattern.compile("((0*)\\d*)(.*)");
Comparator<String> comp = new Comparator<String>() {
public int compare(String o1, String o2) {
final Matcher m1 = pat.matcher(o1);
final Matcher m2 = pat.matcher(o2);
if (!m1.matches()) {
// impossible
throw new IllegalStateException();
}
if (!m2.matches()) {
// impossible
throw new IllegalStateException();
}
// count leading zeros
final int z1 = m1.group(2).length();
final int z2 = m2.group(2).length();
// more leading zeros comes first
if (z1 < z2) {
return 1;
} else if (z1 > z2) {
return -1;
}
// same number of leading zeros
final String o1IntStr = m1.group(1);
final String o2IntStr = m2.group(1);
if (o1IntStr.length() > 0) {
if (o2IntStr.length() > 0) {
try {
// both strings have integer parts
final BigInteger o1Int = new BigInteger(o1IntStr);
final BigInteger o2Int = new BigInteger(o2IntStr);
if (!o1Int.equals(o2Int)) {
// one integer part is smaller than the other
return o1Int.compareTo(o2Int);
}
} catch (NumberFormatException e) {
// impossible
throw new IllegalStateException(e);
}
} else {
// only o1 has an integer part
return -1;
}
} else if (o2IntStr.length() > 0) {
// only o2 has an integer part
return 1;
}
// the traling string part is decisive
return alpha.compare(m1.group(3), m2.group(3));
}
};
Collections.sort(sorted, comp);
possibleBoards.clear();
for (int i = 0; i < sorted.size(); ++i) {
addBoard((String) sorted.get(i));
}
}
public void build(Element e) {
allowMultiple = true;
}
/*
* Tiles a board by common name (e.g. 21, not bd21)
*/
private void tileBoard(String commonName) {
final GameModule g = GameModule.getGameModule();
final String hstr =
DigestUtils.shaHex(g.getGameName() + "_" + g.getGameVersion());
String unReversedBoardName;
if (commonName.startsWith("r")) {
if (commonName.equalsIgnoreCase("r")) {
// board r or R, this is ok
unReversedBoardName = commonName;
} else {
// board rX, this is really X
// Red Barricades (RB) and Ruweisat Ridge (RR) should not have gotten here
unReversedBoardName = commonName.substring(1);
}
} else {
unReversedBoardName = commonName;
}
final File fpath = new File(boardDir, "bd" + unReversedBoardName);
final ASLTilingHandler th = new ASLTilingHandler(
fpath.getAbsolutePath(),
new File(Info.getConfDir(), "tiles/" + hstr),
new Dimension(256, 256),
1024,
42
);
try {
th.sliceTiles();
} catch (IOException e) {
ReadErrorDialog.error(e, fpath);
}
}
public void addBoard(String name) {
final ASLBoard b = new VASLBoard();
b.setCommonName(name);
possibleBoards.add(b);
}
public void validate(Buildable target, ValidationReport report) {
}
public String[] getAllowableBoardNames() {
String s[] = new String[possibleBoards.size()];
for (int i = 0; i < s.length; ++i) {
s[i] = ((ASLBoard) possibleBoards.get(i)).getCommonName();
}
return s;
}
public Configurable[] getConfigureComponents() {
return new Configurable[0];
}
public Board getBoard(String name, boolean localized) {
this.tileBoard(name);
ASLBoard b = new VASLBoard();
if (name != null) {
if (name.length() == 1 && name.charAt(0) <= '9' && name.charAt(0) >= '0') {
name = '0' + name;
} else if (name.length() == 1 && name.charAt(0) <= 'H' && name.charAt(0) >= 'A') {
name = "dx" + name.toLowerCase();
}
try {
buildBoard(b, "0\t0\t" + name);
} catch (BoardException e) {
ErrorDialog.dataError(new BadDataReport("Unable to build board", name, e));
}
}
if (enableDeluxe) {
b.setMagnification(3.0);
((HexGrid) b.getGrid()).setSnapScale(2);
}
return b;
}
public void buildBoard(ASLBoard b, String bd) throws BoardException {
StringTokenizer st2 = new StringTokenizer(bd, "\t\n");
try {
b.relativePosition().move(Integer.parseInt(st2.nextToken()), Integer.parseInt(st2.nextToken()));
String baseName = st2.nextToken();
String unReversedBoardName;
if (baseName.startsWith("r")) {
if (baseName.equalsIgnoreCase("r")) {
// board r or R, this is ok
unReversedBoardName = baseName;
b.setReversed(false);
} else {
// board rX, this is really X
// Red Barricades (RB) and Ruweisat Ridge (RR) should not have gotten here
unReversedBoardName = baseName.substring(1);
b.setReversed(true);
}
} else {
unReversedBoardName = baseName;
b.setReversed(false);
}
File f;
f = new File(boardDir, "bd" + unReversedBoardName);
if (f.exists()) {
b.setCommonName(unReversedBoardName);
b.setBaseImageFileName("bd" + unReversedBoardName + ".gif", f);
} else {
throw new BoardException("Unable to find board " + baseName);
}
b.readData();
} catch (Exception eParse) {
// eParse.printStackTrace();
throw new BoardException(eParse.getMessage(), eParse);
}
try {
int x1 = Integer.parseInt(st2.nextToken());
int y1 = Integer.parseInt(st2.nextToken());
int wid = Integer.parseInt(st2.nextToken());
int hgt = Integer.parseInt(st2.nextToken());
b.setCropBounds(new Rectangle(x1, y1, wid, hgt));
} catch (Exception e) {
b.setCropBounds(new Rectangle(0, 0, -1, -1));
}
if (bd.indexOf("VER") >= 0) {
StringTokenizer st = new StringTokenizer(bd.substring(bd.indexOf("VER") + 4), "\t");
if (st.countTokens() >= 1) {
String reqver = st.nextToken();
if (reqver.compareTo(b.getVersion()) != 0)
GameModule.getGameModule().warn("This game was saved with board " + b.getName() + " v" + reqver + ". You are using v" + b.getVersion());
}
}
while (bd.indexOf("OVR") >= 0) {
bd = bd.substring(bd.indexOf("OVR") + 4);
try {
b.addOverlay(new Overlay(bd, b, new File(getBoardDir(), "overlays")));
} catch (IOException e) {
e.printStackTrace();
}
}
if (bd.indexOf("SSR") >= 0) {
b.setTerrain(bd.substring(bd.indexOf("SSR") + 4));
}
if (bd.indexOf("ZOOM") >= 0) {
// occasionally ZOOM is encoded multiple times - ignore this error as it's very rare
// and ignoring zoom has no real side effects
try {
b.setMagnification(Double.parseDouble(bd.substring(bd.indexOf("ZOOM") + 5)));
}
catch (Exception e) {
// bury
}
}
}
protected void addColumn() {
slotPanel.setLayout(new GridLayout(ny, ++nx));
for (int j = 0; j < ny; ++j) {
slotPanel.add(new ASLBoardSlot(this), (j + 1) * nx - 1);
}
slotPanel.revalidate();
}
protected void addRow() {
slotPanel.setLayout(new GridLayout(++ny, nx));
for (int i = 0; i < nx; ++i) {
slotPanel.add(new ASLBoardSlot(this), -1);
}
slotPanel.revalidate();
}
public void reset() {
super.reset();
removeAllBoards();
slotPanel.add(new ASLBoardSlot(this), 0);
terrain.reset();
if (setupControls == null) {
setupControls = new SetupControls();
}
setupControls.reset();
}
public void actionPerformed(ActionEvent e) {
String label = e.getActionCommand();
if ("Add overlays".equals(label)) {
Overlayer o;
Dialog d = getDialogContainer();
o = d == null ? new Overlayer(getFrameContainer()) : new Overlayer(d);
o.setLocationRelativeTo(controls.getTopLevelAncestor());
o.setVisible(true);
} else if ("Crop boards".equals(label)) {
Cropper crop;
Dialog d = getDialogContainer();
crop = d == null ? new Cropper(getFrameContainer()) : new Cropper(d);
crop.setLocationRelativeTo(controls.getTopLevelAncestor());
crop.setVisible(true);
} else if ("Terrain SSR".equals(label)) {
currentBoards = getBoardsFromControls();
terrain.setup(currentBoards);
} else {
super.actionPerformed(e);
}
}
protected Dialog getDialogContainer() {
Container top = controls.getTopLevelAncestor();
return (Dialog) (top instanceof Dialog ? top : null);
}
protected Frame getFrameContainer() {
Container top = controls.getTopLevelAncestor();
return (Frame) (top instanceof Frame ? top : null);
}
public BoardSlot match(String s) throws BoardException {
if ("".equals(s)) {
if (slotPanel.getComponentCount() == 1)
return (BoardSlot) slotPanel.getComponent(0);
else
throw new BoardException("No Such Board");
}
for (int i = 0; i < nx; ++i)
for (int j = 0; j < ny; ++j) {
BoardSlot b = getSlot(i + nx * j);
if (b.getBoard() == null)
continue;
if (b.getBoard().getName().equalsIgnoreCase(s))
return (b);
}
throw new BoardException("No Such Board");
}
public org.w3c.dom.Element getBuildElement(org.w3c.dom.Document doc) {
org.w3c.dom.Element el = doc.createElement(getClass().getName());
return el;
}
public Component getControls() {
reset();
return setupControls;
}
private class SetupControls extends JPanel {
private DirectoryConfigurer dirConfig;
public SetupControls() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
final DirectoryConfigurer pref = (DirectoryConfigurer) GameModule.getGameModule().getPrefs().getOption(BOARD_DIR);
dirConfig = new DirectoryConfigurer(null, pref.getName());
dirConfig.setValue(pref.getFileValue());
add(dirConfig.getControls());
JCheckBox deluxe = new JCheckBox("Deluxe-size hexes");
deluxe.setAlignmentX(0.0F);
deluxe.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
enableDeluxe = e.getStateChange() == ItemEvent.SELECTED;
int n = 0;
ASLBoardSlot slot;
while ((slot = (ASLBoardSlot) getSlot(n++)) != null) {
if (slot.getBoard() != null) {
slot.getBoard().setMagnification(enableDeluxe ? 3.0 : 1.0);
slot.setSize(slot.getPreferredSize());
slot.revalidate();
slot.repaint();
}
}
}
});
add(deluxe);
add(controls);
dirConfig.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
pref.setFrozen(true);
pref.setValue(evt.getNewValue());
pref.setFrozen(false);
setBoardDir((File) evt.getNewValue());
}
});
pref.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
pref.setFrozen(true);
dirConfig.setValue(evt.getNewValue());
pref.setFrozen(false);
}
});
}
public void reset() {
}
}
protected class Cropper extends JDialog implements ActionListener {
private JTextField row1, row2, coord1, coord2;
private JComboBox<String> bdName;
private JRadioButton halfrow, fullrow;
protected Cropper(Frame owner) {
super(owner, true);
init();
}
protected Cropper(Dialog owner) {
super(owner, true);
init();
}
private void init() {
row1 = new JTextField(2);
row1.addActionListener(this);
row2 = new JTextField(2);
row2.addActionListener(this);
coord1 = new JTextField(2);
coord1.addActionListener(this);
coord2 = new JTextField(2);
coord2.addActionListener(this);
halfrow = new JRadioButton("Crop to middle of hex row");
fullrow = new JRadioButton("Crop to nearest full hex row (no LOS)");
fullrow.setSelected(true);
ButtonGroup bg = new ButtonGroup();
bg.add(halfrow);
bg.add(fullrow);
halfrow.setSelected(true);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
Box box = Box.createHorizontalBox();
JLabel l = new JLabel("Board:");
box.add(l);
bdName = new JComboBox<String>(getBoards());
box.add(bdName);
getContentPane().add(box);
box = Box.createHorizontalBox();
box.add(new JLabel("Hexrows:"));
box.add(row1);
box.add(new JLabel("-"));
box.add(row2);
getContentPane().add(box);
box = Box.createHorizontalBox();
box.add(new JLabel("Coords:"));
box.add(coord1);
box.add(new JLabel("-"));
box.add(coord2);
getContentPane().add(box);
box = Box.createVerticalBox();
box.add(halfrow);
box.add(fullrow);
getContentPane().add(box);
box = Box.createHorizontalBox();
JButton b = new JButton("Crop");
b.addActionListener(this);
box.add(b);
b = new JButton("Done");
b.addActionListener(this);
box.add(b);
getContentPane().add(box);
pack();
setLocation(Toolkit.getDefaultToolkit().getScreenSize().width / 2 - getWidth() / 2, Toolkit.getDefaultToolkit().getScreenSize().height / 2 - getHeight()
/ 2);
}
/**
* @return an array of boards in the map
*/
private String[] getBoards() {
List<Board> boards = getBoardsFromControls();
String[] b = new String[boards.size()];
Iterator it = boards.iterator();
for(int x = 0; x < b.length; x++) {
b[x] = ((ASLBoard) it.next()).getCommonName();
}
return b;
}
public void clear() {
row1.setText("");
row2.setText("");
coord1.setText("");
coord2.setText("");
}
public void actionPerformed(ActionEvent e) {
if ("Done".equals(e.getActionCommand())) {
setVisible(false);
return;
}
try {
BoardSlot b = match((String) bdName.getSelectedItem());
((ASLBoard) b.getBoard()).crop(row1.getText().toLowerCase().trim(), row2.getText().toLowerCase().trim(), coord1.getText().toLowerCase().trim(), coord2
.getText().toLowerCase().trim(), fullrow.isSelected());
b.invalidate();
b.repaint();
row1.setText("");
row2.setText("");
coord1.setText("");
coord2.setText("");
} catch (Exception ex) {
}
}
}
protected class Overlayer extends JDialog implements ActionListener {
private JTextField hex1, hex2, ovrName;
private JLabel status;
private JComboBox<String> bdName;
protected Overlayer(Frame f) {
super(f, true);
setTitle("Overlays");
init();
}
protected Overlayer(Dialog d) {
super(d, true);
setTitle("Overlays");
init();
}
private void init() {
hex1 = new JTextField(2);
hex1.addActionListener(this);
hex2 = new JTextField(2);
hex2.addActionListener(this);
ovrName = new JTextField(2);
ovrName.addActionListener(this);
status = new JLabel("Enter blank hexes to delete.", JLabel.CENTER);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(status);
Box box = Box.createHorizontalBox();
Box vBox = Box.createVerticalBox();
vBox.add(new JLabel("Overlay"));
vBox.add(ovrName);
box.add(vBox);
vBox = Box.createVerticalBox();
vBox.add(new JLabel("Board"));
bdName = new JComboBox<String>(getBoards());
vBox.add(bdName);
box.add(vBox);
vBox = Box.createVerticalBox();
vBox.add(new JLabel("Hex 1"));
vBox.add(hex1);
box.add(vBox);
vBox = Box.createVerticalBox();
vBox.add(new JLabel("Hex 2"));
vBox.add(hex2);
box.add(vBox);
getContentPane().add(box);
box = Box.createHorizontalBox();
JButton b = new JButton("Add");
b.addActionListener(this);
box.add(b);
b = new JButton("Done");
b.addActionListener(this);
box.add(b);
getContentPane().add(box);
pack();
setLocation(Toolkit.getDefaultToolkit().getScreenSize().width / 2 - getSize().width / 2, Toolkit.getDefaultToolkit().getScreenSize().height / 2
- getSize().height / 2);
}
public void clear() {
status.setText("Enter blank hexes to delete.");
hex1.setText("");
hex2.setText("");
ovrName.setText("");
}
public void actionPerformed(ActionEvent e) {
if ("Done".equals(e.getActionCommand())) {
setVisible(false);
return;
}
try {
status.setText(((ASLBoardSlot) (match((String) bdName.getSelectedItem()))).addOverlay(ovrName.getText().toLowerCase(), hex1.getText().toLowerCase(), hex2.getText()
.toLowerCase()));
ovrName.setText("");
hex1.setText("");
hex2.setText("");
if (false)
throw new BoardException("Now that's weird");
} catch (BoardException excep) {
status.setText(excep.getMessage());
}
}
/**
* @return an array of boards in the map
*/
private String[] getBoards() {
List<Board> boards = getBoardsFromControls();
String[] b = new String[boards.size()];
Iterator it = boards.iterator();
for(int x = 0; x < b.length; x++) {
b[x] = ((ASLBoard) it.next()).getCommonName();
}
return b;
}
}
protected class TerrainEditor extends JDialog implements ActionListener {
private Vector optionGroup = new Vector();
private JList optionList;
private JTextField status;
private JPanel options;
private CardLayout card;
private Vector basicOptions = new Vector();
private TerrainMediator mediator = new TerrainMediator();
private Vector boards;
protected JButton apply, reset, done;
private JComboBox<String> bdName = new JComboBox<String>();
protected TerrainEditor() {
super((Frame) null, true);
setTitle("Terrain Transformations");
boards = new Vector();
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
status = new JTextField("Leave board number blank to apply to all boards: ");
status.setMaximumSize(new Dimension(status.getMaximumSize().width, status.getPreferredSize().height));
status.setEditable(false);
card = new CardLayout();
options = new JPanel();
options.setLayout(card);
optionList = new JList(new DefaultListModel());
optionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
optionList.setVisibleRowCount(4);
optionList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent e) {
showOption();
}
});
getContentPane().add(status);
Box box = Box.createHorizontalBox();
JPanel p = new JPanel();
p.setLayout(new GridLayout(4, 1));
JPanel pp = new JPanel();
pp.setLayout(new GridBagLayout());
pp.add(new JLabel("Board "));
pp.add(bdName);
p.add(pp);
apply = new JButton("Apply");
apply.addActionListener(this);
reset = new JButton("Reset");
reset.addActionListener(this);
done = new JButton("Done");
done.addActionListener(this);
p.add(apply);
p.add(reset);
p.add(done);
box.add(p);
box.add(new JScrollPane(optionList));
box.add(options);
getContentPane().add(box, -1);
pack();
}
private void showOption() {
card.show(options, (String) optionList.getSelectedValue());
}
public ASLBoardPicker getBoardPicker() {
return ASLBoardPicker.this;
}
public void setup(Collection<Board> boardList) {
Box box = Box.createVerticalBox();
for (int i = 0; i < 4; ++i) {
TransformOption opt = new TransformOption();
box.add(opt.getComponent());
optionGroup.addElement(opt);
}
addOption("Transformations", box);
boards.removeAllElements();
String version = "";
int nboards = 0;
for (Board board : boardList) {
ASLBoard b = (ASLBoard) board;
boards.addElement(b);
if (b != null) {
if (b.getBoardArchive() != null) {
InputStream in = null;
try {
in = b.getBoardArchive().getInputStream("SSRControls");
readOptions(in);
} catch (IOException ignore) {
} finally {
IOUtils.closeQuietly(in);
}
}
for (Enumeration oEnum = b.getOverlays(); oEnum.hasMoreElements(); ) {
Overlay o = (Overlay) oEnum.nextElement();
if (!(o instanceof SSROverlay)) {
InputStream in = null;
try {
in = o.getDataArchive().getInputStream("SSRControls");
readOptions(in);
} catch (IOException ignore) {
} finally {
IOUtils.closeQuietly(in);
}
}
}
nboards++;
version = version.concat(b.getName() + " (ver " + b.version + ") ");
}
}
switch (nboards) {
case 0:
warn("No boards loaded");
break;
case 1:
warn("Loaded board " + version);
break;
default:
warn("Loaded boards " + version + " (leave board number blank to apply to all)");
}
pack();
setVisible(true);
}
public void warn(String s) {
status.setText(s);
Container c = this;
while (c.getParent() != null)
c = c.getParent();
c.invalidate();
c.validate();
c.repaint();
}
public void readOptions(InputStream in) {
if (in != null) {
try {
Document doc = Builder.createDocument(in);
NodeList n = doc.getElementsByTagName("Basic");
if (n.getLength() > 0) {
n = (n.item(0)).getChildNodes();
Box basicPanel = Box.createHorizontalBox();
for (int j = 0; j < n.getLength(); ++j) {
if (n.item(j).getNodeType() == Node.ELEMENT_NODE) {
Element el2 = (Element) n.item(j);
TerrainOption opt = new TerrainOption(mediator, el2);
((Container) opt.getComponent()).setLayout(new BoxLayout((Container) opt.getComponent(), BoxLayout.Y_AXIS));
basicPanel.add(opt.getComponent());
basicOptions.addElement(opt);
}
}
getContentPane().add(basicPanel, 0);
}
n = doc.getElementsByTagName("Option");
for (int i = 0; i < n.getLength(); ++i) {
Element el = (Element) n.item(i);
Box box = Box.createVerticalBox();
NodeList nl = el.getChildNodes();
for (int j = 0; j < nl.getLength(); ++j) {
if (nl.item(j).getNodeType() == Node.ELEMENT_NODE) {
Element el2 = (Element) nl.item(j);
TerrainOption opt = new TerrainOption(mediator, el2);
box.add(opt.getComponent());
optionGroup.addElement(opt);
}
}
addOption(el.getAttribute("name"), box);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void addOption(String name, Component c) {
for (int i = 0; i < optionList.getModel().getSize(); ++i) {
if (optionList.getModel().getElementAt(i).equals(name))
return;
}
((DefaultListModel) optionList.getModel()).addElement(name);
options.add(c, name);
card.addLayoutComponent(c, name);
}
private void reset(Vector opts) {
for (int i = 0; i < opts.size(); ++i) {
((TerrainOption) opts.elementAt(i)).reset();
}
}
public void reset() {
reset(basicOptions);
reset(optionGroup);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
if ("Apply".equals(e.getActionCommand())) {
warn("Working ...");
String opText = optionText();
String bText = basicText();
try {
String boardName = (String) bdName.getSelectedItem();
int n = 0;
ASLBoardSlot slot;
while ((slot = (ASLBoardSlot) getSlot(n++)) != null) {
if (boardName.length() == 0 || match(boardName) == slot) {
slot.setTerrain(slot.getTerrain() + '\t' + optionRules());
if (slot.getBoard() == null) continue;
((ASLBoard) slot.getBoard()).setTerrain(basicRules() + slot.getTerrain());
slot.repaint();
}
}
if (opText.length() > 0) {
bText = bText.length() == 0 ? opText : bText + ", " + opText;
}
warn((boardName.length() == 0 ? "All boards" : "Board " + bdName.getSelectedItem()) + ": " + bText);
} catch (BoardException e1) {
e1.printStackTrace();
warn(e1.getMessage());
}
reset(optionGroup);
} else if ("Reset".equals(e.getActionCommand())) {
reset();
try {
int n = 0;
while (true) {
ASLBoardSlot slot = null;
try {
slot = (ASLBoardSlot) getSlot(n++);
} catch (Exception noSuchSlot) {
break;
}
slot.setTerrain("");
try {
((ASLBoard) slot.getBoard()).setTerrain("");
} catch (Exception e2) {
}
slot.repaint();
}
warn("Back to normal");
} catch (Exception resetError) {
warn(resetError.getMessage());
}
} else if ("Done".equals(e.getActionCommand())) {
reset();
setVisible(false);
}
}
}
public String basicRules() {
String s = "";
for (int i = 0; i < basicOptions.size(); ++i) {
s = s.concat(((TerrainOption) basicOptions.elementAt(i)).getRule());
}
return s;
}
public String basicText() {
String s = "";
for (int i = 0; i < basicOptions.size(); ++i) {
s = s.concat(((TerrainOption) basicOptions.elementAt(i)).getText());
}
return s;
}
public String optionRules() {
String s = "";
for (int i = 0; i < optionGroup.size(); ++i) {
// s = s.concat(((TerrainOption) optionGroup.elementAt(i)).getRule());
if (s.length() > 0 && ((TerrainOption) optionGroup.elementAt(i)).getRule().length() > 0) {
s = s.concat("\t").concat(((TerrainOption) optionGroup.elementAt(i)).getRule());
} else {
s = s.concat(((TerrainOption) optionGroup.elementAt(i)).getRule());
}
}
return s;
}
public String optionText() {
String s = "";
for (int i = 0; i < optionGroup.size(); ++i) {
s = s.concat(((TerrainOption) optionGroup.elementAt(i)).getText());
}
return s.endsWith(", ") ? s.substring(0, s.length() - 2) : s;
}
protected class TerrainOption {
protected Component comp;
protected JPanel panel = new JPanel();
private Vector active;
private String text;
private String rule;
private String name;
protected Hashtable rules = new Hashtable();
protected Hashtable texts = new Hashtable();
protected Vector defaults = new Vector();
protected PropertyChangeSupport propChange = new PropertyChangeSupport(this);
protected TerrainOption() {
}
public TerrainOption(TerrainMediator mediator, Element e) {
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
name = e.getAttribute("name");
if (e.getElementsByTagName("Source").getLength() > 0)
mediator.addSource(this);
if (e.getTagName().equals("Menu")) {
comp = new JComboBox();
((JComboBox) comp).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
invalidate();
propChange.firePropertyChange("active", null, getActive());
}
});
comp.setMaximumSize(new Dimension(comp.getMaximumSize().width, comp.getPreferredSize().height));
} else if (e.getTagName().equals("ScrollList")) {
comp = new JList(new DefaultListModel());
((JList) comp).addListSelectionListener(new ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
invalidate();
propChange.firePropertyChange("active", null, getActive());
}
});
} else if (e.getTagName().equals("Checkbox")) {
comp = new JCheckBox();
((JCheckBox) comp).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
invalidate();
propChange.firePropertyChange("active", null, getActive());
}
});
} else {
throw new RuntimeException("Unrecognized SSR component type " + e.getTagName());
}
NodeList n = e.getElementsByTagName("entry");
for (int i = 0; i < n.getLength(); ++i) {
Element entry = (Element) n.item(i);
String entryName = entry.getAttribute("name");
rules.put(entryName, entry.getAttribute("rule").replace(',', '\t'));
texts.put(entryName, entry.getAttribute("text"));
if (comp instanceof JCheckBox) {
((JCheckBox) comp).setText(entryName);
} else if (comp instanceof JList) {
((DefaultListModel) ((JList) comp).getModel()).addElement(entryName);
} else if (comp instanceof JComboBox) {
((DefaultComboBoxModel) ((JComboBox) comp).getModel()).addElement(entryName);
if (entry.getAttribute("default").length() > 0) {
defaults.addElement(entryName);
}
}
NodeList targList = entry.getElementsByTagName("Target");
for (int targIndex = 0; targIndex < targList.getLength(); ++targIndex) {
Vector activate = null;
Vector deactivate = null;
String sourceName = null;
Element targ = (Element) targList.item(targIndex);
sourceName = targ.getAttribute("sourceName");
NodeList nl = targ.getElementsByTagName("activate");
if (nl.getLength() > 0) {
activate = new Vector();
for (int j = 0; j < nl.getLength(); ++j) {
activate.addElement(((Element) nl.item(j)).getAttribute("sourceProperty"));
}
}
nl = targ.getElementsByTagName("deactivate");
if (nl.getLength() > 0) {
deactivate = new Vector();
for (int j = 0; j < nl.getLength(); ++j) {
deactivate.addElement(((Element) nl.item(j)).getAttribute("sourceProperty"));
}
}
if (activate != null || deactivate != null) {
mediator.addTarget(this, entryName, sourceName, activate, deactivate);
}
}
}
if (!(comp instanceof JCheckBox) || !getName().equals(((JCheckBox) comp).getText())) {
panel.add(new JLabel(getName()));
}
if (comp instanceof JList) {
panel.add(new JScrollPane(comp));
} else {
panel.add(comp);
}
panel.setVisible(e.getElementsByTagName("invisible").getLength() == 0);
}
public Component getComponent() {
return panel;
}
public void reset() {
for (Enumeration e = getActive().elements(); e.hasMoreElements(); ) {
activate((String) e.nextElement(), false);
}
for (Enumeration e = defaults.elements(); e.hasMoreElements(); ) {
activate((String) e.nextElement(), true);
}
}
public void activate(String val, boolean isActive) {
invalidate();
if (comp instanceof JCheckBox) {
((JCheckBox) comp).setSelected(isActive && ((JCheckBox) comp).getText().equals(val));
} else if (comp instanceof JComboBox) {
if (val == null || !isActive) {
if (defaults.size() > 0) {
((JComboBox) comp).setSelectedItem(defaults.elementAt(0));
} else {
((JComboBox) comp).setSelectedIndex(0);
}
} else {
((JComboBox) comp).setSelectedItem(val);
}
} else if (comp instanceof JList) {
ListModel model = ((JList) comp).getModel();
for (int j = 0; j < model.getSize(); ++j) {
if (model.getElementAt(j).equals(val)) {
if (isActive) {
((JList) comp).addSelectionInterval(j, j);
} else {
((JList) comp).removeSelectionInterval(j, j);
}
break;
}
}
}
propChange.firePropertyChange("active", null, getActive());
}
public String getName() {
return name;
}
private void invalidate() {
active = null;
rule = null;
text = null;
}
public Vector getActive() {
if (active == null) {
active = new Vector();
if (comp instanceof JCheckBox) {
active.addElement(((JCheckBox) comp).isSelected() ? ((JCheckBox) comp).getText() : "");
} else if (comp instanceof JComboBox) {
active.addElement(((JComboBox) comp).getSelectedItem());
} else if (comp instanceof JList) {
Object val[] = ((JList) comp).getSelectedValues();
for (int i = 0; i < val.length; ++i) {
active.addElement(val[i]);
}
}
}
return active;
}
public String getRule() {
if (rule == null) {
rule = "";
for (Enumeration e = getActive().elements(); e.hasMoreElements(); ) {
String s = (String) rules.get(e.nextElement());
if (s != null && s.length() > 0)
rule = rule.concat(s + '\t');
}
}
return rule;
}
public String getText() {
if (text == null) {
text = "";
for (Enumeration e = getActive().elements(); e.hasMoreElements(); ) {
String s = (String) texts.get(e.nextElement());
if (s != null && s.length() > 0)
text = text.concat(s + ", ");
}
}
return text;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propChange.addPropertyChangeListener(l);
}
}
protected abstract class TerrainOptions extends JPanel {
protected Vector choices = new Vector();
protected Vector checkboxes = new Vector();
protected Vector lists = new Vector();
protected Hashtable translations;
protected Hashtable plain;
TerrainOptions() {
translations = new Hashtable();
plain = new Hashtable();
translations.put("Normal", "");
plain.put("Normal", "");
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
}
void addComponent(String name, Component c) {
Box box = Box.createHorizontalBox();
box.add(new JLabel(name));
box.add(c);
add(box);
if (c instanceof JCheckBox) {
checkboxes.addElement(c);
} else if (c instanceof JComboBox) {
choices.addElement(c);
} else if (c instanceof JList) {
lists.addElement(c);
}
}
void addToChoice(JComboBox c, String text, String translation, String plainName) {
((DefaultComboBoxModel) c.getModel()).addElement(text);
setTranslation(text, translation, plainName);
}
void setTranslation(String text, String translation, String plainName) {
if (translation.length() > 0) {
StringTokenizer st = new StringTokenizer(translation, ",");
while (st.hasMoreTokens()) {
translations.put(text, st.nextToken() + "\t");
}
} else
translations.put(text, "");
if (plainName.length() > 0)
plain.put(text, plainName + ", ");
else
plain.put(text, "");
}
public void reset() {
JCheckBox cb;
JComboBox c;
JList l;
for (int i = 0; i < checkboxes.size(); ++i) {
cb = (JCheckBox) checkboxes.elementAt(i);
cb.setSelected(false);
}
for (int i = 0; i < choices.size(); ++i) {
c = (JComboBox) choices.elementAt(i);
c.setSelectedIndex(0);
}
for (int i = 0; i < lists.size(); ++i) {
l = (JList) lists.elementAt(i);
l.setSelectedIndex(-1);
}
}
public String toString() {
String s = "";
JCheckBox cb;
JComboBox c;
JList l;
for (int i = 0; i < checkboxes.size(); ++i) {
cb = (JCheckBox) checkboxes.elementAt(i);
if (cb.isSelected())
s = s.concat((String) translations.get(cb.getText()));
}
for (int i = 0; i < choices.size(); ++i) {
c = (JComboBox) choices.elementAt(i);
s = s.concat((String) translations.get(c.getSelectedItem()));
}
for (int i = 0; i < lists.size(); ++i) {
l = (JList) lists.elementAt(i);
for (int n = 0; n < l.getModel().getSize(); ++n) {
if (l.isSelectedIndex(n)) {
s = s.concat((String) translations.get(l.getModel().getElementAt(n)));
}
}
}
return s;
}
public String plainText() {
String s = "";
JCheckBox cb;
JComboBox c;
JList l;
for (int i = 0; i < checkboxes.size(); ++i) {
cb = (JCheckBox) checkboxes.elementAt(i);
if (cb.isSelected())
s = s.concat((String) plain.get(cb.getText()));
}
for (int i = 0; i < choices.size(); ++i) {
c = (JComboBox) choices.elementAt(i);
s = s.concat((String) plain.get(c.getSelectedItem()));
}
for (int i = 0; i < lists.size(); ++i) {
l = (JList) lists.elementAt(i);
for (int n = 0; n < l.getModel().getSize(); ++n) {
if (l.isSelectedIndex(n)) {
s = s.concat((String) plain.get(l.getModel().getElementAt(n)));
}
}
}
return s;
}
}
protected class TerrainMediator implements PropertyChangeListener {
private Hashtable targets = new Hashtable();
private Hashtable sources = new Hashtable();
TerrainMediator() {
}
public void addSource(TerrainOption opt) {
opt.addPropertyChangeListener(this);
sources.put(opt.getName(), opt);
}
public void addTarget(TerrainOption targ, String targetProp, String sourceName, Vector activate, Vector deactivate) {
getTargets(sourceName).addElement(new Target(targ, targetProp, activate, deactivate));
}
public void propertyChange(PropertyChangeEvent evt) {
Vector v = getTargets(((TerrainOption) evt.getSource()).getName());
for (Enumeration e = v.elements(); e.hasMoreElements(); ) {
((Target) e.nextElement()).sourceStateChanged((Vector) evt.getNewValue());
}
}
public void itemStateChanged(ItemEvent e) {
sourceStateChanged((String) sources.get(e.getSource()), getSourceSelection((Component) e.getSource()));
}
public void valueChanged(javax.swing.event.ListSelectionEvent e) {
sourceStateChanged((String) sources.get(e.getSource()), getSourceSelection((Component) e.getSource()));
}
private Vector getTargets(String srcName) {
Vector v = (Vector) targets.get(srcName);
if (v == null) {
v = new Vector();
targets.put(srcName, v);
}
return v;
}
private Vector getSourceSelection(Component source) {
Vector v = new Vector();
if (source instanceof JCheckBox) {
if (((JCheckBox) source).isSelected()) {
v.addElement(((JCheckBox) source).getText());
}
} else if (source instanceof JComboBox) {
Object o = ((JComboBox) source).getSelectedItem();
if (o != null)
v.addElement(o);
} else if (source instanceof JList) {
Object o[] = ((JList) source).getSelectedValues();
for (int i = 0; i < o.length; ++i) {
v.addElement(o);
}
} else {
throw new RuntimeException("Illegal source component " + source);
}
return v;
}
private void sourceStateChanged(String srcName, Vector active) {
Vector v = getTargets(srcName);
if (v != null) {
for (int i = 0; i < v.size(); ++i) {
((Target) v.elementAt(i)).sourceStateChanged(active);
}
}
}
}
protected class Target {
private TerrainOption target;
private String targetProperty;
private Vector activators;
private Vector deactivators;
Target(TerrainOption opt, String prop, Vector activate, Vector deactivate) {
activators = activate;
deactivators = deactivate;
targetProperty = prop;
target = opt;
}
public void sourceStateChanged(Vector active) {
if (activators != null) {
for (int i = 0; i < activators.size(); ++i) {
if (active.contains(activators.elementAt(i))) {
target.activate(targetProperty, true);
return;
}
}
}
if (deactivators != null) {
for (int i = 0; i < deactivators.size(); ++i) {
if (active.contains(deactivators.elementAt(i))) {
target.activate(targetProperty, false);
return;
}
}
}
}
public String toString() {
return target.getName() + "[" + targetProperty + "] " + activators;
}
}
protected class TransformOption extends TerrainOption {
private JComboBox from;
private JComboBox to = new JComboBox();
TransformOption() {
from = new JComboBox();
DefaultComboBoxModel model = (DefaultComboBoxModel) from.getModel();
model.addElement("-");
model.addElement("Woods");
model.addElement("Brush");
model.addElement("Grain");
model.addElement("Marsh");
model.addElement("Level -1");
model.addElement("Level 1");
model.addElement("Level 2");
model.addElement("Level 3");
model.addElement("Level 4");
from.setMaximumSize(new Dimension(from.getMaximumSize().width, from.getPreferredSize().height));
to = new JComboBox();
model = (DefaultComboBoxModel) to.getModel();
model.addElement("-");
model.addElement("Woods");
model.addElement("Brush");
model.addElement("Grain");
model.addElement("Marsh");
model.addElement("Level -1");
model.addElement("Level 0");
model.addElement("Level 1");
to.setMaximumSize(new Dimension(to.getMaximumSize().width, to.getPreferredSize().height));
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(new JLabel("All"));
panel.add(from);
panel.add(new JLabel("is"));
panel.add(to);
}
public String getRule() {
String s = "";
if (!from.getSelectedItem().equals("-") && !to.getSelectedItem().equals("-")) {
String fromRule = "";
for (StringTokenizer st = new StringTokenizer((String) from.getSelectedItem()); st.hasMoreTokens(); ) {
fromRule += st.nextToken();
}
fromRule = fromRule.replace('-', '_');
String toRule = "";
for (StringTokenizer st = new StringTokenizer((String) to.getSelectedItem()); st.hasMoreTokens(); ) {
toRule += st.nextToken();
}
toRule = toRule.replace('-', '_');
s = s.concat(fromRule);
s = s.concat("To");
s = s.concat(toRule);
}
return s;
}
public void reset() {
from.setSelectedIndex(0);
to.setSelectedIndex(0);
}
public String getText() {
String s = "";
if (!from.getSelectedItem().equals("-") && !to.getSelectedItem().equals("-")) {
s = "all " + ((String) from.getSelectedItem()).toLowerCase() + " is " + ((String) to.getSelectedItem()).toLowerCase();
}
return s;
}
}
@Override
public void setVisible(boolean visible) {
// update the board list when the dialog is shown
if(visible) {
bdName.removeAllItems();
bdName.addItem(""); // need a blank board name for "all"
Iterator it = getBoardsFromControls().iterator();
while (it.hasNext()) {
bdName.addItem(((ASLBoard) it.next()).getCommonName());
}
}
super.setVisible(visible);
}
}
}
|
package GraphBrowser;
import java.awt.*;
import java.applet.*;
import java.io.*;
import java.util.*;
import java.net.*;
import awtUtilities.*;
public class GraphBrowser extends Applet {
GraphView gv;
TreeBrowser tb=null;
String gfname;
static boolean isApplet;
static Frame f;
public GraphBrowser(String name) {
gfname=name;
}
public GraphBrowser() {}
public void showWaitMessage() {
if (isApplet)
getAppletContext().showStatus("calculating layout, please wait ...");
else {
f.setCursor(new Cursor(Cursor.WAIT_CURSOR));
}
}
public void showReadyMessage() {
if (isApplet)
getAppletContext().showStatus("ready !");
else {
f.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
public void viewFile(String fname) {
try {
if (isApplet)
getAppletContext().showDocument(new URL(getDocumentBase(), fname), "_blank");
else {
String path = gfname.substring(0, gfname.lastIndexOf('/') + 1);
Reader rd;
BufferedReader br;
String line, text = "";
try {
rd = new BufferedReader(new InputStreamReader((new URL(fname)).openConnection().getInputStream()));
} catch (Exception exn) {
rd = new FileReader(path + fname);
}
br = new BufferedReader(rd);
while ((line = br.readLine()) != null)
text += line + "\n";
if (fname.endsWith(".html")) {
String buf="";
char[] text2,text3;
int i,j=0;
boolean special=false, html=false;
char ctrl;
text2 = text.toCharArray();
text3 = new char[text.length()];
for (i = 0; i < text.length(); i++) {
char c = text2[i];
if (c == '&') {
special = true;
buf = "";
} else if (special) {
if (c == ';') {
special = false;
if (buf.equals("lt"))
text3[j++] = '<';
else if (buf.equals("gt"))
text3[j++] = '>';
else if (buf.equals("amp"))
text3[j++] = '&';
} else
buf += c;
} else if (c == '<') {
html = true;
ctrl = text2[i+1];
if ((ctrl == 'P') || (ctrl == 'B'))
text3[j++] = '\n';
} else if (c == '>')
html = false;
else if (!html)
text3[j++] = c;
}
text = String.valueOf(text3);
}
Frame f=new TextFrame(fname.substring(fname.lastIndexOf('/')+1),text);
f.setSize(500,600);
f.show();
}
} catch (Exception exn) {
System.out.println("Can't read file "+fname);
}
}
public void PS(String fname,boolean printable) throws IOException {
gv.PS(fname,printable);
}
public boolean isEmpty() {
return tb==null;
}
public void initBrowser(InputStream is) {
try {
TreeNode tn=new TreeNode("Root","",-1,true);
gv=new GraphView(new Graph(is,tn),this);
tb=new TreeBrowser(tn,gv);
gv.setTreeBrowser(tb);
Vector v = new Vector(10,10);
tn.collapsedDirectories(v);
gv.collapseDir(v);
ScrollPane scrollp1 = new ScrollPane();
ScrollPane scrollp2 = new ScrollPane();
scrollp1.add(gv);
scrollp2.add(tb);
scrollp1.getHAdjustable().setUnitIncrement(20);
scrollp1.getVAdjustable().setUnitIncrement(20);
scrollp2.getHAdjustable().setUnitIncrement(20);
scrollp2.getVAdjustable().setUnitIncrement(20);
Component gv2 = new Border(scrollp1, 3);
Component tb2 = new Border(scrollp2, 3);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints cnstr = new GridBagConstraints();
setLayout(gridbag);
cnstr.fill = GridBagConstraints.BOTH;
cnstr.insets = new Insets(5,5,5,5);
cnstr.weightx = 1;
cnstr.weighty = 1;
cnstr.gridwidth = 1;
gridbag.setConstraints(tb2,cnstr);
add(tb2);
cnstr.weightx = 2.5;
cnstr.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(gv2,cnstr);
add(gv2);
} catch (IOException exn) {
System.out.println("\nI/O error while reading graph file.");
} catch (ParseError exn) {
System.out.println("\nParse error in graph file:");
System.out.println(exn.getMessage());
System.out.println("\nSyntax:\n<vertexname> <vertexID> <dirname> [ + ] <path> [ < | > ] [ <vertexID> [ ... [ <vertexID> ] ... ] ] ;");
}
}
public void init() {
isApplet=true;
gfname=getParameter("graphfile");
try {
InputStream is=(new URL(getDocumentBase(), gfname)).openConnection().getInputStream();
initBrowser(is);
is.close();
} catch (MalformedURLException exn) {
System.out.println("Invalid URL: "+gfname);
} catch (IOException exn) {
System.out.println("I/O error while reading "+gfname+".");
}
}
public static void main(String[] args) {
isApplet=false;
try {
GraphBrowser gb=new GraphBrowser(args.length > 0 ? args[0] : "");
if (args.length>0) {
InputStream is=new FileInputStream(args[0]);
gb.initBrowser(is);
is.close();
}
f=new GraphBrowserFrame(gb);
f.setSize(700,500);
f.show();
} catch (IOException exn) {
System.out.println("Can't open graph file "+args[0]);
}
}
}
|
package org.fedorahosted.flies.webtrans.client;
import java.util.ArrayList;
import net.customware.gwt.presenter.client.EventBus;
import org.fedorahosted.flies.gwt.model.TransMemory;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.weborient.codemirror.client.HighlightingLabel;
import com.weborient.codemirror.client.ParserSyntax;
public class TransMemoryView extends FlowPanel implements TransMemoryPresenter.Display {
private static final int CELL_PADDING = 5;
private static final int HEADER_ROW = 0;
private static final int SOURCE_COL = 0;
private static final int TARGET_COL = 1;
private static final int ACTION_COL = 2;
private final TextBox tmTextBox = new TextBox();
private final CheckBox phraseButton = new CheckBox("Exact");
private final Button searchButton = new Button("Search");
private final Button clearButton = new Button("Clear");
final DecoratedPopupPanel resultSuppPanel = new DecoratedPopupPanel(true);
private final FlexTable resultTable = new FlexTable();
@Inject
private EventBus eventBus;
public TransMemoryView() {
tmTextBox.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if( event.getNativeKeyCode() == KeyCodes.KEY_ENTER ) {
searchButton.click();
}
}
});
clearButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent arg0) {
tmTextBox.setText("");
clearResults();
}
});
add(tmTextBox);
add(phraseButton);
add(searchButton);
add(clearButton);
add(resultTable);
}
@Override
public HasValue<Boolean> getExactButton() {
return phraseButton;
}
@Override
public Button getSearchButton() {
return searchButton;
}
public TextBox getTmTextBox() {
return tmTextBox;
}
@Override
public Widget asWidget() {
return this;
}
@Override
public void startProcessing() {
}
@Override
public void stopProcessing() {
}
@Override
public void createTable(ArrayList<TransMemory> memories) {
clearResults();
addColumn("Source", SOURCE_COL);
addColumn("Target", TARGET_COL);
addColumn("Action", ACTION_COL);
int row = HEADER_ROW;
for(final TransMemory memory: memories) {
++row;
final String sourceMessage = memory.getSource();
final String targetMessage = memory.getMemory();
final String sourceComment = memory.getSourceComment();
// final String targetComment = memory.getTargetComment();
final String docID = memory.getDocID();
resultTable.setWidget(row, SOURCE_COL, new HighlightingLabel(sourceMessage, ParserSyntax.MIXED));
resultTable.setWidget(row, TARGET_COL, new HighlightingLabel(targetMessage, ParserSyntax.MIXED));
final Anchor copyLink = new Anchor("Copy To Target");
copyLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
eventBus.fireEvent(new TransMemoryCopyEvent(sourceMessage, targetMessage));
Log.info("TransMemoryCopyEvent event is sent. (" + targetMessage + ")");
}
});
resultTable.setWidget(row, ACTION_COL, copyLink);
// Use ToolTips for supplementary info.
resultTable.getWidget(row, SOURCE_COL).setTitle("Source Comment: " + sourceComment);
// resultTable.getWidget(row, TARGET_COL).setTitle("Target Comment: " + targetComment);
resultTable.getWidget(row, ACTION_COL).setTitle("Document Name: " + docID);
}
resultTable.setCellPadding(CELL_PADDING);
}
private void addColumn(String columnHeading, int pos) {
Label widget = new Label(columnHeading);
widget.setWidth("100%");
widget.addStyleName("TransMemoryTableColumnHeader");
resultTable.setWidget(HEADER_ROW, pos, widget);
}
@Override
public void clearResults() {
resultTable.removeAllRows();
}
}
|
package actions.backend;
import bl.beans.CustomerBean;
import bl.beans.OrderBean;
import bl.beans.VolunteerBean;
import bl.constants.BusTieConstant;
import bl.instancepool.SingleBusinessPoolManager;
import bl.mongobus.CustomerBusiness;
import bl.mongobus.OrderBusiness;
import bl.mongobus.VolunteerBusiness;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vo.table.TableHeaderVo;
import vo.table.TableInitVo;
import vo.table.TableQueryVo;
import java.util.Date;
import java.util.List;
public class OrderAction extends BaseBackendAction<OrderBusiness> {
private static final CustomerBusiness orderBusiness = (CustomerBusiness) SingleBusinessPoolManager.getBusObj(BusTieConstant.BUS_CPATH_CUSTOMER);
private static final long serialVersionUID = -5222876000116738224L;
private static Logger LOG = LoggerFactory.getLogger(OrderAction.class);
protected final static VolunteerBusiness VTB = (VolunteerBusiness) SingleBusinessPoolManager.getBusObj(BusTieConstant.BUS_CPATH_VOLUNTEER);
protected final static CustomerBusiness CTB = (CustomerBusiness) SingleBusinessPoolManager.getBusObj(BusTieConstant.BUS_CPATH_CUSTOMER);
private List<CustomerBean> listCustomerBean;
private List<VolunteerBean> listVolunteerBean;
public List<CustomerBean> getListCustomerBean() {
return listCustomerBean;
}
public void setListCustomerBean(List<CustomerBean> listCustomerBean) {
this.listCustomerBean = listCustomerBean;
}
public List<VolunteerBean> getListVolunteerBean() {
return listVolunteerBean;
}
public void setListVolunteerBean(List<VolunteerBean> listVolunteerBean) {
this.listVolunteerBean = listVolunteerBean;
}
private OrderBean order;
public OrderBean getOrder() {
return order;
}
public void setOrder(OrderBean order) {
this.order = order;
}
@Override
public String getActionPrex() {
return getRequest().getContextPath() + "/backend/order";
}
@Override
public String getCustomJsp() {
return "/pages/menu_order/makeOrder.jsp";
}
@Override
public TableQueryVo getModel() {
if (model == null) {
model = new TableQueryVo();
}
//TableIndex.jsp
model.getSort().remove("userName");
model.getSort().put("createTime", "desc");
model.getFilter().put("isDeleted_!=", true);
return model;
}
@Override
public TableInitVo getTableInit() {
TableInitVo init = new TableInitVo();
init.getAoColumns().add(new TableHeaderVo("createTime", "").disableSearch());
init.getAoColumns().add(new TableHeaderVo("payDate", "").disableSearch());
init.getAoColumns().add(new TableHeaderVo("createTime_gteq", ">=").setHiddenColumn(true).enableSearch());
init.getAoColumns().add(new TableHeaderVo("createTime_lteq", "<=").setHiddenColumn(true).enableSearch());
init.getAoColumns().add(new TableHeaderVo("customerCompany", "").enableSearch());
init.getAoColumns().add(new TableHeaderVo("payDate_gteq", ">=").setHiddenColumn(true).enableSearch());
init.getAoColumns().add(new TableHeaderVo("payDate_lteq", "<=").setHiddenColumn(true).enableSearch());
listCustomerBean = (List<CustomerBean>) CTB.getAllLeaves().getResponseData();
String[][] listCustomerCodes = new String[2][listCustomerBean.size()];
if (listCustomerBean.size() > 0) {
for (int i = 0; i < listCustomerBean.size(); i++) {
listCustomerCodes[0][i] = listCustomerBean.get(i).getId();
listCustomerCodes[1][i] = listCustomerBean.get(i).getName();
}
} else {
listCustomerCodes = null;
}
init.getAoColumns().add(new TableHeaderVo("customerId", "").addSearchOptions(listCustomerCodes).enableSearch());
init.getAoColumns().add(new TableHeaderVo("customerCellPhone", "").enableSearch());
init.getAoColumns().add(new TableHeaderVo("name", "").enableSearch());
//init.getAoColumns().add(new TableHeaderVo("offerPrice", "()").disableSearch());
//init.getAoColumns().add(new TableHeaderVo("price", "()").disableSearch());
//init.getAoColumns().add(new TableHeaderVo("prePayment", "()").disableSearch());
//init.getAoColumns().add(new TableHeaderVo("actualIncome", "()").disableSearch());
//init.getAoColumns().add(new TableHeaderVo("unPayment", "()").disableSearch());
//init.getAoColumns().add(new TableHeaderVo("closePayment", "()").disableSearch());
init.getAoColumns().add(new TableHeaderVo("state", "").addSearchOptions(new String[][]{{"0", "1", "2", "3", "4", "5", "6", "7", "8"}, {"", "", "", "", "", "", "", "", ""}}).enableSearch());
listVolunteerBean = (List<VolunteerBean>) VTB.getPassedInterviewedVolunteers();
String[][] listVolunteerCodes = new String[2][listVolunteerBean.size()];
if (listVolunteerBean.size() > 0) {
for (int i = 0; i < listVolunteerBean.size(); i++) {
listVolunteerCodes[0][i] = listVolunteerBean.get(i).getId();
listVolunteerCodes[1][i] = listVolunteerBean.get(i).getName();
}
} else {
listVolunteerCodes = null;
}
init.getAoColumns().add(new TableHeaderVo("resOfficer", "").addSearchOptions(listVolunteerCodes).enableSearch());
return init;
}
@Override
public String getTableTitle() {
return "<ul class=\"breadcrumb\"><li></li><li class=\"active\"></li></ul>";
}
@Override
public String save() throws Exception {
if (StringUtils.isBlank(order.getId())) {
order.set_id(ObjectId.get());
getBusiness().createLeaf(order);
} else {
OrderBean origCustomer = (OrderBean) getBusiness().getLeaf(order.getId().toString()).getResponseData();
OrderBean newCustomer = (OrderBean) origCustomer.clone();
BeanUtils.copyProperties(newCustomer, order);
if (newCustomer.getPayDate() == null && order.getState() == OrderBean.OState.Close.getValue()) {
newCustomer.setPayDate(new Date(System.currentTimeMillis()));
}
getBusiness().updateLeaf(origCustomer, newCustomer);
}
return SUCCESS;
}
@Override
public String add() {
listVolunteerBean = (List<VolunteerBean>) VTB.getPassedInterviewedVolunteers();
listCustomerBean = (List<CustomerBean>) CTB.getAllLeaves().getResponseData();
order = new OrderBean();
return SUCCESS;
}
@Override
public String edit() throws Exception {
order = (OrderBean) getBusiness().getLeaf(getId()).getResponseData();
listVolunteerBean = (List<VolunteerBean>) VTB.getPassedInterviewedVolunteers();
listCustomerBean = (List<CustomerBean>) CTB.getAllLeaves().getResponseData();
return SUCCESS;
}
@Override
public String delete() throws Exception {
if (getId() != null) {
getBusiness().deleteLeaf(getId());
}
return SUCCESS;
}
}
|
package com.oracle.graal.compiler.alloc;
import static com.oracle.graal.api.code.CodeUtil.*;
import static com.oracle.graal.api.code.ValueUtil.*;
import static com.oracle.graal.compiler.GraalDebugConfig.*;
import static com.oracle.graal.compiler.common.cfg.AbstractControlFlowGraph.*;
import static com.oracle.graal.lir.LIRValueUtil.*;
import java.util.*;
import com.oracle.graal.alloc.*;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.compiler.alloc.Interval.RegisterBinding;
import com.oracle.graal.compiler.alloc.Interval.RegisterPriority;
import com.oracle.graal.compiler.alloc.Interval.SpillState;
import com.oracle.graal.compiler.common.*;
import com.oracle.graal.compiler.common.cfg.*;
import com.oracle.graal.compiler.gen.*;
import com.oracle.graal.debug.*;
import com.oracle.graal.debug.Debug.Scope;
import com.oracle.graal.lir.*;
import com.oracle.graal.lir.LIRInstruction.OperandFlag;
import com.oracle.graal.lir.LIRInstruction.OperandMode;
import com.oracle.graal.lir.StandardOp.MoveOp;
import com.oracle.graal.nodes.*;
import com.oracle.graal.options.*;
import com.oracle.graal.phases.util.*;
public final class LinearScan {
final TargetDescription target;
final LIR ir;
final FrameMap frameMap;
final RegisterAttributes[] registerAttributes;
final Register[] registers;
boolean callKillsRegisters;
public static final int DOMINATOR_SPILL_MOVE_ID = -2;
private static final int SPLIT_INTERVALS_CAPACITY_RIGHT_SHIFT = 1;
public static class Options {
// @formatter:off
@Option(help = "Enable spill position optimization")
public static final OptionValue<Boolean> LSRAOptimizeSpillPosition = new OptionValue<>(true);
// @formatter:on
}
public static class BlockData {
/**
* Bit map specifying which operands are live upon entry to this block. These are values
* used in this block or any of its successors where such value are not defined in this
* block. The bit index of an operand is its {@linkplain LinearScan#operandNumber(Value)
* operand number}.
*/
public BitSet liveIn;
/**
* Bit map specifying which operands are live upon exit from this block. These are values
* used in a successor block that are either defined in this block or were live upon entry
* to this block. The bit index of an operand is its
* {@linkplain LinearScan#operandNumber(Value) operand number}.
*/
public BitSet liveOut;
/**
* Bit map specifying which operands are used (before being defined) in this block. That is,
* these are the values that are live upon entry to the block. The bit index of an operand
* is its {@linkplain LinearScan#operandNumber(Value) operand number}.
*/
public BitSet liveGen;
/**
* Bit map specifying which operands are defined/overwritten in this block. The bit index of
* an operand is its {@linkplain LinearScan#operandNumber(Value) operand number}.
*/
public BitSet liveKill;
}
public final BlockMap<BlockData> blockData;
/**
* List of blocks in linear-scan order. This is only correct as long as the CFG does not change.
*/
final List<? extends AbstractBlock<?>> sortedBlocks;
/**
* Map from {@linkplain #operandNumber(Value) operand numbers} to intervals.
*/
Interval[] intervals;
/**
* The number of valid entries in {@link #intervals}.
*/
int intervalsSize;
/**
* The index of the first entry in {@link #intervals} for a
* {@linkplain #createDerivedInterval(Interval) derived interval}.
*/
int firstDerivedIntervalIndex = -1;
/**
* Intervals sorted by {@link Interval#from()}.
*/
Interval[] sortedIntervals;
/**
* Map from an instruction {@linkplain LIRInstruction#id id} to the instruction. Entries should
* be retrieved with {@link #instructionForId(int)} as the id is not simply an index into this
* array.
*/
LIRInstruction[] opIdToInstructionMap;
/**
* Map from an instruction {@linkplain LIRInstruction#id id} to the {@linkplain AbstractBlock
* block} containing the instruction. Entries should be retrieved with {@link #blockForId(int)}
* as the id is not simply an index into this array.
*/
AbstractBlock<?>[] opIdToBlockMap;
/**
* Bit set for each variable that is contained in each loop.
*/
BitMap2D intervalInLoop;
/**
* The {@linkplain #operandNumber(Value) number} of the first variable operand allocated.
*/
private final int firstVariableNumber;
public LinearScan(TargetDescription target, LIR ir, FrameMap frameMap) {
this.target = target;
this.ir = ir;
this.frameMap = frameMap;
this.sortedBlocks = ir.linearScanOrder();
this.registerAttributes = frameMap.registerConfig.getAttributesMap();
this.registers = target.arch.getRegisters();
this.firstVariableNumber = registers.length;
this.blockData = new BlockMap<>(ir.getControlFlowGraph());
}
public int getFirstLirInstructionId(AbstractBlock<?> block) {
int result = ir.getLIRforBlock(block).get(0).id();
assert result >= 0;
return result;
}
public int getLastLirInstructionId(AbstractBlock<?> block) {
List<LIRInstruction> instructions = ir.getLIRforBlock(block);
int result = instructions.get(instructions.size() - 1).id();
assert result >= 0;
return result;
}
public static boolean isVariableOrRegister(Value value) {
return isVariable(value) || isRegister(value);
}
/**
* Converts an operand (variable or register) to an index in a flat address space covering all
* the {@linkplain Variable variables} and {@linkplain RegisterValue registers} being processed
* by this allocator.
*/
private int operandNumber(Value operand) {
if (isRegister(operand)) {
int number = asRegister(operand).number;
assert number < firstVariableNumber;
return number;
}
assert isVariable(operand) : operand;
return firstVariableNumber + ((Variable) operand).index;
}
/**
* Gets the number of operands. This value will increase by 1 for new variable.
*/
private int operandSize() {
return firstVariableNumber + ir.numVariables();
}
/**
* Gets the highest operand number for a register operand. This value will never change.
*/
public int maxRegisterNumber() {
return firstVariableNumber - 1;
}
static final IntervalPredicate IS_PRECOLORED_INTERVAL = new IntervalPredicate() {
@Override
public boolean apply(Interval i) {
return isRegister(i.operand);
}
};
static final IntervalPredicate IS_VARIABLE_INTERVAL = new IntervalPredicate() {
@Override
public boolean apply(Interval i) {
return isVariable(i.operand);
}
};
static final IntervalPredicate IS_STACK_INTERVAL = new IntervalPredicate() {
@Override
public boolean apply(Interval i) {
return !isRegister(i.operand);
}
};
/**
* Gets an object describing the attributes of a given register according to this register
* configuration.
*/
RegisterAttributes attributes(Register reg) {
return registerAttributes[reg.number];
}
void assignSpillSlot(Interval interval) {
// assign the canonical spill slot of the parent (if a part of the interval
// is already spilled) or allocate a new spill slot
if (interval.canMaterialize()) {
interval.assignLocation(Value.ILLEGAL);
} else if (interval.spillSlot() != null) {
interval.assignLocation(interval.spillSlot());
} else {
StackSlot slot = frameMap.allocateSpillSlot(interval.kind());
interval.setSpillSlot(slot);
interval.assignLocation(slot);
}
}
/**
* Creates a new interval.
*
* @param operand the operand for the interval
* @return the created interval
*/
Interval createInterval(AllocatableValue operand) {
assert isLegal(operand);
int operandNumber = operandNumber(operand);
Interval interval = new Interval(operand, operandNumber);
assert operandNumber < intervalsSize;
assert intervals[operandNumber] == null;
intervals[operandNumber] = interval;
return interval;
}
/**
* Creates an interval as a result of splitting or spilling another interval.
*
* @param source an interval being split of spilled
* @return a new interval derived from {@code source}
*/
Interval createDerivedInterval(Interval source) {
if (firstDerivedIntervalIndex == -1) {
firstDerivedIntervalIndex = intervalsSize;
}
if (intervalsSize == intervals.length) {
intervals = Arrays.copyOf(intervals, intervals.length + (intervals.length >> SPLIT_INTERVALS_CAPACITY_RIGHT_SHIFT));
}
intervalsSize++;
Variable variable = new Variable(source.kind(), ir.nextVariable());
Interval interval = createInterval(variable);
assert intervals[intervalsSize - 1] == interval;
return interval;
}
// access to block list (sorted in linear scan order)
int blockCount() {
return sortedBlocks.size();
}
AbstractBlock<?> blockAt(int index) {
return sortedBlocks.get(index);
}
/**
* Gets the size of the {@link BlockData#liveIn} and {@link BlockData#liveOut} sets for a basic
* block. These sets do not include any operands allocated as a result of creating
* {@linkplain #createDerivedInterval(Interval) derived intervals}.
*/
int liveSetSize() {
return firstDerivedIntervalIndex == -1 ? operandSize() : firstDerivedIntervalIndex;
}
int numLoops() {
return ir.getControlFlowGraph().getLoops().size();
}
boolean isIntervalInLoop(int interval, int loop) {
return intervalInLoop.at(interval, loop);
}
Interval intervalFor(int operandNumber) {
return intervals[operandNumber];
}
Interval intervalFor(Value operand) {
int operandNumber = operandNumber(operand);
assert operandNumber < intervalsSize;
return intervals[operandNumber];
}
Interval getOrCreateInterval(AllocatableValue operand) {
Interval ret = intervalFor(operand);
if (ret == null) {
return createInterval(operand);
} else {
return ret;
}
}
/**
* Gets the highest instruction id allocated by this object.
*/
int maxOpId() {
assert opIdToInstructionMap.length > 0 : "no operations";
return (opIdToInstructionMap.length - 1) << 1;
}
/**
* Converts an {@linkplain LIRInstruction#id instruction id} to an instruction index. All LIR
* instructions in a method have an index one greater than their linear-scan order predecesor
* with the first instruction having an index of 0.
*/
static int opIdToIndex(int opId) {
return opId >> 1;
}
/**
* Retrieves the {@link LIRInstruction} based on its {@linkplain LIRInstruction#id id}.
*
* @param opId an instruction {@linkplain LIRInstruction#id id}
* @return the instruction whose {@linkplain LIRInstruction#id} {@code == id}
*/
LIRInstruction instructionForId(int opId) {
assert isEven(opId) : "opId not even";
LIRInstruction instr = opIdToInstructionMap[opIdToIndex(opId)];
assert instr.id() == opId;
return instr;
}
/**
* Gets the block containing a given instruction.
*
* @param opId an instruction {@linkplain LIRInstruction#id id}
* @return the block containing the instruction denoted by {@code opId}
*/
AbstractBlock<?> blockForId(int opId) {
assert opIdToBlockMap.length > 0 && opId >= 0 && opId <= maxOpId() + 1 : "opId out of range";
return opIdToBlockMap[opIdToIndex(opId)];
}
boolean isBlockBegin(int opId) {
return opId == 0 || blockForId(opId) != blockForId(opId - 1);
}
boolean coversBlockBegin(int opId1, int opId2) {
return blockForId(opId1) != blockForId(opId2);
}
/**
* Determines if an {@link LIRInstruction} destroys all caller saved registers.
*
* @param opId an instruction {@linkplain LIRInstruction#id id}
* @return {@code true} if the instruction denoted by {@code id} destroys all caller saved
* registers.
*/
boolean hasCall(int opId) {
assert isEven(opId) : "opId not even";
return instructionForId(opId).destroysCallerSavedRegisters();
}
/**
* Eliminates moves from register to stack if the stack slot is known to be correct.
*/
void changeSpillDefinitionPos(Interval interval, int defPos) {
assert interval.isSplitParent() : "can only be called for split parents";
switch (interval.spillState()) {
case NoDefinitionFound:
assert interval.spillDefinitionPos() == -1 : "must no be set before";
interval.setSpillDefinitionPos(defPos);
interval.setSpillState(SpillState.NoSpillStore);
break;
case NoSpillStore:
assert defPos <= interval.spillDefinitionPos() : "positions are processed in reverse order when intervals are created";
if (defPos < interval.spillDefinitionPos() - 2) {
// second definition found, so no spill optimization possible for this interval
interval.setSpillState(SpillState.NoOptimization);
} else {
// two consecutive definitions (because of two-operand LIR form)
assert blockForId(defPos) == blockForId(interval.spillDefinitionPos()) : "block must be equal";
}
break;
case NoOptimization:
// nothing to do
break;
default:
throw new BailoutException("other states not allowed at this time");
}
}
// called during register allocation
void changeSpillState(Interval interval, int spillPos) {
switch (interval.spillState()) {
case NoSpillStore: {
int defLoopDepth = blockForId(interval.spillDefinitionPos()).getLoopDepth();
int spillLoopDepth = blockForId(spillPos).getLoopDepth();
if (defLoopDepth < spillLoopDepth) {
// the loop depth of the spilling position is higher then the loop depth
// at the definition of the interval . move write to memory out of loop.
if (Options.LSRAOptimizeSpillPosition.getValue()) {
// find best spill position in dominator the tree
interval.setSpillState(SpillState.SpillInDominator);
} else {
// store at definition of the interval
interval.setSpillState(SpillState.StoreAtDefinition);
}
} else {
// the interval is currently spilled only once, so for now there is no
// reason to store the interval at the definition
interval.setSpillState(SpillState.OneSpillStore);
}
break;
}
case OneSpillStore: {
if (Options.LSRAOptimizeSpillPosition.getValue()) {
// the interval is spilled more then once
interval.setSpillState(SpillState.SpillInDominator);
} else {
// it is better to store it to
// memory at the definition
interval.setSpillState(SpillState.StoreAtDefinition);
}
break;
}
case SpillInDominator:
case StoreAtDefinition:
case StartInMemory:
case NoOptimization:
case NoDefinitionFound:
// nothing to do
break;
default:
throw new BailoutException("other states not allowed at this time");
}
}
abstract static class IntervalPredicate {
abstract boolean apply(Interval i);
}
private static final IntervalPredicate mustStoreAtDefinition = new IntervalPredicate() {
@Override
public boolean apply(Interval i) {
return i.isSplitParent() && i.spillState() == SpillState.StoreAtDefinition;
}
};
// called once before assignment of register numbers
void eliminateSpillMoves() {
try (Indent indent = Debug.logAndIndent("Eliminating unnecessary spill moves")) {
// collect all intervals that must be stored after their definition.
// the list is sorted by Interval.spillDefinitionPos
Interval interval;
interval = createUnhandledLists(mustStoreAtDefinition, null).first;
if (DetailedAsserts.getValue()) {
checkIntervals(interval);
}
LIRInsertionBuffer insertionBuffer = new LIRInsertionBuffer();
for (AbstractBlock<?> block : sortedBlocks) {
List<LIRInstruction> instructions = ir.getLIRforBlock(block);
int numInst = instructions.size();
// iterate all instructions of the block. skip the first
// because it is always a label
for (int j = 1; j < numInst; j++) {
LIRInstruction op = instructions.get(j);
int opId = op.id();
if (opId == -1) {
MoveOp move = (MoveOp) op;
// remove move from register to stack if the stack slot is guaranteed to be
// correct.
// only moves that have been inserted by LinearScan can be removed.
assert isVariable(move.getResult()) : "LinearScan inserts only moves to variables";
Interval curInterval = intervalFor(move.getResult());
if (!isRegister(curInterval.location()) && curInterval.alwaysInMemory()) {
// move target is a stack slot that is always correct, so eliminate
// instruction
if (Debug.isLogEnabled()) {
Debug.log("eliminating move from interval %d to %d", operandNumber(move.getInput()), operandNumber(move.getResult()));
}
// null-instructions are deleted by assignRegNum
instructions.set(j, null);
}
} else {
// insert move from register to stack just after
// the beginning of the interval
assert interval == Interval.EndMarker || interval.spillDefinitionPos() >= opId : "invalid order";
assert interval == Interval.EndMarker || (interval.isSplitParent() && interval.spillState() == SpillState.StoreAtDefinition) : "invalid interval";
while (interval != Interval.EndMarker && interval.spillDefinitionPos() == opId) {
if (!interval.canMaterialize()) {
if (!insertionBuffer.initialized()) {
// prepare insertion buffer (appended when all instructions in
// the block are processed)
insertionBuffer.init(instructions);
}
AllocatableValue fromLocation = interval.location();
AllocatableValue toLocation = canonicalSpillOpr(interval);
assert isRegister(fromLocation) : "from operand must be a register but is: " + fromLocation + " toLocation=" + toLocation + " spillState=" + interval.spillState();
assert isStackSlot(toLocation) : "to operand must be a stack slot";
insertionBuffer.append(j + 1, ir.getSpillMoveFactory().createMove(toLocation, fromLocation));
Debug.log("inserting move after definition of interval %d to stack slot %s at opId %d", interval.operandNumber, interval.spillSlot(), opId);
}
interval = interval.next;
}
}
} // end of instruction iteration
if (insertionBuffer.initialized()) {
insertionBuffer.finish();
}
} // end of block iteration
assert interval == Interval.EndMarker : "missed an interval";
}
}
private static void checkIntervals(Interval interval) {
Interval prev = null;
Interval temp = interval;
while (temp != Interval.EndMarker) {
assert temp.spillDefinitionPos() > 0 : "invalid spill definition pos";
if (prev != null) {
assert temp.from() >= prev.from() : "intervals not sorted";
assert temp.spillDefinitionPos() >= prev.spillDefinitionPos() : "when intervals are sorted by from : then they must also be sorted by spillDefinitionPos";
}
assert temp.spillSlot() != null || temp.canMaterialize() : "interval has no spill slot assigned";
assert temp.spillDefinitionPos() >= temp.from() : "invalid order";
assert temp.spillDefinitionPos() <= temp.from() + 2 : "only intervals defined once at their start-pos can be optimized";
Debug.log("interval %d (from %d to %d) must be stored at %d", temp.operandNumber, temp.from(), temp.to(), temp.spillDefinitionPos());
prev = temp;
temp = temp.next;
}
}
/**
* Numbers all instructions in all blocks. The numbering follows the
* {@linkplain ComputeBlockOrder linear scan order}.
*/
void numberInstructions() {
intervalsSize = operandSize();
intervals = new Interval[intervalsSize + (intervalsSize >> SPLIT_INTERVALS_CAPACITY_RIGHT_SHIFT)];
ValueConsumer setVariableConsumer = new ValueConsumer() {
@Override
public void visitValue(Value value) {
if (isVariable(value)) {
getOrCreateInterval(asVariable(value));
}
}
};
// Assign IDs to LIR nodes and build a mapping, lirOps, from ID to LIRInstruction node.
int numInstructions = 0;
for (AbstractBlock<?> block : sortedBlocks) {
numInstructions += ir.getLIRforBlock(block).size();
}
// initialize with correct length
opIdToInstructionMap = new LIRInstruction[numInstructions];
opIdToBlockMap = new AbstractBlock<?>[numInstructions];
int opId = 0;
int index = 0;
for (AbstractBlock<?> block : sortedBlocks) {
blockData.put(block, new BlockData());
List<LIRInstruction> instructions = ir.getLIRforBlock(block);
int numInst = instructions.size();
for (int j = 0; j < numInst; j++) {
LIRInstruction op = instructions.get(j);
op.setId(opId);
opIdToInstructionMap[index] = op;
opIdToBlockMap[index] = block;
assert instructionForId(opId) == op : "must match";
op.visitEachTemp(setVariableConsumer);
op.visitEachOutput(setVariableConsumer);
index++;
opId += 2; // numbering of lirOps by two
}
}
assert index == numInstructions : "must match";
assert (index << 1) == opId : "must match: " + (index << 1);
}
/**
* Computes local live sets (i.e. {@link BlockData#liveGen} and {@link BlockData#liveKill})
* separately for each block.
*/
void computeLocalLiveSets() {
int liveSize = liveSetSize();
intervalInLoop = new BitMap2D(operandSize(), numLoops());
// iterate all blocks
for (final AbstractBlock<?> block : sortedBlocks) {
try (Indent indent = Debug.logAndIndent("compute local live sets for block %d", block.getId())) {
final BitSet liveGen = new BitSet(liveSize);
final BitSet liveKill = new BitSet(liveSize);
List<LIRInstruction> instructions = ir.getLIRforBlock(block);
int numInst = instructions.size();
ValueConsumer useConsumer = new ValueConsumer() {
@Override
protected void visitValue(Value operand) {
if (isVariable(operand)) {
int operandNum = operandNumber(operand);
if (!liveKill.get(operandNum)) {
liveGen.set(operandNum);
Debug.log("liveGen for operand %d", operandNum);
}
if (block.getLoop() != null) {
intervalInLoop.setBit(operandNum, block.getLoop().getIndex());
}
}
if (DetailedAsserts.getValue()) {
verifyInput(block, liveKill, operand);
}
}
};
ValueConsumer stateConsumer = new ValueConsumer() {
@Override
public void visitValue(Value operand) {
int operandNum = operandNumber(operand);
if (!liveKill.get(operandNum)) {
liveGen.set(operandNum);
Debug.log("liveGen in state for operand %d", operandNum);
}
}
};
ValueConsumer defConsumer = new ValueConsumer() {
@Override
public void visitValue(Value operand) {
if (isVariable(operand)) {
int varNum = operandNumber(operand);
liveKill.set(varNum);
Debug.log("liveKill for operand %d", varNum);
if (block.getLoop() != null) {
intervalInLoop.setBit(varNum, block.getLoop().getIndex());
}
}
if (DetailedAsserts.getValue()) {
// fixed intervals are never live at block boundaries, so
// they need not be processed in live sets
// process them only in debug mode so that this can be checked
verifyTemp(liveKill, operand);
}
}
};
// iterate all instructions of the block
for (int j = 0; j < numInst; j++) {
final LIRInstruction op = instructions.get(j);
try (Indent indent2 = Debug.logAndIndent("handle op %d", op.id())) {
op.visitEachInput(useConsumer);
op.visitEachAlive(useConsumer);
// Add uses of live locals from interpreter's point of view for proper debug
// information generation
op.visitEachState(stateConsumer);
op.visitEachTemp(defConsumer);
op.visitEachOutput(defConsumer);
}
} // end of instruction iteration
BlockData blockSets = blockData.get(block);
blockSets.liveGen = liveGen;
blockSets.liveKill = liveKill;
blockSets.liveIn = new BitSet(liveSize);
blockSets.liveOut = new BitSet(liveSize);
Debug.log("liveGen B%d %s", block.getId(), blockSets.liveGen);
Debug.log("liveKill B%d %s", block.getId(), blockSets.liveKill);
}
} // end of block iteration
}
private void verifyTemp(BitSet liveKill, Value operand) {
// fixed intervals are never live at block boundaries, so
// they need not be processed in live sets
// process them only in debug mode so that this can be checked
if (isRegister(operand)) {
if (isProcessed(operand)) {
liveKill.set(operandNumber(operand));
}
}
}
private void verifyInput(AbstractBlock<?> block, BitSet liveKill, Value operand) {
// fixed intervals are never live at block boundaries, so
// they need not be processed in live sets.
// this is checked by these assertions to be sure about it.
// the entry block may have incoming
// values in registers, which is ok.
if (isRegister(operand) && block != ir.getControlFlowGraph().getStartBlock()) {
if (isProcessed(operand)) {
assert liveKill.get(operandNumber(operand)) : "using fixed register that is not defined in this block";
}
}
}
/**
* Performs a backward dataflow analysis to compute global live sets (i.e.
* {@link BlockData#liveIn} and {@link BlockData#liveOut}) for each block.
*/
void computeGlobalLiveSets() {
try (Indent indent = Debug.logAndIndent("compute global live sets")) {
int numBlocks = blockCount();
boolean changeOccurred;
boolean changeOccurredInBlock;
int iterationCount = 0;
BitSet liveOut = new BitSet(liveSetSize()); // scratch set for calculations
// Perform a backward dataflow analysis to compute liveOut and liveIn for each block.
// The loop is executed until a fixpoint is reached (no changes in an iteration)
do {
changeOccurred = false;
try (Indent indent2 = Debug.logAndIndent("new iteration %d", iterationCount)) {
// iterate all blocks in reverse order
for (int i = numBlocks - 1; i >= 0; i
AbstractBlock<?> block = blockAt(i);
BlockData blockSets = blockData.get(block);
changeOccurredInBlock = false;
// liveOut(block) is the union of liveIn(sux), for successors sux of block
int n = block.getSuccessorCount();
if (n > 0) {
liveOut.clear();
// block has successors
if (n > 0) {
for (AbstractBlock<?> successor : block.getSuccessors()) {
liveOut.or(blockData.get(successor).liveIn);
}
}
if (!blockSets.liveOut.equals(liveOut)) {
// A change occurred. Swap the old and new live out
// sets to avoid copying.
BitSet temp = blockSets.liveOut;
blockSets.liveOut = liveOut;
liveOut = temp;
changeOccurred = true;
changeOccurredInBlock = true;
}
}
if (iterationCount == 0 || changeOccurredInBlock) {
// liveIn(block) is the union of liveGen(block) with (liveOut(block) &
// !liveKill(block))
// note: liveIn has to be computed only in first iteration
// or if liveOut has changed!
BitSet liveIn = blockSets.liveIn;
liveIn.clear();
liveIn.or(blockSets.liveOut);
liveIn.andNot(blockSets.liveKill);
liveIn.or(blockSets.liveGen);
Debug.log("block %d: livein = %s, liveout = %s", block.getId(), liveIn, blockSets.liveOut);
}
}
iterationCount++;
if (changeOccurred && iterationCount > 50) {
throw new BailoutException("too many iterations in computeGlobalLiveSets");
}
}
} while (changeOccurred);
if (DetailedAsserts.getValue()) {
verifyLiveness();
}
// check that the liveIn set of the first block is empty
AbstractBlock<?> startBlock = ir.getControlFlowGraph().getStartBlock();
if (blockData.get(startBlock).liveIn.cardinality() != 0) {
if (DetailedAsserts.getValue()) {
reportFailure(numBlocks);
}
// bailout if this occurs in product mode.
throw new GraalInternalError("liveIn set of first block must be empty: " + blockData.get(startBlock).liveIn);
}
}
}
private static NodeLIRBuilder getNodeLIRGeneratorFromDebugContext() {
if (Debug.isEnabled()) {
NodeLIRBuilder lirGen = Debug.contextLookup(NodeLIRBuilder.class);
assert lirGen != null;
return lirGen;
}
return null;
}
private static ValueNode getValueForOperandFromDebugContext(Value value) {
NodeLIRBuilder gen = getNodeLIRGeneratorFromDebugContext();
if (gen != null) {
return gen.valueForOperand(value);
}
return null;
}
private void reportFailure(int numBlocks) {
try (Scope s = Debug.forceLog()) {
try (Indent indent = Debug.logAndIndent("report failure")) {
BitSet startBlockLiveIn = blockData.get(ir.getControlFlowGraph().getStartBlock()).liveIn;
try (Indent indent2 = Debug.logAndIndent("Error: liveIn set of first block must be empty (when this fails, variables are used before they are defined):")) {
for (int operandNum = startBlockLiveIn.nextSetBit(0); operandNum >= 0; operandNum = startBlockLiveIn.nextSetBit(operandNum + 1)) {
Interval interval = intervalFor(operandNum);
if (interval != null) {
Value operand = interval.operand;
Debug.log("var %d; operand=%s; node=%s", operandNum, operand, getValueForOperandFromDebugContext(operand));
} else {
Debug.log("var %d; missing operand", operandNum);
}
}
}
// print some additional information to simplify debugging
for (int operandNum = startBlockLiveIn.nextSetBit(0); operandNum >= 0; operandNum = startBlockLiveIn.nextSetBit(operandNum + 1)) {
Interval interval = intervalFor(operandNum);
Value operand = null;
ValueNode valueForOperandFromDebugContext = null;
if (interval != null) {
operand = interval.operand;
valueForOperandFromDebugContext = getValueForOperandFromDebugContext(operand);
}
try (Indent indent2 = Debug.logAndIndent("
Deque<AbstractBlock<?>> definedIn = new ArrayDeque<>();
HashSet<AbstractBlock<?>> usedIn = new HashSet<>();
for (AbstractBlock<?> block : sortedBlocks) {
if (blockData.get(block).liveGen.get(operandNum)) {
usedIn.add(block);
try (Indent indent3 = Debug.logAndIndent("used in block B%d", block.getId())) {
for (LIRInstruction ins : ir.getLIRforBlock(block)) {
try (Indent indent4 = Debug.logAndIndent("%d: %s", ins.id(), ins)) {
ins.forEachState(new ValueProcedure() {
@Override
public Value doValue(Value liveStateOperand) {
Debug.log("operand=%s", liveStateOperand);
return liveStateOperand;
}
});
}
}
}
}
if (blockData.get(block).liveKill.get(operandNum)) {
definedIn.add(block);
try (Indent indent3 = Debug.logAndIndent("defined in block B%d", block.getId())) {
for (LIRInstruction ins : ir.getLIRforBlock(block)) {
Debug.log("%d: %s", ins.id(), ins);
}
}
}
}
int[] hitCount = new int[numBlocks];
while (!definedIn.isEmpty()) {
AbstractBlock<?> block = definedIn.removeFirst();
usedIn.remove(block);
for (AbstractBlock<?> successor : block.getSuccessors()) {
if (successor.isLoopHeader()) {
if (!block.isLoopEnd()) {
definedIn.add(successor);
}
} else {
if (++hitCount[successor.getId()] == successor.getPredecessorCount()) {
definedIn.add(successor);
}
}
}
}
try (Indent indent3 = Debug.logAndIndent("**** offending usages are in: ")) {
for (AbstractBlock<?> block : usedIn) {
Debug.log("B%d", block.getId());
}
}
}
}
}
}
}
private void verifyLiveness() {
// check that fixed intervals are not live at block boundaries
// (live set must be empty at fixed intervals)
for (AbstractBlock<?> block : sortedBlocks) {
for (int j = 0; j <= maxRegisterNumber(); j++) {
assert !blockData.get(block).liveIn.get(j) : "liveIn set of fixed register must be empty";
assert !blockData.get(block).liveOut.get(j) : "liveOut set of fixed register must be empty";
assert !blockData.get(block).liveGen.get(j) : "liveGen set of fixed register must be empty";
}
}
}
void addUse(AllocatableValue operand, int from, int to, RegisterPriority registerPriority, LIRKind kind) {
if (!isProcessed(operand)) {
return;
}
Interval interval = getOrCreateInterval(operand);
if (!kind.equals(LIRKind.Illegal)) {
interval.setKind(kind);
}
interval.addRange(from, to);
// Register use position at even instruction id.
interval.addUsePos(to & ~1, registerPriority);
Debug.log("add use: %s, from %d to %d (%s)", interval, from, to, registerPriority.name());
}
void addTemp(AllocatableValue operand, int tempPos, RegisterPriority registerPriority, LIRKind kind) {
if (!isProcessed(operand)) {
return;
}
Interval interval = getOrCreateInterval(operand);
if (!kind.equals(LIRKind.Illegal)) {
interval.setKind(kind);
}
interval.addRange(tempPos, tempPos + 1);
interval.addUsePos(tempPos, registerPriority);
interval.addMaterializationValue(null);
Debug.log("add temp: %s tempPos %d (%s)", interval, tempPos, RegisterPriority.MustHaveRegister.name());
}
boolean isProcessed(Value operand) {
return !isRegister(operand) || attributes(asRegister(operand)).isAllocatable();
}
void addDef(AllocatableValue operand, LIRInstruction op, RegisterPriority registerPriority, LIRKind kind) {
if (!isProcessed(operand)) {
return;
}
int defPos = op.id();
Interval interval = getOrCreateInterval(operand);
if (!kind.equals(LIRKind.Illegal)) {
interval.setKind(kind);
}
Range r = interval.first();
if (r.from <= defPos) {
// Update the starting point (when a range is first created for a use, its
// start is the beginning of the current block until a def is encountered.)
r.from = defPos;
interval.addUsePos(defPos, registerPriority);
} else {
// Dead value - make vacuous interval
// also add register priority for dead intervals
interval.addRange(defPos, defPos + 1);
interval.addUsePos(defPos, registerPriority);
Debug.log("Warning: def of operand %s at %d occurs without use", operand, defPos);
}
changeSpillDefinitionPos(interval, defPos);
if (registerPriority == RegisterPriority.None && interval.spillState().ordinal() <= SpillState.StartInMemory.ordinal()) {
// detection of method-parameters and roundfp-results
interval.setSpillState(SpillState.StartInMemory);
}
interval.addMaterializationValue(LinearScan.getMaterializedValue(op, operand, interval));
Debug.log("add def: %s defPos %d (%s)", interval, defPos, registerPriority.name());
}
/**
* Determines the register priority for an instruction's output/result operand.
*/
static RegisterPriority registerPriorityOfOutputOperand(LIRInstruction op) {
if (op instanceof MoveOp) {
MoveOp move = (MoveOp) op;
if (optimizeMethodArgument(move.getInput())) {
return RegisterPriority.None;
}
}
// all other operands require a register
return RegisterPriority.MustHaveRegister;
}
/**
* Determines the priority which with an instruction's input operand will be allocated a
* register.
*/
static RegisterPriority registerPriorityOfInputOperand(EnumSet<OperandFlag> flags) {
if (flags.contains(OperandFlag.STACK)) {
return RegisterPriority.ShouldHaveRegister;
}
// all other operands require a register
return RegisterPriority.MustHaveRegister;
}
private static boolean optimizeMethodArgument(Value value) {
/*
* Object method arguments that are passed on the stack are currently not optimized because
* this requires that the runtime visits method arguments during stack walking.
*/
return isStackSlot(value) && asStackSlot(value).isInCallerFrame() && value.getKind() != Kind.Object;
}
/**
* Optimizes moves related to incoming stack based arguments. The interval for the destination
* of such moves is assigned the stack slot (which is in the caller's frame) as its spill slot.
*/
void handleMethodArguments(LIRInstruction op) {
if (op instanceof MoveOp) {
MoveOp move = (MoveOp) op;
if (optimizeMethodArgument(move.getInput())) {
StackSlot slot = asStackSlot(move.getInput());
if (DetailedAsserts.getValue()) {
assert op.id() > 0 : "invalid id";
assert blockForId(op.id()).getPredecessorCount() == 0 : "move from stack must be in first block";
assert isVariable(move.getResult()) : "result of move must be a variable";
Debug.log("found move from stack slot %s to %s", slot, move.getResult());
}
Interval interval = intervalFor(move.getResult());
interval.setSpillSlot(slot);
interval.assignLocation(slot);
}
}
}
void addRegisterHint(final LIRInstruction op, final Value targetValue, OperandMode mode, EnumSet<OperandFlag> flags, final boolean hintAtDef) {
if (flags.contains(OperandFlag.HINT) && isVariableOrRegister(targetValue)) {
op.forEachRegisterHint(targetValue, mode, new ValueProcedure() {
@Override
protected Value doValue(Value registerHint) {
if (isVariableOrRegister(registerHint)) {
Interval from = getOrCreateInterval((AllocatableValue) registerHint);
Interval to = getOrCreateInterval((AllocatableValue) targetValue);
// hints always point from def to use
if (hintAtDef) {
to.setLocationHint(from);
} else {
from.setLocationHint(to);
}
Debug.log("operation at opId %d: added hint from interval %d to %d", op.id(), from.operandNumber, to.operandNumber);
return registerHint;
}
return null;
}
});
}
}
void buildIntervals() {
try (Indent indent = Debug.logAndIndent("build intervals")) {
InstructionValueConsumer outputConsumer = new InstructionValueConsumer() {
@Override
public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) {
if (isVariableOrRegister(operand)) {
addDef((AllocatableValue) operand, op, registerPriorityOfOutputOperand(op), operand.getLIRKind());
addRegisterHint(op, operand, mode, flags, true);
}
}
};
InstructionValueConsumer tempConsumer = new InstructionValueConsumer() {
@Override
public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) {
if (isVariableOrRegister(operand)) {
addTemp((AllocatableValue) operand, op.id(), RegisterPriority.MustHaveRegister, operand.getLIRKind());
addRegisterHint(op, operand, mode, flags, false);
}
}
};
InstructionValueConsumer aliveConsumer = new InstructionValueConsumer() {
@Override
public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) {
if (isVariableOrRegister(operand)) {
RegisterPriority p = registerPriorityOfInputOperand(flags);
final int opId = op.id();
final int blockFrom = getFirstLirInstructionId((blockForId(opId)));
addUse((AllocatableValue) operand, blockFrom, opId + 1, p, operand.getLIRKind());
addRegisterHint(op, operand, mode, flags, false);
}
}
};
InstructionValueConsumer inputConsumer = new InstructionValueConsumer() {
@Override
public void visitValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) {
if (isVariableOrRegister(operand)) {
final int opId = op.id();
final int blockFrom = getFirstLirInstructionId((blockForId(opId)));
RegisterPriority p = registerPriorityOfInputOperand(flags);
addUse((AllocatableValue) operand, blockFrom, opId, p, operand.getLIRKind());
addRegisterHint(op, operand, mode, flags, false);
}
}
};
InstructionValueConsumer stateProc = new InstructionValueConsumer() {
@Override
public void visitValue(LIRInstruction op, Value operand) {
final int opId = op.id();
final int blockFrom = getFirstLirInstructionId((blockForId(opId)));
addUse((AllocatableValue) operand, blockFrom, opId + 1, RegisterPriority.None, operand.getLIRKind());
}
};
// create a list with all caller-save registers (cpu, fpu, xmm)
Register[] callerSaveRegs = frameMap.registerConfig.getCallerSaveRegisters();
// iterate all blocks in reverse order
for (int i = blockCount() - 1; i >= 0; i
AbstractBlock<?> block = blockAt(i);
try (Indent indent2 = Debug.logAndIndent("handle block %d", block.getId())) {
List<LIRInstruction> instructions = ir.getLIRforBlock(block);
final int blockFrom = getFirstLirInstructionId(block);
int blockTo = getLastLirInstructionId(block);
assert blockFrom == instructions.get(0).id();
assert blockTo == instructions.get(instructions.size() - 1).id();
// Update intervals for operands live at the end of this block;
BitSet live = blockData.get(block).liveOut;
for (int operandNum = live.nextSetBit(0); operandNum >= 0; operandNum = live.nextSetBit(operandNum + 1)) {
assert live.get(operandNum) : "should not stop here otherwise";
AllocatableValue operand = intervalFor(operandNum).operand;
Debug.log("live in %d: %s", operandNum, operand);
addUse(operand, blockFrom, blockTo + 2, RegisterPriority.None, LIRKind.Illegal);
// add special use positions for loop-end blocks when the
// interval is used anywhere inside this loop. It's possible
// that the block was part of a non-natural loop, so it might
// have an invalid loop index.
if (block.isLoopEnd() && block.getLoop() != null && isIntervalInLoop(operandNum, block.getLoop().getIndex())) {
intervalFor(operandNum).addUsePos(blockTo + 1, RegisterPriority.LiveAtLoopEnd);
}
}
// iterate all instructions of the block in reverse order.
// definitions of intervals are processed before uses
for (int j = instructions.size() - 1; j >= 0; j
final LIRInstruction op = instructions.get(j);
final int opId = op.id();
try (Indent indent3 = Debug.logAndIndent("handle inst %d: %s", opId, op)) {
// add a temp range for each register if operation destroys
// caller-save registers
if (op.destroysCallerSavedRegisters()) {
for (Register r : callerSaveRegs) {
if (attributes(r).isAllocatable()) {
addTemp(r.asValue(), opId, RegisterPriority.None, LIRKind.Illegal);
}
}
Debug.log("operation destroys all caller-save registers");
}
op.visitEachOutput(outputConsumer);
op.visitEachTemp(tempConsumer);
op.visitEachAlive(aliveConsumer);
op.visitEachInput(inputConsumer);
// Add uses of live locals from interpreter's point of view for proper
// debug information generation
// Treat these operands as temp values (if the live range is extended
// to a call site, the value would be in a register at
// the call otherwise)
op.visitEachState(stateProc);
// special steps for some instructions (especially moves)
handleMethodArguments(op);
}
} // end of instruction iteration
}
} // end of block iteration
// add the range [0, 1] to all fixed intervals.
// the register allocator need not handle unhandled fixed intervals
for (Interval interval : intervals) {
if (interval != null && isRegister(interval.operand)) {
interval.addRange(0, 1);
}
}
}
}
// * Phase 5: actual register allocation
private static boolean isSorted(Interval[] intervals) {
int from = -1;
for (Interval interval : intervals) {
assert interval != null;
assert from <= interval.from();
from = interval.from();
}
return true;
}
static Interval addToList(Interval first, Interval prev, Interval interval) {
Interval newFirst = first;
if (prev != null) {
prev.next = interval;
} else {
newFirst = interval;
}
return newFirst;
}
Interval.Pair createUnhandledLists(IntervalPredicate isList1, IntervalPredicate isList2) {
assert isSorted(sortedIntervals) : "interval list is not sorted";
Interval list1 = Interval.EndMarker;
Interval list2 = Interval.EndMarker;
Interval list1Prev = null;
Interval list2Prev = null;
Interval v;
int n = sortedIntervals.length;
for (int i = 0; i < n; i++) {
v = sortedIntervals[i];
if (v == null) {
continue;
}
if (isList1.apply(v)) {
list1 = addToList(list1, list1Prev, v);
list1Prev = v;
} else if (isList2 == null || isList2.apply(v)) {
list2 = addToList(list2, list2Prev, v);
list2Prev = v;
}
}
if (list1Prev != null) {
list1Prev.next = Interval.EndMarker;
}
if (list2Prev != null) {
list2Prev.next = Interval.EndMarker;
}
assert list1Prev == null || list1Prev.next == Interval.EndMarker : "linear list ends not with sentinel";
assert list2Prev == null || list2Prev.next == Interval.EndMarker : "linear list ends not with sentinel";
return new Interval.Pair(list1, list2);
}
void sortIntervalsBeforeAllocation() {
int sortedLen = 0;
for (Interval interval : intervals) {
if (interval != null) {
sortedLen++;
}
}
Interval[] sortedList = new Interval[sortedLen];
int sortedIdx = 0;
int sortedFromMax = -1;
// special sorting algorithm: the original interval-list is almost sorted,
// only some intervals are swapped. So this is much faster than a complete QuickSort
for (Interval interval : intervals) {
if (interval != null) {
int from = interval.from();
if (sortedFromMax <= from) {
sortedList[sortedIdx++] = interval;
sortedFromMax = interval.from();
} else {
// the assumption that the intervals are already sorted failed,
// so this interval must be sorted in manually
int j;
for (j = sortedIdx - 1; j >= 0 && from < sortedList[j].from(); j
sortedList[j + 1] = sortedList[j];
}
sortedList[j + 1] = interval;
sortedIdx++;
}
}
}
sortedIntervals = sortedList;
}
void sortIntervalsAfterAllocation() {
if (firstDerivedIntervalIndex == -1) {
// no intervals have been added during allocation, so sorted list is already up to date
return;
}
Interval[] oldList = sortedIntervals;
Interval[] newList = Arrays.copyOfRange(intervals, firstDerivedIntervalIndex, intervalsSize);
int oldLen = oldList.length;
int newLen = newList.length;
// conventional sort-algorithm for new intervals
Arrays.sort(newList, (Interval a, Interval b) -> a.from() - b.from());
// merge old and new list (both already sorted) into one combined list
Interval[] combinedList = new Interval[oldLen + newLen];
int oldIdx = 0;
int newIdx = 0;
while (oldIdx + newIdx < combinedList.length) {
if (newIdx >= newLen || (oldIdx < oldLen && oldList[oldIdx].from() <= newList[newIdx].from())) {
combinedList[oldIdx + newIdx] = oldList[oldIdx];
oldIdx++;
} else {
combinedList[oldIdx + newIdx] = newList[newIdx];
newIdx++;
}
}
sortedIntervals = combinedList;
}
public void allocateRegisters() {
try (Indent indent = Debug.logAndIndent("allocate registers")) {
Interval precoloredIntervals;
Interval notPrecoloredIntervals;
Interval.Pair result = createUnhandledLists(IS_PRECOLORED_INTERVAL, IS_VARIABLE_INTERVAL);
precoloredIntervals = result.first;
notPrecoloredIntervals = result.second;
// allocate cpu registers
LinearScanWalker lsw;
if (OptimizingLinearScanWalker.Options.LSRAOptimization.getValue()) {
lsw = new OptimizingLinearScanWalker(this, precoloredIntervals, notPrecoloredIntervals);
} else {
lsw = new LinearScanWalker(this, precoloredIntervals, notPrecoloredIntervals);
}
lsw.walk();
lsw.finishAllocation();
}
}
// * Phase 6: resolve data flow
// (insert moves at edges between blocks if intervals have been split)
// wrapper for Interval.splitChildAtOpId that performs a bailout in product mode
// instead of returning null
Interval splitChildAtOpId(Interval interval, int opId, LIRInstruction.OperandMode mode) {
Interval result = interval.getSplitChildAtOpId(opId, mode, this);
if (result != null) {
Debug.log("Split child at pos %d of interval %s is %s", opId, interval, result);
return result;
}
throw new BailoutException("LinearScan: interval is null");
}
Interval intervalAtBlockBegin(AbstractBlock<?> block, int operandNumber) {
return splitChildAtOpId(intervalFor(operandNumber), getFirstLirInstructionId(block), LIRInstruction.OperandMode.DEF);
}
Interval intervalAtBlockEnd(AbstractBlock<?> block, int operandNumber) {
return splitChildAtOpId(intervalFor(operandNumber), getLastLirInstructionId(block) + 1, LIRInstruction.OperandMode.DEF);
}
void resolveCollectMappings(AbstractBlock<?> fromBlock, AbstractBlock<?> toBlock, MoveResolver moveResolver) {
assert moveResolver.checkEmpty();
int numOperands = operandSize();
BitSet liveAtEdge = blockData.get(toBlock).liveIn;
// visit all variables for which the liveAtEdge bit is set
for (int operandNum = liveAtEdge.nextSetBit(0); operandNum >= 0; operandNum = liveAtEdge.nextSetBit(operandNum + 1)) {
assert operandNum < numOperands : "live information set for not exisiting interval";
assert blockData.get(fromBlock).liveOut.get(operandNum) && blockData.get(toBlock).liveIn.get(operandNum) : "interval not live at this edge";
Interval fromInterval = intervalAtBlockEnd(fromBlock, operandNum);
Interval toInterval = intervalAtBlockBegin(toBlock, operandNum);
if (fromInterval != toInterval && !fromInterval.location().equals(toInterval.location())) {
// need to insert move instruction
moveResolver.addMapping(fromInterval, toInterval);
}
}
}
void resolveFindInsertPos(AbstractBlock<?> fromBlock, AbstractBlock<?> toBlock, MoveResolver moveResolver) {
if (fromBlock.getSuccessorCount() <= 1) {
Debug.log("inserting moves at end of fromBlock B%d", fromBlock.getId());
List<LIRInstruction> instructions = ir.getLIRforBlock(fromBlock);
LIRInstruction instr = instructions.get(instructions.size() - 1);
if (instr instanceof StandardOp.JumpOp) {
// insert moves before branch
moveResolver.setInsertPosition(instructions, instructions.size() - 1);
} else {
moveResolver.setInsertPosition(instructions, instructions.size());
}
} else {
Debug.log("inserting moves at beginning of toBlock B%d", toBlock.getId());
if (DetailedAsserts.getValue()) {
assert ir.getLIRforBlock(fromBlock).get(0) instanceof StandardOp.LabelOp : "block does not start with a label";
// because the number of predecessor edges matches the number of
// successor edges, blocks which are reached by switch statements
// may have be more than one predecessor but it will be guaranteed
// that all predecessors will be the same.
for (AbstractBlock<?> predecessor : toBlock.getPredecessors()) {
assert fromBlock == predecessor : "all critical edges must be broken";
}
}
moveResolver.setInsertPosition(ir.getLIRforBlock(toBlock), 1);
}
}
/**
* Inserts necessary moves (spilling or reloading) at edges between blocks for intervals that
* have been split.
*/
void resolveDataFlow() {
try (Indent indent = Debug.logAndIndent("resolve data flow")) {
int numBlocks = blockCount();
MoveResolver moveResolver = new MoveResolver(this);
BitSet blockCompleted = new BitSet(numBlocks);
BitSet alreadyResolved = new BitSet(numBlocks);
for (AbstractBlock<?> block : sortedBlocks) {
// check if block has only one predecessor and only one successor
if (block.getPredecessorCount() == 1 && block.getSuccessorCount() == 1) {
List<LIRInstruction> instructions = ir.getLIRforBlock(block);
assert instructions.get(0) instanceof StandardOp.LabelOp : "block must start with label";
assert instructions.get(instructions.size() - 1) instanceof StandardOp.JumpOp : "block with successor must end with unconditional jump";
// check if block is empty (only label and branch)
if (instructions.size() == 2) {
AbstractBlock<?> pred = block.getPredecessors().iterator().next();
AbstractBlock<?> sux = block.getSuccessors().iterator().next();
// prevent optimization of two consecutive blocks
if (!blockCompleted.get(pred.getLinearScanNumber()) && !blockCompleted.get(sux.getLinearScanNumber())) {
Debug.log(" optimizing empty block B%d (pred: B%d, sux: B%d)", block.getId(), pred.getId(), sux.getId());
blockCompleted.set(block.getLinearScanNumber());
// directly resolve between pred and sux (without looking
// at the empty block
// between)
resolveCollectMappings(pred, sux, moveResolver);
if (moveResolver.hasMappings()) {
moveResolver.setInsertPosition(instructions, 1);
moveResolver.resolveAndAppendMoves();
}
}
}
}
}
for (AbstractBlock<?> fromBlock : sortedBlocks) {
if (!blockCompleted.get(fromBlock.getLinearScanNumber())) {
alreadyResolved.clear();
alreadyResolved.or(blockCompleted);
for (AbstractBlock<?> toBlock : fromBlock.getSuccessors()) {
// check for duplicate edges between the same blocks (can happen with switch
// blocks)
if (!alreadyResolved.get(toBlock.getLinearScanNumber())) {
Debug.log("processing edge between B%d and B%d", fromBlock.getId(), toBlock.getId());
alreadyResolved.set(toBlock.getLinearScanNumber());
// collect all intervals that have been split between
// fromBlock and toBlock
resolveCollectMappings(fromBlock, toBlock, moveResolver);
if (moveResolver.hasMappings()) {
resolveFindInsertPos(fromBlock, toBlock, moveResolver);
moveResolver.resolveAndAppendMoves();
}
}
}
}
}
}
}
// * Phase 7: assign register numbers back to LIR
// (includes computation of debug information and oop maps)
static StackSlot canonicalSpillOpr(Interval interval) {
assert interval.spillSlot() != null : "canonical spill slot not set";
return interval.spillSlot();
}
/**
* Assigns the allocated location for an LIR instruction operand back into the instruction.
*
* @param operand an LIR instruction operand
* @param opId the id of the LIR instruction using {@code operand}
* @param mode the usage mode for {@code operand} by the instruction
* @return the location assigned for the operand
*/
private Value colorLirOperand(Variable operand, int opId, OperandMode mode) {
Interval interval = intervalFor(operand);
assert interval != null : "interval must exist";
if (opId != -1) {
if (DetailedAsserts.getValue()) {
AbstractBlock<?> block = blockForId(opId);
if (block.getSuccessorCount() <= 1 && opId == getLastLirInstructionId(block)) {
// check if spill moves could have been appended at the end of this block, but
// before the branch instruction. So the split child information for this branch
// would
// be incorrect.
LIRInstruction instr = ir.getLIRforBlock(block).get(ir.getLIRforBlock(block).size() - 1);
if (instr instanceof StandardOp.JumpOp) {
if (blockData.get(block).liveOut.get(operandNumber(operand))) {
assert false : "can't get split child for the last branch of a block because the information would be incorrect (moves are inserted before the branch in resolveDataFlow)";
}
}
}
}
// operands are not changed when an interval is split during allocation,
// so search the right interval here
interval = splitChildAtOpId(interval, opId, mode);
}
if (isIllegal(interval.location()) && interval.canMaterialize()) {
assert mode != OperandMode.DEF;
return interval.getMaterializedValue();
}
return interval.location();
}
private boolean isMaterialized(AllocatableValue operand, int opId, OperandMode mode) {
Interval interval = intervalFor(operand);
assert interval != null : "interval must exist";
if (opId != -1) {
// operands are not changed when an interval is split during allocation,
// so search the right interval here
interval = splitChildAtOpId(interval, opId, mode);
}
return isIllegal(interval.location()) && interval.canMaterialize();
}
protected IntervalWalker initIntervalWalker(IntervalPredicate predicate) {
// setup lists of potential oops for walking
Interval oopIntervals;
Interval nonOopIntervals;
oopIntervals = createUnhandledLists(predicate, null).first;
// intervals that have no oops inside need not to be processed.
// to ensure a walking until the last instruction id, add a dummy interval
// with a high operation id
nonOopIntervals = new Interval(Value.ILLEGAL, -1);
nonOopIntervals.addRange(Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 1);
return new IntervalWalker(this, oopIntervals, nonOopIntervals);
}
/**
* Visits all intervals for a frame state. The frame state use this information to build the OOP
* maps.
*/
void markFrameLocations(IntervalWalker iw, LIRInstruction op, LIRFrameState info) {
Debug.log("creating oop map at opId %d", op.id());
// walk before the current operation . intervals that start at
// the operation (i.e. output operands of the operation) are not
// included in the oop map
iw.walkBefore(op.id());
// TODO(je) we could pass this as parameter
AbstractBlock<?> block = blockForId(op.id());
// Iterate through active intervals
for (Interval interval = iw.activeLists.get(RegisterBinding.Fixed); interval != Interval.EndMarker; interval = interval.next) {
Value operand = interval.operand;
assert interval.currentFrom() <= op.id() && op.id() <= interval.currentTo() : "interval should not be active otherwise";
assert isVariable(interval.operand) : "fixed interval found";
// Check if this range covers the instruction. Intervals that
// start or end at the current operation are not included in the
// oop map, except in the case of patching moves. For patching
// moves, any intervals which end at this instruction are included
// in the oop map since we may safepoint while doing the patch
// before we've consumed the inputs.
if (op.id() < interval.currentTo() && !isIllegal(interval.location())) {
// caller-save registers must not be included into oop-maps at calls
assert !op.destroysCallerSavedRegisters() || !isRegister(operand) || !isCallerSave(operand) : "interval is in a caller-save register at a call . register will be overwritten";
info.markLocation(interval.location(), frameMap);
// Spill optimization: when the stack value is guaranteed to be always correct,
// then it must be added to the oop map even if the interval is currently in a
// register
int spillPos = interval.spillDefinitionPos();
if (interval.spillState() != SpillState.SpillInDominator) {
if (interval.alwaysInMemory() && op.id() > interval.spillDefinitionPos() && !interval.location().equals(interval.spillSlot())) {
assert interval.spillDefinitionPos() > 0 : "position not set correctly";
assert spillPos > 0 : "position not set correctly";
assert interval.spillSlot() != null : "no spill slot assigned";
assert !isRegister(interval.operand) : "interval is on stack : so stack slot is registered twice";
info.markLocation(interval.spillSlot(), frameMap);
}
} else {
AbstractBlock<?> spillBlock = blockForId(spillPos);
if (interval.alwaysInMemory() && !interval.location().equals(interval.spillSlot())) {
if ((spillBlock.equals(block) && op.id() > spillPos) || dominates(spillBlock, block)) {
assert spillPos > 0 : "position not set correctly";
assert interval.spillSlot() != null : "no spill slot assigned";
assert !isRegister(interval.operand) : "interval is on stack : so stack slot is registered twice";
info.markLocation(interval.spillSlot(), frameMap);
}
}
}
}
}
}
private boolean isCallerSave(Value operand) {
return attributes(asRegister(operand)).isCallerSave();
}
private InstructionValueProcedure debugInfoProc = new InstructionValueProcedure() {
@Override
public Value doValue(LIRInstruction op, Value operand) {
int tempOpId = op.id();
OperandMode mode = OperandMode.USE;
AbstractBlock<?> block = blockForId(tempOpId);
if (block.getSuccessorCount() == 1 && tempOpId == getLastLirInstructionId(block)) {
// generating debug information for the last instruction of a block.
// if this instruction is a branch, spill moves are inserted before this branch
// and so the wrong operand would be returned (spill moves at block boundaries
// are not
// considered in the live ranges of intervals)
// Solution: use the first opId of the branch target block instead.
final LIRInstruction instr = ir.getLIRforBlock(block).get(ir.getLIRforBlock(block).size() - 1);
if (instr instanceof StandardOp.JumpOp) {
if (blockData.get(block).liveOut.get(operandNumber(operand))) {
tempOpId = getFirstLirInstructionId(block.getSuccessors().iterator().next());
mode = OperandMode.DEF;
}
}
}
// Get current location of operand
// The operand must be live because debug information is considered when building
// the intervals
// if the interval is not live, colorLirOperand will cause an assert on failure
Value result = colorLirOperand((Variable) operand, tempOpId, mode);
assert !hasCall(tempOpId) || isStackSlot(result) || isConstant(result) || !isCallerSave(result) : "cannot have caller-save register operands at calls";
return result;
}
};
private void computeDebugInfo(IntervalWalker iw, final LIRInstruction op, LIRFrameState info) {
info.initDebugInfo(frameMap, !op.destroysCallerSavedRegisters() || !callKillsRegisters);
markFrameLocations(iw, op, info);
info.forEachState(op, debugInfoProc);
info.finish(op, frameMap);
}
private void assignLocations(List<LIRInstruction> instructions, final IntervalWalker iw) {
int numInst = instructions.size();
boolean hasDead = false;
InstructionValueProcedure assignProc = new InstructionValueProcedure() {
@Override
public Value doValue(LIRInstruction op, Value operand, OperandMode mode, EnumSet<OperandFlag> flags) {
if (isVariable(operand)) {
return colorLirOperand((Variable) operand, op.id(), mode);
}
return operand;
}
};
InstructionStateProcedure stateProc = new InstructionStateProcedure() {
@Override
protected void doState(LIRInstruction op, LIRFrameState state) {
computeDebugInfo(iw, op, state);
}
};
for (int j = 0; j < numInst; j++) {
final LIRInstruction op = instructions.get(j);
if (op == null) { // this can happen when spill-moves are removed in eliminateSpillMoves
hasDead = true;
continue;
}
// remove useless moves
MoveOp move = null;
if (op instanceof MoveOp) {
move = (MoveOp) op;
AllocatableValue result = move.getResult();
if (isVariable(result) && isMaterialized(result, op.id(), OperandMode.DEF)) {
/*
* This happens if a materializable interval is originally not spilled but then
* kicked out in LinearScanWalker.splitForSpilling(). When kicking out such an
* interval this move operation was already generated.
*/
instructions.set(j, null);
hasDead = true;
continue;
}
}
op.forEachInput(assignProc);
op.forEachAlive(assignProc);
op.forEachTemp(assignProc);
op.forEachOutput(assignProc);
// compute reference map and debug information
op.forEachState(stateProc);
// remove useless moves
if (move != null) {
if (move.getInput().equals(move.getResult())) {
instructions.set(j, null);
hasDead = true;
}
}
}
if (hasDead) {
// Remove null values from the list.
instructions.removeAll(Collections.singleton(null));
}
}
private void assignLocations() {
IntervalWalker iw = initIntervalWalker(IS_STACK_INTERVAL);
try (Indent indent = Debug.logAndIndent("assign locations")) {
for (AbstractBlock<?> block : sortedBlocks) {
try (Indent indent2 = Debug.logAndIndent("assign locations in block B%d", block.getId())) {
assignLocations(ir.getLIRforBlock(block), iw);
}
}
}
}
public static void allocate(TargetDescription target, LIR lir, FrameMap frameMap) {
new LinearScan(target, lir, frameMap).allocate();
}
private void allocate() {
/*
* This is the point to enable debug logging for the whole register allocation.
*/
try (Indent indent = Debug.logAndIndent("LinearScan allocate")) {
try (Scope s = Debug.scope("LifetimeAnalysis")) {
numberInstructions();
printLir("Before register allocation", true);
computeLocalLiveSets();
computeGlobalLiveSets();
buildIntervals();
sortIntervalsBeforeAllocation();
} catch (Throwable e) {
throw Debug.handle(e);
}
try (Scope s = Debug.scope("RegisterAllocation")) {
printIntervals("Before register allocation");
allocateRegisters();
} catch (Throwable e) {
throw Debug.handle(e);
}
if (Options.LSRAOptimizeSpillPosition.getValue()) {
try (Scope s = Debug.scope("OptimizeSpillPosition")) {
optimizeSpillPosition();
} catch (Throwable e) {
throw Debug.handle(e);
}
}
try (Scope s = Debug.scope("ResolveDataFlow")) {
resolveDataFlow();
} catch (Throwable e) {
throw Debug.handle(e);
}
try (Scope s = Debug.scope("DebugInfo")) {
frameMap.finish();
printIntervals("After register allocation");
printLir("After register allocation", true);
sortIntervalsAfterAllocation();
if (DetailedAsserts.getValue()) {
verify();
}
try (Scope s1 = Debug.scope("EliminateSpillMove")) {
eliminateSpillMoves();
} catch (Throwable e) {
throw Debug.handle(e);
}
printLir("After spill move elimination", true);
try (Scope s1 = Debug.scope("AssignLocations")) {
assignLocations();
} catch (Throwable e) {
throw Debug.handle(e);
}
if (DetailedAsserts.getValue()) {
verifyIntervals();
}
} catch (Throwable e) {
throw Debug.handle(e);
}
printLir("After register number assignment", true);
}
}
private DebugMetric betterSpillPos = Debug.metric("BetterSpillPosition");
private DebugMetric betterSpillPosWithLowerProbability = Debug.metric("BetterSpillPositionWithLowerProbability");
private void optimizeSpillPosition() {
LIRInsertionBuffer[] insertionBuffers = new LIRInsertionBuffer[ir.linearScanOrder().size()];
for (Interval interval : intervals) {
if (interval != null && interval.isSplitParent() && interval.spillState() == SpillState.SpillInDominator) {
AbstractBlock<?> defBlock = blockForId(interval.spillDefinitionPos());
AbstractBlock<?> spillBlock = null;
Interval firstSpillChild = null;
try (Indent indent = Debug.logAndIndent("interval %s (%s)", interval, defBlock)) {
for (Interval splitChild : interval.getSplitChildren()) {
if (isStackSlot(splitChild.location())) {
if (firstSpillChild == null || splitChild.from() < firstSpillChild.from()) {
firstSpillChild = splitChild;
} else {
assert firstSpillChild.from() < splitChild.from();
}
// iterate all blocks where the interval has use positions
for (AbstractBlock<?> splitBlock : blocksForInterval(splitChild)) {
if (dominates(defBlock, splitBlock)) {
Debug.log("Split interval %s, block %s", splitChild, splitBlock);
if (spillBlock == null) {
spillBlock = splitBlock;
} else {
spillBlock = commonDominator(spillBlock, splitBlock);
assert spillBlock != null;
}
}
}
}
}
if (spillBlock == null) {
// no spill interval
interval.setSpillState(SpillState.StoreAtDefinition);
} else {
// move out of loops
if (defBlock.getLoopDepth() < spillBlock.getLoopDepth()) {
spillBlock = moveSpillOutOfLoop(defBlock, spillBlock);
}
/*
* If the spill block is the begin of the first split child (aka the value
* is on the stack) spill in the dominator.
*/
assert firstSpillChild != null;
if (!defBlock.equals(spillBlock) && spillBlock.equals(blockForId(firstSpillChild.from()))) {
AbstractBlock<?> dom = spillBlock.getDominator();
Debug.log("Spill block (%s) is the beginning of a spill child -> use dominator (%s)", spillBlock, dom);
spillBlock = dom;
}
if (!defBlock.equals(spillBlock)) {
assert dominates(defBlock, spillBlock);
betterSpillPos.increment();
Debug.log("Better spill position found (Block %s)", spillBlock);
if (defBlock.probability() <= spillBlock.probability()) {
// better spill block has the same probability -> do nothing
interval.setSpillState(SpillState.StoreAtDefinition);
} else {
LIRInsertionBuffer insertionBuffer = insertionBuffers[spillBlock.getId()];
if (insertionBuffer == null) {
insertionBuffer = new LIRInsertionBuffer();
insertionBuffers[spillBlock.getId()] = insertionBuffer;
insertionBuffer.init(ir.getLIRforBlock(spillBlock));
}
int spillOpId = getFirstLirInstructionId(spillBlock);
// insert spill move
AllocatableValue fromLocation = interval.getSplitChildAtOpId(spillOpId, OperandMode.DEF, this).location();
AllocatableValue toLocation = canonicalSpillOpr(interval);
LIRInstruction move = ir.getSpillMoveFactory().createMove(toLocation, fromLocation);
move.setId(DOMINATOR_SPILL_MOVE_ID);
/*
* We can use the insertion buffer directly because we always insert
* at position 1.
*/
insertionBuffer.append(1, move);
betterSpillPosWithLowerProbability.increment();
interval.setSpillDefinitionPos(spillOpId);
}
} else {
// definition is the best choice
interval.setSpillState(SpillState.StoreAtDefinition);
}
}
}
}
}
for (LIRInsertionBuffer insertionBuffer : insertionBuffers) {
if (insertionBuffer != null) {
assert insertionBuffer.initialized() : "Insertion buffer is nonnull but not initialized!";
insertionBuffer.finish();
}
}
}
/**
* Iterate over all {@link AbstractBlock blocks} of an interval.
*/
private class IntervalBlockIterator implements Iterator<AbstractBlock<?>> {
Range range;
AbstractBlock<?> block;
public IntervalBlockIterator(Interval interval) {
range = interval.first();
block = blockForId(range.from);
}
public AbstractBlock<?> next() {
AbstractBlock<?> currentBlock = block;
int nextBlockIndex = block.getLinearScanNumber() + 1;
if (nextBlockIndex < sortedBlocks.size()) {
block = sortedBlocks.get(nextBlockIndex);
if (range.to <= getFirstLirInstructionId(block)) {
range = range.next;
if (range == Range.EndMarker) {
block = null;
} else {
block = blockForId(range.from);
}
}
} else {
block = null;
}
return currentBlock;
}
public boolean hasNext() {
return block != null;
}
}
private Iterable<AbstractBlock<?>> blocksForInterval(Interval interval) {
return new Iterable<AbstractBlock<?>>() {
public Iterator<AbstractBlock<?>> iterator() {
return new IntervalBlockIterator(interval);
}
};
}
private static AbstractBlock<?> moveSpillOutOfLoop(AbstractBlock<?> defBlock, AbstractBlock<?> spillBlock) {
int defLoopDepth = defBlock.getLoopDepth();
for (AbstractBlock<?> block = spillBlock.getDominator(); !defBlock.equals(block); block = block.getDominator()) {
assert block != null : "spill block not dominated by definition block?";
if (block.getLoopDepth() <= defLoopDepth) {
assert block.getLoopDepth() == defLoopDepth : "Cannot spill an interval outside of the loop where it is defined!";
return block;
}
}
return defBlock;
}
void printIntervals(String label) {
if (Debug.isLogEnabled()) {
try (Indent indent = Debug.logAndIndent("intervals %s", label)) {
for (Interval interval : intervals) {
if (interval != null) {
Debug.log("%s", interval.logString(this));
}
}
try (Indent indent2 = Debug.logAndIndent("Basic Blocks")) {
for (int i = 0; i < blockCount(); i++) {
AbstractBlock<?> block = blockAt(i);
Debug.log("B%d [%d, %d, %s] ", block.getId(), getFirstLirInstructionId(block), getLastLirInstructionId(block), block.getLoop());
}
}
}
}
Debug.dump(Arrays.copyOf(intervals, intervalsSize), label);
}
void printLir(String label, @SuppressWarnings("unused") boolean hirValid) {
Debug.dump(ir, label);
}
boolean verify() {
// (check that all intervals have a correct register and that no registers are overwritten)
verifyIntervals();
verifyRegisters();
Debug.log("no errors found");
return true;
}
private void verifyRegisters() {
// Enable this logging to get output for the verification process.
try (Indent indent = Debug.logAndIndent("verifying register allocation")) {
RegisterVerifier verifier = new RegisterVerifier(this);
verifier.verify(blockAt(0));
}
}
void verifyIntervals() {
try (Indent indent = Debug.logAndIndent("verifying intervals")) {
int len = intervalsSize;
for (int i = 0; i < len; i++) {
Interval i1 = intervals[i];
if (i1 == null) {
continue;
}
i1.checkSplitChildren();
if (i1.operandNumber != i) {
Debug.log("Interval %d is on position %d in list", i1.operandNumber, i);
Debug.log(i1.logString(this));
throw new GraalInternalError("");
}
if (isVariable(i1.operand) && i1.kind().equals(LIRKind.Illegal)) {
Debug.log("Interval %d has no type assigned", i1.operandNumber);
Debug.log(i1.logString(this));
throw new GraalInternalError("");
}
if (i1.location() == null) {
Debug.log("Interval %d has no register assigned", i1.operandNumber);
Debug.log(i1.logString(this));
throw new GraalInternalError("");
}
if (i1.first() == Range.EndMarker) {
Debug.log("Interval %d has no Range", i1.operandNumber);
Debug.log(i1.logString(this));
throw new GraalInternalError("");
}
for (Range r = i1.first(); r != Range.EndMarker; r = r.next) {
if (r.from >= r.to) {
Debug.log("Interval %d has zero length range", i1.operandNumber);
Debug.log(i1.logString(this));
throw new GraalInternalError("");
}
}
for (int j = i + 1; j < len; j++) {
Interval i2 = intervals[j];
if (i2 == null) {
continue;
}
// special intervals that are created in MoveResolver
// . ignore them because the range information has no meaning there
if (i1.from() == 1 && i1.to() == 2) {
continue;
}
if (i2.from() == 1 && i2.to() == 2) {
continue;
}
Value l1 = i1.location();
Value l2 = i2.location();
if (i1.intersects(i2) && !isIllegal(l1) && (l1.equals(l2))) {
if (DetailedAsserts.getValue()) {
Debug.log("Intervals %d and %d overlap and have the same register assigned", i1.operandNumber, i2.operandNumber);
Debug.log(i1.logString(this));
Debug.log(i2.logString(this));
}
throw new BailoutException("");
}
}
}
}
}
class CheckConsumer extends ValueConsumer {
boolean ok;
Interval curInterval;
@Override
protected void visitValue(Value operand) {
if (isRegister(operand)) {
if (intervalFor(operand) == curInterval) {
ok = true;
}
}
}
}
void verifyNoOopsInFixedIntervals() {
try (Indent indent = Debug.logAndIndent("verifying that no oops are in fixed intervals *")) {
CheckConsumer checkConsumer = new CheckConsumer();
Interval fixedIntervals;
Interval otherIntervals;
fixedIntervals = createUnhandledLists(IS_PRECOLORED_INTERVAL, null).first;
// to ensure a walking until the last instruction id, add a dummy interval
// with a high operation id
otherIntervals = new Interval(Value.ILLEGAL, -1);
otherIntervals.addRange(Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 1);
IntervalWalker iw = new IntervalWalker(this, fixedIntervals, otherIntervals);
for (AbstractBlock<?> block : sortedBlocks) {
List<LIRInstruction> instructions = ir.getLIRforBlock(block);
for (int j = 0; j < instructions.size(); j++) {
LIRInstruction op = instructions.get(j);
if (op.hasState()) {
iw.walkBefore(op.id());
boolean checkLive = true;
// Make sure none of the fixed registers is live across an
// oopmap since we can't handle that correctly.
if (checkLive) {
for (Interval interval = iw.activeLists.get(RegisterBinding.Fixed); interval != Interval.EndMarker; interval = interval.next) {
if (interval.currentTo() > op.id() + 1) {
// This interval is live out of this op so make sure
// that this interval represents some value that's
// referenced by this op either as an input or output.
checkConsumer.curInterval = interval;
checkConsumer.ok = false;
op.visitEachInput(checkConsumer);
op.visitEachAlive(checkConsumer);
op.visitEachTemp(checkConsumer);
op.visitEachOutput(checkConsumer);
assert checkConsumer.ok : "fixed intervals should never be live across an oopmap point";
}
}
}
}
}
}
}
}
/**
* Returns a value for a interval definition, which can be used for re-materialization.
*
* @param op An instruction which defines a value
* @param operand The destination operand of the instruction
* @param interval The interval for this defined value.
* @return Returns the value which is moved to the instruction and which can be reused at all
* reload-locations in case the interval of this instruction is spilled. Currently this
* can only be a {@link Constant}.
*/
public static Constant getMaterializedValue(LIRInstruction op, Value operand, Interval interval) {
if (op instanceof MoveOp) {
MoveOp move = (MoveOp) op;
if (move.getInput() instanceof Constant) {
/*
* Check if the interval has any uses which would accept an stack location (priority
* == ShouldHaveRegister). Rematerialization of such intervals can result in a
* degradation, because rematerialization always inserts a constant load, even if
* the value is not needed in a register.
*/
Interval.UsePosList usePosList = interval.usePosList();
int numUsePos = usePosList.size();
for (int useIdx = 0; useIdx < numUsePos; useIdx++) {
Interval.RegisterPriority priority = usePosList.registerPriority(useIdx);
if (priority == Interval.RegisterPriority.ShouldHaveRegister) {
return null;
}
}
return (Constant) move.getInput();
}
}
return null;
}
}
|
package org.chromium;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.hardware.display.DisplayManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.os.Build;
import android.view.Display;
import android.view.Surface;
public class ChromeSystemDisplay extends CordovaPlugin {
private static final String LOG_TAG = "ChromeSystemDisplay";
private DisplayManager displayManager;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Activity activity = cordova.getActivity();
displayManager = (DisplayManager) cordova.getActivity().getSystemService(Activity.DISPLAY_SERVICE);
}
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if ("getInfo".equals(action)) {
getInfo(args, callbackContext);
return true;
}
return false;
}
private int getRotation(final Display display) {
final int rotation = display.getRotation();
final int DEFAULT_ROTATION = 0;
if (rotation == Surface.ROTATION_0) {
return 0;
} else if (rotation == Surface.ROTATION_90) {
return 90;
} else if (rotation == Surface.ROTATION_180) {
return 180;
} else if (rotation == Surface.ROTATION_270) {
return 270;
}
return DEFAULT_ROTATION;
}
private JSONObject getBounds(final Display display) throws JSONException {
JSONObject ret = new JSONObject();
int widthPixels = 0;
int heightPixels = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
final DisplayMetrics displayMetrics = new DisplayMetrics();
display.getRealMetrics(displayMetrics);
widthPixels = displayMetrics.widthPixels;
heightPixels = displayMetrics.heightPixels;
}
ret.put("left", 0);
ret.put("top", 0);
ret.put("width", widthPixels);
ret.put("height", heightPixels);
return ret;
}
private JSONObject getOverscan() throws JSONException {
JSONObject ret = new JSONObject();
ret.put("left", 0);
ret.put("top", 0);
ret.put("right", 0);
ret.put("bottom", 0);
return ret;
}
private float getDpiX(final Display display) {
final DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
// displayMetrics.xdpi is not reliable.
return displayMetrics.densityDpi;
}
private float getDpiY(final Display display) {
final DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
// displayMetrics.ydpi is not reliable.
return displayMetrics.densityDpi;
}
private JSONObject getWorkArea(final Display display) throws JSONException {
JSONObject ret = new JSONObject();
final DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
ret.put("left", 0);
ret.put("top", 0);
ret.put("width", displayMetrics.widthPixels);
ret.put("height", displayMetrics.heightPixels);
return ret;
}
private void getInfo(final CordovaArgs args, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
JSONArray ret = new JSONArray();
Display[] displays = displayManager.getDisplays();
for (Display display : displays) {
JSONObject displayInfo = new JSONObject();
displayInfo.put("id", Integer.toString(display.getDisplayId()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
displayInfo.put("name", display.getName());
}
displayInfo.put("isPrimary", display.getDisplayId() == android.view.Display.DEFAULT_DISPLAY);
displayInfo.put("dpiX", getDpiX(display));
displayInfo.put("dpiY", getDpiY(display));
displayInfo.put("rotation", getRotation(display));
displayInfo.put("bounds", getBounds(display));
displayInfo.put("overscan", getOverscan());
displayInfo.put("workArea", getWorkArea(display));
// mirroringSourceId, isInternal and isEnabled cannot be retrieved at this moment.
ret.put(displayInfo);
}
callbackContext.success(ret);
} catch (Exception e) {
Log.e(LOG_TAG, "Error occured while getting display info", e);
callbackContext.error("Could not get display info");
}
}
});
}
}
|
package com.oracle.truffle.api.dsl;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Specialization {
int DEFAULT_ORDER = -1;
@Deprecated
int order() default DEFAULT_ORDER;
String insertBefore() default "";
Class<? extends Throwable>[] rewriteOn() default {};
String[] contains() default {};
String[] guards() default {};
/**
* Defines the assumptions to check for this specialization. When the specialization method is
* invoked it is guaranteed that these assumptions still hold. It is not guaranteed that they
* are checked before the {@link #guards()} methods. They may be checked before after or in
* between {@link #guards()}. To declare assumptions use the {@link NodeAssumptions} annotation
* at class level.
*/
String[] assumptions() default {};
}
|
package org.jnosql.artemis.graph;
import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, TYPE})
@Retention(RUNTIME)
@Qualifier
/**
* All Graph operation go through the Graph traversal e.g. the GraphConverter and GraphTemplate implementation will use
* {@link org.apache.tinkerpop.gremlin.structure.Graph#traversal()} in all operations.
*/
public @interface GraphTraversalOperation {
}
|
package com.orientechnologies.orient.graph;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODirtyManager;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.tinkerpop.blueprints.impls.orient.OrientEdge;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import org.junit.Ignore;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class DirtyManagerGraphTest {
@Test
public void testLoopOfNew() {
OrientGraph graph = new OrientGraph("memory:" + DirtyManagerGraphTest.class.getSimpleName());
try {
graph.createEdgeType("next");
OrientVertex vertex = graph.addVertex(null);
OrientVertex vertex1 = graph.addVertex(null);
OrientVertex vertex2 = graph.addVertex(null);
OrientVertex vertex3 = graph.addVertex(null);
OrientEdge edge1 = (OrientEdge) vertex.addEdge("next", vertex1);
OrientEdge edge2 = (OrientEdge) vertex1.addEdge("next", vertex2);
OrientEdge edge3 = (OrientEdge) vertex2.addEdge("next", vertex3);
OrientEdge edge4 = (OrientEdge) vertex3.addEdge("next", vertex);
graph.commit();
assertTrue(vertex.getIdentity().isPersistent());
assertTrue(vertex1.getIdentity().isPersistent());
assertTrue(vertex2.getIdentity().isPersistent());
assertTrue(vertex3.getIdentity().isPersistent());
assertTrue(edge1.getIdentity().isPersistent());
assertTrue(edge2.getIdentity().isPersistent());
assertTrue(edge3.getIdentity().isPersistent());
assertTrue(edge4.getIdentity().isPersistent());
} finally {
graph.drop();
}
}
@Test
public void testLoopOfNewTree() {
OrientGraph graph = new OrientGraph("memory:" + DirtyManagerGraphTest.class.getSimpleName());
Object prev = OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.getValue();
OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(-1);
try {
graph.createEdgeType("next");
OrientVertex vertex = graph.addVertex(null);
OrientVertex vertex1 = graph.addVertex(null);
OrientVertex vertex2 = graph.addVertex(null);
OrientVertex vertex3 = graph.addVertex(null);
OrientEdge edge1 = (OrientEdge) vertex.addEdge("next", vertex1);
OrientEdge edge2 = (OrientEdge) vertex1.addEdge("next", vertex2);
OrientEdge edge3 = (OrientEdge) vertex2.addEdge("next", vertex3);
OrientEdge edge4 = (OrientEdge) vertex3.addEdge("next", vertex);
graph.commit();
assertTrue(vertex.getIdentity().isPersistent());
assertTrue(vertex1.getIdentity().isPersistent());
assertTrue(vertex2.getIdentity().isPersistent());
assertTrue(vertex3.getIdentity().isPersistent());
assertTrue(edge1.getIdentity().isPersistent());
assertTrue(edge2.getIdentity().isPersistent());
assertTrue(edge3.getIdentity().isPersistent());
assertTrue(edge4.getIdentity().isPersistent());
} finally {
OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(prev);
graph.drop();
}
}
}
|
package com.tinkerpop.gremlin.process.util;
import com.tinkerpop.gremlin.process.Step;
import com.tinkerpop.gremlin.process.Traversal;
import com.tinkerpop.gremlin.process.TraversalEngine;
import com.tinkerpop.gremlin.process.TraversalSideEffects;
import com.tinkerpop.gremlin.process.TraversalStrategies;
import com.tinkerpop.gremlin.process.Traverser;
import com.tinkerpop.gremlin.process.graph.marker.TraversalHolder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
public class DefaultTraversal<S, E> implements Traversal<S, E>, Traversal.Admin<S, E> {
private E lastEnd = null;
private long lastEndCount = 0l;
private boolean locked = false; // an optimization so getTraversalEngine().isEmpty() isn't required on each next()/hasNext()
private Step<?, E> finalEndStep = EmptyStep.instance();
private final StepPosition stepPosition = new StepPosition();
protected List<Step> steps = new ArrayList<>();
protected TraversalStrategies strategies;
protected TraversalSideEffects sideEffects = new DefaultTraversalSideEffects();
protected Optional<TraversalEngine> traversalEngine = Optional.empty();
protected TraversalHolder traversalHolder = (TraversalHolder) EmptyStep.instance();
public DefaultTraversal(final Class emanatingClass) {
this.strategies = TraversalStrategies.GlobalCache.getStrategies(emanatingClass);
}
@Override
public Traversal.Admin<S, E> asAdmin() {
return this;
}
@Override
public void applyStrategies(final TraversalEngine engine) throws IllegalStateException {
if (this.locked)
throw Traversal.Exceptions.traversalIsLocked();
TraversalHelper.reIdSteps(this.stepPosition, this);
this.strategies.applyStrategies(this, engine);
for (final Step<?, ?> step : this.getSteps()) {
if (step instanceof TraversalHolder) {
((TraversalHolder) step).setStrategies(this.strategies); // TODO: should we clone?
for (final Traversal<?, ?> nested : ((TraversalHolder) step).getGlobalTraversals()) {
nested.asAdmin().applyStrategies(engine);
}
}
}
this.traversalEngine = Optional.of(engine);
this.locked = true;
this.finalEndStep = this.getEndStep();
}
@Override
public Optional<TraversalEngine> getTraversalEngine() {
return this.traversalEngine;
}
@Override
public List<Step> getSteps() {
return Collections.unmodifiableList(this.steps);
}
@Override
public boolean hasNext() {
if (!this.locked) this.applyStrategies(TraversalEngine.STANDARD);
return this.lastEndCount > 0l || this.finalEndStep.hasNext();
}
@Override
public E next() {
if (!this.locked) this.applyStrategies(TraversalEngine.STANDARD);
if (this.lastEndCount > 0l) {
this.lastEndCount
return this.lastEnd;
} else {
final Traverser<E> next = this.finalEndStep.next();
final long nextBulk = next.bulk();
if (nextBulk == 1) {
return next.get();
} else {
this.lastEndCount = nextBulk - 1;
this.lastEnd = next.get();
return this.lastEnd;
}
}
}
@Override
public void reset() {
this.steps.forEach(Step::reset);
this.lastEndCount = 0l;
}
@Override
public void addStart(final Traverser<S> start) {
if (!this.steps.isEmpty()) this.steps.get(0).addStart(start);
}
@Override
public void addStarts(final Iterator<Traverser<S>> starts) {
if (!this.steps.isEmpty()) this.steps.get(0).addStarts(starts);
}
@Override
public String toString() {
return TraversalHelper.makeTraversalString(this);
}
@Override
public boolean equals(final Object object) {
return object instanceof Iterator && TraversalHelper.areEqual(this, (Iterator) object);
}
@Override
public Step<S, ?> getStartStep() {
return this.steps.isEmpty() ? EmptyStep.instance() : this.steps.get(0);
}
@Override
public Step<?, E> getEndStep() {
return this.steps.isEmpty() ? EmptyStep.instance() : this.steps.get(this.steps.size() - 1);
}
@Override
public DefaultTraversal<S, E> clone() throws CloneNotSupportedException {
final DefaultTraversal<S, E> clone = (DefaultTraversal<S, E>) super.clone();
clone.steps = new ArrayList<>();
clone.sideEffects = this.sideEffects.clone();
clone.strategies = this.strategies.clone();
clone.lastEnd = null;
clone.lastEndCount = 0l;
//clone.traversalEngine = Optional.empty();
//clone.locked = false;
for (final Step<?, ?> step : this.steps) {
final Step<?, ?> clonedStep = step.clone();
clonedStep.setTraversal(clone);
final Step previousStep = clone.steps.isEmpty() ? EmptyStep.instance() : clone.steps.get(clone.steps.size() - 1);
clonedStep.setPreviousStep(previousStep);
previousStep.setNextStep(clonedStep);
clone.steps.add(clonedStep);
}
return clone;
}
@Override
public void setSideEffects(final TraversalSideEffects sideEffects) {
this.sideEffects = sideEffects;
}
@Override
public TraversalSideEffects getSideEffects() {
return this.sideEffects;
}
@Override
public void setStrategies(final TraversalStrategies strategies) {
this.strategies = strategies;
}
@Override
public TraversalStrategies getStrategies() {
return this.strategies;
}
@Override
public <S2, E2> Traversal<S2, E2> addStep(final int index, final Step<?, ?> step) throws IllegalStateException {
if (this.locked) throw Exceptions.traversalIsLocked();
step.setId(this.stepPosition.nextXId());
this.steps.add(index, step);
final Step previousStep = this.steps.size() > 0 && index != 0 ? steps.get(index - 1) : null;
final Step nextStep = this.steps.size() > index + 1 ? steps.get(index + 1) : null;
step.setPreviousStep(null != previousStep ? previousStep : EmptyStep.instance());
step.setNextStep(null != nextStep ? nextStep : EmptyStep.instance());
if (null != previousStep) previousStep.setNextStep(step);
if (null != nextStep) nextStep.setPreviousStep(step);
return (Traversal<S2, E2>) this;
}
@Override
public <S2, E2> Traversal<S2, E2> removeStep(final int index) throws IllegalStateException {
if (this.locked) throw Exceptions.traversalIsLocked();
final Step<?, ?> removedStep = this.steps.remove(index);
final Step previousStep = removedStep.getPreviousStep();
final Step nextStep = removedStep.getNextStep();
previousStep.setNextStep(nextStep);
nextStep.setPreviousStep(previousStep);
return (Traversal<S2, E2>) this;
}
@Override
public void setTraversalHolder(final TraversalHolder step) {
this.traversalHolder = step;
}
@Override
public TraversalHolder getTraversalHolder() {
return this.traversalHolder;
}
}
|
package org.jboss.as.console.client.shared.general;
import com.gargoylesoftware.htmlunit.ConfirmHandler;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.as.console.client.core.DisposableViewImpl;
import org.jboss.as.console.client.shared.general.model.SocketBinding;
import org.jboss.as.console.client.shared.help.FormHelpPanel;
import org.jboss.as.console.client.widgets.forms.FormToolStrip;
import org.jboss.ballroom.client.widgets.ContentGroupLabel;
import org.jboss.ballroom.client.widgets.ContentHeaderLabel;
import org.jboss.ballroom.client.widgets.forms.ComboBox;
import org.jboss.ballroom.client.widgets.forms.DisclosureGroupRenderer;
import org.jboss.ballroom.client.widgets.forms.Form;
import org.jboss.ballroom.client.widgets.forms.NumberBoxItem;
import org.jboss.ballroom.client.widgets.forms.StatusItem;
import org.jboss.ballroom.client.widgets.forms.TextBoxItem;
import org.jboss.ballroom.client.widgets.forms.TextItem;
import org.jboss.ballroom.client.widgets.tables.DefaultCellTable;
import org.jboss.ballroom.client.widgets.tables.DefaultPager;
import org.jboss.ballroom.client.widgets.tabs.FakeTabPanel;
import org.jboss.ballroom.client.widgets.tools.ToolButton;
import org.jboss.ballroom.client.widgets.tools.ToolStrip;
import org.jboss.ballroom.client.widgets.window.Feedback;
import org.jboss.dmr.client.ModelNode;
import java.util.List;
import java.util.Map;
/**
* @author Heiko Braun
* @date 4/6/11
*/
public class SocketBindingView extends DisposableViewImpl implements SocketBindingPresenter.MyView {
private SocketBindingPresenter presenter;
private SocketTable socketTable;
private ComboBox groupFilter;
private Form<SocketBinding> form;
@Override
public Widget createWidget() {
LayoutPanel layout = new LayoutPanel();
FakeTabPanel titleBar = new FakeTabPanel("Socket Binding Groups");
layout.add(titleBar);
ToolStrip toolstrip = new ToolStrip();
toolstrip.addToolButtonRight(new ToolButton("Add", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.launchNewSocketDialogue();
}
}));
toolstrip.addToolButtonRight(new ToolButton("Remove", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
final SocketBinding editedEntity = form.getEditedEntity();
Feedback.confirm("Remove Socket Binding", "Really remove socket binding "+editedEntity.getName()+"?",
new Feedback.ConfirmationHandler() {
@Override
public void onConfirmation(boolean isConfirmed) {
if(isConfirmed)
presenter.onDelete(editedEntity);
}
});
}
}));
layout.add(toolstrip);
VerticalPanel panel = new VerticalPanel();
panel.setStyleName("rhs-content-panel");
ContentHeaderLabel nameLabel = new ContentHeaderLabel("Socket Binding Declarations");
HorizontalPanel horzPanel = new HorizontalPanel();
horzPanel.getElement().setAttribute("style", "width:100%;");
//Image image = new Image(Icons.INSTANCE.deployment());
//horzPanel.add(image);
//image.getElement().getParentElement().setAttribute("width", "25");
horzPanel.add(nameLabel);
panel.add(horzPanel);
socketTable = new SocketTable();
HorizontalPanel tableOptions = new HorizontalPanel();
tableOptions.getElement().setAttribute("cellpadding", "2px");
groupFilter = new ComboBox();
groupFilter.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
presenter.onFilterGroup(event.getValue());
}
});
Widget groupFilterWidget = groupFilter.asWidget();
groupFilterWidget.getElement().setAttribute("style", "width:200px;");
tableOptions.add(new Label("Socket Binding Group:"));
tableOptions.add(groupFilterWidget);
tableOptions.getElement().setAttribute("style", "float:right;");
panel.add(tableOptions);
DefaultCellTable socketTableWidget = socketTable.asWidget();
panel.add(socketTableWidget);
DefaultPager pager = new DefaultPager();
pager.setPage(0);
pager.setPageSize(6);
pager.setDisplay(socketTableWidget);
panel.add(pager);
ScrollPanel scroll = new ScrollPanel(panel);
layout.add(scroll);
layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 26, Style.Unit.PX);
layout.setWidgetTopHeight(toolstrip, 26, Style.Unit.PX, 30, Style.Unit.PX);
layout.setWidgetTopHeight(scroll, 56, Style.Unit.PX, 100, Style.Unit.PCT);
form = new Form<SocketBinding>(SocketBinding.class);
form.setNumColumns(2);
FormToolStrip<SocketBinding> detailToolStrip = new FormToolStrip<SocketBinding>(
form,
new FormToolStrip.FormCallback<SocketBinding>()
{
@Override
public void onSave(Map<String, Object> changeset) {
SocketBinding updatedEntity = form.getUpdatedEntity();
presenter.saveSocketBinding(
updatedEntity.getName(),
form.getEditedEntity().getGroup(), // TODO: why does it not get pushed through?
form.getChangedValues()
);
}
@Override
public void onDelete(SocketBinding entity) {
}
}
);
detailToolStrip.providesDeleteOp(false);
panel.add(new ContentGroupLabel("Socket Binding"));
panel.add(detailToolStrip.asWidget());
TextItem nameItem = new TextItem("name", "Name");
TextItem interfaceItem = new TextItem("interface", "Interface");
TextItem defaultInterface = new TextItem("defaultInterface", "Default Interface");
NumberBoxItem portItem = new NumberBoxItem("port", "Port");
StatusItem fixedPort = new StatusItem("fixedPort", "Fixed Port?");
TextBoxItem multicastItem = new TextBoxItem("multiCastAddress", "Multicast Address") {
@Override
public boolean isRequired() {
return false;
}
};
NumberBoxItem multicastPortItem = new NumberBoxItem("multiCastPort", "Multicast Port") {
@Override
public boolean isRequired() {
return false;
}
};
form.setFields(nameItem, interfaceItem, portItem, fixedPort, defaultInterface);
form.setFieldsInGroup("Multicast", new DisclosureGroupRenderer(), multicastPortItem, multicastItem);
form.bind(socketTable.getCellTable());
Widget formWidget = form.asWidget();
form.setEnabled(false);
final FormHelpPanel helpPanel = new FormHelpPanel(
new FormHelpPanel.AddressCallback() {
@Override
public ModelNode getAddress() {
ModelNode address = new ModelNode();
address.add("socket-binding-group", form.getEditedEntity().getGroup());
address.add("socket-binding", "*");
return address;
}
}, form
);
panel.add(helpPanel.asWidget());
panel.add(formWidget);
return layout;
}
@Override
public void setPresenter(SocketBindingPresenter presenter) {
this.presenter = presenter;
}
@Override
public void updateGroups(List<String> groups) {
groupFilter.setValues(groups);
int i=0;
for(String group : groups)
{
if(group.equals("standard-sockets"))
break;
i++;
}
groupFilter.setItemSelected(i, true);
}
@Override
public void setBindings(String groupName, List<SocketBinding> bindings) {
socketTable.updateFrom(groupName, bindings);
}
@Override
public void setEnabled(boolean b) {
form.setEnabled(b);
}
}
|
package org.jboss.as.console.client.shared.general;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.as.console.client.Console;
import org.jboss.as.console.client.core.DisposableViewImpl;
import org.jboss.as.console.client.shared.general.model.SocketBinding;
import org.jboss.as.console.client.shared.help.FormHelpPanel;
import org.jboss.as.console.client.widgets.ContentDescription;
import org.jboss.as.console.client.widgets.forms.FormToolStrip;
import org.jboss.ballroom.client.widgets.ContentGroupLabel;
import org.jboss.ballroom.client.widgets.ContentHeaderLabel;
import org.jboss.ballroom.client.widgets.forms.ComboBox;
import org.jboss.ballroom.client.widgets.forms.DisclosureGroupRenderer;
import org.jboss.ballroom.client.widgets.forms.Form;
import org.jboss.ballroom.client.widgets.forms.NumberBoxItem;
import org.jboss.ballroom.client.widgets.forms.StatusItem;
import org.jboss.ballroom.client.widgets.forms.TextBoxItem;
import org.jboss.ballroom.client.widgets.forms.TextItem;
import org.jboss.ballroom.client.widgets.tables.DefaultCellTable;
import org.jboss.ballroom.client.widgets.tables.DefaultPager;
import org.jboss.ballroom.client.widgets.tabs.FakeTabPanel;
import org.jboss.ballroom.client.widgets.tools.ToolButton;
import org.jboss.ballroom.client.widgets.tools.ToolStrip;
import org.jboss.ballroom.client.widgets.window.Feedback;
import org.jboss.dmr.client.ModelNode;
import java.util.List;
import java.util.Map;
/**
* @author Heiko Braun
* @date 4/6/11
*/
public class SocketBindingView extends DisposableViewImpl implements SocketBindingPresenter.MyView {
private SocketBindingPresenter presenter;
private SocketTable socketTable;
private ComboBox groupFilter;
private Form<SocketBinding> form;
@Override
public Widget createWidget() {
LayoutPanel layout = new LayoutPanel();
FakeTabPanel titleBar = new FakeTabPanel("Socket Binding");
layout.add(titleBar);
ToolStrip toolstrip = new ToolStrip();
ToolButton addBtn = new ToolButton("Add", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.launchNewSocketDialogue();
}
});
addBtn.ensureDebugId(Console.DEBUG_CONSTANTS.debug_label_add_socketBindingView());
toolstrip.addToolButtonRight(addBtn);
ToolButton removeBtn = new ToolButton("Remove", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
final SocketBinding editedEntity = form.getEditedEntity();
Feedback.confirm(
Console.MESSAGES.deleteTitle("Socket Binding"),
Console.MESSAGES.deleteConfirm("Socket Binding " + editedEntity.getName()),
new Feedback.ConfirmationHandler() {
@Override
public void onConfirmation(boolean isConfirmed) {
if(isConfirmed)
presenter.onDelete(editedEntity);
}
});
}
});
removeBtn.ensureDebugId(Console.DEBUG_CONSTANTS.debug_label_remove_socketBindingView());
toolstrip.addToolButtonRight(removeBtn);
/*
TODO: this is more complex then I thought...
toolstrip.addToolButtonRight(
new ToolButton(Console.CONSTANTS.common_label_newGroup(), new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.launchNewGroupDialogue();
}
}));
*/
layout.add(toolstrip);
VerticalPanel panel = new VerticalPanel();
panel.setStyleName("rhs-content-panel");
ContentHeaderLabel nameLabel = new ContentHeaderLabel("Socket Bindings");
panel.add(nameLabel);
panel.add(new ContentDescription(Console.CONSTANTS.common_socket_bindings_desc()));
panel.add(new ContentGroupLabel(Console.MESSAGES.available("Socket Bindings")));
socketTable = new SocketTable();
HorizontalPanel tableOptions = new HorizontalPanel();
tableOptions.getElement().setAttribute("cellpadding", "2px");
groupFilter = new ComboBox();
groupFilter.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
presenter.onFilterGroup(event.getValue());
}
});
Widget groupFilterWidget = groupFilter.asWidget();
groupFilterWidget.getElement().setAttribute("style", "width:200px;");
tableOptions.add(new Label("Socket Binding Group:"));
tableOptions.add(groupFilterWidget);
tableOptions.getElement().setAttribute("style", "float:right;");
panel.add(tableOptions);
DefaultCellTable socketTableWidget = socketTable.asWidget();
panel.add(socketTableWidget);
DefaultPager pager = new DefaultPager();
pager.setPage(0);
pager.setPageSize(6);
pager.setDisplay(socketTableWidget);
panel.add(pager);
ScrollPanel scroll = new ScrollPanel(panel);
layout.add(scroll);
layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX);
layout.setWidgetTopHeight(toolstrip, 40, Style.Unit.PX, 30, Style.Unit.PX);
layout.setWidgetTopHeight(scroll, 70, Style.Unit.PX, 100, Style.Unit.PCT);
form = new Form<SocketBinding>(SocketBinding.class);
form.setNumColumns(2);
FormToolStrip<SocketBinding> detailToolStrip = new FormToolStrip<SocketBinding>(
form,
new FormToolStrip.FormCallback<SocketBinding>()
{
@Override
public void onSave(Map<String, Object> changeset) {
SocketBinding updatedEntity = form.getUpdatedEntity();
presenter.saveSocketBinding(
updatedEntity.getName(),
form.getEditedEntity().getGroup(), // TODO: why does it not get pushed through?
form.getChangedValues()
);
}
@Override
public void onDelete(SocketBinding entity) {
}
}
);
detailToolStrip.providesDeleteOp(false);
panel.add(new ContentGroupLabel(Console.CONSTANTS.common_label_selection()));
panel.add(detailToolStrip.asWidget());
TextItem nameItem = new TextItem("name", "Name");
TextItem interfaceItem = new TextItem("interface", "Interface");
//TextItem defaultInterface = new TextItem("defaultInterface", "Default Interface");
NumberBoxItem portItem = new NumberBoxItem("port", "Port");
StatusItem fixedPort = new StatusItem("fixedPort", "Fixed Port?");
TextBoxItem multicastItem = new TextBoxItem("multiCastAddress", "Multicast Address") {
@Override
public boolean isRequired() {
return false;
}
};
NumberBoxItem multicastPortItem = new NumberBoxItem("multiCastPort", "Multicast Port") {
@Override
public boolean isRequired() {
return false;
}
};
form.setFields(nameItem, interfaceItem, portItem, fixedPort);
form.setFieldsInGroup("Multicast", new DisclosureGroupRenderer(), multicastPortItem, multicastItem);
form.bind(socketTable.getCellTable());
Widget formWidget = form.asWidget();
form.setEnabled(false);
final FormHelpPanel helpPanel = new FormHelpPanel(
new FormHelpPanel.AddressCallback() {
@Override
public ModelNode getAddress() {
ModelNode address = new ModelNode();
address.add("socket-binding-group", form.getEditedEntity().getGroup());
address.add("socket-binding", "*");
return address;
}
}, form
);
panel.add(helpPanel.asWidget());
panel.add(formWidget);
return layout;
}
@Override
public void setPresenter(SocketBindingPresenter presenter) {
this.presenter = presenter;
}
@Override
public void updateGroups(List<String> groups) {
groupFilter.setValues(groups);
int i=0;
for(String group : groups)
{
if(group.equals("standard-sockets"))
break;
i++;
}
groupFilter.setItemSelected(i, true);
}
@Override
public void setBindings(String groupName, List<SocketBinding> bindings) {
socketTable.updateFrom(groupName, bindings);
}
@Override
public void setEnabled(boolean b) {
form.setEnabled(b);
}
}
|
package pl.greywarden.openr.gui.favourite_programs;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedList;
import java.util.stream.Collectors;
@Log4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FavouritePrograms {
private static final Collection<ProgramWrapper> programs = new LinkedList<>();
static {
loadFromFile();
}
private static void loadFromFile() {
File sourceXml = getProgramsXml();
SAXBuilder builder = new SAXBuilder();
try {
Document xml = builder.build(sourceXml);
Element root = xml.getRootElement();
root.getChildren().forEach(element -> programs.add(new ProgramWrapper(
element.getAttributeValue("name"),
element.getAttributeValue("path"),
element.getAttributeValue("icon"))));
} catch (JDOMException exception) {
log.error("Parse xml exception", exception);
} catch (FileNotFoundException exception) {
log.warn(String.format("File %s does not exist", sourceXml.getName()));
} catch (IOException exception) {
log.error(String.format("IOException during loading %s", sourceXml.getName()), exception);
}
}
private static File getProgramsXml() {
URL configFileUrl = FavouritePrograms.class.getProtectionDomain().getCodeSource().getLocation();
try {
File parentDir = new File(configFileUrl.toURI()).getParentFile();
return new File(parentDir, "programs.xml");
} catch (URISyntaxException exception) {
throw new RuntimeException(exception);
}
}
public static void storeProgramsToFile() {
File targetXml = getProgramsXml();
Document xml = new Document(new Element("programs"));
programs.forEach(program -> {
Element element = new Element("program");
element.setAttribute("name", program.getName());
element.setAttribute("path", program.getPath());
element.setAttribute("icon", program.getIcon());
xml.getRootElement().addContent(element);
});
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
try {
OutputStream out = new FileOutputStream(targetXml);
outputter.output(xml, out);
} catch (IOException exception) {
log.error("Unable to store programs to xml", exception);
}
}
public static void add(ProgramWrapper program) {
programs.add(program);
}
public static void remove(ProgramWrapper program) {
programs.remove(program);
}
public static Collection<ProgramWrapper> getPrograms() {
return programs.stream().sorted((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()))
.collect(Collectors.toList());
}
}
|
package jsettlers.ai.economy;
import jsettlers.ai.highlevel.AiStatistics;
import jsettlers.common.buildings.EBuildingType;
import jsettlers.common.material.EMaterialType;
import jsettlers.common.movable.EMovableType;
import jsettlers.logic.player.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static jsettlers.common.buildings.EBuildingType.*;
import static jsettlers.common.buildings.EBuildingType.IRONMELT;
import static jsettlers.common.buildings.EBuildingType.WEAPONSMITH;
/**
* This economy minister is as optimized as possible to create fast and many level 3 soldiers with high combat strength. It builds a longterm economy
* with rush defence if needed. It starts with 8 lumberjacks first, then it builds mana. Then food, weapons, more lumberjacks and gold economy is
* build in parallel until the full amount of possible buildings of the map is reached. If the map is smaller than 8 lumberjacks, it builds weapon
* smiths before mana. The minister is down sizable by a weapon smiths factor and a building industry factor.
*
* @author codingberlin
*/
public class BuildingListEconomyMinister implements EconomyMinister {
private static final EBuildingType[] RUSH_DEFENCE_BUILDINGS = {
LUMBERJACK, SAWMILL, STONECUTTER, IRONMELT, WEAPONSMITH, BARRACK, SMALL_LIVINGHOUSE, COALMINE, IRONMINE, MEDIUM_LIVINGHOUSE };
private static final Collection<EBuildingType> BUILDING_INDUSTRY;
private int[] mapBuildingCounts;
private final List<EBuildingType> buildingsToBuild;
private int numberOfMidGameStoneCutters = 0;
private AiStatistics aiStatistics;
private float buildingIndustryFactor;
private byte playerId;
private float weaponSmithFactor;
private boolean isHighGoodsGame;
private boolean isMiddleGoodsGame;
static {
EBuildingType[] buildingIndustry = {LUMBERJACK, FORESTER, SAWMILL, STONECUTTER};
BUILDING_INDUSTRY = Arrays.asList(buildingIndustry);
}
/**
*
* @param weaponSmithFactor
* influences the power of the AI. Use 1 for full power. Use < 1 for weaker AIs. The factor is used to determine the maximum amount of
* weapon smiths build on the map and shifts the point of time when the weapon smiths are build.
* @param buildingIndustryFactor
* influences the amount of lumberjacks, sawmills, foresters and stone cutters to slow down the AI.
*/
public BuildingListEconomyMinister(AiStatistics aiStatistics, Player player, float weaponSmithFactor, float buildingIndustryFactor) {
this.aiStatistics = aiStatistics;
this.buildingIndustryFactor = buildingIndustryFactor;
this.playerId = player.playerId;
this.weaponSmithFactor = weaponSmithFactor;
this.buildingsToBuild = new ArrayList<>();
this.isHighGoodsGame = isHighGoodsGame();
this.isMiddleGoodsGame = isMiddleGoodsGame();
};
@Override
public void update() {
buildingsToBuild.clear();
this.mapBuildingCounts = aiStatistics.getAiMapInformation().getBuildingCounts(playerId);
addMinimalBuildingMaterialBuildings();
if (isVerySmallMap()) {
addSmallWeaponProduction();
addFoodAndBuildingMaterialAndWeaponAndGoldIndustry();
addManaBuildings();
} else {
addManaBuildings();
addFoodAndBuildingMaterialAndWeaponAndGoldIndustry();
}
}
@Override
public boolean isEndGame() {
double remaningGrass = aiStatistics.getAiMapInformation().getRemainingGrassTiles(aiStatistics, playerId)
- aiStatistics.getTreesForPlayer(playerId).size()
- aiStatistics.getStonesForPlayer(playerId).size();
double availableGrass = aiStatistics.getAiMapInformation().getGrassTilesOf(playerId);
return remaningGrass / availableGrass <= 0.6F;
}
private void addFoodAndBuildingMaterialAndWeaponAndGoldIndustry() {
List<EBuildingType> weaponsBuildings = determineWeaponAndGoldBuildings();
List<EBuildingType> foodBuildings = determineFoodBuildings();
List<EBuildingType> buildingMaterialBuildings = determineBuildingMaterialBuildings();
float allBuildingsCount = foodBuildings.size() + buildingMaterialBuildings.size() + weaponsBuildings.size();
float weaponsBuildingsRatio = ((float) weaponsBuildings.size()) / allBuildingsCount;
float foodBuildingsRatio = ((float) foodBuildings.size()) / (allBuildingsCount * weaponSmithFactor);
float buildingMaterialBuildingRatio = ((float) buildingMaterialBuildings.size()) / (allBuildingsCount * weaponSmithFactor);
int maxSize = Math.max(foodBuildings.size(), Math.max(buildingMaterialBuildings.size(), weaponsBuildings.size()));
for (int i = 0; i < maxSize; i++) {
if (weaponsBuildingsRatio > foodBuildingsRatio && weaponsBuildingsRatio > buildingMaterialBuildingRatio) {
mergeAndAddNextItems(
weaponsBuildings, foodBuildings, foodBuildingsRatio, buildingMaterialBuildings, buildingMaterialBuildingRatio);
} else if (buildingMaterialBuildingRatio > foodBuildingsRatio && buildingMaterialBuildingRatio > weaponsBuildingsRatio) {
mergeAndAddNextItems(
buildingMaterialBuildings, weaponsBuildings, weaponsBuildingsRatio, foodBuildings, foodBuildingsRatio);
} else {
mergeAndAddNextItems(
foodBuildings, weaponsBuildings, weaponsBuildingsRatio, buildingMaterialBuildings, buildingMaterialBuildingRatio);
}
}
numberOfMidGameStoneCutters = (currentCountOf(STONECUTTER) / 2);
}
private List<EBuildingType> determineBuildingMaterialBuildings() {
List<EBuildingType> buildingMaterialBuildings = new ArrayList<>();
for (int i = 0; i < Math.ceil(mapBuildingCounts[LUMBERJACK.ordinal] * buildingIndustryFactor) - 8; i++) {
buildingMaterialBuildings.add(LUMBERJACK);
if (i % 3 == 1)
buildingMaterialBuildings.add(FORESTER);
if (i % 2 == 1)
buildingMaterialBuildings.add(SAWMILL);
if (i % 2 == 1)
buildingMaterialBuildings.add(STONECUTTER);
}
return buildingMaterialBuildings;
}
private List<EBuildingType> determineFoodBuildings() {
List<EBuildingType> foodBuildings = new ArrayList<>();
for (int i = 0; i < mapBuildingCounts[FISHER.ordinal]; i++) {
foodBuildings.add(FISHER);
}
for (int i = 0; i < mapBuildingCounts[FARM.ordinal]; i++) {
foodBuildings.add(FARM);
if (i % 2 == 0)
foodBuildings.add(WATERWORKS);
if (i % 3 == 0)
foodBuildings.add(MILL);
if (i % 3 == 0)
foodBuildings.add(BAKER);
if (i % 3 == 0)
foodBuildings.add(BAKER);
if (i % 3 == 1)
foodBuildings.add(BAKER);
if (i % 6 == 1 || i % 6 == 2 || i % 6 == 5)
foodBuildings.add(PIG_FARM);
if (i % 6 == 1)
foodBuildings.add(SLAUGHTERHOUSE);
}
return foodBuildings;
}
private List<EBuildingType> determineWeaponAndGoldBuildings() {
List<EBuildingType> weaponsBuildings = new ArrayList<>();
for (int i = 0; i < (mapBuildingCounts[WEAPONSMITH.ordinal] * weaponSmithFactor); i++) {
weaponsBuildings.add(COALMINE);
if (i % 2 == 0)
weaponsBuildings.add(IRONMINE);
weaponsBuildings.add(IRONMELT);
if (i == 0 && currentCountOf(TOOLSMITH) < 1)
weaponsBuildings.add(TOOLSMITH);
weaponsBuildings.add(WEAPONSMITH);
if (i % 3 == 0)
weaponsBuildings.add(BARRACK);
if (i == 3)
addGoldBuildings(weaponsBuildings);
}
if (mapBuildingCounts[WEAPONSMITH.ordinal] < 4)
addGoldBuildings(weaponsBuildings);
return weaponsBuildings;
}
private void addSmallWeaponProduction() {
buildingsToBuild.add(FISHER);
buildingsToBuild.add(COALMINE);
buildingsToBuild.add(IRONMINE);
buildingsToBuild.add(IRONMELT);
buildingsToBuild.add(WEAPONSMITH);
buildingsToBuild.add(BARRACK);
}
protected int currentCountOf(EBuildingType targetBuildingType) {
int result = 0;
for (EBuildingType buildingType : buildingsToBuild) {
if (buildingType == targetBuildingType) {
result++;
}
}
return result;
}
protected void addIfPossible(EBuildingType buildingType) {
float factor = 1F;
if (BUILDING_INDUSTRY.contains(buildingType)) {
factor = buildingIndustryFactor;
}
if (currentCountOf(buildingType) < Math.ceil(mapBuildingCounts[buildingType.ordinal]*factor)) {
buildingsToBuild.add(buildingType);
}
}
private boolean isVerySmallMap() {
return mapBuildingCounts[LUMBERJACK.ordinal] < 8;
}
private void addManaBuildings() {
for (int i = 0; i < mapBuildingCounts[WINEGROWER.ordinal]; i++) {
addIfPossible(WINEGROWER);
}
for (int i = 0; i < mapBuildingCounts[WINEGROWER.ordinal]; i++) {
addIfPossible(TEMPLE);
}
if (mapBuildingCounts[BIG_TEMPLE.ordinal] > 0) {
addIfPossible(BIG_TEMPLE);
}
}
private void mergeAndAddNextItems(
List<EBuildingType> dominantBuildingList,
List<EBuildingType> slaveBuildingListA, float targetSlaveRatioA,
List<EBuildingType> slaveBuildingListB, float targetSlaveRatioB) {
addFirstItemToBuildingList(dominantBuildingList);
float allBuildingsCount = dominantBuildingList.size() + slaveBuildingListA.size() + slaveBuildingListB.size();
if (allBuildingsCount == 0)
return;
float currentSlaveRatioA = ((float) slaveBuildingListA.size()) / allBuildingsCount;
float currentSlaveRatioB = ((float) slaveBuildingListB.size()) / allBuildingsCount;
if (currentSlaveRatioA > targetSlaveRatioA) {
addFirstItemToBuildingList(slaveBuildingListA);
}
if (currentSlaveRatioB > targetSlaveRatioB) {
addFirstItemToBuildingList(slaveBuildingListB);
}
}
private void addFirstItemToBuildingList(List<EBuildingType> buildingList) {
if (buildingList.size() > 0) {
addIfPossible(buildingList.remove(0));
}
}
private void addMinimalBuildingMaterialBuildings() {
buildingsToBuild.add(TOWER); // Start Tower
if (isHighGoodsGame) {
addIfPossible(LUMBERJACK);
addIfPossible(SAWMILL);
addIfPossible(LUMBERJACK);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
buildingsToBuild.add(MEDIUM_LIVINGHOUSE);
addIfPossible(STONECUTTER);
buildingsToBuild.add(TOWER);
addIfPossible(LUMBERJACK);
addIfPossible(SAWMILL);
addIfPossible(LUMBERJACK);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
addIfPossible(FORESTER);
addIfPossible(LUMBERJACK);
addIfPossible(SAWMILL);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
addIfPossible(STONECUTTER);
addIfPossible(STONECUTTER);
addIfPossible(STONECUTTER);
addIfPossible(STONECUTTER);
} else if (isMiddleGoodsGame) {
addIfPossible(LUMBERJACK);
addIfPossible(SAWMILL);
addIfPossible(LUMBERJACK);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
buildingsToBuild.add(MEDIUM_LIVINGHOUSE);
addIfPossible(STONECUTTER);
buildingsToBuild.add(TOWER);
addIfPossible(LUMBERJACK);
addIfPossible(SAWMILL);
addIfPossible(LUMBERJACK);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
addIfPossible(STONECUTTER);
addIfPossible(IRONMELT);
addIfPossible(TOOLSMITH);
addIfPossible(FORESTER);
addIfPossible(LUMBERJACK);
addIfPossible(SAWMILL);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
addIfPossible(STONECUTTER);
addIfPossible(STONECUTTER);
addIfPossible(STONECUTTER);
} else {
addIfPossible(LUMBERJACK);
addIfPossible(SAWMILL);
addIfPossible(LUMBERJACK);
buildingsToBuild.add(SMALL_LIVINGHOUSE);
addIfPossible(STONECUTTER);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
buildingsToBuild.add(TOWER);
buildingsToBuild.add(MEDIUM_LIVINGHOUSE);
addIfPossible(IRONMELT);
addIfPossible(TOOLSMITH);
addIfPossible(COALMINE);
addIfPossible(IRONMINE);
addIfPossible(FISHER);
addIfPossible(FARM);
addIfPossible(WATERWORKS);
addIfPossible(MILL);
addIfPossible(BAKER);
addIfPossible(COALMINE);
addIfPossible(SAWMILL);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
addIfPossible(STONECUTTER);
addIfPossible(LUMBERJACK);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
addIfPossible(LUMBERJACK);
addIfPossible(SAWMILL);
addIfPossible(LUMBERJACK);
addIfPossible(FORESTER);
buildingsToBuild.add(MEDIUM_LIVINGHOUSE);
addIfPossible(STONECUTTER);
addIfPossible(STONECUTTER);
addIfPossible(STONECUTTER);
}
}
private boolean isHighGoodsGame() {
return aiStatistics.getNumberOfMaterialTypeForPlayer(EMaterialType.AXE, playerId) >= 8 &&
aiStatistics.getNumberOfMaterialTypeForPlayer(EMaterialType.SAW, playerId) >= 3 &&
aiStatistics.getNumberOfMaterialTypeForPlayer(EMaterialType.PICK, playerId) >= 5;
}
private boolean isMiddleGoodsGame() {
return aiStatistics.getNumberOfMaterialTypeForPlayer(EMaterialType.AXE, playerId) >= 6 &&
aiStatistics.getNumberOfMaterialTypeForPlayer(EMaterialType.SAW, playerId) >= 2 &&
aiStatistics.getNumberOfMaterialTypeForPlayer(EMaterialType.PICK, playerId) >= 4;
}
private void addGoldBuildings(List<EBuildingType> weaponsBuildings) {
if (mapBuildingCounts[GOLDMELT.ordinal] > 0) {
weaponsBuildings.add(GOLDMINE);
for (int ii = 0; ii < mapBuildingCounts[GOLDMELT.ordinal]; ii++) {
weaponsBuildings.add(GOLDMELT);
weaponsBuildings.add(STOCK);
}
}
}
@Override
public int getNumberOfParallelConstructionSites() {
if (aiStatistics.getNumberOfMaterialTypeForPlayer(EMaterialType.PLANK, playerId) > 1
&& aiStatistics.getNumberOfMaterialTypeForPlayer(EMaterialType.STONE, playerId) > 1) {
// If plank and stone is still offered, we can build the next building.
// If the next building will consume all remaining offers we won't return 100 in the next tick
return 100;
}
return Math.max((int) Math.ceil((float) aiStatistics.getNumberOfBuildingTypeForPlayer(LUMBERJACK, playerId) / 2F), 2);
}
@Override
public List<EBuildingType> getBuildingsToBuild() {
if (isDanger()) {
return prefixBuildingsToBuildWithRushDefence();
} else {
return buildingsToBuild;
}
}
private boolean isDanger() {
if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(BARRACK, playerId) < 1) {
int numberOfSwordsmen = aiStatistics.getMovablePositionsByTypeForPlayer(EMovableType.SWORDSMAN_L1, playerId).size()
+ aiStatistics.getMovablePositionsByTypeForPlayer(EMovableType.SWORDSMAN_L2, playerId).size()
+ aiStatistics.getMovablePositionsByTypeForPlayer(EMovableType.SWORDSMAN_L3, playerId).size();
if (aiStatistics.getTotalNumberOfBuildingTypeForPlayer(TOWER, playerId) >= numberOfSwordsmen) {
return true;
}
for (byte enemy : aiStatistics.getEnemiesOf(playerId)) {
if (aiStatistics.getNumberOfBuildingTypeForPlayer(WEAPONSMITH, enemy) > 0) {
return true;
}
}
}
return false;
}
private List<EBuildingType> prefixBuildingsToBuildWithRushDefence() {
List<EBuildingType> allBuildingsToBuild = new ArrayList<EBuildingType>(RUSH_DEFENCE_BUILDINGS.length + buildingsToBuild.size());
allBuildingsToBuild.addAll(Arrays.asList(RUSH_DEFENCE_BUILDINGS));
allBuildingsToBuild.addAll(buildingsToBuild);
return allBuildingsToBuild;
}
@Override
public int getMidGameNumberOfStoneCutters() {
return numberOfMidGameStoneCutters;
}
@Override
public boolean automaticTowersEnabled() {
return aiStatistics.getNumberOfBuildingTypeForPlayer(TOWER, playerId) >= 2;
}
@Override
public boolean automaticLivingHousesEnabled() {
return aiStatistics.getNumberOfBuildingTypeForPlayer(LUMBERJACK, playerId) >= 8
|| aiStatistics.getNumberOfBuildingTypeForPlayer(LUMBERJACK, playerId) >= mapBuildingCounts[LUMBERJACK.ordinal]
|| aiStatistics.getNumberOfBuildingTypeForPlayer(WEAPONSMITH, playerId) >= 1;
}
@Override
public String toString() {
return this.getClass().getName();
}
}
|
package org.kurento.client.internal.test;
import java.util.Properties;
import org.kurento.client.internal.transport.jsonrpc.RomServerJsonRpcHandler;
import org.kurento.jsonrpc.client.JsonRpcClient;
import org.kurento.jsonrpc.client.JsonRpcClientWebSocket;
import org.kurento.jsonrpc.internal.server.config.JsonRpcConfiguration;
import org.kurento.jsonrpc.server.JsonRpcConfigurer;
import org.kurento.jsonrpc.server.JsonRpcHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
public class WebSocketRomTest extends AbstractRomTest {
private static Logger log = LoggerFactory.getLogger(WebSocketRomTest.class);
private static RomServerJsonRpcHandler handler;
@Configuration
@ComponentScan(basePackageClasses = JsonRpcConfiguration.class)
@EnableAutoConfiguration
public static class BootTestApplication implements JsonRpcConfigurer {
@Override
public void registerJsonRpcHandlers(JsonRpcHandlerRegistry registry) {
registry.addHandler(handler, "/handler");
}
}
protected ConfigurableApplicationContext context;
@Override
protected JsonRpcClient createJsonRpcClient() {
String uri = "ws://localhost:" + getPort() + "/handler";
log.info("Creating client in URI: " + uri);
return new JsonRpcClientWebSocket(uri);
}
@Override
protected void startJsonRpcServer(RomServerJsonRpcHandler jsonRpcHandler) {
handler = jsonRpcHandler;
Properties properties = new Properties();
String port = getPort();
properties.put("server.port", port);
SpringApplication application = new SpringApplication(
BootTestApplication.class);
application.setDefaultProperties(properties);
log.info("Creating server in port: " + port);
context = application.run();
}
protected static String getPort() {
String port = System.getProperty("http.port");
if (port == null) {
port = "7788";
}
return port;
}
@Override
protected void destroyJsonRpcServer() {
context.close();
}
}
|
package uk.co.cloudhunter.rpgthing;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
@Mod(modid = "RPGThing", name = "RPGThing", version = "0.1")
@NetworkMod
public class RPGThing
{
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
LoggerRPG.setupLogger(event);
LoggerRPG.info("RPGThing starting up! PreInit."); // much modjam, very pause :(
}
@EventHandler
public void init(FMLInitializationEvent event)
{
LoggerRPG.info("RPGThing starting up! Init.");
}
}
|
package com.qiniu.android.utils;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Process;
import android.telephony.CellInfo;
import android.telephony.CellInfoCdma;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.CellSignalStrengthCdma;
import android.telephony.CellSignalStrengthGsm;
import android.telephony.CellSignalStrengthLte;
import android.telephony.CellSignalStrengthWcdma;
import android.telephony.TelephonyManager;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;
import static android.content.Context.WIFI_SERVICE;
public final class AndroidNetwork {
public static boolean isNetWorkReady() {
Context c = ContextGetter.applicationContext();
if (c == null) {
return true;
}
ConnectivityManager connMgr = (ConnectivityManager)
c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
NetworkInfo info = connMgr.getActiveNetworkInfo();
return info != null && info.isConnected();
} catch (Exception e) {
return true;
}
}
/**
* ip
* DNSIPv4IPv6
* IPv4IPv6IPv6
*
* @return
*/
public static String getHostIP() {
String hostIp = null;
try {
Enumeration nis = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
while (nis.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nis.nextElement();
Enumeration<InetAddress> ias = ni.getInetAddresses();
while (ias.hasMoreElements()) {
ia = ias.nextElement();
if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress()) {
hostIp = ia.getHostAddress();
break;
}
continue;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return hostIp;
}
public static String networkType(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
if (connectivity == null || !networkInfo.isConnected()) {
return Constants.NETWORK_CLASS_UNKNOWN;
}
int netWorkType = connectivity.getActiveNetworkInfo().getType();
if (netWorkType == ConnectivityManager.TYPE_WIFI) {
return Constants.NETWORK_WIFI;
} else if (netWorkType == ConnectivityManager.TYPE_MOBILE) {
return getNetWorkClass(context);
}
return Constants.NETWORK_CLASS_UNKNOWN;
}
private static String getNetWorkClass(Context context) {
if (context.checkPermission(Manifest.permission.READ_PHONE_STATE, Process.myPid(), Process.myUid()) != PackageManager.PERMISSION_GRANTED) {
return Constants.NETWORK_CLASS_UNKNOWN;
}
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager == null){
return Constants.NETWORK_CLASS_UNKNOWN;
}
switch (telephonyManager.getNetworkType()) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return Constants.NETWORK_CLASS_2_G;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return Constants.NETWORK_CLASS_3_G;
case TelephonyManager.NETWORK_TYPE_LTE:
return Constants.NETWORK_CLASS_4_G;
default:
return Constants.NETWORK_CLASS_UNKNOWN;
}
}
public static int getMobileDbm() {
Context context = ContextGetter.applicationContext();
int dbm = -1;
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
List<CellInfo> cellInfoList;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (context.checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION, Process.myPid(), Process.myUid()) != PackageManager.PERMISSION_GRANTED) {
return dbm;
}
if (context.checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, Process.myPid(), Process.myUid()) != PackageManager.PERMISSION_GRANTED) {
return dbm;
}
cellInfoList = tm.getAllCellInfo();
if (null != cellInfoList) {
for (CellInfo cellInfo : cellInfoList) {
if (cellInfo instanceof CellInfoGsm) {
CellSignalStrengthGsm cellSignalStrengthGsm = ((CellInfoGsm) cellInfo).getCellSignalStrength();
dbm = cellSignalStrengthGsm.getDbm();
break;
} else if (cellInfo instanceof CellInfoCdma) {
CellSignalStrengthCdma cellSignalStrengthCdma =
((CellInfoCdma) cellInfo).getCellSignalStrength();
dbm = cellSignalStrengthCdma.getDbm();
break;
} else if (cellInfo instanceof CellInfoLte) {
CellSignalStrengthLte cellSignalStrengthLte = ((CellInfoLte) cellInfo).getCellSignalStrength();
dbm = cellSignalStrengthLte.getDbm();
break;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
if (cellInfo instanceof CellInfoWcdma) {
CellSignalStrengthWcdma cellSignalStrengthWcdma =
((CellInfoWcdma) cellInfo).getCellSignalStrength();
dbm = cellSignalStrengthWcdma.getDbm();
break;
}
}
}
}
}
return dbm;
}
}
|
package org.burntgameproductions.PathToMani.menu;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Rectangle;
import org.burntgameproductions.PathToMani.GameOptions;
import org.burntgameproductions.PathToMani.TextureManager;
import org.burntgameproductions.PathToMani.common.ManiColor;
import org.burntgameproductions.PathToMani.files.FileManager;
import org.burntgameproductions.PathToMani.game.DebugOptions;
import org.burntgameproductions.PathToMani.game.sound.MusicManager;
import org.burntgameproductions.PathToMani.ui.ManiUiScreen;
import org.burntgameproductions.PathToMani.ui.UiDrawer;
import org.burntgameproductions.PathToMani.ManiApplication;
import org.burntgameproductions.PathToMani.ui.ManiInputManager;
import org.burntgameproductions.PathToMani.ui.ManiUiControl;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class MainScreen implements ManiUiScreen {
public static final float CREDITS_BTN_W = .15f;
public static final float CREDITS_BTN_H = .07f;
private final ArrayList<ManiUiControl> myControls;
private final ManiUiControl myPlayCtrl;
private final ManiUiControl myOptionsCtrl;
private final ManiUiControl myCreditsCtrl;
private final ManiUiControl myQuitCtrl;
/**We have these listed here as a texture so then we can use them later on.**/
private final TextureAtlas.AtlasRegion logo;
private final TextureAtlas.AtlasRegion aprilfools;
private final TextureAtlas.AtlasRegion australiaday;
private final TextureAtlas.AtlasRegion newyears;
private final TextureAtlas.AtlasRegion wilsonBday;
/**Boolean's for date checker**/
private boolean isNewYears;
private boolean isAustraliaDay;
private boolean isAprilFools;
private boolean isWilsonsBday;
private final boolean isMobile;
GameOptions gameOptions;
public MainScreen(MenuLayout menuLayout, TextureManager textureManager, boolean mobile, float r, GameOptions gameOptions) {
isMobile = mobile;
myControls = new ArrayList<ManiUiControl>();
this.gameOptions = gameOptions;
/**Play button**/
myPlayCtrl = new ManiUiControl(menuLayout.buttonRect(-1, 1), true, Input.Keys.P);
myPlayCtrl.setDisplayName("Play");
myControls.add(myPlayCtrl);
/**Options button**/
myOptionsCtrl = new ManiUiControl(menuLayout.buttonRect(-1, 2), true, Input.Keys.O);
myOptionsCtrl.setDisplayName("Options");
myControls.add(myOptionsCtrl);
/**Credits button**/
myCreditsCtrl = new ManiUiControl(menuLayout.buttonRect(-1, 3), true, Input.Keys.C);
myCreditsCtrl.setDisplayName("Credits");
myControls.add(myCreditsCtrl);
/**Quit button**/
myQuitCtrl = new ManiUiControl(menuLayout.buttonRect(-1, 4), true, Input.Keys.Q);
myQuitCtrl.setDisplayName("Quit");
myControls.add(myQuitCtrl);
/**
* Logos for date changer are loaded here.
**/
/**Normal.**/
FileHandle imageFile = FileManager.getInstance().getImagesDirectory().child("logo.png");
logo = textureManager.getTexture(imageFile);
/**Australiad Day.**/
FileHandle imageFile2 = FileManager.getInstance().getImagesDirectory().child("australiaday.png");
australiaday = textureManager.getTexture(imageFile2);
/**April Fools.**/
FileHandle imageFile3 = FileManager.getInstance().getImagesDirectory().child("aprilfools.png");
aprilfools = textureManager.getTexture(imageFile3);
/**New years.**/
FileHandle imageFile4 = FileManager.getInstance().getImagesDirectory().child("newyears.png");
newyears = textureManager.getTexture(imageFile4);
/**Wilsons bday.**/
FileHandle imageFile4 = FileManager.getInstance().getImagesDirectory().child("wilson.png");
wilsonBday = textureManager.getTexture(imageFile4);
/**Calendar**/
Calendar var1 = Calendar.getInstance();
if (var1.get(2) + 1 == 04 && var1.get(5) >= 01 && var1.get(5) <= 03)
{/**This ^^^^ here... We want to display the logo between these days of this month.**/
this.isAprilFools = true;
}
else if (var1.get(2) + 1 == 01 && var1.get(5) >= 26 && var1.get(5) <= 28)
{/**This ^^^^ here... We want to display the logo between these days of this month.**/
this.isAustraliaDay = true;
}
else if (var1.get(2) + 1 == 01 && var1.get(5) >= 01 && var1.get(5) <= 07)
{/**This ^^^^ here... We want to display the logo between these days of this month.**/
this.isNewYears = true;
}
else if (var1.get(2) + 1 == 06 && var1.get(5) >= 21 && var1.get(5) <= 23)
{/**This ^^^^ here... We want to display the logo between these days of this month.**/
this.isWilsonsBday = true;
}
}
public static Rectangle creditsBtnRect(float r) {
return new Rectangle(r - CREDITS_BTN_W, 1 - CREDITS_BTN_H, CREDITS_BTN_W, CREDITS_BTN_H);
}
public List<ManiUiControl> getControls() {
return myControls;
}
@Override
public void updateCustom(ManiApplication cmp, ManiInputManager.Ptr[] ptrs, boolean clickedOutside) {
ManiInputManager im = cmp.getInputMan();
MenuScreens screens = cmp.getMenuScreens();
/**What to do when "Play" button is pressed.**/
if (myPlayCtrl.isJustOff()) {
im.setScreen(cmp, screens.playScreen);
return;
}
/**What to do when "Options" button is pressed.**/
if (myOptionsCtrl.isJustOff()) {
im.setScreen(cmp, screens.options);
return;
}
/**What to do when "Credits" button is pressed.**/
if (myCreditsCtrl.isJustOff()) {
im.setScreen(cmp, screens.credits);
return;
}
/**What to do when "Quit" button is pressed.**/
if (myQuitCtrl.isJustOff()) {
/** Save the settings on exit, but not on mobile as settings don't exist there.**/
if (isMobile == false) {
cmp.getOptions().save();
}
Gdx.app.exit();
return;
}
}
@Override
public boolean isCursorOnBg(ManiInputManager.Ptr ptr) {
return false;
}
@Override
public void onAdd(ManiApplication cmp) {
MusicManager.getInstance().PlayMenuMusic(gameOptions);
}
@Override
public void drawBg(UiDrawer uiDrawer, ManiApplication cmp) {
}
@Override
public void drawImgs(UiDrawer uiDrawer, ManiApplication cmp) {
/**We are now loading the correct image for the date**/
if (this.isNewYears)
{/**Load this logo when the date on the players computer is the same as the one we set above.**/
float sz = .55f;
if (!DebugOptions.PRINT_BALANCE) uiDrawer.draw(newyears, sz, sz, sz/2, sz/2, uiDrawer.r/2, sz/2, 0, ManiColor.W);
}
else if (this.isAustraliaDay)
{/**Load this logo when the date on the players computer is the same as the one we set above.**/
float sz = .55f;
if (!DebugOptions.PRINT_BALANCE) uiDrawer.draw(australiaday, sz, sz, sz/2, sz/2, uiDrawer.r/2, sz/2, 0, ManiColor.W);
}
else if (this.isAprilFools)
{/**Load this logo when the date on the players computer is the same as the one we set above.**/
float sz = .55f;
if (!DebugOptions.PRINT_BALANCE) uiDrawer.draw(aprilfools, sz, sz, sz/2, sz/2, uiDrawer.r/2, sz/2, 0, ManiColor.W);
}
else
{/**Load this logo when the date on the players computer is the same as the one we set above.**/
float sz = .55f;
if (!DebugOptions.PRINT_BALANCE) uiDrawer.draw(logo, sz, sz, sz/2, sz/2, uiDrawer.r/2, sz/2, 0, ManiColor.W);
}
}
@Override
public void drawText(UiDrawer uiDrawer, ManiApplication cmp) {
}
@Override
public boolean reactsToClickOutside() {
return false;
}
@Override
public void blurCustom(ManiApplication cmp) {
}
}
|
package manage.format;
import manage.conf.MetaDataAutoConfiguration;
import manage.model.EntityType;
import org.springframework.core.io.Resource;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import static manage.format.Importer.ARP;
import static manage.format.Importer.META_DATA_FIELDS;
@SuppressWarnings("unchecked")
public class MetaDataFeedParser {
private static final List<String> languages = Arrays.asList("en", "nl");
private static final String ATTRIBUTES = "attributes";
public List<Map<String, Object>> importFeed(Resource xml,
MetaDataAutoConfiguration metaDataAutoConfiguration) throws
XMLStreamException, IOException {
//despite it's name, the XMLInputFactoryImpl is not thread safe
XMLInputFactory factory = getFactory();
XMLStreamReader reader = factory.createXMLStreamReader(xml.getInputStream());
List<Map<String, Object>> results = new ArrayList<>();
while (reader.hasNext()) {
Map<String, Object> entity = parseEntity(EntityType.SP, Optional.empty(), metaDataAutoConfiguration,
reader, true);
results.add(entity);
}
return results;
}
private XMLInputFactory getFactory() {
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // This disables DTDs entirely for that factory
xmlInputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); // disable external entities
return xmlInputFactory;
}
public Map<String, Object> importXML(Resource xml,
EntityType entityType,
Optional<String> entityIDOptional,
MetaDataAutoConfiguration metaDataAutoConfiguration) throws
XMLStreamException, IOException {
//despite it's name, the XMLInputFactoryImpl is not thread safe
XMLInputFactory factory = getFactory();
XMLStreamReader reader = factory.createXMLStreamReader(xml.getInputStream());
return parseEntity(entityType, entityIDOptional, metaDataAutoConfiguration, reader, false);
}
private Map<String, Object> parseEntity(EntityType entityType,
Optional<String> entityIDOptional,
MetaDataAutoConfiguration metaDataAutoConfiguration,
XMLStreamReader reader,
boolean enforceTypeStrictness) throws XMLStreamException {
Map<String, Object> result = new TreeMap<>();
Map<String, String> metaDataFields = new TreeMap<>();
result.put(META_DATA_FIELDS, metaDataFields);
boolean inKeyDescriptor = false;
boolean inContact = true;
boolean inUIInfo = false;
boolean inCorrectEntityDescriptor = !entityIDOptional.isPresent();
boolean inAttributeConsumingService = false;
boolean inEntityAttributes = false;
boolean typeMismatch = false;
result.put("type", entityType.getJanusDbValue());
boolean isSp = entityType.equals(EntityType.SP);
Set<String> arpKeys = new HashSet<>();
Map<String, String> arpAliases = new HashMap<>();
while (reader.hasNext()) {
int next = reader.next();
switch (next) {
case START_ELEMENT:
String startLocalName = reader.getLocalName();
switch (startLocalName) {
case "EntityDescriptor":
Optional<String> optional = getAttributeValue(reader, "entityID");
if (optional.isPresent()) {
if (entityIDOptional.isPresent()) {
inCorrectEntityDescriptor = entityIDOptional.get().equalsIgnoreCase(optional.get());
}
if (inCorrectEntityDescriptor) {
result.put("entityid", optional.get());
}
}
break;
case "SPSSODescriptor":
if (inCorrectEntityDescriptor) {
if (isSp) {
arpKeys = arpKeys(EntityType.SP, metaDataAutoConfiguration, isSp);
arpAliases = arpAliases(EntityType.SP, metaDataAutoConfiguration, isSp);
Map<String, Object> arp = new TreeMap<>();
arp.put("enabled", false);
Map<String, Object> attributes = new TreeMap<>();
arp.put(ATTRIBUTES, attributes);
result.put(ARP, arp);
} else {
//This should not happen, but an exception breaks reading the feed
typeMismatch = true;
}
}
break;
case "IDPSSODescriptor":
if (inCorrectEntityDescriptor) {
if (isSp) {
//This should not happen, but an exception breaks reading the feed
typeMismatch = true;
}
}
break;
case "KeyDescriptor":
if (!inCorrectEntityDescriptor) {
break;
}
Optional<String> use = getAttributeValue(reader, "use");
if (!use.isPresent() || use.get().equals("signing")) {
inKeyDescriptor = true;
}
break;
case "X509Certificate":
if (!inCorrectEntityDescriptor) {
break;
}
if (inKeyDescriptor) {
inKeyDescriptor = false;
String cert = reader.getElementText().replaceAll("[\n\r]", "").trim();
addCert(metaDataFields, cert);
}
break;
case "SingleLogoutService":
if (inCorrectEntityDescriptor && isSp) {
addMetaDataField(metaDataFields, reader, "Binding", "SingleLogoutService_Binding");
addMetaDataField(metaDataFields, reader, "Location", "SingleLogoutService_Location");
}
break;
case "AssertionConsumerService":
if (inCorrectEntityDescriptor && isSp) {
Optional<String> bindingOpt = getAttributeValue(reader, "Binding");
bindingOpt.ifPresent(binding ->
addMultiplicity(metaDataFields, "AssertionConsumerService:%s:Binding",
10, binding));
Optional<String> locationOpt = getAttributeValue(reader, "Location");
locationOpt.ifPresent(location ->
addMultiplicity(metaDataFields, "AssertionConsumerService:%s:Location",
10, location));
Optional<String> indexOpt = getAttributeValue(reader, "index");
indexOpt.ifPresent(index ->
addMultiplicity(metaDataFields, "AssertionConsumerService:%s:index",
10, index));
}
break;
case "SingleSignOnService":
if (!inCorrectEntityDescriptor || isSp) {
break;
}
Optional<String> bindingOpt = getAttributeValue(reader, "Binding");
bindingOpt.ifPresent(binding ->
addMultiplicity(metaDataFields, "SingleSignOnService:%s:Binding",
10, binding));
Optional<String> locationOpt = getAttributeValue(reader, "Location");
locationOpt.ifPresent(location ->
addMultiplicity(metaDataFields, "SingleSignOnService:%s:Location",
10, location));
break;
case "RegistrationInfo": {
if (inCorrectEntityDescriptor) {
getAttributeValue(reader, "registrationAuthority").ifPresent(authority -> {
metaDataFields.put("mdrpi:RegistrationInfo", authority);
});
}
break;
}
case "RegistrationPolicy":
if (inCorrectEntityDescriptor) {
addLanguageElement(metaDataFields, reader, "mdrpi:RegistrationPolicy");
}
break;
case "AttributeConsumingService":
inAttributeConsumingService = inCorrectEntityDescriptor;
break;
case "UIInfo":
inUIInfo = inCorrectEntityDescriptor;
break;
case "DisplayName":
if (inUIInfo) {
addLanguageElement(metaDataFields, reader, "name");
}
break;
case "Logo":
if (inUIInfo) {
addLogo(metaDataFields, reader);
}
break;
case "Description":
if (inUIInfo) {
addLanguageElement(metaDataFields, reader, "description");
}
break;
case "PrivacyStatementURL":
if (inUIInfo) {
addLanguageElement(metaDataFields, reader, "mdui:PrivacyStatementURL");
}
break;
case "ServiceName":
if (inAttributeConsumingService) {
addLanguageElement(metaDataFields, reader, "name");
}
break;
case "ServiceDescription":
if (inAttributeConsumingService) {
addLanguageElement(metaDataFields, reader, "description");
}
break;
case "RequestedAttribute":
if (inAttributeConsumingService && isSp) {
addArpAttribute(result, reader, arpKeys, arpAliases);
}
break;
case "OrganizationName":
if (!inCorrectEntityDescriptor) {
break;
}
addLanguageElement(metaDataFields, reader, "OrganizationName");
break;
case "OrganizationDisplayName":
if (!inCorrectEntityDescriptor) {
break;
}
addLanguageElement(metaDataFields, reader, "OrganizationDisplayName");
break;
case "OrganizationURL":
if (!inCorrectEntityDescriptor) {
break;
}
addLanguageElement(metaDataFields, reader, "OrganizationURL");
break;
case "ContactPerson":
if (!inCorrectEntityDescriptor) {
break;
}
String contactType = getAttributeValue(reader, "contactType").orElse("other");
addMultiplicity(metaDataFields, "contacts:%s:contactType", 4, contactType);
inContact = true;
break;
case "GivenName":
if (inCorrectEntityDescriptor && inContact) {
addMultiplicity(metaDataFields, "contacts:%s:givenName", 4, reader.getElementText());
}
break;
case "SurName":
if (inCorrectEntityDescriptor && inContact) {
addMultiplicity(metaDataFields, "contacts:%s:surName", 4, reader.getElementText());
}
break;
case "EmailAddress":
if (inCorrectEntityDescriptor && inContact) {
addMultiplicity(metaDataFields, "contacts:%s:emailAddress", 4,
reader.getElementText().replaceAll(Pattern.quote("mailto:"), ""));
}
break;
case "TelephoneNumber":
if (inCorrectEntityDescriptor && inContact) {
addMultiplicity(metaDataFields, "contacts:%s:telephoneNumber", 4, reader
.getElementText());
}
break;
case "EntityAttributes":
inEntityAttributes = inCorrectEntityDescriptor;
break;
case "AttributeValue":
if (inEntityAttributes) {
addCoinEntityCategories(entityType, metaDataFields, metaDataAutoConfiguration,
reader.getElementText());
}
break;
}
break;
case END_ELEMENT:
String localName = reader.getLocalName();
switch (localName) {
case "ContactPerson":
inContact = false;
break;
case "AttributeConsumingService":
inAttributeConsumingService = false;
break;
case "UIInfo":
inUIInfo = false;
break;
case "EntityDescriptor":
if (inCorrectEntityDescriptor) {
//we got what we came for
return typeMismatch && enforceTypeStrictness ? new HashMap<>() :
this.enrichMetaData(result);
}
break;
case "EntityAttributes":
inEntityAttributes = false;
break;
}
break;
}
}
return new HashMap<>();
}
private Map<String, Object> enrichMetaData(Map<String, Object> metaData) {
Map<String, String> metaDataFields = (Map<String, String>) metaData.get(META_DATA_FIELDS);
if (!metaDataFields.containsKey("name:en") && metaDataFields.containsKey("OrganizationName:en")) {
metaDataFields.put("name:en", metaDataFields.get("OrganizationName:en"));
}
if (!metaDataFields.containsKey("name:nl") && metaDataFields.containsKey("OrganizationName:nl")) {
metaDataFields.put("name:nl", metaDataFields.get("OrganizationName:nl"));
}
return metaData;
}
private Set<String> arpKeys(EntityType type, MetaDataAutoConfiguration metaDataAutoConfiguration, boolean isSp) {
return arpAttributes(type, metaDataAutoConfiguration, isSp).keySet();
}
private Map<String, String> arpAliases(EntityType type, MetaDataAutoConfiguration metaDataAutoConfiguration,
boolean isSp) {
Map<String, Object> arp = arpAttributes(type, metaDataAutoConfiguration, isSp);
return arp.entrySet().stream()
.filter(entry -> Map.class.cast(entry.getValue()).containsKey("alias"))
.collect(toMap(
entry -> (String) Map.class.cast(entry.getValue()).get("alias"),
entry -> entry.getKey(),
(alias1, alias2) -> alias1));
}
private Map<String, Object> arpAttributes(EntityType type, MetaDataAutoConfiguration metaDataAutoConfiguration,
boolean isSp) {
Map<String, Object> schema = metaDataAutoConfiguration.schemaRepresentation(type);
Map<String, Object> arpAttributes = isSp ? Map.class.cast(schema.get("properties")) : new HashMap<>();
if (isSp) {
for (String s : Arrays.asList("arp", "properties", "attributes", "properties")) {
arpAttributes = Map.class.cast(arpAttributes.get(s));
}
}
return arpAttributes;
}
private void addArpAttribute(Map<String, Object> result, XMLStreamReader reader, Set<String> arpKeys,
Map<String, String> arpAliases) {
Optional<String> name = getAttributeValue(reader, "Name");
Optional<String> friendlyName = getAttributeValue(reader, "FriendlyName");
if (this.shouldAddAttributeToArp(name, arpKeys)) {
doAddArpAttribute(result, arpKeys, name.get());
} else if (this.shouldAddAttributeToArp(friendlyName, arpKeys)) {
doAddArpAttribute(result, arpKeys, friendlyName.get());
} else if (name.isPresent() && arpAliases.containsKey(name.get())) {
doAddArpAttribute(result, arpKeys, arpAliases.get(name.get()));
}
}
private boolean shouldAddAttributeToArp(Optional<String> name, Set<String> allowedArpKeys) {
return name.isPresent() && allowedArpKeys.stream().anyMatch(arpKey -> arpKey.endsWith(name.get()));
}
private void doAddArpAttribute(Map<String, Object> result, Set<String> arpKeys, String friendlyName) {
Map<String, Object> arp = Map.class.cast(result.getOrDefault(ARP, new TreeMap<>()));
arp.put("enabled", true);
final Map<String, Object> attributes = Map.class.cast(arp.getOrDefault(ATTRIBUTES, new TreeMap<>()));
arpKeys.stream().filter(arpKey -> arpKey.endsWith(friendlyName)).findFirst().ifPresent(arpKey -> {
List<Map<String, String>> arpEntry = List.class.cast(attributes.getOrDefault(arpKey, new ArrayList<>()));
Map<String, String> arpValue = new HashMap<>();
arpValue.put("source", "idp");
arpValue.put("value", "*");
arpEntry.add(arpValue);
attributes.put(arpKey, arpEntry);
});
arp.put(ATTRIBUTES, attributes);
result.put(ARP, arp);
}
private void addMetaDataField(Map<String, String> metaDataFields, XMLStreamReader reader, String attributeName,
String metaDataKey) {
Optional<String> optional = getAttributeValue(reader, attributeName);
optional.ifPresent(value -> metaDataFields.put(metaDataKey, value));
}
private void addLanguageElement(Map<String, String> metaDataFields, XMLStreamReader reader, String elementName)
throws XMLStreamException {
String language = getAttributeValue(reader, "lang").orElse("en");
if (languages.contains(language)) {
metaDataFields.put(String.format("%s:%s", elementName, language), reader.getElementText());
}
}
private void addMultiplicity(Map<String, String> result, String format, int multiplicity, String value) {
List<String> keys = IntStream.range(0, multiplicity).mapToObj(nbr -> String.format(format, nbr))
.collect(toList());
long count = result.keySet().stream().filter(key -> keys.contains(key)).count();
if (count < keys.size()) {
result.put(keys.get((int) count), value);
}
}
private void addCert(Map<String, String> result, String cert) {
List<String> certDataKeys = Arrays.asList("certData", "certData2", "certData3");
long count = result.keySet().stream().filter(certDataKeys::contains).count();
if (count < certDataKeys.size()) {
// we don't want duplicates
if (!certDataKeys.stream().map(key -> cert.equals(result.get(key))).anyMatch(b -> b)) {
result.put(certDataKeys.get((int) count), cert);
}
}
}
private void addLogo(Map<String, String> metaDataFields, XMLStreamReader reader) throws XMLStreamException {
getAttributeValue(reader, "width")
.ifPresent(width -> metaDataFields.put("logo:0:width", width));
getAttributeValue(reader, "height")
.ifPresent(height -> metaDataFields.put("logo:0:height", height));
metaDataFields.put("logo:0:url", reader.getElementText());
}
private Optional<String> getAttributeValue(XMLStreamReader reader, String attributeName) {
int attributeCount = reader.getAttributeCount();
for (int i = 0; i < attributeCount; i++) {
QName qName = reader.getAttributeName(i);
if (qName.getLocalPart().equalsIgnoreCase(attributeName)) {
return Optional.of(reader.getAttributeValue(qName.getNamespaceURI(), qName.getLocalPart()));
}
}
return Optional.empty();
}
private void addCoinEntityCategories(EntityType entityType, Map<String, String> metaDataFields,
MetaDataAutoConfiguration metaDataAutoConfiguration, String elementText) {
Map<String, Object> schema = metaDataAutoConfiguration.schemaRepresentation(entityType);
Map<String, Object> schemaPart = this.unpack(schema,
Arrays.asList("properties", "metaDataFields", "patternProperties", "^coin:entity_categories:"));
List<String> enumeration = (List<String>) schemaPart.get("enum");
String strippedValue = elementText.replaceAll("\n", "").trim();
if (!enumeration.contains(strippedValue)) {
return;
}
String entityCategoryKey = "coin:entity_categories:";
//do not add the same entity category twice as we limit the number
List<String> categories = metaDataFields.entrySet().stream()
.filter(e -> e.getKey().startsWith(entityCategoryKey))
.map(Map.Entry::getValue)
.collect(toList());
if (categories.contains(strippedValue)) {
return;
}
int multiplicity = (int) schemaPart.get("multiplicity");
int startIndex = (int) schemaPart.get("startIndex");
metaDataFields.keySet().stream()
.filter(s -> s.startsWith(entityCategoryKey))
.map(s -> Integer.valueOf(s.substring(entityCategoryKey.length())))
.max(Integer::compareTo)
.map(i -> multiplicity >= startIndex + i ? "put returns null" + metaDataFields.put(entityCategoryKey + ++i,
strippedValue) : "")
.orElseGet(() -> metaDataFields.put(entityCategoryKey + startIndex, strippedValue));
}
private Map<String, Object> unpack(Map<String, Object> schema, List<String> keys) {
return keys.stream().sequential().reduce(schema, (map, s) -> s.startsWith("^") ?
Map.class.cast(map.get(map.keySet().stream().filter(k -> k.startsWith(s)).findAny()
.orElseThrow(() -> new IllegalArgumentException("Key not present: " + s)))) :
Map.class.cast(map.get(s)),
(acc, com) -> com);
}
}
|
package dpm.lejos.project;
import dpm.lejos.orientation.Coordinate;
import dpm.lejos.orientation.Orienteering;
import lejos.nxt.Button;
import lejos.nxt.Sound;
import lejos.nxt.comm.RConsole;
/**
* High level mission planning.
*
* Implements the over all strategy of the application. This class
* Manages the high level switching between the subsystems needed to
* accomplish the task.
*
* @author David Lavoie-Boutin
* @version 1.0
*/
public class MissionPlanner {
private final Odometer odometer;
private final SystemDisplay display;
private final Navigation m_Navigation;
private final Grabber m_Grabber;
private final Orienteering orienteering;
private final BlockDetection blockDetection;
private final Robot robot;
private int dropOffX;
private int dropOffY;
/**
* Initializes a MissionPlanner instance, used to complete the search and rescue task.
* @param navigation Navigation instance used to travel between tiles.
* @param grabber Grabber instance used to locate and pick-up blocks
* @param orienteering Orienteering instance used to localize the robot on the grid.
* @param odometer Odometer instance used to keep track of the position of the robot
* on the coordinate system.
* @param display Display instance used to print to the LCD screen of the master brick.
* @param blockDetection Block detection instance used to determine the location of
* blocks on the pick-up area.
* @param robot Robot instance used to control the movement of the robot.
* @param dropOffX X coordinate where the grabbed blocks should be dropped.
* @param dropOffY Y coordinate where the grabbed blocks should be dropped.
*/
public MissionPlanner(Navigation navigation, Grabber grabber, Orienteering orienteering, Odometer odometer, SystemDisplay display,
BlockDetection blockDetection, Robot robot, int dropOffX, int dropOffY) {
this.m_Navigation = navigation;
this.m_Grabber = grabber;
this.orienteering = orienteering;
this.odometer = odometer;
this.display = display;
this.blockDetection = blockDetection;
this.robot = robot;
this.dropOffX = dropOffX;
this.dropOffY = dropOffY;
}
/**
* perform the mission
*
* steps:
*
* 1- Localise within the playground
* 2- Navigate to pickup zone
* 3- Pickup blocks
* 4- Navigate to drop off area
* 5- Drop blocks
*/
public void startMission(){
completeTask();
}
public void odoCorrectionTest(){
odometer.startCorrection();
odometer.start();
display.start();
m_Navigation.travelTo(60,0);
Button.waitForAnyPress();
}
public void demoMission(){
display.start();
odometer.start();
int option = 0;
while (option == 0)
option = Button.waitForAnyPress();
switch(option) {
case Button.ID_LEFT:
m_Navigation.moveForward();
m_Navigation.rotate90ClockWise();
m_Navigation.moveForward();
m_Navigation.rotate90ClockWise();
m_Navigation.moveForward();
m_Navigation.rotate90ClockWise();
m_Navigation.moveForward();
m_Navigation.rotate90ClockWise();
case Button.ID_RIGHT:
m_Grabber.lowerClaw();
Button.waitForAnyPress();
m_Grabber.riseClaw();
default:
System.out.println("Error - invalid button");
System.exit(-1);
break;
}
}
/**
* Protocol used to calibrate the radius of the wheels for the best
* possible turning.
*/
public void calibrateRadius(){
odometer.start();
display.start();
m_Navigation.travelTo(2 * Robot.tileLength, 0);
System.exit(0);
}
/**
* Protocol used to calibrate the size of the wheelbase for the best
* possible navigation.
*/
public void calibrateBase(){
odometer.start();
display.start();
m_Navigation.rotateTo(180);
m_Navigation.moveForward();
m_Navigation.moveForward();
m_Navigation.rotateTo(180);
Button.waitForAnyPress();
System.exit(0);
}
/**
* Odometer test to verify that the subsystem is working properly.
*/
public void odometryTest(){
odometer.start();
display.start();
RConsole.println("I made it this far!");
m_Navigation.rotateTo(2);
RConsole.println("I made it this far 2!");
Button.waitForAnyPress();
System.exit(0);
}
/**
* Subroutine to test that the vehicle is capable of
* localizing on a specified map
*/
public void localizationTest() {
Button.waitForAnyPress();
odometer.start();
RConsole.println("Initiated ODO and ODO Display");
orienteering.deterministicPositioning(odometer);
}
/**
* Subroutine to test that the vehicle is capable of
* navigating on a specified map
* @param robot Robot instance used to control the movement of the robot.
*/
public void navigationTest(Robot robot) {
odometer.start();
display.start();
RConsole.println("Initiated ODO and ODO Display");
robot.setPositionOnGrid(new Coordinate(0, 1));
robot.setDirection(Orienteering.Direction.SOUTH);
odometer.setX(45);
odometer.setY(15);
odometer.setThetaInDegrees(0);
m_Navigation.navigate(new Coordinate(3,3));
}
/**
* Integration test of the localization and navigation
* subroutines.
*/
public void localizationAndNavigationTest() {
odometer.start();
display.start();
RConsole.println("Initiated ODO and ODO Display");
orienteering.deterministicPositioning(odometer);
Sound.beep();
m_Navigation.navigate(new Coordinate(5,1));
}
/**
* Main subroutine for the entire search and rescue task.
*/
public void completeTask() {
odometer.start();
//localize
orienteering.deterministicPositioning(odometer);
Sound.beep();
Sound.beep();
//navigate to the north-east corner of the pick-up location
m_Navigation.navigate(new Coordinate(9,1));
//Look south towards the blocks
m_Navigation.rotateTo(0);
//Initiate blockpicking algorithm
blockDetection.lookForBlock(m_Grabber);
robot.setPositionOnGrid(new Coordinate(9,1));
robot.setDirection(Orienteering.Direction.NORTH);
//Navigate towards the drop-off location
m_Navigation.navigate(new Coordinate(dropOffY, dropOffX));
m_Navigation.moveBackwardHalfATile();
//Drop the block
m_Grabber.lowerClaw();
m_Grabber.openClaw();
Button.waitForAnyPress();
}
/**
* Test used to determine the effectiveness of the robot
* rotation.
*/
public void rotationTest() {
odometer.start();
display.start();
m_Navigation.rotate90ClockWise();
m_Navigation.rotate90ClockWise();
m_Navigation.rotate90CounterClock();
m_Navigation.rotate90CounterClock();
}
/**
* Test used to verify the functionality of the claw.
*/
public void clawTest() {
display.start();
odometer.start();
m_Grabber.deployArms();
m_Grabber.lowerClaw();
m_Grabber.closeClaw();
m_Grabber.riseClaw();
Button.waitForAnyPress();
}
/**
* Test to verify the functionality of the block-picking
* algorithm.
*/
public void pickBlockTest() {
odometer.start();
display.start();
blockDetection.lookForBlock(m_Grabber);
}
/**
* Second test for the block-picking algorithm with a variation
* in the starting position. Instead of standing at the north-east corner
* we stand at the north-west corner.
*/
public void pickBlockTestWithDifferentStartingPosition() {
display.start();
odometer.start();
m_Grabber.deployArms();
m_Grabber.lowerClaw();
Button.waitForAnyPress();
m_Grabber.closeClaw();
Button.waitForAnyPress();
m_Grabber.riseClaw();
Button.waitForAnyPress();
}
/**
* Test the straight driving capabilities of the robot.
*/
public void straightDriverTest() {
odometer.start();
display.start();
blockDetection.lookForBlock(m_Grabber);
}
/**
* Test the functionality of the touch sensor on the left
* arm of the claw.
*/
public void touchSensorTest() {
while (true) {
if (robot.clawTouch.isPressed()) {
RConsole.println("Touch sensor pressed!");
}
}
}
}//end MissionPlanner
|
/* Currently managed by: Levi Raby
*
*
*
*/
package edu.ames.frc.robot;
//Non-explicit imports of io libraries. Once code is finished it should be changed into a set of explicit imports.
import java.io.*;
import javax.microedition.io.*;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.Watchdog;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class Communication {
public static boolean isinit = false; // make sure we're already initted
public static boolean debugmode = false; // debugging symbols enabled/disabled?
public static long time;
public static int step = 0;
public static double voltage;
public static boolean mainlcd = false; // enable/disable main led
public static boolean sensorlighton;
public static String[] messages = new String[5];
public static int cycle = 0; // how many clock cycles the robot ran, divided by 500
public void ConsoleMsg(String msg, int type) {
messages[type] = msg;
}
public void MsgPrint() {
}
public class PISocket {
boolean active;
ServerSocketConnection psock = null;
public PISocket(boolean activated) {
active = activated;
try {
psock = (ServerSocketConnection) Connector.open("socket://127.0.0.1:3243");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
|
package edu.iu.grid.oim.model.db;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import edu.iu.grid.oim.model.Context;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.model.db.record.DNAuthorizationTypeRecord;
import edu.iu.grid.oim.model.db.record.DNRecord;
import edu.iu.grid.oim.model.db.record.RecordBase;
public class DNModel extends SmallTableModelBase<DNRecord> {
static Logger log = Logger.getLogger(DNModel.class);
public DNModel(Context context)
{
super(context, "dn");
}
public String getName()
{
return "DN";
}
public String getHumanValue(String field_name, String value) throws NumberFormatException, SQLException
{
if(field_name.equals("contact_id")) {
ContactModel model = new ContactModel(context);
ContactRecord rec = model.get(Integer.parseInt(value));
return value + " (" + rec.name + ")";
}
return value;
}
public Boolean hasLogAccess(XPath xpath, Document doc) throws XPathExpressionException
{
//Integer id = Integer.parseInt((String)xpath.evaluate("//Keys/Key[Name='id']/Value", doc, XPathConstants.STRING));
if(auth.allows("admin")) {
return true;
}
return false;
}
DNRecord createRecord() throws SQLException
{
return new DNRecord();
}
public DNRecord getByDNString(String dn_string) throws SQLException
{
if(dn_string != null) {
for(RecordBase it : getCache())
{
DNRecord rec = (DNRecord)it;
if(rec.dn_string.compareTo(dn_string) == 0) {
return rec;
}
}
}
return null;
}
public DNRecord getByContactID(int contact_id) throws SQLException
{
for(RecordBase it : getCache())
{
DNRecord rec = (DNRecord)it;
if(rec.contact_id.compareTo(contact_id) == 0) {
return rec;
}
}
return null;
}
public DNRecord get(int id) throws SQLException {
DNRecord keyrec = new DNRecord();
keyrec.id = id;
return get(keyrec);
}
public ArrayList<DNRecord> getAll() throws SQLException
{
ArrayList<DNRecord> list = new ArrayList<DNRecord>();
for(RecordBase it : getCache()) {
list.add((DNRecord)it);
}
return list;
}
public void insertDetail(DNRecord rec,
ArrayList<Integer> auth_types) throws Exception
{
Connection conn = connectOIM();
try {
//process detail information
conn.setAutoCommit(false);
//insert rec itself and get the new ID
insert(rec);
//insert auth_type
DNAuthorizationTypeModel amodel = new DNAuthorizationTypeModel(context);
ArrayList<DNAuthorizationTypeRecord> arecs = new ArrayList<DNAuthorizationTypeRecord>();
for(Integer auth_type : auth_types) {
DNAuthorizationTypeRecord arec = new DNAuthorizationTypeRecord();
arec.dn_id = rec.id;
arec.authorization_type_id = auth_type;
arecs.add(arec);
}
amodel.insert(arecs);
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
log.error(e);
log.info("Rolling back DN detail insert transaction.");
if(conn != null) {
conn.rollback();
conn.setAutoCommit(true);
}
//re-throw original exception
throw new Exception(e);
}
}
public void updateDetail(DNRecord rec,
ArrayList<Integer> auth_types) throws Exception
{
//Do insert / update to our DB
Connection conn = connectOIM();
try {
//process detail information
conn.setAutoCommit(false);
update(get(rec), rec);
//update auth_type
DNAuthorizationTypeModel amodel = new DNAuthorizationTypeModel(context);
ArrayList<DNAuthorizationTypeRecord> arecs = new ArrayList<DNAuthorizationTypeRecord>();
for(Integer auth_type : auth_types) {
DNAuthorizationTypeRecord arec = new DNAuthorizationTypeRecord();
arec.dn_id = rec.id;
arec.authorization_type_id = auth_type;
arecs.add(arec);
}
amodel.update(amodel.getAllByDNID(rec.id), arecs);
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
log.error(e);
log.info("Rolling back DN detail update transaction.");
if(conn != null) {
conn.rollback();
conn.setAutoCommit(true);
}
//re-throw original exception
throw new Exception(e);
}
}
}
|
package edu.swin.SwinNetSim;
import java.io.IOException;
import org.apache.commons.lang3.time.StopWatch;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
public class TestDownload {
public final static String SERVER_URL = "http://ec2-54-196-212-34.compute-1.amazonaws.com/";
public final static String SMALL_FILE = "texter/small";
public final static String MEDIUM_FILE = "texter/medium";
public final static String LARGE_FILE = "texter/large";
public final static String XLARGE_FILE = "texter/xlarge";
public final static int REPEAT = 50;
public static void main(String [] args) throws IOException, JSONException {
System.out.println("=====================================================");
System.out.println("Running on server url " + SERVER_URL);
System.out.println("=====================================================");
// SMALL_FILE over REPEAT times
System.out.println("Downloading small files...");
testDownload(TestDownload.SMALL_FILE);
System.out.println("=====================================================");
System.out.println("Downloading medium files...");
testDownload(TestDownload.MEDIUM_FILE);
System.out.println("=====================================================");
System.out.println("Downloading x-large files...");
testDownload(TestDownload.XLARGE_FILE);
}
private static void testDownload(String testFile) throws IOException,
JSONException {
// Get the starting time
StopWatch watch = new StopWatch();
watch.start();
for(int i = 0; i < TestDownload.REPEAT; i++) {
JSONObject json = JsonReader.readJsonFromUrl(SERVER_URL + testFile);
System.out.print('.');
}
watch.stop();
long totalTime = watch.getTime();
System.out.println("done!");
System.out.println("Time taken: " + totalTime + " ms");
System.out.println("On average: " + (totalTime / TestDownload.REPEAT) + " ms");
}
}
|
package wifi;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
public class LanNetwork extends JDialog implements ClosableWindow {
private static final long serialVersionUID = 8237689034968088432L;
private final JPanel contentPanel = new JPanel();
private Server server;
private JButton cancelButton;
public LanNetwork() {
server = new Server(this);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 325, 147);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JLabel lblYourIpIs = new JLabel("Your IP is: " + Utils.getLocalIP());
contentPanel.add(lblYourIpIs, BorderLayout.NORTH);
lblYourIpIs.setHorizontalAlignment(SwingConstants.CENTER);
}
{
JPanel panel = new JPanel();
contentPanel.add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
{
JSeparator separator = new JSeparator();
panel.add(separator, BorderLayout.NORTH);
}
{
JLabel lblNewLabel = new JLabel("Waiting for establishing a connection...");
panel.add(lblNewLabel, BorderLayout.CENTER);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
}
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
MainMenu.instance.setVisible(true);
System.out.println("Cancel clicked");
if(server != null)
{
System.out.println("Destroying server");
server.destroy();
}
destroy();
}
});
cancelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
MainMenu.instance.setVisible(true);
System.out.println("Cancel clicked");
if(server != null)
{
System.out.println("Destroying server");
server.destroy();
}
destroy();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.out.println("NetworkConfig.java: Closed");
cancelButton.doClick();
}
});
}
}
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void destroy() {
dispose();
}
@Override
public void setVisibility(boolean visible) {
setVisible(visible);
}
}
|
package org.multibit.hd.core.services;
import com.google.bitcoin.core.Address;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.multibit.hd.core.dto.Contact;
import org.multibit.hd.core.dto.WalletId;
import org.multibit.hd.core.exceptions.ContactsLoadException;
import org.multibit.hd.core.exceptions.ContactsSaveException;
import org.multibit.hd.core.files.SecureFiles;
import org.multibit.hd.core.managers.InstallationManager;
import org.multibit.hd.core.managers.WalletManager;
import org.multibit.hd.core.store.ContactsProtobufSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* <p>Service to provide the following to application:</p>
* <ul>
* <li>CRUD operations on Contacts</li>
* </ul>
*
* @since 0.0.1
*
*/
public class PersistentContactService implements ContactService {
private static final Logger log = LoggerFactory.getLogger(PersistentContactService.class);
/**
* The in-memory cache of contacts for the current wallet
*/
private final Set<Contact> contacts = Sets.newHashSet();
/**
* The location of the backing writeContacts for the contacts
*/
private File backingStoreFile;
/**
* The serializer for the backing writeContacts
*/
private ContactsProtobufSerializer protobufSerializer;
/**
* <p>Create a ContactService for a Wallet with the given walletId</p>
*
* <p>Reduced visibility constructor to prevent accidental instance creation outside of CoreServices.</p>
*/
PersistentContactService(WalletId walletId) {
Preconditions.checkNotNull(walletId, "'walletId' must be present");
// Register for events
CoreServices.uiEventBus.register(this);
// Work out where to writeContacts the contacts for this wallet id.
File applicationDataDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
String walletRoot = WalletManager.createWalletRoot(walletId);
File walletDirectory = WalletManager.getOrCreateWalletDirectory(applicationDataDirectory, walletRoot);
File contactsDirectory = new File(walletDirectory.getAbsolutePath() + File.separator + CONTACTS_DIRECTORY_NAME);
SecureFiles.verifyOrCreateDirectory(contactsDirectory);
this.backingStoreFile = new File(contactsDirectory.getAbsolutePath() + File.separator + CONTACTS_DATABASE_NAME);
initialise();
}
/**
* <p>Create a ContactService with the specified File as the backing writeContacts. (This exists primarily for testing where you just run things in a temporary directory)</p>
* <p>Reduced visibility constructor to prevent accidental instance creation outside of CoreServices.</p>
*/
PersistentContactService(File backingStoreFile) {
this.backingStoreFile = backingStoreFile;
initialise();
}
private void initialise() {
protobufSerializer = new ContactsProtobufSerializer();
// Load the contact data from the backing writeContacts if it exists
if (backingStoreFile.exists()) {
loadContacts();
}
}
/**
* <p>Create a new contact and add it to the internal cache</p>
*
* @param name A name (normally first name and last name)
*
* @return A new contact with a fresh ID
*/
@Override
public Contact newContact(String name) {
return new Contact(UUID.randomUUID(), name);
}
/**
* @return A list of all Contacts for the given page
*/
@Override
public List<Contact> allContacts() {
return Lists.newArrayList(contacts);
}
@Override
public List<Contact> filterContactsByBitcoinAddress(Address address) {
Preconditions.checkNotNull(address,"'address' must be present");
String queryAddress = address.toString();
List<Contact> filteredContacts = Lists.newArrayList();
for (Contact contact : contacts) {
if (contact.getBitcoinAddress().or("").equals(queryAddress)) {
filteredContacts.add(contact);
}
}
return filteredContacts;
}
@Override
public List<Contact> filterContactsByContent(String query, boolean excludeNotPayable) {
Preconditions.checkNotNull(query, "'query' must be present. Use * for wildcard.");
String lowerQuery = query.toLowerCase();
List<Contact> filteredContacts = Lists.newArrayList();
for (Contact contact : contacts) {
// No Bitcoin address and excluding not payable
if (excludeNotPayable && Strings.isNullOrEmpty(contact.getBitcoinAddress().or("").trim())) {
continue;
}
// TODO Add support for EPK in later releases
// TODO (GR) Consider regex matching
// Note: Do not include a Bitcoin address or EPK in this search
// because vanity addresses can cause an attack vector
// Instead use the dedicated methods for those fields
final boolean isNameMatched;
final boolean isEmailMatched;
final boolean isNoteMatched;
if ("*".equals(query)) {
// Note: Do not include a Bitcoin address or EPK in this search
// because vanity addresses can cause an attack vector
// Instead use the dedicated methods for those fields
isNameMatched = true;
isEmailMatched = true;
isNoteMatched = true;
} else {
// Note: Do not include a Bitcoin address or EPK in this search
// because vanity addresses can cause an attack vector
// Instead use the dedicated methods for those fields
isNameMatched = contact.getName().toLowerCase().contains(lowerQuery);
isEmailMatched = contact.getEmail().or("").toLowerCase().contains(lowerQuery);
isNoteMatched = contact.getNotes().or("").toLowerCase().contains(lowerQuery);
}
boolean isTagMatched = false;
for (String tag : contact.getTags()) {
if (tag.toLowerCase().contains(lowerQuery)) {
isTagMatched = true;
break;
}
}
if (isNameMatched
|| isEmailMatched
|| isNoteMatched
|| isTagMatched
) {
filteredContacts.add(contact);
}
}
return filteredContacts;
}
@Override
public void addAll(Collection<Contact> selectedContacts) {
contacts.addAll(selectedContacts);
}
@Override
public void loadContacts() throws ContactsLoadException {
log.debug("Loading contacts from '{}'", backingStoreFile.getAbsolutePath());
try {
ByteArrayInputStream decryptedInputStream = EncryptedFileReaderWriter.readAndDecrypt(backingStoreFile, WalletManager.INSTANCE.getCurrentWalletData().get().getPassword());
Set<Contact> loadedContacts = protobufSerializer.readContacts(decryptedInputStream);
contacts.clear();
contacts.addAll(loadedContacts);
} catch (EncryptedFileReaderWriterException e) {
throw new ContactsLoadException("Could not loadContacts contacts db '" + backingStoreFile.getAbsolutePath() + "'. Error was '" + e.getMessage() + "'.");
}
}
/**
* <p>Clear all contact data</p>
* <p>Reduced visibility for testing</p>
*/
void clear() {
contacts.clear();
}
@Override
public void removeAll(Collection<Contact> selectedContacts) {
Preconditions.checkNotNull(selectedContacts, "'selectedContacts' must be present");
log.debug("Removing {} contact(s)", selectedContacts.size());
contacts.removeAll(selectedContacts);
}
@Override
public void updateContacts(Collection<Contact> editedContacts) {
Preconditions.checkNotNull(editedContacts, "'editedContacts' must be present");
log.debug("Updating {} contact(s)", editedContacts.size());
for (Contact editedContact : editedContacts) {
if (!contacts.contains(editedContact)) {
contacts.add(editedContact);
}
}
}
@Override
public void writeContacts() throws ContactsSaveException {
log.debug("Writing {} contact(s)", contacts.size());
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
protobufSerializer.writeContacts(contacts, byteArrayOutputStream);
EncryptedFileReaderWriter.encryptAndWrite(byteArrayOutputStream.toByteArray(), WalletManager.INSTANCE.getCurrentWalletData().get().getPassword(), backingStoreFile);
} catch (Exception e) {
throw new ContactsSaveException("Could not save contacts db '" + backingStoreFile.getAbsolutePath() + "'. Error was '" + e.getMessage() + "'.");
}
}
@Override
public void addDemoContacts() {
// Only add the demo contacts if there are none present
if (!contacts.isEmpty()) {
return;
}
Contact contact1 = newContact("Alice Capital");
contact1.setEmail("g.rowe@froot.co.uk");
contact1.getTags().add("VIP");
contact1.getTags().add("Family");
contact1.setNotes("This is a really long note that should span over several lines when finally rendered to the screen. It began with Alice Capital.");
contacts.add(contact1);
Contact contact2 = newContact("Bob Capital");
contact2.setEmail("bob.capital@example.org");
contact2.setNotes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
contact2.getTags().add("VIP");
contact2.getTags().add("Merchandise");
contacts.add(contact2);
Contact contact3 = newContact("Charles Capital");
contact2.setNotes("Charles Capital's note 1\n\nCharles Capital's note 2");
contact3.setEmail("charles.capital@example.org");
contacts.add(contact3);
// No email for Derek
Contact contact4 = newContact("Derek Capital");
contact2.setNotes("Derek Capital's note 1\n\nDerek Capital's note 2");
contact4.getTags().add("Family");
contacts.add(contact4);
Contact contact5 = newContact("alice Lower");
contact5.setEmail("alice.lower@example.org");
contacts.add(contact5);
Contact contact6 = newContact("alicia Lower");
contact6.setEmail("alicia.lower@example.org");
contacts.add(contact6);
}
}
|
package com.github.dreamhead.moco.parser.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.dreamhead.moco.util.Globs;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import static com.github.dreamhead.moco.util.Files.join;
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public final class GlobalSetting {
private String include;
private String context;
@JsonProperty("file_root")
private String fileRoot;
private String env;
private RequestSetting request;
private ResponseSetting response;
public ImmutableList<String> includes() {
return Globs.glob(join(fileRoot, include));
}
public String getContext() {
return context;
}
public String getFileRoot() {
return fileRoot;
}
public String getEnv() {
return env;
}
public RequestSetting getRequest() {
return request;
}
public ResponseSetting getResponse() {
return response;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("include", include)
.add("context", context)
.add("file root", fileRoot)
.add("env", env)
.add("request", request)
.add("response", response)
.toString();
}
}
|
package io.spine.client;
import com.google.protobuf.FieldMask;
import io.spine.base.EntityState;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.spine.client.OrderBy.Direction.OD_UNKNOWN;
import static io.spine.client.OrderBy.Direction.UNRECOGNIZED;
/**
* A builder for the {@link Query} instances.
*
* <p>None of the parameters set by the builder methods are required. Call {@link #build()} to
* retrieve the resulting {@link Query} instance.
*
* <p>Usage example:
* <pre>{@code
* ActorRequestFactory factory = ... ;
* Query query = factory.query()
* .select(Customer.class)
* .byId(westCoastCustomerIds())
* .withMask("name", "address", "email")
* .where(eq("type", "permanent"),
* eq("discountPercent", 10),
* eq("companySize", Company.Size.SMALL))
* .orderBy("name", ASCENDING)
* .limit(20)
* .build();
* }</pre>
*
* <p>Arguments for the {@link #where(Filter...)} method can be composed using the {@link Filters}
* utility class.
*
* @see Filters
* @see TargetBuilder
*/
//TODO:2020-10-08:alex.tymchenko: review again and deprecate
public final class QueryBuilder extends TargetBuilder<Query, QueryBuilder> {
private final QueryFactory queryFactory;
private String orderingColumn;
private OrderBy.Direction direction;
private int limit = 0;
QueryBuilder(Class<? extends EntityState<?>> targetType, QueryFactory queryFactory) {
super(targetType);
this.queryFactory = checkNotNull(queryFactory);
}
/**
* Sets the sorting order by the target column and order direction.
*
* @param column
* the entity column to sort by
* @param direction
* sorting direction
*/
public QueryBuilder orderBy(String column, OrderBy.Direction direction) {
checkNotNull(column);
checkNotNull(direction);
checkArgument(
direction != OD_UNKNOWN && direction != UNRECOGNIZED,
"Invalid ordering direction"
);
this.orderingColumn = column;
this.direction = direction;
return self();
}
/**
* Limits the number of results returned by the query.
*
* @param count
* the number of results to be returned
*/
public QueryBuilder limit(int count) {
checkLimit(count);
this.limit = count;
return self();
}
private static void checkLimit(long count) {
checkArgument(count > 0, "A query limit must be a positive value.");
}
/**
* Generates a new {@link Query} instance with current builder configuration.
*
* @return the built {@link Query}
*/
@Override
@SuppressWarnings("OptionalIsPresent") // For better readability.
public Query build() {
Optional<OrderBy> orderBy = orderBy();
Target target = buildTarget();
FieldMask mask = composeMask();
if (limit > 0) {
checkState(orderBy.isPresent(), "Limit cannot be set for unordered Queries.");
return queryFactory.composeQuery(target, orderBy.get(), limit, mask);
}
if (orderBy.isPresent()) {
return queryFactory.composeQuery(target, orderBy.get(), mask);
}
return queryFactory.composeQuery(target, mask);
}
private Optional<OrderBy> orderBy() {
if (orderingColumn == null) {
return Optional.empty();
}
OrderBy result = OrderBy.newBuilder()
.setColumn(orderingColumn)
.setDirection(direction)
.build();
return Optional.of(result);
}
@Override
QueryBuilder self() {
return this;
}
}
|
package pe.chalk.takoyaki;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author ChalkPE <chalkpe@gmail.com>
* @since 2015-09-27
*/
public class Staff extends WebClient {
public Staff(JSONObject accountProperties, int timeout) throws IOException {
super(BrowserVersion.CHROME);
this.getOptions().setTimeout(timeout);
this.getOptions().setJavaScriptEnabled(false);
Logger.getLogger("org.apache").setLevel(Level.OFF);
Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
Takoyaki.getInstance().getLogger().info(" : " + accountProperties.getString("username"));
this.login(accountProperties);
}
private void login(JSONObject accountProperties) throws IOException {
final HtmlPage loginPage = this.getPage("https://nid.naver.com/nidlogin.login?url=");
final HtmlForm loginForm = loginPage.getFormByName("frmNIDLogin");
final HtmlTextInput idInput = loginForm.getInputByName("id");
final HtmlPasswordInput pwInput = loginForm.getInputByName("pw");
final HtmlSubmitInput loginButton = (HtmlSubmitInput) loginForm.getByXPath("//fieldset/span/input").get(0);
final String id = accountProperties.getString("username");
final String pw = accountProperties.getString("password");
if(id.equals("") || pw.equals("")){
Takoyaki.getInstance().getLogger().notice(" : ");
return;
}
idInput.setValueAttribute(id);
pwInput.setValueAttribute(pw);
Elements errors = Jsoup.parse(((HtmlPage) loginButton.click()).asXml().replaceFirst("<\\?xml version=\"1.0\" encoding=\"(.+)\"\\?>", "<!DOCTYPE html>")).select("div.error");
if(!errors.isEmpty()){
Takoyaki.getInstance().getLogger().warning(" : " + errors.text());
}
this.close();
}
public Document parse(String url) throws IOException {
return this.parse(new URL(url));
}
public Document parse(URL url) throws IOException {
final String html = this.getPage(url).getWebResponse().getContentAsString();
this.close();
return Jsoup.parse(html);
}
}
|
package com.haulmont.cuba.gui.app.core.showinfo;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.cuba.core.entity.*;
import com.haulmont.cuba.core.global.MessageProvider;
import com.haulmont.cuba.gui.data.impl.CollectionDatasourceImpl;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.UUID;
/**
* @author artamonov
* @version $Id$
*/
public class EntityParamsDatasource extends CollectionDatasourceImpl<KeyValueEntity, UUID> {
private Entity instance;
private MetaClass instanceMetaClass;
@Override
protected void loadData(Map<String, Object> params) {
if ((instance != null) && (instanceMetaClass != null)) {
data.clear();
compileInfo();
}
}
private void compileInfo() {
Class<?> javaClass = instanceMetaClass.getJavaClass();
includeParam("table.showInfoAction.entityName", instanceMetaClass.getName());
includeParam("table.showInfoAction.entityClass", javaClass.getName());
javax.persistence.Table annotation = javaClass.getAnnotation(javax.persistence.Table.class);
if (annotation != null)
includeParam("table.showInfoAction.entityTable", annotation.name());
if (instance != null) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
includeParam("table.showInfoAction.id", instance.getId().toString());
if (instance instanceof Versioned && ((Versioned) instance).getVersion() != null) {
Integer version = ((Versioned) instance).getVersion();
includeParam("table.showInfoAction.version", version.toString());
}
if (instance instanceof BaseEntity) {
BaseEntity baseEntity = (BaseEntity) instance;
if (baseEntity.getCreateTs() != null)
includeParam("table.showInfoAction.createTs", df.format(((BaseEntity) instance).getCreateTs()));
if (baseEntity.getCreatedBy() != null)
includeParam("table.showInfoAction.createdBy", baseEntity.getCreatedBy());
}
if (instance instanceof Updatable) {
Updatable updatableEntity = (Updatable) instance;
if (updatableEntity.getUpdateTs() != null)
includeParam("table.showInfoAction.updateTs", df.format(updatableEntity.getUpdateTs()));
if (updatableEntity.getUpdatedBy() != null)
includeParam("table.showInfoAction.updatedBy", updatableEntity.getUpdatedBy());
}
if (instance instanceof SoftDelete) {
SoftDelete softDeleteEntity = (SoftDelete) instance;
if (softDeleteEntity.getDeleteTs() != null)
includeParam("table.showInfoAction.deleteTs", df.format(softDeleteEntity.getDeleteTs()));
if (softDeleteEntity.getDeletedBy() != null)
includeParam("table.showInfoAction.deletedBy", softDeleteEntity.getDeletedBy());
}
}
}
private void includeParam(String messageKey, String value) {
KeyValueEntity keyValueEntity = new KeyValueEntity(MessageProvider.getMessage(getClass(), messageKey), value);
data.put(keyValueEntity.getId(), keyValueEntity);
}
public Entity getInstance() {
return instance;
}
public void setInstance(Entity instance) {
this.instance = instance;
}
public MetaClass getInstanceMetaClass() {
return instanceMetaClass;
}
public void setInstanceMetaClass(MetaClass instanceMetaClass) {
this.instanceMetaClass = instanceMetaClass;
}
}
|
//This is me testing a thing
package Factory;
//This is me testing another thing
import java.awt.Dimension;
import java.awt.Toolkit;
public class Launcher {
public static void main(String [] args){
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
Game game = new Game("The Factory", (int)width, (int)height);
game.start(); }
}
|
package heufybot.modules;
import heufybot.utils.StringUtils;
import java.util.List;
import java.util.Random;
public class Choose extends Module
{
public Choose()
{
this.authType = AuthType.Anyone;
this.apiVersion = "0.5.0";
this.triggerTypes = new TriggerType[] { TriggerType.Message };
this.trigger = "^" + commandPrefix + "(choose|choice)($| .*)";
}
@Override
public void processEvent(String source, String message, String triggerUser, List<String> params)
{
if (params.size() == 1)
{
bot.getIRC().cmdPRIVMSG(source, "Choose what?");
}
else
{
params.remove(0);
String[] choices = new String[0];
if(message.contains(","))
{
choices = StringUtils.parseStringtoList(StringUtils.join(params, " "), ",").toArray(choices);
}
else if(message.contains(" "))
{
choices = params.toArray(choices);
}
else
{
choices = new String[] { params.get(0) };
}
for(int i = 0; i < choices.length; i++)
{
choices[i] = choices[i].trim();
}
Random random = new Random();
int choiceNumber = random.nextInt(choices.length);
bot.getIRC().cmdPRIVMSG(source, "Choice: " + choices[choiceNumber]);
}
}
public String getHelp(String message)
{
return "Commands: " + commandPrefix + "choose <choice1>, <choice2> | Makes the bot choose one of the given options at random.";
}
@Override
public void onLoad()
{
}
@Override
public void onUnload()
{
}
}
|
package com.danchu.momuck.controller;
import static org.hamcrest.Matchers.hasKey;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.danchu.momuck.dao.AccountDao;
import com.danchu.momuck.dao.RestaurantDao;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:/root-context.xml", "classpath:servlet-context.xml" })
public class RestaurantControllerTest {
private static final String NAME = " ";
private static final float AVG_SCORE = 0;
private static final String LOCATION_COORD = "0,0";
private static final String LOCATION_TEXT = " ";
private static final String PHONE_NUMBER = "010-4444-4444";
private static final String IMAGE_MAIN = "test.jpg";
private static final String IMAGE_EXTRA = "test_extra.jpg";
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Autowired
private RestaurantDao restaurantDao;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void insertRestaurant() throws Exception {
String jsonParm = "{" + "\"name\" : \"" + NAME + "\"," + "\"avg_score\" : " + AVG_SCORE + "," + "\"location_coord\" : \""
+ LOCATION_COORD + "\"," + "\"location_text\" : \"" + LOCATION_TEXT + "\"," + "\"phone_number\" : \""
+ PHONE_NUMBER + "\"," + "\"image_main\" : \"" + IMAGE_MAIN + "\","+ "\"image_extra\" : \"" + IMAGE_EXTRA + "\"}";
this.mockMvc.perform(post("/restaurants").contentType(MediaType.APPLICATION_JSON).content(jsonParm))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$", hasKey("code")))
.andExpect(jsonPath("$.code").value("200"))
.andReturn();
}
@Test
public void selectRestaurant() throws Exception {
this.mockMvc.perform(get("/restaurants/{restaurant_id}", 7).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$", hasKey("code")))
.andExpect(jsonPath("$.code").value("200"))
.andReturn();
}
@After
public void clear() {
restaurantDao.deleteRestaurant(NAME);
}
}
|
package group5.trackerexpress;
import java.util.ArrayList;
import java.util.UUID;
import android.content.Context;
// TODO: Auto-generated Javadoc
/**
* The Class Claim.
*/
public class Claim extends TModel implements Comparable<Claim>{
/** The user name. */
private String userName;
/** The claim name. */
private String claimName;
/** The Description. */
private String Description;
/** The expense list. */
private ExpenseList expenseList;
/** The destination. */
private ArrayList<String[]> destination = new ArrayList<String[]>();
/** The status. */
private int status;
/** The start date. */
private Date startDate;
/** The end date. */
private Date endDate;
/** The incomplete. */
private boolean incomplete;
private ArrayList<UUID> tagsIds;
/** The Constant IN_PROGRESS. */
public static final int IN_PROGRESS = 0;
/** The Constant SUBMITTED. */
public static final int SUBMITTED = 1;
/** The Constant RETURNED. */
public static final int RETURNED = 2;
/** The Constant APPROVED. */
public static final int APPROVED = 3;
/** The uuid. */
private UUID uuid = UUID.randomUUID();
/**
* Instantiates a new claim.
*
* @param claimName the claim name
*/
public Claim(String claimName) {
// TODO Auto-generated constructor stub
this.claimName = claimName;
this.expenseList = new ExpenseList();
this.status = IN_PROGRESS;
}
/**
* Checks if is incomplete.
*
* @return true, if is incomplete
*/
public boolean isIncomplete() {
return incomplete;
}
/**
* Sets the incomplete.
*
* @param context the context
* @param incomplete the incomplete
*/
public void setIncomplete(Context context, boolean incomplete) {
this.incomplete = incomplete;
notifyViews(context);
}
/**
* Gets the uuid.
*
* @return the uuid
*/
public UUID getUuid() {
return uuid;
}
/**
* Sets the uuid.
*
* @param context the context
* @param uuid the uuid
*/
public void setUuid(Context context, UUID uuid) {
this.uuid = uuid;
notifyViews(context);
}
/**
* Gets the user name.
*
* @return the user name
*/
public String getuserName(){
return userName;
}
/**
* Setuser name.
*
* @param context the context
* @param userName the user name
*/
public void setuserName(Context context, String userName){
this.userName = userName;
notifyViews(context);
}
/**
* Gets the claim name.
*
* @return the claim name
*/
public String getClaimName() {
return claimName;
}
/**
* Sets the claim name.
*
* @param context the context
* @param claimName the claim name
*/
public void setClaimName(Context context, String claimName) {
this.claimName = claimName;
notifyViews(context);
}
/**
* Adds the expense.
*
* @param context the context
* @param expense the expense
*/
public void addExpense(Context context, Expense expense) {
expenseList.addExpense(expense);
notifyViews(context);
}
/**
* Gets the expense list.
*
* @return the expense list
*/
public ExpenseList getExpenseList() {
return expenseList;
}
/**
* Sets the expense list.
*
* @param context the context
* @param expenseList the expense list
*/
public void setExpenseList(Context context, ExpenseList expenseList) {
this.expenseList = expenseList;
notifyViews(context);
}
/**
* Removes the expense.
*
* @param context the context
* @param expenseUuid the expense uuid
*/
public void removeExpense(Context context, UUID expenseUuid) {
// TODO Auto-generated method stub
expenseList.deleteExpense(expenseUuid);
//expenseList.remove(expenseList.indexOf(string));
notifyViews(context);
}
/**
* Sets the start date.
*
* @param context the context
* @param d1 the d1
*/
public void setStartDate(Context context, Date d1) {
// TODO Auto-generated method stub
this.startDate = d1;
notifyViews(context);
}
/**
* Gets the start date.
*
* @return the start date
*/
public Date getStartDate() {
return startDate;
}
/**
* Sets the end date.
*
* @param context the context
* @param d2 the d2
*/
public void setEndDate(Context context, Date d2){
this.endDate = d2;
notifyViews(context);
}
/**
* Gets the end date.
*
* @return the end date
*/
public Date getEndDate() {
return endDate;
}
/**
* Adds the destination.
*
* @param context the context
* @param place the place
* @param Reason the reason
*/
public void addDestination(Context context, String place, String Reason){
String[] travelInfo = new String[2];
travelInfo[0] = place;
travelInfo[1] = Reason;
destination.add(travelInfo);
notifyViews(context);
}
/**
* Sets the destination.
*
* @param context the context
* @param destination the destination
*/
public void setDestination(Context context, ArrayList<String[]> destination) {
this.destination = destination;
notifyViews(context);
}
/**
* To string destinations.
*
* @return the string
*/
public String toStringDestinations(){
// Get the destinations in a list format
String str_destinations = "";
for ( int i = 0; i < destination.size() - 1; i++ ){
str_destinations += destination.get(i)[0] + ", ";
}
if (destination.size()>0)
str_destinations += destination.get(destination.size() - 1)[0];
return str_destinations;
}
/**
* Gets the destination.
*
* @return the destination
*/
public ArrayList<String[]> getDestination() {
return destination;
}
/**
* Sets the description.
*
* @param context the context
* @param Description the description
*/
public void setDescription(Context context, String Description){
this.Description = Description;
notifyViews(context);
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription(){
return Description;
}
/**
* Sets the status.
*
* @param context the context
* @param status the status
*/
public void setStatus(Context context, int status) {
this.status = status;
notifyViews(context);
}
/**
* Gets the status.
*
* @return the status
*/
public int getStatus() {
return status;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Claim arg0) {
if (startDate == null){
return -1;
}
return startDate.compareTo(arg0.getStartDate());
}
public ArrayList<UUID> getTagsIds() {
return tagsIds;
}
public void setTagsIds(ArrayList<UUID> tagsIds) {
this.tagsIds = tagsIds;
}
}
|
package org.gbif.occurrence.search.es;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.bucket.filter.Filter;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.gbif.api.model.common.Identifier;
import org.gbif.api.model.common.MediaObject;
import org.gbif.api.model.common.paging.Pageable;
import org.gbif.api.model.common.search.Facet;
import org.gbif.api.model.common.search.SearchResponse;
import org.gbif.api.model.occurrence.Occurrence;
import org.gbif.api.model.occurrence.OccurrenceRelation;
import org.gbif.api.model.occurrence.search.OccurrenceSearchParameter;
import org.gbif.api.model.occurrence.search.OccurrenceSearchRequest;
import org.gbif.api.vocabulary.*;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.gbif.occurrence.search.es.EsQueryUtils.DATE_FORMAT;
import static org.gbif.occurrence.search.es.EsQueryUtils.ES_TO_SEARCH_MAPPING;
import static org.gbif.occurrence.search.es.OccurrenceEsField.*;
public class EsResponseParser {
private EsResponseParser() {}
/**
* Builds a SearchResponse instance using the current builder state.
*
* @return a new instance of a SearchResponse.
*/
static SearchResponse<Occurrence, OccurrenceSearchParameter> buildResponse(
org.elasticsearch.action.search.SearchResponse esResponse, OccurrenceSearchRequest request) {
SearchResponse<Occurrence, OccurrenceSearchParameter> response = new SearchResponse<>(request);
response.setCount(esResponse.getHits().getTotalHits());
parseHits(esResponse).ifPresent(response::setResults);
parseFacets(esResponse, request).ifPresent(response::setFacets);
return response;
}
private static Optional<List<Facet<OccurrenceSearchParameter>>> parseFacets(
org.elasticsearch.action.search.SearchResponse esResponse, OccurrenceSearchRequest request) {
if (esResponse.getAggregations() == null) {
return Optional.empty();
}
return Optional.of(
esResponse
.getAggregations()
.asList()
.stream()
.map(
aggs -> {
// get buckets
List<? extends Terms.Bucket> buckets = null;
if (aggs instanceof Terms) {
buckets = ((Terms) aggs).getBuckets();
} else if (aggs instanceof Filter) {
buckets =
((Filter) aggs)
.getAggregations()
.asList()
.stream()
.flatMap(agg -> ((Terms) agg).getBuckets().stream())
.collect(Collectors.toList());
} else {
throw new IllegalArgumentException(
aggs.getClass() + " aggregation not supported");
}
// get facet of the agg
OccurrenceSearchParameter facet = ES_TO_SEARCH_MAPPING.get(aggs.getName());
// check for paging in facets
Pageable facetPage = request.getFacetPage(facet);
if (facetPage != null && facetPage.getOffset() < buckets.size()) {
// take only the buckets requested according to the paging params
buckets =
buckets.subList(
(int) facetPage.getOffset(),
(int)
Math.min(
facetPage.getOffset() + facetPage.getLimit(), buckets.size()));
}
// set counts
List<Facet.Count> counts = new ArrayList<>(buckets.size());
buckets.forEach(
bucket ->
counts.add(
new Facet.Count(bucket.getKeyAsString(), bucket.getDocCount())));
// build facet response
Facet<OccurrenceSearchParameter> facetResult = new Facet<>(facet);
facetResult.setCounts(counts);
return facetResult;
})
.collect(Collectors.toList()));
}
private static Optional<List<Occurrence>> parseHits(
org.elasticsearch.action.search.SearchResponse esResponse) {
if (esResponse.getHits() == null
|| esResponse.getHits().getHits() == null
|| esResponse.getHits().getHits().length == 0) {
return Optional.empty();
}
final DateFormat dateFormat =
new SimpleDateFormat("yyyy-MM-dd"); // Quoted "Z" to indicate UTC, no timezone offset
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
SearchHits hits = esResponse.getHits();
List<Occurrence> occurrences = new ArrayList<>();
hits.forEach(
hit -> {
// create occurrence
Occurrence occ = new Occurrence();
occurrences.add(occ);
// fill out fields
getValue(hit, GBIF_ID, Integer::valueOf).ifPresent(occ::setKey);
getValue(hit, BASIS_OF_RECORD, BasisOfRecord::valueOf).ifPresent(occ::setBasisOfRecord);
getValue(hit, CONTINENT).ifPresent(v -> occ.setContinent(Continent.valueOf(v)));
getValue(hit, COORDINATE_ACCURACY, Double::valueOf).ifPresent(occ::setCoordinateAccuracy);
getValue(hit, COORDINATE_PRECISION, Double::valueOf)
.ifPresent(occ::setCoordinatePrecision);
getValue(hit, COORDINATE_UNCERTAINTY_METERS, Double::valueOf)
.ifPresent(occ::setCoordinateUncertaintyInMeters);
getValue(hit, COUNTRY, v -> Country.valueOf(v.toUpperCase())).ifPresent(occ::setCountry);
// TODO: date identified shouldnt be a timestamp
getValue(hit, DATE_IDENTIFIED, v -> new Date(Long.valueOf(v)))
.ifPresent(occ::setDateIdentified);
getValue(hit, DAY, Integer::valueOf).ifPresent(occ::setDay);
getValue(hit, MONTH, Integer::valueOf).ifPresent(occ::setMonth);
getValue(hit, YEAR, Integer::valueOf).ifPresent(occ::setYear);
getValue(hit, LATITUDE, Double::valueOf).ifPresent(occ::setDecimalLatitude);
getValue(hit, LONGITUDE, Double::valueOf).ifPresent(occ::setDecimalLongitude);
getValue(hit, DEPTH, Double::valueOf).ifPresent(occ::setDepth);
getValue(hit, DEPTH_ACCURACY, Double::valueOf).ifPresent(occ::setDepthAccuracy);
getValue(hit, ELEVATION, Double::valueOf).ifPresent(occ::setElevation);
getValue(hit, ELEVATION_ACCURACY, Double::valueOf).ifPresent(occ::setElevationAccuracy);
getValue(hit, ESTABLISHMENT_MEANS, EstablishmentMeans::valueOf)
.ifPresent(occ::setEstablishmentMeans);
// FIXME: should we have a list of identifiers in the schema?
getValue(hit, IDENTIFIER)
.ifPresent(
v -> {
Identifier identifier = new Identifier();
identifier.setIdentifier(v);
occ.setIdentifiers(Collections.singletonList(identifier));
});
getValue(hit, INDIVIDUAL_COUNT, Integer::valueOf).ifPresent(occ::setIndividualCount);
getValue(hit, LICENSE, License::valueOf).ifPresent(occ::setLicense);
getValue(hit, ELEVATION, Double::valueOf).ifPresent(occ::setElevation);
// TODO: facts??
// issues
getValueList(hit, ISSUE)
.ifPresent(
v -> {
Set<OccurrenceIssue> issues = new HashSet<>();
v.forEach(issue -> issues.add(OccurrenceIssue.valueOf(issue)));
occ.setIssues(issues);
});
// FIXME: should we have a list in the schema and all the info of the enum?
getValue(hit, RELATION)
.ifPresent(
v -> {
OccurrenceRelation occRelation = new OccurrenceRelation();
occRelation.setId(v);
occ.setRelations(Collections.singletonList(occRelation));
});
getValue(hit, LAST_INTERPRETED, v -> DATE_FORMAT.apply(v, dateFormat))
.ifPresent(occ::setLastInterpreted);
getValue(hit, LAST_CRAWLED, v -> DATE_FORMAT.apply(v, dateFormat))
.ifPresent(occ::setLastCrawled);
getValue(hit, LAST_PARSED, v -> DATE_FORMAT.apply(v, dateFormat))
.ifPresent(occ::setLastParsed);
getValue(hit, EVENT_DATE, v -> DATE_FORMAT.apply(v, dateFormat))
.ifPresent(occ::setEventDate);
getValue(hit, LIFE_STAGE, LifeStage::valueOf).ifPresent(occ::setLifeStage);
// TODO: modified shouldnt be a timestamp
getValue(hit, MODIFIED, v -> new Date(Long.valueOf(v))).ifPresent(occ::setModified);
getValue(hit, REFERENCES, URI::create).ifPresent(occ::setReferences);
getValue(hit, SEX, Sex::valueOf).ifPresent(occ::setSex);
getValue(hit, STATE_PROVINCE).ifPresent(occ::setStateProvince);
getValue(hit, TYPE_STATUS, TypeStatus::valueOf).ifPresent(occ::setTypeStatus);
getValue(hit, WATER_BODY).ifPresent(occ::setWaterBody);
getValue(hit, TYPIFIED_NAME).ifPresent(occ::setTypifiedName);
// taxon
getValue(hit, KINGDOM_KEY, Integer::valueOf).ifPresent(occ::setKingdomKey);
getValue(hit, KINGDOM).ifPresent(occ::setKingdom);
getValue(hit, PHYLUM_KEY, Integer::valueOf).ifPresent(occ::setPhylumKey);
getValue(hit, PHYLUM).ifPresent(occ::setPhylum);
getValue(hit, CLASS_KEY, Integer::valueOf).ifPresent(occ::setClassKey);
getValue(hit, CLASS).ifPresent(occ::setClazz);
getValue(hit, ORDER_KEY, Integer::valueOf).ifPresent(occ::setOrderKey);
getValue(hit, ORDER).ifPresent(occ::setOrder);
getValue(hit, FAMILY_KEY, Integer::valueOf).ifPresent(occ::setFamilyKey);
getValue(hit, FAMILY).ifPresent(occ::setFamily);
getValue(hit, GENUS_KEY, Integer::valueOf).ifPresent(occ::setGenusKey);
getValue(hit, GENUS).ifPresent(occ::setGenus);
getValue(hit, SUBGENUS_KEY, Integer::valueOf).ifPresent(occ::setSubgenusKey);
getValue(hit, SUBGENUS).ifPresent(occ::setSubgenus);
getValue(hit, SPECIES_KEY, Integer::valueOf).ifPresent(occ::setSpeciesKey);
getValue(hit, SPECIES).ifPresent(occ::setSpecies);
getValue(hit, SCIENTIFIC_NAME).ifPresent(occ::setScientificName);
getValue(hit, SPECIFIC_EPITHET).ifPresent(occ::setSpecificEpithet);
getValue(hit, INFRA_SPECIFIC_EPITHET).ifPresent(occ::setInfraspecificEpithet);
getValue(hit, GENERIC_NAME).ifPresent(occ::setGenericName);
getValue(hit, TAXON_RANK).ifPresent(v -> occ.setTaxonRank(Rank.valueOf(v)));
getValue(hit, TAXON_KEY, Integer::valueOf).ifPresent(occ::setTaxonKey);
// multimedia
// TODO: change when we have the full info about multimedia
getValue(hit, MEDIA_TYPE)
.ifPresent(
mediaType -> {
MediaObject mediaObject = new MediaObject();
// media type has to be compared ignoring the case
Arrays.stream(MediaType.values())
.filter(v -> v.name().equalsIgnoreCase(mediaType))
.findFirst()
.ifPresent(mediaObject::setType);
occ.setMedia(Collections.singletonList(mediaObject));
});
getValue(hit, PUBLISHING_COUNTRY, v -> Country.fromIsoCode(v.toUpperCase()))
.ifPresent(occ::setPublishingCountry);
getValue(hit, DATASET_KEY, UUID::fromString).ifPresent(occ::setDatasetKey);
getValue(hit, INSTALLATION_KEY, UUID::fromString).ifPresent(occ::setInstallationKey);
getValue(hit, PUBLISHING_ORGANIZATION_KEY, UUID::fromString)
.ifPresent(occ::setPublishingOrgKey);
getValue(hit, CRAWL_ID, Integer::valueOf).ifPresent(occ::setCrawlId);
getValue(hit, PROTOCOL, EndpointType::fromString).ifPresent(occ::setProtocol);
// FIXME: shouldn't networkkey be a list in the schema?
getValue(hit, NETWORK_KEY)
.ifPresent(v -> occ.setNetworkKeys(Collections.singletonList(UUID.fromString(v))));
});
return Optional.of(occurrences);
}
private static Optional<String> getValue(SearchHit hit, OccurrenceEsField esField) {
return getValue(hit, esField, Function.identity());
}
private static <T> Optional<T> getValue(
SearchHit hit, OccurrenceEsField esField, Function<String, T> mapper) {
return Optional.ofNullable(hit.getSourceAsMap().get(esField.getFieldName()))
.map(String::valueOf)
.filter(v -> !v.isEmpty())
.map(mapper);
}
private static Optional<List<String>> getValueList(SearchHit hit, OccurrenceEsField esField) {
return Optional.ofNullable(hit.getSourceAsMap().get(esField.getFieldName()))
.map(v -> (List<String>) v)
.filter(v -> !v.isEmpty());
}
}
|
import java.util.*;
import java.lang.Math;
import java.io.FileReader;
import java.io.BufferedReader;
/**
* Stores all levels of the brick breaker game.
* With methods to load the levels into an arrayList of Bricks, and add them to the GameArena
*/
public class BrickBreakerLevels{
private List<Brick> bricks;
/**
* Basic constructor
* @param bs The arrayList of bricks which the game is using
*/
public BrickBreakerLevels(List<Brick> bs){
bricks = bs;
}
private void level_1(GameArena ga){
//bricks.add( new Brick( ) );
/**
* Loads levels onto the GameArena
* @param level The level to load
* @param gameWindow The GameArena to load the level onto.
*/
public void load(int level, GameArena gameWindow){
boolean validLevel;
switch (level){
case -1: level_lose(gameWindow); validLevel = true;
break;
case 0: level_win(gameWindow); validLevel = true;
break;
case 1: level_1(gameWindow); validLevel = true;
break;
case 2: level_2(gameWindow); validLevel = true;
break;
default: validLevel = false;
}
if(validLevel){
for(int i = 0; i<bricks.size(); i++){
bricks.get(i).addBrick(gameWindow);
}
}else{
System.out.print("Invalid level loaded");
System.exit(0);
};
}
}
|
package nakadi;
import java.util.Map;
/**
* Supports API operations related to subscriptions.
*/
public interface SubscriptionResource {
/**
* Set the OAuth scope to be used for the request. This can be reset between requests.
*
* @param scope the OAuth scope to be used for the request
* @return this
*/
SubscriptionResource scope(String scope);
/**
* Set the retry policy to be used for the request. This can be reset between requests. Setting
* it to null (the default) disables retries.
*
* @param retryPolicy the retry policy
* @return this
*/
SubscriptionResource retryPolicy(RetryPolicy retryPolicy);
/**
* Create a new subscription on the server.
*
* @param subscription the new subscription
* @return the response result
* @throws AuthorizationException unauthorised
* @throws ClientException for a 400 or generic client error
* @throws ServerException for a 400 or generic client error
* @throws InvalidException for a 422
* @throws RateLimitException for a 429
* @throws ConflictException for a 409
* @throws NakadiException for a general exception
*/
Response create(Subscription subscription)
throws AuthorizationException, ClientException, ServerException, InvalidException,
RateLimitException, ConflictException, NakadiException;
/**
* Find a subscription by id.
*
* @param id the subscription id
* @return the subscription result
* @throws AuthorizationException unauthorised
* @throws ClientException for a 400 or generic client error
* @throws ServerException for a 400 or generic client error
* @throws InvalidException for a 422
* @throws RateLimitException for a 429
* @throws NotFoundException for a 404
* @throws NakadiException for a general exception
*/
Subscription find(String id)
throws AuthorizationException, ClientException, ServerException, InvalidException,
RateLimitException, NotFoundException, NakadiException;
/**
* List the subscriptions on the server.
*
* @return a list that will automatically page when iterated.
* @throws AuthorizationException unauthorised
* @throws ClientException for a 400 or generic client error
* @throws ServerException for a 400 or generic client error
* @throws InvalidException for a 422
* @throws RateLimitException for a 429
* @throws NotFoundException for a 404
* @throws NakadiException for a general exception
*/
SubscriptionCollection list()
throws AuthorizationException, ClientException, ServerException, InvalidException,
RateLimitException, NotFoundException, NakadiException;
/**
* List the subscriptions on the server according to query optipns.
*
* @return a list that will automatically page when iterated.
* @throws AuthorizationException unauthorised
* @throws ClientException for a 400 or generic client error
* @throws ServerException for a 400 or generic client error
* @throws InvalidException for a 422
* @throws RateLimitException for a 429
* @throws NotFoundException for a 404
* @throws NakadiException for a general exception
*/
SubscriptionCollection list(QueryParams params)
throws AuthorizationException, ClientException, ServerException, InvalidException,
RateLimitException, NakadiException;
/**
* Delete a subscription by id.
*
* @param id the subscription id
* @return the response
* @throws AuthorizationException unauthorised
* @throws ClientException for a 400 or generic client error
* @throws ServerException for a 400 or generic client error
* @throws InvalidException for a 422
* @throws RateLimitException for a 429
* @throws NotFoundException for a 404
* @throws NakadiException for a general exception
*/
Response delete(String id)
throws AuthorizationException, ClientException, ServerException, InvalidException,
RateLimitException, NotFoundException, NakadiException;
/**
* Commit a checkpoint.
*
* @param context contains the stream id header and subscription id.
* @param cursors the cursors to commit
* @return the result
* @throws AuthorizationException unauthorised
* @throws ClientException for a 400 or generic client error
* @throws ServerException for a 400 or generic client error
* @throws InvalidException for a 422
* @throws RateLimitException for a 429
* @throws NotFoundException for a 404
* @throws ContractException for a "successful" request but which does not follow the api
* @throws NakadiException for a general exception
*/
CursorCommitResultCollection checkpoint(Map<String, String> context, Cursor... cursors)
throws AuthorizationException, ClientException, ServerException, InvalidException,
RateLimitException, NotFoundException, NakadiException;
/**
* Find the cursors for a subscription.
*
* @param id the subscription id
* @return the response as a collection of cursors
* @throws AuthorizationException unauthorised
* @throws ClientException for a 400 or generic client error
* @throws ServerException for a 400 or generic client error
* @throws InvalidException for a 422
* @throws RateLimitException for a 429
* @throws NotFoundException for a 404
* @throws NakadiException for a general exception
*/
SubscriptionCursorCollection cursors(String id)
throws AuthorizationException, ClientException, ServerException, InvalidException,
RateLimitException, NotFoundException, NakadiException;
/**
* The stats for a subscription.
*
* @param id the subscription id
* @return the response as a collection of cursors
* @throws AuthorizationException unauthorised
* @throws ClientException for a 400 or generic client error
* @throws ServerException for a 400 or generic client error
* @throws InvalidException for a 422
* @throws RateLimitException for a 429
* @throws NotFoundException for a 404
* @throws NakadiException for a general exception
*/
SubscriptionEventTypeStatsCollection stats(String id)
throws AuthorizationException, ClientException, ServerException, InvalidException,
RateLimitException, NotFoundException, NakadiException;
}
|
package jlibs.nblr.codegen.java;
import jlibs.core.lang.StringUtil;
import jlibs.nblr.Syntax;
import jlibs.nblr.codegen.CodeGenerator;
import jlibs.nblr.matchers.Any;
import jlibs.nblr.matchers.Matcher;
import jlibs.nblr.matchers.Not;
import jlibs.nblr.rules.*;
import jlibs.nbp.NBParser;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import static jlibs.core.annotation.processing.Printer.MINUS;
import static jlibs.core.annotation.processing.Printer.PLUS;
/**
* @author Santhosh Kumar T
*/
public class JavaCodeGenerator extends CodeGenerator{
public JavaCodeGenerator(Syntax syntax){
super(syntax);
}
@Override
protected void printTitleComment(String title){
printer.println("");
}
@Override
protected void startParser(){
String className[] = className(parserName);
if(className[0].length()>0){
printer.printlns(
"package"+(finalParser ? " final " :" ")+className[0]+";",
""
);
}
printer.printClassDoc();
printer.printlns(
"public class "+className[1]+" extends "+superClass.getName()+"{",
PLUS
);
}
private String[] className(String className){
String pakage = "";
String simpleName = className;
int dot = simpleName.lastIndexOf('.');
if(dot!=-1){
pakage = simpleName.substring(0, dot);
simpleName = simpleName.substring(dot+1);
}
return new String[]{ pakage, simpleName };
}
@Override
protected void finishParser(int maxLookAhead){
String className = className(parserName)[1];
String debuggerArgs = debuggable ? "handler, " : "";
printer.emptyLine(true);
printer.printlns(
"@Override",
"public void onSuccessful() throws Exception{",
PLUS,
"handler.onSuccessful();",
MINUS,
"}",
"",
"@Override",
"public void fatalError(String message) throws Exception{",
PLUS,
"handler.fatalError(message);",
MINUS,
"}",
"",
"protected final "+ handlerName +" handler;",
"public "+className+"("+ handlerName +" handler, int startingRule){",
PLUS,
"super("+debuggerArgs+maxLookAhead+", startingRule);",
"this.handler = handler;",
MINUS,
"}",
MINUS,
"}"
);
}
@Override
protected void printMatcherMethod(Matcher matcher){
if(!matcher.canInline()){
printer.printlns(
"private static boolean "+matcher.name+"(int ch){",
PLUS,
"return "+matcher.javaCode("ch")+';',
MINUS,
"}"
);
}
}
@Override
protected void addRuleID(String name, int id){
printer.println("public static final int RULE_"+name.toUpperCase()+" = "+id+';');
}
@Override
protected void startRuleMethod(Rule rule){
printer.printlns(
"private boolean "+rule.name+"() throws Exception{",
PLUS,
"int state = stack[free-1];",
"while(true){",
PLUS,
"int ch;",
"if(stop || (ch=codePoint())==EOC){",
PLUS,
"stack[free-1] = state;",
"return false;",
MINUS,
"}",
"",
"switch(state){",
PLUS
);
}
@Override
protected void startCase(int id){
printer.printlns(
"case "+id+":",
PLUS
);
}
@Override
protected void endCase(){
printer.printlns(
MINUS
);
}
@Override
protected void finishRuleMethod(Rule rule){
printer.printlns(
"default:",
PLUS,
"throw new Error(\"impossible state: \"+state);",
MINUS,
MINUS,
"}",
MINUS,
"}",
MINUS,
"}"
);
}
@Override
protected void startCallRuleMethod(){
String prefix = debuggable ? "_" : "";
printer.printlns(
"@Override",
"protected final boolean "+prefix+"callRule() throws Exception{",
PLUS,
"if(SHOW_STATS)",
PLUS,
"callRuleCount++;",
MINUS,
"switch(stack[free-2]){",
PLUS
);
}
@Override
protected void callRuleMethod(String ruleName){
printer.println("return "+ruleName+"();");
}
@Override
protected void finishCallRuleMethod(){
printer.printlns(
"default:",
PLUS,
"throw new Error(\"impossible rule: \"+stack[free-2]);",
MINUS,
MINUS,
"}",
MINUS,
"}"
);
}
private Rule curRule;
@Override
protected void addRoutes(Routes routes){
curRule = routes.rule;
String expected = "expected(ch, \""+ StringUtil.toLiteral(routes.toString(), false)+"\");";
boolean lookAheadBufferReqd = routes.maxLookAhead>1;
if(lookAheadBufferReqd)
printer.printlns("addToLookAhead(ch);");
for(int lookAhead: routes.lookAheads()){
if(lookAheadBufferReqd){
printer.printlns(
"if(ch!=EOF && lookAhead.length()<"+lookAhead+")",
PLUS,
"continue;",
MINUS
);
printer.printlns(
"if(lookAhead.length()=="+lookAhead+"){",
PLUS
);
}
print(routes.determinateRoutes(lookAhead), 1 ,lookAheadBufferReqd);
if(lookAheadBufferReqd){
printer.printlns(
MINUS,
"}"
);
}
}
if(routes.indeterminateRoute !=null){
Path path = routes.indeterminateRoute.route()[0];
Matcher matcher = path.matcher();
startIf(matcher, 0);
consumeLAFirst = false;
consumeLALen = 0;
Destination dest = _travelPath(curRule, path, true);
println("lookAhead.reset();");
returnDestination(dest);
endIf(1);
}
if(routes.routeStartingWithEOF!=null)
travelPath(routes.routeStartingWithEOF, false);
else
printer.println(expected);
}
private void print(List<Path> routes, int depth, boolean consumeLookAhead){
List<List<Path>> groups = new ArrayList<List<Path>>();
Matcher matcher = null;
for(Path route: routes){
Path path = route.route()[depth-1];
Matcher curMatcher = path.matcher();
if(curMatcher==null)
curMatcher = eofMatcher;
if(matcher==null || !curMatcher.same(matcher)){
groups.add(new ArrayList<Path>());
matcher = curMatcher;
}
groups.get(groups.size()-1).add(route);
}
for(List<Path> group: groups){
Path route = group.get(0);
matcher = route.route()[depth-1].matcher();
boolean endIf = false;
if(matcher!=null){
int lookAheadIndex = route.depth>1 && depth!=route.depth ? depth-1 : -1;
startIf(matcher, lookAheadIndex);
endIf = true;
}
if(depth<routes.get(0).depth)
print(group, depth+1, consumeLookAhead);
if(depth==route.depth)
travelRoute(route, consumeLookAhead);
if(endIf)
endIf(1);
}
}
private void startIf(Matcher matcher, int lookAheadIndex){
String ch = lookAheadIndex==-1 ? "ch" : "lookAhead.charAt("+lookAheadIndex+')';
String condition = matcher._javaCode(ch);
Not.minValue = -1;
try{
if(lookAheadIndex==-1 && (matcher.hasCustomJavaCode() || matcher.clashesWith(new Any(-1)))){
if(matcher.name==null)
condition = '('+condition+')';
condition = "ch!=EOF && "+condition;
}
}finally{
Not.minValue = Character.MIN_VALUE;
}
printer.printlns(
"if("+condition+"){",
PLUS
);
}
private void endIf(int count){
while(count
printer.printlns(
MINUS,
"}"
);
}
}
private StringBuilder nodesToBeExecuted = new StringBuilder();
private int consumeLALen = 0;
private boolean consumeLAFirst = false;
private void printlnConsumeLA(){
if(consumeLALen>0){
if(consumeLALen==1)
printer.println("consume(FROM_LA);");
else
printer.println("consumeLookAhead("+consumeLALen+");");
}
}
private void println(String line){
if(consumeLAFirst)
printlnConsumeLA();
if(nodesToBeExecuted.length()>0){
printer.println("handler.execute(stack[free-2], "+nodesToBeExecuted+");");
nodesToBeExecuted.setLength(0);
}
if(!consumeLAFirst)
printlnConsumeLA();
printer.println(line);
consumeLAFirst = false;
consumeLALen = 0;
}
private void travelRoute(Path route, boolean consumeLookAhead){
consumeLAFirst = false;
consumeLALen = 0;
Destination dest = new Destination(consumeLookAhead, curRule, null);
for(Path path: route.route())
dest = _travelPath(dest.rule, path, consumeLookAhead);
returnDestination(dest);
}
private void travelPath(Path path, boolean consumeLookAhead){
consumeLAFirst = false;
consumeLALen = 0;
Destination dest = _travelPath(curRule, path, consumeLookAhead);
returnDestination(dest);
}
private void returnDestination(Destination dest){
int state = dest.state();
if(state<0){
if(state==-2 && !dest.consumedFromLookAhead)
println("consume(ch);");
println("stack[free-1] = -1;");
println("return true;");
}else if(dest.rule==curRule){
println("state = "+state+";");
if(!dest.consumedFromLookAhead)
println("consume(ch);");
println("continue;");
}else{
if(!dest.consumedFromLookAhead)
println("consume(ch);");
println("stack[free-1] = "+state+";");
println("return true;");
}
}
class Destination{
boolean consumedFromLookAhead;
Rule rule;
Node node;
Destination(boolean consumedFromLookAhead, Rule rule, Node node){
this.consumedFromLookAhead = consumedFromLookAhead;
this.rule = rule;
this.node = node;
}
public int state(){
if(node==null)
return -1;
else{
if(debuggable)
return node.id;
else
return new Routes(rule, node).isEOF() ? -2 : node.id;
}
}
}
public static boolean COELSCE_LA_CONSUME_CALLS = false;
private Destination _travelPath(Rule rule, Path path, boolean consumeLookAhead){
nodesToBeExecuted.setLength(0);
Deque<Rule> ruleStack = new ArrayDeque<Rule>();
ruleStack.push(rule);
Node destNode = null;
boolean wasNode = false;
for(Object obj: path){
if(obj instanceof Node){
if(wasNode){
println("free -= 2;");
ruleStack.pop();
}
wasNode = true;
Node node = (Node)obj;
if(debuggable){
if(nodesToBeExecuted.length()>0)
nodesToBeExecuted.append(", ");
nodesToBeExecuted.append(node.id);
}else if(node.action!=null)
printer.println(node.action.javaCode()+';');
}else if(obj instanceof Edge){
wasNode = false;
Edge edge = (Edge)obj;
if(edge.ruleTarget!=null){
int stateAfterRule = new Destination(consumeLookAhead, ruleStack.peek(), edge.target).state();
if(stateAfterRule==-2)
stateAfterRule = -1;
println("push(RULE_"+edge.ruleTarget.rule.name.toUpperCase()+", "+stateAfterRule+", "+edge.ruleTarget.node().id+");");
ruleStack.push(edge.ruleTarget.rule);
}
else if(edge.matcher!=null){
destNode = edge.target;
if(consumeLookAhead){
if(COELSCE_LA_CONSUME_CALLS){
if(nodesToBeExecuted.length()==0)
consumeLAFirst = true;
consumeLALen++;
}else
println("consume(FROM_LA);"); }
break;
}
}
}
return new Destination(consumeLookAhead, ruleStack.peek(), destNode);
}
protected void startHandler(){
printer.printClassDoc();
String className[] = className(handlerName);
if(className[0].length()>0){
printer.printlns(
"package "+className[0]+";",
""
);
}
String keyWord = handlerClass ? "class" : "interface";
String suffix = handlerClass ? " implements " : " extends ";
printer.printlns(
"public "+keyWord+" "+className[1]+"<E extends Exception>"+suffix+"<E>{",
PLUS
);
}
protected void addPublishMethod(String name){
if(handlerClass){
printer.printlns(
"public void "+name+"(Chars data){",
PLUS,
"System.out.println(\""+name+"(\\\"\"+data+\"\\\")\");",
MINUS,
"}"
);
}else
printer.println("public void "+name+"(Chars data);");
}
protected void addEventMethod(String name){
if(handlerClass){
printer.printlns(
"public void "+name+"(){",
PLUS,
"System.out.println(\""+name+"\");",
MINUS,
"}"
);
}else
printer.println("public void "+name+"();");
}
protected void finishHandler(){
if(handlerClass){
printer.printlns(
"@Override",
"public void fatalError(String message) throws E{",
PLUS,
"throw new Exception(message);",
MINUS,
"}",
MINUS,
"}"
);
}
printer.printlns(
MINUS,
"}"
);
}
private String parserName = "jlibs.xml.sax.async.XMLScanner";
public boolean finalParser = true;
private Class superClass = NBParser.class;
public void setParserName(String parserName){
this.parserName = parserName;
}
private String handlerName = "jlibs.xml.sax.async.AsyncXMLReader";
private boolean handlerClass = false;
public void setHandlerName(String handlerName, boolean isClass){
this.handlerName = handlerName;
this.handlerClass = isClass;
}
public void setDebuggable(Class superClass, Class handler){
debuggable = true;
this.superClass = superClass;
this.handlerName = handler.getName();
}
}
|
package org.nd4j.linalg.api.test;
import org.nd4j.linalg.api.ndarray.DimensionSlice;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ndarray.SliceOp;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.NDArrayIndex;
import org.nd4j.linalg.ops.reduceops.Ops;
import org.nd4j.linalg.ops.transforms.Transforms;
import org.nd4j.linalg.util.ArrayUtil;
import org.nd4j.linalg.util.Shape;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
/**
* NDArrayTests
* @author Adam Gibson
*/
public abstract class NDArrayTests {
private static Logger log = LoggerFactory.getLogger(NDArrayTests.class);
private INDArray n = Nd4j.create(Nd4j.linspace(1, 8, 8).data(), new int[]{2, 2, 2});
@Before
public void before() {
Nd4j.factory().setOrder('c');
}
@After
public void after() {
Nd4j.factory().setOrder('c');
}
@Test
public void testScalarOps() {
INDArray n = Nd4j.create(Nd4j.ones(27).data(), new int[]{3, 3, 3});
assertEquals(27d,n.length(),1e-1);
n.checkDimensions(n.addi(Nd4j.scalar(1d)));
n.checkDimensions(n.subi(Nd4j.scalar(1.0d)));
n.checkDimensions(n.muli(Nd4j.scalar(1.0d)));
n.checkDimensions(n.divi(Nd4j.scalar(1.0d)));
n = Nd4j.create(Nd4j.ones(27).data(), new int[]{3, 3, 3});
assertEquals(27,(float) n.sum(Integer.MAX_VALUE).element(),1e-1);
INDArray a = n.slice(2);
assertEquals(true,Arrays.equals(new int[]{3,3},a.shape()));
}
@Test
public void testLinearViewGetAndPut() {
INDArray test = Nd4j.linspace(1, 4, 4).reshape(2,2);
INDArray linear = test.linearView();
linear.putScalar(2,6);
linear.putScalar(3,7);
assertEquals(6,linear.get(2),1e-1);
assertEquals(7,linear.get(3),1e-1);
}
@Test
public void testGetIndices() {
/*[[[1.0 ,13.0],[5.0 ,17.0],[9.0 ,21.0]],[[2.0 ,14.0],[6.0 ,18.0],[10.0 ,22.0]],[[3.0 ,15.0],[7.0 ,19.0],[11.0 ,23.0]],[[4.0 ,16.0],[8.0 ,20.0],[12.0 ,24.0]]]*/
Nd4j.factory().setOrder('f');
INDArray test = Nd4j.linspace(1, 24, 24).reshape(new int[]{4,3,2});
NDArrayIndex oneTwo = NDArrayIndex.interval(1, 2);
NDArrayIndex twoToThree = NDArrayIndex.interval(1,3);
INDArray get = test.get(oneTwo,twoToThree);
assertTrue(Arrays.equals(new int[]{1,2,2},get.shape()));
assertEquals(Nd4j.create(new float[]{6, 10, 18, 22}, new int[]{1, 2, 2}),get);
INDArray anotherGet = Nd4j.create(new float[]{6, 7, 10, 11, 18, 19, 22, 23}, new int[]{2, 1, 2});
INDArray test2 = test.get(NDArrayIndex.interval(1,3),NDArrayIndex.interval(1,4));
assertEquals(5,test2.offset());
//offset is off: should be 5
assertTrue(Arrays.equals(new int[]{2,1,2},test2.shape()));
assertEquals(test2,anotherGet);
}
@Test
public void testSwapAxesFortranOrder() {
Nd4j.factory().setOrder('f');
INDArray n = Nd4j.create(Nd4j.linspace(1, 30, 30).data(),new int[]{3,5,2});
}
@Test
public void testGetIndicesVector() {
INDArray line = Nd4j.linspace(1, 4, 4);
INDArray test = Nd4j.create(new float[]{2, 3});
INDArray result = line.get(NDArrayIndex.interval(1, 3));
assertEquals(test,result);
}
@Test
public void testGetIndices2d() {
Nd4j.factory().setOrder('f');
INDArray twoByTwo = Nd4j.linspace(1, 6, 6).reshape(3,2);
INDArray firstRow = twoByTwo.getRow(0);
INDArray secondRow = twoByTwo.getRow(1);
INDArray firstAndSecondRow = twoByTwo.getRows(new int[]{1,2});
INDArray firstRowViaIndexing = twoByTwo.get(NDArrayIndex.interval(0,1));
assertEquals(firstRow,firstRowViaIndexing);
INDArray secondRowViaIndexing = twoByTwo.get(NDArrayIndex.interval(1,2));
assertEquals(secondRow,secondRowViaIndexing);
INDArray individualElement = twoByTwo.get(NDArrayIndex.interval(1,2),NDArrayIndex.interval(1,2));
assertEquals(Nd4j.create(new float[]{5}),individualElement);
INDArray firstAndSecondRowTest = twoByTwo.get(NDArrayIndex.interval(1, 3));
assertEquals(firstAndSecondRow, firstAndSecondRowTest);
}
@Test
public void testGetVsGetScalar() {
INDArray a = Nd4j.linspace(1, 4, 4).reshape(2,2);
float element = a.get(0,1);
float element2 = (float) a.getScalar(0,1).element();
assertEquals(element,element2,1e-1);
Nd4j.factory().setOrder('f');
INDArray a2 = Nd4j.linspace(1, 4, 4).reshape(2,2);
float element23 = a2.get(0,1);
float element22 = (float) a2.getScalar(0,1).element();
assertEquals(element23,element22,1e-1);
}
@Test
public void testDivide() {
INDArray two = Nd4j.create(new float[]{2, 2, 2, 2});
INDArray div = two.div(two);
assertEquals(Nd4j.ones(4),div);
INDArray half = Nd4j.create(new float[]{0.5f, 0.5f, 0.5f, 0.5f}, new int[]{2, 2});
INDArray divi = Nd4j.create(new float[]{0.3f, 0.6f, 0.9f, 0.1f}, new int[]{2, 2});
INDArray assertion = Nd4j.create(new float[]{1.6666666f, 0.8333333f, 0.5555556f, 5}, new int[]{2, 2});
INDArray result = half.div(divi);
assertEquals(assertion,result);
}
@Test
public void testSigmoid() {
INDArray n = Nd4j.create(new float[]{1, 2, 3, 4});
INDArray assertion = Nd4j.create(new float[]{0.73105858f, 0.88079708f, 0.95257413f, 0.98201379f});
INDArray sigmoid = Transforms.sigmoid(n);
assertEquals(assertion,sigmoid);
}
@Test
public void testNeg() {
INDArray n = Nd4j.create(new float[]{1, 2, 3, 4});
INDArray assertion = Nd4j.create(new float[]{-1, -2, -3, -4});
INDArray neg = Transforms.neg(n);
assertEquals(assertion,neg);
}
@Test
public void testNorm2() {
INDArray n = Nd4j.create(new float[]{1, 2, 3, 4});
float assertion = 5.47722557505f;
assertEquals(assertion,n.norm2(Integer.MAX_VALUE).get(0),1e-1);
}
@Test
public void testExp() {
INDArray n = Nd4j.create(new float[]{1, 2, 3, 4});
INDArray assertion = Nd4j.create(new float[]{2.71828183f, 7.3890561f, 20.08553692f, 54.59815003f});
INDArray exped = Transforms.exp(n);
assertEquals(assertion,exped);
}
@Test
public void testSlices() {
INDArray arr = Nd4j.create(Nd4j.linspace(1, 24, 24).data(), new int[]{4, 3, 2});
for(int i = 0; i < arr.slices(); i++) {
assertEquals(2, arr.slice(i).slice(1).slices());
}
}
@Test
public void testScalar() {
INDArray a = Nd4j.scalar(1.0);
assertEquals(true,a.isScalar());
INDArray n = Nd4j.create(new float[]{1.0f}, new int[]{1, 1});
assertEquals(n,a);
assertTrue(n.isScalar());
}
@Test
public void testWrap() {
int[] shape = {2,4};
INDArray d = Nd4j.linspace(1, 8, 8).reshape(shape[0],shape[1]);
INDArray n =d;
assertEquals(d.rows(),n.rows());
assertEquals(d.columns(),n.columns());
INDArray vector = Nd4j.linspace(1, 3, 3);
INDArray testVector = vector;
for(int i = 0; i < vector.length(); i++)
assertEquals((float) vector.getScalar(i).element(),(float) testVector.getScalar(i).element(),1e-1);
assertEquals(3,testVector.length());
assertEquals(true,testVector.isVector());
assertEquals(true,Shape.shapeEquals(new int[]{3},testVector.shape()));
INDArray row12 = Nd4j.linspace(1, 2, 2).reshape(2,1);
INDArray row22 = Nd4j.linspace(3, 4, 2).reshape(1,2);
assertEquals(row12.rows(),2);
assertEquals(row12.columns(),1);
assertEquals(row22.rows(),1);
assertEquals(row22.columns(),2);
}
@Test
public void testGetRowFortran() {
Nd4j.factory().setOrder('f');
INDArray n = Nd4j.create(Nd4j.linspace(1, 4, 4).data(), new int[]{2, 2});
INDArray column = Nd4j.create(new float[]{1, 3});
INDArray column2 = Nd4j.create(new float[]{2, 4});
INDArray testColumn = n.getRow(0);
INDArray testColumn1 = n.getRow(1);
assertEquals(column,testColumn);
assertEquals(column2,testColumn1);
Nd4j.factory().setOrder('c');
}
@Test
public void testGetColumnFortran() {
Nd4j.factory().setOrder('f');
INDArray n = Nd4j.create(Nd4j.linspace(1, 4, 4).data(), new int[]{2, 2});
INDArray column = Nd4j.create(new float[]{1, 2});
INDArray column2 = Nd4j.create(new float[]{3, 4});
INDArray testColumn = n.getColumn(0);
INDArray testColumn1 = n.getColumn(1);
assertEquals(column,testColumn);
assertEquals(column2,testColumn1);
Nd4j.factory().setOrder('c');
}
@Test
public void testVectorInit() {
float[] data = Nd4j.linspace(1, 4, 4).data();
INDArray arr = Nd4j.create(data, new int[]{4});
assertEquals(true,arr.isRowVector());
INDArray arr2 = Nd4j.create(data, new int[]{1, 4});
assertEquals(true,arr2.isRowVector());
INDArray columnVector = Nd4j.create(data, new int[]{4, 1});
assertEquals(true,columnVector.isColumnVector());
}
@Test
public void testColumns() {
INDArray arr = Nd4j.create(new int[]{3, 2});
INDArray column2 = arr.getColumn(0);
assertEquals(true,Shape.shapeEquals(new int[]{3,1}, column2.shape()));
INDArray column = Nd4j.create(new float[]{1, 2, 3}, new int[]{3});
arr.putColumn(0,column);
INDArray firstColumn = arr.getColumn(0);
assertEquals(column,firstColumn);
INDArray column1 = Nd4j.create(new float[]{4, 5, 6}, new int[]{3});
arr.putColumn(1,column1);
assertEquals(true, Shape.shapeEquals(new int[]{3,1}, arr.getColumn(1).shape()));
INDArray testRow1 = arr.getColumn(1);
assertEquals(column1,testRow1);
INDArray evenArr = Nd4j.create(new float[]{1, 2, 3, 4}, new int[]{2, 2});
INDArray put = Nd4j.create(new float[]{5, 6}, new int[]{2});
evenArr.putColumn(1,put);
INDArray testColumn = evenArr.getColumn(1);
assertEquals(put,testColumn);
INDArray n = Nd4j.create(Nd4j.linspace(1, 4, 4).data(), new int[]{2, 2});
INDArray column23 = n.getColumn(0);
INDArray column12 = Nd4j.create(new float[]{1, 3}, new int[]{2});
assertEquals(column23,column12);
INDArray column0 = n.getColumn(1);
INDArray column01 = Nd4j.create(new float[]{2, 4}, new int[]{2});
assertEquals(column0,column01);
}
@Test
public void testPutRow() {
INDArray d = Nd4j.linspace(1, 4, 4).reshape(2,2);
INDArray n = d.dup();
//works fine according to matlab, let's go with it..
//reproduce with: A = reshape(linspace(1,4,4),[2 2 ]);
//A(1,2) % 1 index based
float nFirst = 2;
float dFirst = d.get(0, 1);
assertEquals(nFirst,dFirst,1e-1);
assertEquals(true,Arrays.equals(d.data(),n.data()));
assertEquals(true,Arrays.equals(new int[]{2,2},n.shape()));
INDArray newRow = Nd4j.linspace(5, 6, 2);
n.putRow(0,newRow);
d.putRow(0,newRow);
INDArray testRow = n.getRow(0);
assertEquals(newRow.length(),testRow.length());
assertEquals(true, Shape.shapeEquals(new int[]{2}, testRow.shape()));
INDArray nLast = Nd4j.create(Nd4j.linspace(1, 4, 4).data(), new int[]{2, 2});
INDArray row = nLast.getRow(1);
INDArray row1 = Nd4j.create(new float[]{3, 4}, new int[]{2});
assertEquals(row,row1);
INDArray arr = Nd4j.create(new int[]{3, 2});
INDArray evenRow = Nd4j.create(new float[]{1, 2}, new int[]{2});
arr.putRow(0,evenRow);
INDArray firstRow = arr.getRow(0);
assertEquals(true, Shape.shapeEquals(new int[]{2},firstRow.shape()));
INDArray testRowEven = arr.getRow(0);
assertEquals(evenRow,testRowEven);
INDArray row12 = Nd4j.create(new float[]{5, 6}, new int[]{2});
arr.putRow(1,row12);
assertEquals(true, Shape.shapeEquals(new int[]{2}, arr.getRow(0).shape()));
INDArray testRow1 = arr.getRow(1);
assertEquals(row12,testRow1);
INDArray multiSliceTest = Nd4j.create(Nd4j.linspace(1, 16, 16).data(), new int[]{4, 2, 2});
INDArray test = Nd4j.create(new float[]{7, 8}, new int[]{2});
INDArray test2 = Nd4j.create(new float[]{9, 10}, new int[]{2});
assertEquals(test,multiSliceTest.slice(1).getRow(1));
assertEquals(test2,multiSliceTest.slice(1).getRow(2));
}
@Test
public void testOrdering() {
//c ordering first
Nd4j.factory().setOrder('c');
Nd4j.factory().setDType("float");
INDArray data = Nd4j.create(new float[]{1, 2, 3, 4}, new int[]{2, 2});
assertEquals(2.0,(float) data.getScalar(0,1).element(),1e-1);
Nd4j.factory().setOrder('f');
INDArray data2 = Nd4j.create(new float[]{1, 2, 3, 4}, new int[]{2, 2});
assertNotEquals(data2.getScalar(0,1),data.getScalar(0,1));
Nd4j.factory().setOrder('c');
}
@Test
public void testSum() {
INDArray n = Nd4j.create(Nd4j.linspace(1, 8, 8).data(), new int[]{2, 2, 2});
INDArray test = Nd4j.create(new float[]{3, 7, 11, 15}, new int[]{2, 2});
INDArray sum = n.sum(n.shape().length - 1);
assertEquals(test,sum);
}
@Test
public void testMmulF() {
Nd4j.factory().setOrder('f');
float[] data = Nd4j.linspace(1, 10, 10).data();
INDArray n = Nd4j.create(data, new int[]{10});
INDArray transposed = n.transpose();
assertEquals(true,n.isRowVector());
assertEquals(true,transposed.isColumnVector());
INDArray d = Nd4j.create(Arrays.copyOf(n.data(), n.data().length), new int[]{n.rows(), n.columns()});
INDArray innerProduct = n.mmul(transposed);
INDArray scalar = Nd4j.scalar(385);
assertEquals(scalar,innerProduct);
}
@Test
public void testMmul() {
Nd4j.factory().setOrder('c');
float[] data = Nd4j.linspace(1, 10, 10).data();
INDArray n = Nd4j.create(data, new int[]{10});
INDArray transposed = n.transpose();
assertEquals(true,n.isRowVector());
assertEquals(true,transposed.isColumnVector());
INDArray d = Nd4j.create(n.rows(), n.columns());
d.setData(n.data());
INDArray innerProduct = n.mmul(transposed);
INDArray scalar = Nd4j.scalar(385);
assertEquals(scalar,innerProduct);
INDArray outerProduct = transposed.mmul(n);
assertEquals(true, Shape.shapeEquals(new int[]{10,10},outerProduct.shape()));
INDArray testMatrix = Nd4j.create(data, new int[]{5, 2});
INDArray row1 = testMatrix.getRow(0).transpose();
INDArray row2 = testMatrix.getRow(1);
INDArray row12 = Nd4j.linspace(1, 2, 2).reshape(2,1);
INDArray row22 = Nd4j.linspace(3, 4, 2).reshape(1,2);
INDArray row122 = row12;
INDArray row222 = row22;
INDArray rowResult2 = row122.mmul(row222);
INDArray d3 = Nd4j.create(new float[]{1, 2}).reshape(2,1);
INDArray d4 = Nd4j.create(new float[]{3, 4});
INDArray resultNDArray = d3.mmul(d4);
INDArray result = Nd4j.create(new float[][]{{3, 4}, {6, 8}});
assertEquals(result,resultNDArray);
INDArray three = Nd4j.create(new float[]{3, 4}, new int[]{2});
INDArray test = Nd4j.create(Nd4j.linspace(1, 30, 30).data(), new int[]{3, 5, 2});
INDArray sliceRow = test.slice(0).getRow(1);
assertEquals(three,sliceRow);
INDArray twoSix = Nd4j.create(new float[]{2, 6}, new int[]{2, 1});
INDArray threeTwoSix = three.mmul(twoSix);
INDArray sliceRowTwoSix = sliceRow.mmul(twoSix);
assertEquals(threeTwoSix,sliceRowTwoSix);
INDArray vectorVector = Nd4j.create(new float[]{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105, 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108, 117, 126, 135, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 0, 11, 22, 33, 44, 55, 66, 77, 88, 99, 110, 121, 132, 143, 154, 165, 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 168, 180, 0, 13, 26, 39, 52, 65, 78, 91, 104, 117, 130, 143, 156, 169, 182, 195, 0, 14, 28, 42, 56, 70, 84, 98, 112, 126, 140, 154, 168, 182, 196, 210, 0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225
}, new int[]{16, 16});
INDArray n1 = Nd4j.create(Nd4j.linspace(0, 15, 16).data(), new int[]{16});
INDArray k1 = n1.transpose();
INDArray testVectorVector = k1.mmul(n1);
assertEquals(vectorVector,testVectorVector);
}
@Test
public void testRowsColumns() {
float[] data = Nd4j.linspace(1, 6, 6).data();
INDArray rows = Nd4j.create(data, new int[]{2, 3});
assertEquals(2,rows.rows());
assertEquals(3,rows.columns());
INDArray columnVector = Nd4j.create(data, new int[]{6, 1});
assertEquals(6,columnVector.rows());
assertEquals(1,columnVector.columns());
INDArray rowVector = Nd4j.create(data, new int[]{6});
assertEquals(1,rowVector.rows());
assertEquals(6,rowVector.columns());
}
@Test
public void testTranspose() {
INDArray n = Nd4j.create(Nd4j.ones(100).data(), new int[]{5, 5, 4});
INDArray transpose = n.transpose();
assertEquals(n.length(),transpose.length());
assertEquals(true,Arrays.equals(new int[]{4,5,5},transpose.shape()));
INDArray rowVector = Nd4j.linspace(1, 10, 10);
assertTrue(rowVector.isRowVector());
INDArray columnVector = rowVector.transpose();
assertTrue(columnVector.isColumnVector());
INDArray linspaced = Nd4j.linspace(1, 4, 4).reshape(2,2);
INDArray transposed = Nd4j.create(new float[]{1, 3, 2, 4}, new int[]{2, 2});
assertEquals(transposed,linspaced.transpose());
Nd4j.factory().setOrder('f');
linspaced = Nd4j.linspace(1, 4, 4).reshape(2,2);
//fortran ordered
INDArray transposed2 = Nd4j.create(new float[]{1, 3, 2, 4}, new int[]{2, 2});
transposed = linspaced.transpose();
assertEquals(transposed,transposed2);
Nd4j.factory().setOrder('c');
}
@Test
public void testPutSlice() {
INDArray n = Nd4j.create(Nd4j.ones(27).data(), new int[]{3, 3, 3});
INDArray newSlice = Nd4j.zeros(3, 3);
n.putSlice(0,newSlice);
assertEquals(newSlice,n.slice(0));
}
@Test
public void testPermute() {
INDArray n = Nd4j.create(Nd4j.linspace(1, 20, 20).data(), new int[]{5, 4});
INDArray transpose = n.transpose();
INDArray permute = n.permute(new int[]{1,0});
assertEquals(permute,transpose);
assertEquals(transpose.length(),permute.length(),1e-1);
INDArray toPermute = Nd4j.create(Nd4j.linspace(0, 7, 8).data(), new int[]{2, 2, 2});
INDArray permuted = toPermute.permute(new int[]{2,1,0});
INDArray assertion = Nd4j.create(new float[]{0, 4, 2, 6, 1, 5, 3, 7}, new int[]{2, 2, 2});
assertEquals(permuted,assertion);
}
@Test
public void testSlice() {
assertEquals(8,n.length());
assertEquals(true,Arrays.equals(new int[]{2,2,2},n.shape()));
INDArray slice = n.slice(0);
assertEquals(true, Arrays.equals(new int[]{2, 2}, slice.shape()));
INDArray slice1 = n.slice(1);
assertNotEquals(slice,slice1);
INDArray arr = Nd4j.create(Nd4j.linspace(1, 24, 24).data(), new int[]{4, 3, 2});
INDArray slice0 = Nd4j.create(new float[]{1, 2, 3, 4, 5, 6}, new int[]{3, 2});
INDArray slice2 = Nd4j.create(new float[]{7, 8, 9, 10, 11, 12}, new int[]{3, 2});
INDArray testSlice0 = arr.slice(0);
INDArray testSlice1 = arr.slice(1);
assertEquals(slice0,testSlice0);
assertEquals(slice2,testSlice1);
}
@Test
public void testSwapAxes() {
INDArray n = Nd4j.create(Nd4j.linspace(0, 7, 8).data(), new int[]{2, 2, 2});
INDArray assertion = n.permute(new int[]{2,1,0});
float[] data = assertion.data();
INDArray validate = Nd4j.create(new float[]{0, 4, 2, 6, 1, 5, 3, 7}, new int[]{2, 2, 2});
assertEquals(validate,assertion);
}
@Test
public void testLinearIndex() {
INDArray n = Nd4j.create(Nd4j.linspace(1, 8, 8).data(), new int[]{8});
for(int i = 0; i < n.length(); i++) {
int linearIndex = n.linearIndex(i);
assertEquals(i ,linearIndex);
float d = (float) n.getScalar(i).element();
assertEquals(i + 1,d,1e-1);
}
}
@Test
public void testSliceConstructor() {
List<INDArray> testList = new ArrayList<>();
for(int i = 0; i < 5; i++)
testList.add(Nd4j.scalar(i + 1));
INDArray test = Nd4j.create(testList, new int[]{testList.size()});
INDArray expected = Nd4j.create(new float[]{1, 2, 3, 4, 5}, new int[]{5});
assertEquals(expected,test);
}
@Test
public void testVectorDimension() {
INDArray test = Nd4j.create(Nd4j.linspace(1, 4, 4).data(), new int[]{2, 2});
final AtomicInteger count = new AtomicInteger(0);
//row wise
test.iterateOverDimension(1,new SliceOp() {
@Override
public void operate(DimensionSlice nd) {
INDArray test = (INDArray) nd.getResult();
if(count.get() == 0) {
INDArray firstDimension = Nd4j.create(new float[]{1, 2}, new int[]{2});
assertEquals(firstDimension,test);
}
else {
INDArray firstDimension = Nd4j.create(new float[]{3, 4}, new int[]{2});
assertEquals(firstDimension,test);
}
count.incrementAndGet();
}
/**
* Operates on an ndarray slice
*
* @param nd the result to operate on
*/
@Override
public void operate(INDArray nd) {
INDArray test = nd;
if(count.get() == 0) {
INDArray firstDimension = Nd4j.create(new float[]{1, 2}, new int[]{2});
assertEquals(firstDimension,test);
}
else {
INDArray firstDimension = Nd4j.create(new float[]{3, 4}, new int[]{2});
assertEquals(firstDimension,test);
}
count.incrementAndGet();
}
},false);
count.set(0);
//columnwise
test.iterateOverDimension(0,new SliceOp() {
@Override
public void operate(DimensionSlice nd) {
log.info("Operator " + nd);
INDArray test = (INDArray) nd.getResult();
if(count.get() == 0) {
INDArray firstDimension = Nd4j.create(new float[]{1, 3}, new int[]{2});
assertEquals(firstDimension,test);
}
else {
INDArray firstDimension = Nd4j.create(new float[]{2, 4}, new int[]{2});
assertEquals(firstDimension,test);
}
count.incrementAndGet();
}
/**
* Operates on an ndarray slice
*
* @param nd the result to operate on
*/
@Override
public void operate(INDArray nd) {
log.info("Operator " + nd);
INDArray test = nd;
if(count.get() == 0) {
INDArray firstDimension = Nd4j.create(new float[]{1, 3}, new int[]{2});
assertEquals(firstDimension,test);
}
else {
INDArray firstDimension = Nd4j.create(new float[]{2, 4}, new int[]{2});
assertEquals(firstDimension,test);
}
count.incrementAndGet();
}
},false);
}
@Test
public void testDimension() {
INDArray test = Nd4j.create(Nd4j.linspace(1, 4, 4).data(), new int[]{2, 2});
//row
INDArray slice0 = test.slice(0,1);
INDArray slice02 = test.slice(1,1);
INDArray assertSlice0 = Nd4j.create(new float[]{1, 2});
INDArray assertSlice02 = Nd4j.create(new float[]{3, 4});
assertEquals(assertSlice0,slice0);
assertEquals(assertSlice02,slice02);
//column
INDArray assertSlice1 = Nd4j.create(new float[]{1, 3});
INDArray assertSlice12 = Nd4j.create(new float[]{2, 4});
INDArray slice1 = test.slice(0,0);
INDArray slice12 = test.slice(1,0);
assertEquals(assertSlice1,slice1);
assertEquals(assertSlice12,slice12);
INDArray arr = Nd4j.create(Nd4j.linspace(1, 24, 24).data(), new int[]{4, 3, 2});
INDArray firstSliceFirstDimension = arr.slice(0,1);
INDArray secondSliceFirstDimension = arr.slice(1,1);
INDArray firstSliceFirstDimensionAssert = Nd4j.create(new float[]{1, 2, 7, 8, 13, 14, 19, 20});
INDArray secondSliceFirstDimension2Test = firstSliceFirstDimensionAssert.add(1);
assertEquals(secondSliceFirstDimension,secondSliceFirstDimension);
}
@Test
public void testReshape() {
INDArray arr = Nd4j.create(Nd4j.linspace(1, 24, 24).data(), new int[]{4, 3, 2});
INDArray reshaped = arr.reshape(new int[]{2,3,4});
assertEquals(arr.length(),reshaped.length());
assertEquals(true,Arrays.equals(new int[]{4,3,2},arr.shape()));
assertEquals(true,Arrays.equals(new int[]{2,3,4},reshaped.shape()));
INDArray n2 = Nd4j.create(Nd4j.linspace(1, 30, 30).data(), new int[]{3, 5, 2});
INDArray swapped = n2.swapAxes(n2.shape().length - 1,1);
INDArray firstSlice2 = swapped.slice(0).slice(0);
INDArray oneThreeFiveSevenNine = Nd4j.create(new float[]{1, 3, 5, 7, 9});
assertEquals(firstSlice2,oneThreeFiveSevenNine);
INDArray raveled = oneThreeFiveSevenNine.reshape(5,1);
INDArray raveledOneThreeFiveSevenNine = oneThreeFiveSevenNine.reshape(5,1);
assertEquals(raveled,raveledOneThreeFiveSevenNine);
INDArray firstSlice3 = swapped.slice(0).slice(1);
INDArray twoFourSixEightTen = Nd4j.create(new float[]{2, 4, 6, 8, 10});
assertEquals(firstSlice2,oneThreeFiveSevenNine);
INDArray raveled2 = twoFourSixEightTen.reshape(5,1);
INDArray raveled3 = firstSlice3.reshape(5,1);
assertEquals(raveled2,raveled3);
}
@Test
public void reduceTest() {
INDArray arr = Nd4j.create(Nd4j.linspace(1, 24, 24).data(), new int[]{4, 3, 2});
INDArray reduced = arr.reduce(Ops.DimensionOp.MAX,1);
log.info("Reduced " + reduced);
reduced = arr.reduce(Ops.DimensionOp.MAX,1);
log.info("Reduced " + reduced);
reduced = arr.reduce(Ops.DimensionOp.MAX,2);
log.info("Reduced " + reduced);
}
@Test
public void testColumnVectorOpsFortran() {
Nd4j.factory().setOrder('f');
INDArray twoByTwo = Nd4j.create(new float[]{1, 2, 3, 4}, new int[]{2, 2});
INDArray toAdd = Nd4j.create(new float[]{1, 2}, new int[]{2, 1});
twoByTwo.addiColumnVector(toAdd);
INDArray assertion = Nd4j.create(new float[]{2, 4, 4, 6}, new int[]{2, 2});
assertEquals(assertion,twoByTwo);
}
@Test
public void testMeans() {
INDArray a = Nd4j.linspace(1, 4, 4).reshape(2,2);
assertEquals(Nd4j.create(new float[]{2, 3}),a.mean(0));
assertEquals(Nd4j.create(new float[]{1.5f, 3.5f}),a.mean(1));
assertEquals(2.5,(float) a.mean(Integer.MAX_VALUE).element(),1e-1);
}
@Test
public void testSums() {
INDArray a = Nd4j.linspace(1, 4, 4).reshape(2,2);
assertEquals(Nd4j.create(new float[]{4, 6}),a.sum(0));
assertEquals(Nd4j.create(new float[]{3, 7}),a.sum(1));
assertEquals(10,(float) a.sum(Integer.MAX_VALUE).element(),1e-1);
}
@Test
public void testCumSum() {
INDArray n = Nd4j.create(new float[]{1, 2, 3, 4}, new int[]{4});
INDArray cumSumAnswer = Nd4j.create(new float[]{1, 3, 6, 10}, new int[]{4});
INDArray cumSumTest = n.cumsum(0);
assertEquals(cumSumAnswer,cumSumTest);
INDArray n2 = Nd4j.linspace(1, 24, 24).reshape(new int[]{4,3,2});
INDArray cumSumCorrect2 = Nd4j.create(new double[]{1.0, 3.0, 6.0, 10.0, 15.0, 21.0, 28.0, 36.0, 45.0, 55.0, 66.0, 78.0, 91.0, 105.0, 120.0, 136.0, 153.0, 171.0, 190.0, 210.0, 231.0, 253.0, 276.0, 300.0}, new int[]{24});
INDArray cumSumTest2 = n2.cumsum(n2.shape().length - 1);
assertEquals(cumSumCorrect2,cumSumTest2);
INDArray axis0assertion = Nd4j.create(new float[]{1, 2, 3, 4, 5, 6, 8, 10, 12, 14, 16, 18, 21, 24, 27, 30, 33, 36, 40, 44, 48, 52, 56, 60}, n2.shape());
INDArray axis0Test = n2.cumsum(0);
assertEquals(axis0assertion,axis0Test);
}
@Test
public void testRSubi() {
INDArray n2 = Nd4j.ones(2);
INDArray n2Assertion = Nd4j.zeros(2);
INDArray nRsubi = n2.rsubi(1);
assertEquals(n2Assertion,nRsubi);
}
@Test
public void testRDivi() {
INDArray n2 = Nd4j.valueArrayOf(new int[]{2}, 4);
INDArray n2Assertion = Nd4j.valueArrayOf(new int[]{2}, 0.5);
INDArray nRsubi = n2.rdivi(2);
assertEquals(n2Assertion,nRsubi);
}
@Test
public void testVectorAlongDimension() {
INDArray arr = Nd4j.linspace(1, 24, 24).reshape(new int[]{4,3,2});
INDArray assertion = Nd4j.create(new float[]{1, 2}, new int[]{2});
assertEquals(Nd4j.create(new float[]{3, 4}, new int[]{2}),arr.vectorAlongDimension(1,2));
assertEquals(assertion,arr.vectorAlongDimension(0,2));
assertEquals(arr.vectorAlongDimension(0,1), Nd4j.create(new float[]{1, 3, 5}));
INDArray testColumn2Assertion = Nd4j.create(new float[]{7, 9, 11});
INDArray testColumn2 = arr.vectorAlongDimension(1,1);
assertEquals(testColumn2Assertion,testColumn2);
INDArray testColumn3Assertion = Nd4j.create(new float[]{13, 15, 17});
INDArray testColumn3 = arr.vectorAlongDimension(2,1);
assertEquals(testColumn3Assertion,testColumn3);
INDArray v1= Nd4j.linspace(1, 4, 4).reshape(new int[]{2,2});
INDArray testColumnV1 = v1.vectorAlongDimension(0,0);
INDArray testColumnV1Assertion = Nd4j.create(new float[]{1, 3});
assertEquals(testColumnV1Assertion,testColumnV1);
INDArray testRowV1 = v1.vectorAlongDimension(1,0);
INDArray testRowV1Assertion = Nd4j.create(new float[]{2, 4});
assertEquals(testRowV1Assertion,testRowV1);
INDArray lastAxis = arr.vectorAlongDimension(0,2);
assertEquals(assertion,lastAxis);
}
@Test
public void testSquareMatrix() {
INDArray n = Nd4j.create(Nd4j.linspace(1, 8, 8).data(), new int[]{2, 2, 2});
INDArray eightFirstTest = n.vectorAlongDimension(0,2);
INDArray eightFirstAssertion = Nd4j.create(new float[]{1, 2}, new int[]{2});
assertEquals(eightFirstAssertion,eightFirstTest);
INDArray eightFirstTestSecond = n.vectorAlongDimension(1,2);
INDArray eightFirstTestSecondAssertion = Nd4j.create(new float[]{3, 4});
assertEquals(eightFirstTestSecondAssertion,eightFirstTestSecond);
}
@Test
public void testNumVectorsAlongDimension() {
INDArray arr = Nd4j.linspace(1, 24, 24).reshape(new int[]{4,3,2});
assertEquals(12,arr.vectorsAlongDimension(2));
}
@Test
public void testGetScalar() {
INDArray n = Nd4j.create(new float[]{1, 2, 3, 4}, new int[]{4});
assertTrue(n.isVector());
for(int i = 0; i < n.length(); i++) {
INDArray scalar = Nd4j.scalar((float) i + 1);
assertEquals(scalar,n.getScalar(i));
}
Nd4j.factory().setOrder('f');
n = Nd4j.create(new float[]{1, 2, 3, 4}, new int[]{4});
for(int i = 0; i < n.length(); i++) {
INDArray scalar = Nd4j.scalar((float) i + 1);
assertEquals(scalar,n.getScalar(i));
}
INDArray twoByTwo = Nd4j.create(new float[][]{{1, 2}, {3, 4}});
INDArray column = twoByTwo.getColumn(0);
assertEquals(Nd4j.create(new float[]{1, 3}),column);
assertEquals(1,column.get(0),1e-1);
assertEquals(3,column.get(1),1e-1);
assertEquals(Nd4j.scalar(1),column.getScalar(0));
assertEquals(Nd4j.scalar(3),column.getScalar(1));
}
@Test
public void testGetMulti() {
assertEquals(8,n.length());
assertEquals(true,Arrays.equals(ArrayUtil.of(2, 2, 2),n.shape()));
float val = (float) n.getScalar(new int[]{1,1,1}).element();
assertEquals(8.0,val,1e-6);
}
@Test
public void testGetRowOrdering() {
INDArray row1 = Nd4j.linspace(1, 4, 4).reshape(2,2);
Nd4j.factory().setOrder('f');
INDArray row1Fortran = Nd4j.linspace(1, 4, 4).reshape(2,2);
assertNotEquals(row1.get(0,1),row1Fortran.get(0,1),1e-1);
Nd4j.factory().setOrder('c');
}
@Test
public void testPutRowGetRowOrdering() {
INDArray row1 = Nd4j.linspace(1, 4, 4).reshape(2,2);
INDArray put = Nd4j.create(new float[]{5, 6});
row1.putRow(1,put);
Nd4j.factory().setOrder('f');
INDArray row1Fortran = Nd4j.linspace(1, 4, 4).reshape(2,2);
INDArray putFortran = Nd4j.create(new float[]{5, 6});
row1Fortran.putRow(1,putFortran);
assertNotEquals(row1,row1Fortran);
INDArray row1CTest = row1.getRow(1);
INDArray row1FortranTest = row1Fortran.getRow(1);
assertEquals(row1CTest,row1FortranTest);
Nd4j.factory().setOrder('c');
}
@Test
public void testPutRowFortran() {
INDArray row1 = Nd4j.linspace(1, 4, 4).reshape(2,2);
INDArray put = Nd4j.create(new float[]{5, 6});
row1.putRow(1,put);
Nd4j.factory().setOrder('f');
INDArray row1Fortran = Nd4j.create(new float[][]{{1, 2}, {3, 4}});
INDArray putFortran = Nd4j.create(new float[]{5, 6});
row1Fortran.putRow(1,putFortran);
assertEquals(row1,row1Fortran);
Nd4j.factory().setOrder('c');
}
@Test
public void testElementWiseOps() {
INDArray n1 = Nd4j.scalar(1);
INDArray n2 = Nd4j.scalar(2);
assertEquals(Nd4j.scalar(3),n1.add(n2));
assertFalse(n1.add(n2).equals(n1));
INDArray n3 = Nd4j.scalar(3);
INDArray n4 = Nd4j.scalar(4);
INDArray subbed = n4.sub(n3);
INDArray mulled = n4.mul(n3);
INDArray div = n4.div(n3);
assertFalse(subbed.equals(n4));
assertFalse(mulled.equals(n4));
assertEquals(Nd4j.scalar(1),subbed);
assertEquals(Nd4j.scalar(12),mulled);
assertEquals(Nd4j.scalar(1.333333333333333333333),div);
}
@Test
public void testSlicing() {
INDArray arr = n.slice(1, 1);
// assertEquals(1,arr.shape().length());
INDArray n2 = Nd4j.create(Nd4j.linspace(1, 16, 16).data(), new int[]{2, 2, 2, 2});
log.info("N2 shape " + n2.slice(1,1).slice(1));
}
@Test
public void testEndsForSlices() {
INDArray arr = Nd4j.create(Nd4j.linspace(1, 24, 24).data(), new int[]{4, 3, 2});
int[] endsForSlices = arr.endsForSlices();
assertEquals(true,Arrays.equals(new int[]{5,11,17,23},endsForSlices));
}
@Test
public void testFlatten() {
INDArray arr = Nd4j.create(Nd4j.linspace(1, 4, 4).data(), new int[]{2, 2});
INDArray flattened = arr.ravel();
assertEquals(arr.length(),flattened.length());
assertEquals(true,Shape.shapeEquals(new int[]{1, arr.length()}, flattened.shape()));
for(int i = 0; i < arr.length(); i++) {
assertEquals(i + 1, flattened.get(i),1e-1);
}
assertTrue(flattened.isVector());
INDArray n = Nd4j.create(Nd4j.ones(27).data(), new int[]{3, 3, 3});
INDArray nFlattened = n.ravel();
assertTrue(nFlattened.isVector());
INDArray n1 = Nd4j.linspace(1, 24, 24);
assertEquals(n1, Nd4j.linspace(1, 24, 24).reshape(new int[]{4,3,2}).ravel());
}
@Test
public void testVectorDimensionMulti() {
INDArray arr = Nd4j.create(Nd4j.linspace(1, 24, 24).data(), new int[]{4, 3, 2});
final AtomicInteger count = new AtomicInteger(0);
arr.iterateOverDimension(arr.shape().length - 1,new SliceOp() {
@Override
public void operate(DimensionSlice nd) {
INDArray test =(INDArray) nd.getResult();
if(count.get() == 0) {
INDArray answer = Nd4j.create(new float[]{1, 7, 13, 19}, new int[]{4});
assertEquals(answer,test);
}
else if(count.get() == 1) {
INDArray answer = Nd4j.create(new float[]{2, 8, 14, 20}, new int[]{4});
assertEquals(answer,test);
}
else if(count.get() == 2) {
INDArray answer = Nd4j.create(new float[]{3, 9, 15, 21}, new int[]{4});
assertEquals(answer,test);
}
else if(count.get() == 3) {
INDArray answer = Nd4j.create(new float[]{4, 10, 16, 22}, new int[]{4});
assertEquals(answer,test);
}
else if(count.get() == 4) {
INDArray answer = Nd4j.create(new float[]{5, 11, 17, 23}, new int[]{4});
assertEquals(answer,test);
}
else if(count.get() == 5) {
INDArray answer = Nd4j.create(new float[]{6, 12, 18, 24}, new int[]{4});
assertEquals(answer,test);
}
count.incrementAndGet();
}
/**
* Operates on an ndarray slice
*
* @param nd the result to operate on
*/
@Override
public void operate(INDArray nd) {
INDArray test = nd;
if(count.get() == 0) {
INDArray answer = Nd4j.create(new float[]{1, 2}, new int[]{2});
assertEquals(answer,test);
}
else if(count.get() == 1) {
INDArray answer = Nd4j.create(new float[]{3, 4}, new int[]{2});
assertEquals(answer,test);
}
else if(count.get() == 2) {
INDArray answer = Nd4j.create(new float[]{5, 6}, new int[]{2});
assertEquals(answer,test);
}
else if(count.get() == 3) {
INDArray answer = Nd4j.create(new float[]{7, 8}, new int[]{2});
assertEquals(answer,test);
}
else if(count.get() == 4) {
INDArray answer = Nd4j.create(new float[]{9, 10}, new int[]{2});
assertEquals(answer,test);
}
else if(count.get() == 5) {
INDArray answer = Nd4j.create(new float[]{11, 12}, new int[]{2});
assertEquals(answer,test);
}
count.incrementAndGet();
}
},false);
}
}
|
package com.badlogic.gdx.scenes.scene2d.ui;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Value.Fixed;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Pool.Poolable;
/** A cell for a {@link Table}.
* @author Nathan Sweet */
public class Cell<T extends Actor> implements Poolable {
static private final Float zerof = 0f, onef = 1f;
static private final Integer zeroi = 0, onei = 1;
static private final Integer centeri = onei, topi = Align.top, bottomi = Align.bottom, lefti = Align.left,
righti = Align.right;
static private Application app;
static private Cell defaults;
Value minWidth, minHeight;
Value prefWidth, prefHeight;
Value maxWidth, maxHeight;
Value spaceTop, spaceLeft, spaceBottom, spaceRight;
Value padTop, padLeft, padBottom, padRight;
Float fillX, fillY;
Integer align;
Integer expandX, expandY;
Integer colspan;
Boolean uniformX, uniformY;
Actor actor;
float actorX, actorY;
float actorWidth, actorHeight;
private Table table;
boolean endRow;
int column, row;
int cellAboveIndex;
float computedPadTop, computedPadLeft, computedPadBottom, computedPadRight;
public Cell () {
reset();
}
public void setLayout (Table table) {
this.table = table;
}
/** Sets the actor in this cell and adds the actor to the cell's table. If null, removes any current actor. */
public <A extends Actor> Cell<A> setActor (A newActor) {
if (actor != newActor) {
if (actor != null) actor.remove();
actor = newActor;
if (newActor != null) table.addActor(newActor);
}
return (Cell<A>)this;
}
/** Removes the current actor for the cell, if any. */
public Cell<T> clearActor () {
setActor(null);
return this;
}
/** Returns the actor for this cell, or null. */
public T getActor () {
return (T)actor;
}
/** Returns true if the cell's actor is not null. */
public boolean hasActor () {
return actor != null;
}
/** Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified value. */
public Cell<T> size (Value size) {
if (size == null) throw new IllegalArgumentException("size cannot be null.");
minWidth = size;
minHeight = size;
prefWidth = size;
prefHeight = size;
maxWidth = size;
maxHeight = size;
return this;
}
/** Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified values. */
public Cell<T> size (Value width, Value height) {
if (width == null) throw new IllegalArgumentException("width cannot be null.");
if (height == null) throw new IllegalArgumentException("height cannot be null.");
minWidth = width;
minHeight = height;
prefWidth = width;
prefHeight = height;
maxWidth = width;
maxHeight = height;
return this;
}
/** Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified value. */
public Cell<T> size (float size) {
size(new Fixed(size));
return this;
}
/** Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified values. */
public Cell<T> size (float width, float height) {
size(new Fixed(width), new Fixed(height));
return this;
}
/** Sets the minWidth, prefWidth, and maxWidth to the specified value. */
public Cell<T> width (Value width) {
if (width == null) throw new IllegalArgumentException("width cannot be null.");
minWidth = width;
prefWidth = width;
maxWidth = width;
return this;
}
/** Sets the minWidth, prefWidth, and maxWidth to the specified value. */
public Cell<T> width (float width) {
width(new Fixed(width));
return this;
}
/** Sets the minHeight, prefHeight, and maxHeight to the specified value. */
public Cell<T> height (Value height) {
if (height == null) throw new IllegalArgumentException("height cannot be null.");
minHeight = height;
prefHeight = height;
maxHeight = height;
return this;
}
/** Sets the minHeight, prefHeight, and maxHeight to the specified value. */
public Cell<T> height (float height) {
height(new Fixed(height));
return this;
}
/** Sets the minWidth and minHeight to the specified value. */
public Cell<T> minSize (Value size) {
if (size == null) throw new IllegalArgumentException("size cannot be null.");
minWidth = size;
minHeight = size;
return this;
}
/** Sets the minWidth and minHeight to the specified values. */
public Cell<T> minSize (Value width, Value height) {
if (width == null) throw new IllegalArgumentException("width cannot be null.");
if (height == null) throw new IllegalArgumentException("height cannot be null.");
minWidth = width;
minHeight = height;
return this;
}
public Cell<T> minWidth (Value minWidth) {
if (minWidth == null) throw new IllegalArgumentException("minWidth cannot be null.");
this.minWidth = minWidth;
return this;
}
public Cell<T> minHeight (Value minHeight) {
if (minHeight == null) throw new IllegalArgumentException("minHeight cannot be null.");
this.minHeight = minHeight;
return this;
}
/** Sets the minWidth and minHeight to the specified value. */
public Cell<T> minSize (float size) {
minSize(new Fixed(size));
return this;
}
/** Sets the minWidth and minHeight to the specified values. */
public Cell<T> minSize (float width, float height) {
minSize(new Fixed(width), new Fixed(height));
return this;
}
public Cell<T> minWidth (float minWidth) {
this.minWidth = new Fixed(minWidth);
return this;
}
public Cell<T> minHeight (float minHeight) {
this.minHeight = new Fixed(minHeight);
return this;
}
/** Sets the prefWidth and prefHeight to the specified value. */
public Cell<T> prefSize (Value size) {
if (size == null) throw new IllegalArgumentException("size cannot be null.");
prefWidth = size;
prefHeight = size;
return this;
}
/** Sets the prefWidth and prefHeight to the specified values. */
public Cell<T> prefSize (Value width, Value height) {
if (width == null) throw new IllegalArgumentException("width cannot be null.");
if (height == null) throw new IllegalArgumentException("height cannot be null.");
prefWidth = width;
prefHeight = height;
return this;
}
public Cell<T> prefWidth (Value prefWidth) {
if (prefWidth == null) throw new IllegalArgumentException("prefWidth cannot be null.");
this.prefWidth = prefWidth;
return this;
}
public Cell<T> prefHeight (Value prefHeight) {
if (prefHeight == null) throw new IllegalArgumentException("prefHeight cannot be null.");
this.prefHeight = prefHeight;
return this;
}
/** Sets the prefWidth and prefHeight to the specified value. */
public Cell<T> prefSize (float width, float height) {
prefSize(new Fixed(width), new Fixed(height));
return this;
}
/** Sets the prefWidth and prefHeight to the specified values. */
public Cell<T> prefSize (float size) {
prefSize(new Fixed(size));
return this;
}
public Cell<T> prefWidth (float prefWidth) {
this.prefWidth = new Fixed(prefWidth);
return this;
}
public Cell<T> prefHeight (float prefHeight) {
this.prefHeight = new Fixed(prefHeight);
return this;
}
/** Sets the maxWidth and maxHeight to the specified value. */
public Cell<T> maxSize (Value size) {
if (size == null) throw new IllegalArgumentException("size cannot be null.");
maxWidth = size;
maxHeight = size;
return this;
}
/** Sets the maxWidth and maxHeight to the specified values. */
public Cell<T> maxSize (Value width, Value height) {
if (width == null) throw new IllegalArgumentException("width cannot be null.");
if (height == null) throw new IllegalArgumentException("height cannot be null.");
maxWidth = width;
maxHeight = height;
return this;
}
public Cell<T> maxWidth (Value maxWidth) {
if (maxWidth == null) throw new IllegalArgumentException("maxWidth cannot be null.");
this.maxWidth = maxWidth;
return this;
}
public Cell<T> maxHeight (Value maxHeight) {
if (maxHeight == null) throw new IllegalArgumentException("maxHeight cannot be null.");
this.maxHeight = maxHeight;
return this;
}
/** Sets the maxWidth and maxHeight to the specified value. */
public Cell<T> maxSize (float size) {
maxSize(new Fixed(size));
return this;
}
/** Sets the maxWidth and maxHeight to the specified values. */
public Cell<T> maxSize (float width, float height) {
maxSize(new Fixed(width), new Fixed(height));
return this;
}
public Cell<T> maxWidth (float maxWidth) {
this.maxWidth = new Fixed(maxWidth);
return this;
}
public Cell<T> maxHeight (float maxHeight) {
this.maxHeight = new Fixed(maxHeight);
return this;
}
/** Sets the spaceTop, spaceLeft, spaceBottom, and spaceRight to the specified value. */
public Cell<T> space (Value space) {
if (space == null) throw new IllegalArgumentException("space cannot be null.");
spaceTop = space;
spaceLeft = space;
spaceBottom = space;
spaceRight = space;
return this;
}
public Cell<T> space (Value top, Value left, Value bottom, Value right) {
if (top == null) throw new IllegalArgumentException("top cannot be null.");
if (left == null) throw new IllegalArgumentException("left cannot be null.");
if (bottom == null) throw new IllegalArgumentException("bottom cannot be null.");
if (right == null) throw new IllegalArgumentException("right cannot be null.");
spaceTop = top;
spaceLeft = left;
spaceBottom = bottom;
spaceRight = right;
return this;
}
public Cell<T> spaceTop (Value spaceTop) {
if (spaceTop == null) throw new IllegalArgumentException("spaceTop cannot be null.");
this.spaceTop = spaceTop;
return this;
}
public Cell<T> spaceLeft (Value spaceLeft) {
if (spaceLeft == null) throw new IllegalArgumentException("spaceLeft cannot be null.");
this.spaceLeft = spaceLeft;
return this;
}
public Cell<T> spaceBottom (Value spaceBottom) {
if (spaceBottom == null) throw new IllegalArgumentException("spaceBottom cannot be null.");
this.spaceBottom = spaceBottom;
return this;
}
public Cell<T> spaceRight (Value spaceRight) {
if (spaceRight == null) throw new IllegalArgumentException("spaceRight cannot be null.");
this.spaceRight = spaceRight;
return this;
}
/** Sets the spaceTop, spaceLeft, spaceBottom, and spaceRight to the specified value. */
public Cell<T> space (float space) {
if (space < 0) throw new IllegalArgumentException("space cannot be < 0.");
space(new Fixed(space));
return this;
}
public Cell<T> space (float top, float left, float bottom, float right) {
if (top < 0) throw new IllegalArgumentException("top cannot be < 0.");
if (left < 0) throw new IllegalArgumentException("left cannot be < 0.");
if (bottom < 0) throw new IllegalArgumentException("bottom cannot be < 0.");
if (right < 0) throw new IllegalArgumentException("right cannot be < 0.");
space(new Fixed(top), new Fixed(left), new Fixed(bottom), new Fixed(right));
return this;
}
public Cell<T> spaceTop (float spaceTop) {
if (spaceTop < 0) throw new IllegalArgumentException("spaceTop cannot be < 0.");
this.spaceTop = new Fixed(spaceTop);
return this;
}
public Cell<T> spaceLeft (float spaceLeft) {
if (spaceLeft < 0) throw new IllegalArgumentException("spaceLeft cannot be < 0.");
this.spaceLeft = new Fixed(spaceLeft);
return this;
}
public Cell<T> spaceBottom (float spaceBottom) {
if (spaceBottom < 0) throw new IllegalArgumentException("spaceBottom cannot be < 0.");
this.spaceBottom = new Fixed(spaceBottom);
return this;
}
public Cell<T> spaceRight (float spaceRight) {
if (spaceRight < 0) throw new IllegalArgumentException("spaceRight cannot be < 0.");
this.spaceRight = new Fixed(spaceRight);
return this;
}
/** Sets the padTop, padLeft, padBottom, and padRight to the specified value. */
public Cell<T> pad (Value pad) {
if (pad == null) throw new IllegalArgumentException("pad cannot be null.");
padTop = pad;
padLeft = pad;
padBottom = pad;
padRight = pad;
return this;
}
public Cell<T> pad (Value top, Value left, Value bottom, Value right) {
if (top == null) throw new IllegalArgumentException("top cannot be null.");
if (left == null) throw new IllegalArgumentException("left cannot be null.");
if (bottom == null) throw new IllegalArgumentException("bottom cannot be null.");
if (right == null) throw new IllegalArgumentException("right cannot be null.");
padTop = top;
padLeft = left;
padBottom = bottom;
padRight = right;
return this;
}
public Cell<T> padTop (Value padTop) {
if (padTop == null) throw new IllegalArgumentException("padTop cannot be null.");
this.padTop = padTop;
return this;
}
public Cell<T> padLeft (Value padLeft) {
if (padLeft == null) throw new IllegalArgumentException("padLeft cannot be null.");
this.padLeft = padLeft;
return this;
}
public Cell<T> padBottom (Value padBottom) {
if (padBottom == null) throw new IllegalArgumentException("padBottom cannot be null.");
this.padBottom = padBottom;
return this;
}
public Cell<T> padRight (Value padRight) {
if (padRight == null) throw new IllegalArgumentException("padRight cannot be null.");
this.padRight = padRight;
return this;
}
/** Sets the padTop, padLeft, padBottom, and padRight to the specified value. */
public Cell<T> pad (float pad) {
pad(new Fixed(pad));
return this;
}
public Cell<T> pad (float top, float left, float bottom, float right) {
pad(new Fixed(top), new Fixed(left), new Fixed(bottom), new Fixed(right));
return this;
}
public Cell<T> padTop (float padTop) {
this.padTop = new Fixed(padTop);
return this;
}
public Cell<T> padLeft (float padLeft) {
this.padLeft = new Fixed(padLeft);
return this;
}
public Cell<T> padBottom (float padBottom) {
this.padBottom = new Fixed(padBottom);
return this;
}
public Cell<T> padRight (float padRight) {
this.padRight = new Fixed(padRight);
return this;
}
/** Sets fillX and fillY to 1. */
public Cell<T> fill () {
fillX = onef;
fillY = onef;
return this;
}
/** Sets fillX to 1. */
public Cell<T> fillX () {
fillX = onef;
return this;
}
/** Sets fillY to 1. */
public Cell<T> fillY () {
fillY = onef;
return this;
}
public Cell<T> fill (float x, float y) {
fillX = x;
fillY = y;
return this;
}
/** Sets fillX and fillY to 1 if true, 0 if false. */
public Cell<T> fill (boolean x, boolean y) {
fillX = x ? onef : zerof;
fillY = y ? onef : zerof;
return this;
}
/** Sets fillX and fillY to 1 if true, 0 if false. */
public Cell<T> fill (boolean fill) {
fillX = fill ? onef : zerof;
fillY = fill ? onef : zerof;
return this;
}
/** Sets the alignment of the actor within the cell. Set to {@link Align#center}, {@link Align#top}, {@link Align#bottom},
* {@link Align#left}, {@link Align#right}, or any combination of those. */
public Cell<T> align (int align) {
this.align = align;
return this;
}
/** Sets the alignment of the actor within the cell to {@link Align#center}. This clears any other alignment. */
public Cell<T> center () {
align = centeri;
return this;
}
/** Adds {@link Align#top} and clears {@link Align#bottom} for the alignment of the actor within the cell. */
public Cell<T> top () {
if (align == null)
align = topi;
else
align = (align | Align.top) & ~Align.bottom;
return this;
}
/** Adds {@link Align#left} and clears {@link Align#right} for the alignment of the actor within the cell. */
public Cell<T> left () {
if (align == null)
align = lefti;
else
align = (align | Align.left) & ~Align.right;
return this;
}
/** Adds {@link Align#bottom} and clears {@link Align#top} for the alignment of the actor within the cell. */
public Cell<T> bottom () {
if (align == null)
align = bottomi;
else
align = (align | Align.bottom) & ~Align.top;
return this;
}
/** Adds {@link Align#right} and clears {@link Align#left} for the alignment of the actor within the cell. */
public Cell<T> right () {
if (align == null)
align = righti;
else
align = (align | Align.right) & ~Align.left;
return this;
}
/** Sets expandX, expandY, fillX, and fillY to 1. */
public Cell<T> grow () {
expandX = onei;
expandY = onei;
fillX = onef;
fillY = onef;
return this;
}
/** Sets expandX and fillX to 1. */
public Cell<T> growX () {
expandX = onei;
fillX = onef;
return this;
}
/** Sets expandY and fillY to 1. */
public Cell<T> growY () {
expandY = onei;
fillY = onef;
return this;
}
/** Sets expandX and expandY to 1. */
public Cell<T> expand () {
expandX = onei;
expandY = onei;
return this;
}
/** Sets expandX to 1. */
public Cell<T> expandX () {
expandX = onei;
return this;
}
/** Sets expandY to 1. */
public Cell<T> expandY () {
expandY = onei;
return this;
}
public Cell<T> expand (int x, int y) {
expandX = x;
expandY = y;
return this;
}
/** Sets expandX and expandY to 1 if true, 0 if false. */
public Cell<T> expand (boolean x, boolean y) {
expandX = x ? onei : zeroi;
expandY = y ? onei : zeroi;
return this;
}
public Cell<T> colspan (int colspan) {
this.colspan = colspan;
return this;
}
/** Sets uniformX and uniformY to true. */
public Cell<T> uniform () {
uniformX = Boolean.TRUE;
uniformY = Boolean.TRUE;
return this;
}
/** Sets uniformX to true. */
public Cell<T> uniformX () {
uniformX = Boolean.TRUE;
return this;
}
/** Sets uniformY to true. */
public Cell<T> uniformY () {
uniformY = Boolean.TRUE;
return this;
}
public Cell<T> uniform (boolean x, boolean y) {
uniformX = x;
uniformY = y;
return this;
}
public void setActorBounds (float x, float y, float width, float height) {
actorX = x;
actorY = y;
actorWidth = width;
actorHeight = height;
}
public float getActorX () {
return actorX;
}
public void setActorX (float actorX) {
this.actorX = actorX;
}
public float getActorY () {
return actorY;
}
public void setActorY (float actorY) {
this.actorY = actorY;
}
public float getActorWidth () {
return actorWidth;
}
public void setActorWidth (float actorWidth) {
this.actorWidth = actorWidth;
}
public float getActorHeight () {
return actorHeight;
}
public void setActorHeight (float actorHeight) {
this.actorHeight = actorHeight;
}
public int getColumn () {
return column;
}
public int getRow () {
return row;
}
/** @return May be null if this cell is row defaults. */
public Value getMinWidthValue () {
return minWidth;
}
public float getMinWidth () {
return minWidth.get(actor);
}
/** @return May be null if this cell is row defaults. */
public Value getMinHeightValue () {
return minHeight;
}
public float getMinHeight () {
return minHeight.get(actor);
}
/** @return May be null if this cell is row defaults. */
public Value getPrefWidthValue () {
return prefWidth;
}
public float getPrefWidth () {
return prefWidth.get(actor);
}
/** @return May be null if this cell is row defaults. */
public Value getPrefHeightValue () {
return prefHeight;
}
public float getPrefHeight () {
return prefHeight.get(actor);
}
/** @return May be null if this cell is row defaults. */
public Value getMaxWidthValue () {
return maxWidth;
}
public float getMaxWidth () {
return maxWidth.get(actor);
}
/** @return May be null if this cell is row defaults. */
public Value getMaxHeightValue () {
return maxHeight;
}
public float getMaxHeight () {
return maxHeight.get(actor);
}
/** @return May be null if this value is not set. */
public Value getSpaceTopValue () {
return spaceTop;
}
public float getSpaceTop () {
return spaceTop.get(actor);
}
/** @return May be null if this value is not set. */
public Value getSpaceLeftValue () {
return spaceLeft;
}
public float getSpaceLeft () {
return spaceLeft.get(actor);
}
/** @return May be null if this value is not set. */
public Value getSpaceBottomValue () {
return spaceBottom;
}
public float getSpaceBottom () {
return spaceBottom.get(actor);
}
/** @return May be null if this value is not set. */
public Value getSpaceRightValue () {
return spaceRight;
}
public float getSpaceRight () {
return spaceRight.get(actor);
}
/** @return May be null if this value is not set. */
public Value getPadTopValue () {
return padTop;
}
public float getPadTop () {
return padTop.get(actor);
}
/** @return May be null if this value is not set. */
public Value getPadLeftValue () {
return padLeft;
}
public float getPadLeft () {
return padLeft.get(actor);
}
/** @return May be null if this value is not set. */
public Value getPadBottomValue () {
return padBottom;
}
public float getPadBottom () {
return padBottom.get(actor);
}
/** @return May be null if this value is not set. */
public Value getPadRightValue () {
return padRight;
}
public float getPadRight () {
return padRight.get(actor);
}
/** Returns {@link #getPadLeft()} plus {@link #getPadRight()}. */
public float getPadX () {
return padLeft.get(actor) + padRight.get(actor);
}
/** Returns {@link #getPadTop()} plus {@link #getPadBottom()}. */
public float getPadY () {
return padTop.get(actor) + padBottom.get(actor);
}
/** @return May be null if this value is not set. */
public float getFillX () {
return fillX;
}
/** @return May be null. */
public float getFillY () {
return fillY;
}
/** @return May be null. */
public int getAlign () {
return align;
}
/** @return May be null. */
public int getExpandX () {
return expandX;
}
/** @return May be null. */
public int getExpandY () {
return expandY;
}
/** @return May be null. */
public int getColspan () {
return colspan;
}
/** @return May be null. */
public boolean getUniformX () {
return uniformX;
}
/** @return May be null. */
public boolean getUniformY () {
return uniformY;
}
/** Returns true if this cell is the last cell in the row. */
public boolean isEndRow () {
return endRow;
}
/** The actual amount of combined padding and spacing from the last layout. */
public float getComputedPadTop () {
return computedPadTop;
}
/** The actual amount of combined padding and spacing from the last layout. */
public float getComputedPadLeft () {
return computedPadLeft;
}
/** The actual amount of combined padding and spacing from the last layout. */
public float getComputedPadBottom () {
return computedPadBottom;
}
/** The actual amount of combined padding and spacing from the last layout. */
public float getComputedPadRight () {
return computedPadRight;
}
public void row () {
table.row();
}
public Table getTable () {
return table;
}
/** Sets all constraint fields to null. */
void clear () {
minWidth = null;
minHeight = null;
prefWidth = null;
prefHeight = null;
maxWidth = null;
maxHeight = null;
spaceTop = null;
spaceLeft = null;
spaceBottom = null;
spaceRight = null;
padTop = null;
padLeft = null;
padBottom = null;
padRight = null;
fillX = null;
fillY = null;
align = null;
expandX = null;
expandY = null;
colspan = null;
uniformX = null;
uniformY = null;
}
/** Reset state so the cell can be reused, setting all constraints to their {@link #defaults() default} values. */
public void reset () {
actor = null;
table = null;
endRow = false;
cellAboveIndex = -1;
Cell defaults = defaults();
if (defaults != null) set(defaults);
}
void set (Cell cell) {
minWidth = cell.minWidth;
minHeight = cell.minHeight;
prefWidth = cell.prefWidth;
prefHeight = cell.prefHeight;
maxWidth = cell.maxWidth;
maxHeight = cell.maxHeight;
spaceTop = cell.spaceTop;
spaceLeft = cell.spaceLeft;
spaceBottom = cell.spaceBottom;
spaceRight = cell.spaceRight;
padTop = cell.padTop;
padLeft = cell.padLeft;
padBottom = cell.padBottom;
padRight = cell.padRight;
fillX = cell.fillX;
fillY = cell.fillY;
align = cell.align;
expandX = cell.expandX;
expandY = cell.expandY;
colspan = cell.colspan;
uniformX = cell.uniformX;
uniformY = cell.uniformY;
}
/** @param cell May be null. */
void merge (Cell cell) {
if (cell == null) return;
if (cell.minWidth != null) minWidth = cell.minWidth;
if (cell.minHeight != null) minHeight = cell.minHeight;
if (cell.prefWidth != null) prefWidth = cell.prefWidth;
if (cell.prefHeight != null) prefHeight = cell.prefHeight;
if (cell.maxWidth != null) maxWidth = cell.maxWidth;
if (cell.maxHeight != null) maxHeight = cell.maxHeight;
if (cell.spaceTop != null) spaceTop = cell.spaceTop;
if (cell.spaceLeft != null) spaceLeft = cell.spaceLeft;
if (cell.spaceBottom != null) spaceBottom = cell.spaceBottom;
if (cell.spaceRight != null) spaceRight = cell.spaceRight;
if (cell.padTop != null) padTop = cell.padTop;
if (cell.padLeft != null) padLeft = cell.padLeft;
if (cell.padBottom != null) padBottom = cell.padBottom;
if (cell.padRight != null) padRight = cell.padRight;
if (cell.fillX != null) fillX = cell.fillX;
if (cell.fillY != null) fillY = cell.fillY;
if (cell.align != null) align = cell.align;
if (cell.expandX != null) expandX = cell.expandX;
if (cell.expandY != null) expandY = cell.expandY;
if (cell.colspan != null) colspan = cell.colspan;
if (cell.uniformX != null) uniformX = cell.uniformX;
if (cell.uniformY != null) uniformY = cell.uniformY;
}
public String toString () {
return actor != null ? actor.toString() : super.toString();
}
/** Returns the defaults to use for all cells. This can be used to avoid needing to set the same defaults for every table (eg,
* for spacing). */
static public Cell defaults () {
if (app == null || app != Gdx.app) {
app = Gdx.app;
defaults = new Cell();
defaults.minWidth = Value.minWidth;
defaults.minHeight = Value.minHeight;
defaults.prefWidth = Value.prefWidth;
defaults.prefHeight = Value.prefHeight;
defaults.maxWidth = Value.maxWidth;
defaults.maxHeight = Value.maxHeight;
defaults.spaceTop = Value.zero;
defaults.spaceLeft = Value.zero;
defaults.spaceBottom = Value.zero;
defaults.spaceRight = Value.zero;
defaults.padTop = Value.zero;
defaults.padLeft = Value.zero;
defaults.padBottom = Value.zero;
defaults.padRight = Value.zero;
defaults.fillX = zerof;
defaults.fillY = zerof;
defaults.align = centeri;
defaults.expandX = zeroi;
defaults.expandY = zeroi;
defaults.colspan = onei;
defaults.uniformX = null;
defaults.uniformY = null;
}
return defaults;
}
}
|
package com.bt.openlink.tinder.internal;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.TimeZone;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.dom4j.Element;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import com.bt.openlink.OpenlinkXmppNamespace;
import com.bt.openlink.message.PubSubMessageBuilder;
import com.bt.openlink.type.Call;
import com.bt.openlink.type.CallDirection;
import com.bt.openlink.type.CallFeature;
import com.bt.openlink.type.CallFeatureBoolean;
import com.bt.openlink.type.CallFeatureDeviceKey;
import com.bt.openlink.type.CallFeatureSpeakerChannel;
import com.bt.openlink.type.CallId;
import com.bt.openlink.type.CallState;
import com.bt.openlink.type.CallStatus;
import com.bt.openlink.type.Changed;
import com.bt.openlink.type.ConferenceId;
import com.bt.openlink.type.DeviceKey;
import com.bt.openlink.type.DeviceStatus;
import com.bt.openlink.type.FeatureId;
import com.bt.openlink.type.FeatureType;
import com.bt.openlink.type.InterestId;
import com.bt.openlink.type.ItemId;
import com.bt.openlink.type.OriginatorReference;
import com.bt.openlink.type.Participant;
import com.bt.openlink.type.ParticipantType;
import com.bt.openlink.type.PhoneNumber;
import com.bt.openlink.type.ProfileId;
import com.bt.openlink.type.PubSubNodeId;
import com.bt.openlink.type.RequestAction;
import com.bt.openlink.type.Site;
import com.bt.openlink.type.TelephonyCallId;
import com.bt.openlink.type.UserId;
/**
* This class is for internal use by the library only; users of the API should not access this class directly.
*/
public final class TinderPacketUtil {
private static final DateTimeFormatter ISO_8601_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
private static final DateTimeFormatter JAVA_UTIL_DATE_FORMATTER = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy");
private static final String ATTRIBUTE_DIRECTION = "direction";
private static final String ATTRIBUTE_DESTINATION = "destination";
private static final String ATTRIBUTE_NUMBER = "number";
private static final String ATTRIBUTE_START_TIME = "start";
private static final String ATTRIBUTE_TIMESTAMP = "timestamp";
private static final String ATTRIBUTE_DURATION = "duration";
private static final String ELEMENT_NUMBER = "number";
private static final String ELEMENT_PROFILE = "profile";
private TinderPacketUtil() {
}
@Nullable
public static Element getIOInElement(@Nonnull final IQ iq) {
return getChildElement(iq.getChildElement(), OpenlinkXmppNamespace.TAG_IODATA, OpenlinkXmppNamespace.TAG_IN);
}
@Nullable
public static Element getIOOutElement(@Nonnull final IQ iq) {
return getChildElement(iq.getChildElement(), OpenlinkXmppNamespace.TAG_IODATA, OpenlinkXmppNamespace.TAG_OUT);
}
@Nullable
public static Element getChildElement(@Nullable final Element element, final String... elementNames) {
Element childElement = element;
for (final String elementName : elementNames) {
if (childElement == null) {
break;
}
childElement = childElement.element(elementName);
}
return childElement;
}
public static void addElementWithTextIfNotNull(
@Nonnull final Element elementToAddTo,
@Nonnull final String elementName,
@Nullable final Object elementValue) {
if (elementValue != null) {
final Element callerElement = elementToAddTo.addElement(elementName);
callerElement.setText(elementValue.toString());
}
}
public static void addElementWithTextIfNotNull(
@Nonnull final Element elementToAddTo,
@Nonnull final String elementName,
@Nullable final LocalDate localDate,
@Nonnull final DateTimeFormatter dateFormatter) {
if (localDate != null) {
final String stringValue = dateFormatter.format(localDate);
addElementWithTextIfNotNull(elementToAddTo, elementName, stringValue);
}
}
@Nonnull
public static Optional<String> getOptionalChildElementString(@Nullable final Element parentElement, @Nonnull final String childElementName) {
return Optional.ofNullable(getNullableChildElementString(parentElement, childElementName));
}
@Nullable
public static String getNullableChildElementString(@Nullable final Element parentElement, @Nonnull final String childElementName) {
final Element childElement = getChildElement(parentElement, childElementName);
if (childElement != null) {
final String childElementText = childElement.getText().trim();
if (!childElementText.isEmpty()) {
return childElementText;
}
}
return null;
}
@Nonnull
public static Optional<LocalDate> getChildElementLocalDate(
@Nullable final Element parentElement,
@Nonnull final String childElementName,
@Nonnull final DateTimeFormatter dateTimeFormatter,
final String stanzaDescription,
@Nonnull final String dateFormat,
final List<String> parseErrors) {
final String dateText = getNullableChildElementString(parentElement, childElementName);
if (dateText != null) {
try {
return Optional.of(LocalDate.parse(dateText, dateTimeFormatter));
} catch (final DateTimeParseException e) {
parseErrors.add(String.format("Invalid %s; invalid %s '%s'; date format is '%s'", stanzaDescription, childElementName, dateText, dateFormat));
}
}
return Optional.empty();
}
@Nonnull
private static Optional<Instant> getChildElementISO8601(
@Nullable final Element parentElement,
@Nonnull final String childElementName,
@Nonnull final String stanzaDescription,
@Nonnull final List<String> parseErrors) {
final String childElementText = getNullableChildElementString(parentElement, childElementName);
if (childElementText != null) {
try {
return Optional.of(Instant.parse(childElementText));
} catch (final DateTimeParseException ignored) {
parseErrors.add(String.format("Invalid %s; invalid %s '%s'; format should be compliant with XEP-0082", stanzaDescription, childElementName, childElementText));
}
}
return Optional.empty();
}
@Nonnull
public static Optional<Long> getChildElementLong(
@Nullable final Element parentElement,
@Nonnull final String childElementName,
@Nonnull final String stanzaDescription,
@Nonnull final List<String> parseErrors) {
final String childElementText = getNullableChildElementString(parentElement, childElementName);
if (childElementText != null) {
try {
return Optional.of(Long.parseLong(childElementText));
} catch (final NumberFormatException ignored) {
parseErrors.add(String.format("Invalid %s; invalid %s '%s'; please supply an integer", stanzaDescription, childElementName, childElementText));
}
}
return Optional.empty();
}
@Nonnull
private static Optional<Boolean> getChildElementBoolean(
@Nullable final Element parentElement,
@Nonnull final String childElementName,
@Nonnull final String stanzaDescription,
@Nonnull final List<String> parseErrors) {
final String childElementText = getNullableChildElementString(parentElement, childElementName);
return getBoolean(childElementText, stanzaDescription, parseErrors);
}
@Nonnull
public static Optional<String> getStringAttribute(@Nullable final Element element, @Nonnull final String attributeName) {
return Optional.ofNullable(getNullableStringAttribute(element, attributeName));
}
@Nullable
public static String getNullableStringAttribute(@Nullable final Element element, @Nonnull final String attributeName) {
return getNullableStringAttribute(element, attributeName, false, "", Collections.emptyList());
}
@Nonnull
public static Optional<String> getStringAttribute(
@Nullable final Element element,
@Nonnull final String attributeName,
final boolean isRequired,
@Nonnull final String stanzaDescription,
@Nonnull final List<String> parseErrors) {
return Optional.ofNullable(getNullableStringAttribute(element, attributeName, isRequired, stanzaDescription, parseErrors));
}
@Nullable
public static String getNullableStringAttribute(
@Nullable final Element element,
@Nonnull final String attributeName,
final boolean isRequired,
@Nonnull final String stanzaDescription,
@Nonnull final List<String> parseErrors) {
final String attributeValue;
if (element == null) {
attributeValue = null;
} else {
final String valueString = element.attributeValue(attributeName);
attributeValue = valueString == null || valueString.isEmpty() ? null : valueString;
}
if (attributeValue == null && isRequired) {
parseErrors.add(String.format("Invalid %s; missing '%s' attribute is mandatory", stanzaDescription, attributeName));
}
return attributeValue;
}
@Nonnull
private static Optional<Long> getLongAttribute(final Element parentElement, final String attributeName, final String description, final List<String> parseErrors) {
final Optional<String> stringValue = getStringAttribute(parentElement, attributeName);
try {
return stringValue.map(Long::valueOf);
} catch (final NumberFormatException e) {
parseErrors.add(String.format("Invalid %s; Unable to parse number attribute %s: '%s'", description, attributeName, stringValue));
return Optional.empty();
}
}
@Nonnull
public static Optional<Integer> getIntegerAttribute(final Element parentElement, final String attributeName, final String description, final List<String> parseErrors) {
final Optional<String> stringValue = getStringAttribute(parentElement, attributeName);
try {
return stringValue.map(Integer::valueOf);
} catch (final NumberFormatException e) {
parseErrors.add(String.format("Invalid %s; Unable to parse number attribute %s: '%s'", description, attributeName, stringValue));
return Optional.empty();
}
}
private static Optional<Instant> getISO8601Attribute(final Element parentElement, final String attributeName, final String description, final List<String> parseErrors) {
final Optional<String> stringValue = getStringAttribute(parentElement, attributeName, false, description, parseErrors);
try {
return stringValue.map(Instant::parse);
} catch (final DateTimeParseException ignored) {
parseErrors.add(String.format("Invalid %s; invalid %s '%s'; format should be compliant with XEP-0082", description, attributeName, stringValue));
return Optional.empty();
}
}
private static Optional<Instant> getJavaUtilDateAttribute(final Element parentElement, final String attributeName, final String description, final List<String> parseErrors) {
final Optional<String> stringValue = getStringAttribute(parentElement, attributeName, false, description, parseErrors);
try {
return stringValue.map(string -> Instant.from(JAVA_UTIL_DATE_FORMATTER.parse(string)));
} catch (final DateTimeParseException ignored) {
parseErrors.add(String.format("Invalid %s; invalid %s '%s'; format should be 'dow mon dd hh:mm:ss zzz yyyy'", description, attributeName, stringValue));
return Optional.empty();
}
}
@Nonnull
public static Optional<Boolean> getBooleanAttribute(final Element element, final String id, final String description, final List<String> parseErrors) {
return getBoolean(getNullableStringAttribute(element, id), description, parseErrors);
}
@Nonnull
private static Element addCommandElement(@Nonnull final IQ request) {
return request.getElement().addElement("command", OpenlinkXmppNamespace.XMPP_COMMANDS.uri());
}
@Nonnull
public static Element addCommandIOInputElement(@Nonnull final IQ request, @Nonnull final OpenlinkXmppNamespace namespace) {
final Element commandElement = addCommandElement(request);
commandElement.addAttribute("action", "execute");
commandElement.addAttribute("node", namespace.uri());
final Element ioInputElement = commandElement.addElement(OpenlinkXmppNamespace.TAG_IODATA, OpenlinkXmppNamespace.XMPP_IO_DATA.uri());
ioInputElement.addAttribute("type", "input");
return ioInputElement.addElement(OpenlinkXmppNamespace.TAG_IN);
}
@Nonnull
public static Element addCommandIOOutputElement(@Nonnull final IQ result, @Nonnull final OpenlinkXmppNamespace namespace) {
final Element commandElement = addCommandElement(result);
commandElement.addAttribute("status", "completed");
commandElement.addAttribute("node", namespace.uri());
final Element ioInputElement = commandElement.addElement(OpenlinkXmppNamespace.TAG_IODATA, OpenlinkXmppNamespace.XMPP_IO_DATA.uri());
ioInputElement.addAttribute("type", "output");
return ioInputElement.addElement(OpenlinkXmppNamespace.TAG_OUT);
}
@Nonnull
public static Optional<JID> getJID(String jidString) {
return jidString == null || jidString.isEmpty() ? Optional.empty() : Optional.of(new JID(jidString));
}
public static void addCallStatus(@Nonnull final Element parentElement, @Nonnull final CallStatus callStatus) {
final Element callStatusElement = parentElement.addElement("callstatus", OpenlinkXmppNamespace.OPENLINK_CALL_STATUS.uri());
callStatus.isCallStatusBusy().ifPresent(callStatusBusy -> callStatusElement.addAttribute("busy", String.valueOf(callStatusBusy)));
callStatus.getCalls().forEach(call -> {
final Element callElement = callStatusElement.addElement("call");
final Element idElement = callElement.addElement("id");
call.getId().ifPresent(callId -> idElement.setText(callId.value()));
call.getTelephonyCallId().ifPresent(telephonyCallId -> idElement.addAttribute("telephony", telephonyCallId.value()));
call.getConferenceId().ifPresent(conferenceId -> callElement.addElement("conference").setText(conferenceId.value()));
call.getSite().ifPresent(site -> addSite(callElement, site));
call.getProfileId().ifPresent(profileId -> callElement.addElement(ELEMENT_PROFILE).setText(profileId.value()));
call.getUserId().ifPresent(userId -> callElement.addElement("user").setText(userId.value()));
call.getInterestId().ifPresent(interestId -> callElement.addElement("interest").setText(interestId.value()));
call.getChanged().ifPresent(changed -> callElement.addElement("changed").setText(changed.getId()));
call.getState().ifPresent(state -> callElement.addElement("state").setText(state.getLabel()));
call.getDirection().ifPresent(direction -> callElement.addElement(ATTRIBUTE_DIRECTION).setText(direction.getLabel()));
final Element callerElement = callElement.addElement("caller");
final Element callerNumberElement = callerElement.addElement(ELEMENT_NUMBER);
call.getCallerNumber().ifPresent(callerNumber -> callerNumberElement.setText(callerNumber.value()));
addList(callerNumberElement, call.getCallerE164Numbers(), "e164");
final Element callerNameElement = callerElement.addElement("name");
call.getCallerName().ifPresent(callerNameElement::setText);
final Element calledElement = callElement.addElement("called");
final Element calledNumberElement = calledElement.addElement(ELEMENT_NUMBER);
call.getCalledNumber().ifPresent(calledNumber -> calledNumberElement.setText(calledNumber.value()));
call.getCalledDestination().ifPresent(calledDestination -> calledNumberElement.addAttribute(ATTRIBUTE_DESTINATION, calledDestination.value()));
addList(calledNumberElement, call.getCalledE164Numbers(), "e164");
addOriginatorReferences(callElement, call.getOriginatorReferences());
final Element calledNameElement = calledElement.addElement("name");
call.getCalledName().ifPresent(calledNameElement::setText);
call.getStartTime().ifPresent(startTime -> callElement.addElement(ATTRIBUTE_START_TIME).setText(ISO_8601_FORMATTER.format(startTime.atZone(ZoneOffset.UTC))));
call.getDuration().ifPresent(duration -> callElement.addElement(ATTRIBUTE_DURATION).setText(String.valueOf(duration.toMillis())));
addActions(call, callElement);
addFeatures(call, callElement);
addParticipants(call, callElement);
});
}
private static void addList(Element element, List<?> list, String attributeName) {
final String string = String.join(",", list.stream().map(Object::toString).collect(Collectors.toList()));
if (!string.isEmpty()) {
element.addAttribute(attributeName, string);
}
}
public static void addOriginatorReferences(final Element callElement, final List<OriginatorReference> originatorReferences) {
if (!originatorReferences.isEmpty()) {
final Element originatorRefElement = callElement.addElement("originator-ref");
originatorReferences.forEach(originatorReference -> {
final Element propertyElement = originatorRefElement.addElement("property").addAttribute("id", originatorReference.getKey());
propertyElement.addElement("value").setText(originatorReference.getValue());
});
}
}
public static void addDeviceStatus(@Nonnull final Element itemElement, @Nonnull final DeviceStatus deviceStatus) {
final Element deviceStatusElement = itemElement.addElement("devicestatus", OpenlinkXmppNamespace.OPENLINK_DEVICE_STATUS.uri());
final Element profileElement = deviceStatusElement.addElement(ELEMENT_PROFILE);
deviceStatus.isOnline().ifPresent(online -> profileElement.addAttribute("online", String.valueOf(online)));
deviceStatus.getProfileId().ifPresent(profileId -> profileElement.setText(profileId.value()));
deviceStatus.getDeviceId().ifPresent(deviceId -> profileElement.addAttribute("devicenum", String.valueOf(deviceId)));
}
private static void addFeatures(@Nonnull final Call call, @Nonnull final Element callElement) {
final List<CallFeature> callFeatures = call.getFeatures();
if (!callFeatures.isEmpty()) {
final Element featuresElement = callElement.addElement("features");
callFeatures.forEach(feature -> {
final Element featureElement = featuresElement.addElement("feature");
feature.getId().ifPresent(id -> featureElement.addAttribute("id", id.value()));
feature.getType().ifPresent(type -> featureElement.addAttribute("type", type.getId()));
final Optional<String> featureLabel;
if (feature instanceof CallFeatureBoolean) {
final CallFeatureBoolean callFeatureBoolean = (CallFeatureBoolean) feature;
callFeatureBoolean.isEnabled().ifPresent(enabled -> featureElement.setText(String.valueOf(enabled)));
featureLabel = feature.getLabel();
} else if (feature instanceof CallFeatureDeviceKey) {
final CallFeatureDeviceKey callFeatureDeviceKey = (CallFeatureDeviceKey) feature;
final Element deviceKeysElement = featureElement.addElement("devicekeys", OpenlinkXmppNamespace.OPENLINK_DEVICE_KEY.uri());
callFeatureDeviceKey.getDeviceKey().ifPresent(deviceKey -> deviceKeysElement.addElement("key").setText(deviceKey.value()));
featureLabel = feature.getLabel();
} else if (feature instanceof CallFeatureSpeakerChannel) {
final CallFeatureSpeakerChannel callFeatureSpeakerChannel = (CallFeatureSpeakerChannel) feature;
final Element speakerChannelElement = featureElement.addElement("speakerchannel", OpenlinkXmppNamespace.OPENLINK_SPEAKER_CHANNEL.uri());
callFeatureSpeakerChannel.getChannel().ifPresent(channelNumber -> speakerChannelElement.addElement("channel").setText(String.valueOf(channelNumber)));
callFeatureSpeakerChannel.isMicrophoneActive().ifPresent(microphoneActive -> speakerChannelElement.addElement("microphone").setText(String.valueOf(microphoneActive)));
callFeatureSpeakerChannel.isMuteRequested().ifPresent(muteRequested -> speakerChannelElement.addElement("mute").setText(String.valueOf(muteRequested)));
featureLabel = Optional.empty();
} else {
featureLabel = feature.getLabel();
}
featureLabel.ifPresent(label -> featureElement.addAttribute("label", label));
});
}
}
private static void addActions(@Nonnull final Call call, @Nonnull final Element callElement) {
final Collection<RequestAction> actions = call.getActions();
if (!actions.isEmpty()) {
final Element actionsElement = callElement.addElement("actions");
actions.forEach(action -> actionsElement.addElement(action.getId()));
}
}
private static void addParticipants(@Nonnull final Call call, @Nonnull final Element callElement) {
final List<Participant> participants = call.getParticipants();
if (!participants.isEmpty()) {
final Element participantsElement = callElement.addElement("participants");
participants.forEach(participant -> {
final Element participantElement = participantsElement.addElement("participant");
participant.getJID().ifPresent(jid -> participantElement.addAttribute("jid", jid));
participant.getNumber().ifPresent(number->participantElement.addAttribute(ATTRIBUTE_NUMBER, number.value()));
addList(participantElement, participant.getE164Numbers(), "e164Number");
participant.getDestinationNumber().ifPresent(destination->participantElement.addAttribute(ATTRIBUTE_DESTINATION, destination.value()));
participant.getType().ifPresent(type -> participantElement.addAttribute("type", type.getId()));
participant.getDirection().ifPresent(direction -> participantElement.addAttribute(ATTRIBUTE_DIRECTION, direction.getLabel()));
participant.getStartTime().ifPresent(startTime -> {
final ZonedDateTime startTimeInUTC = startTime.atZone(TimeZone.getTimeZone("UTC").toZoneId());
participantElement.addAttribute(ATTRIBUTE_START_TIME, ISO_8601_FORMATTER.format(startTimeInUTC));
// Include the legacy timestamp attribute too
participantElement.addAttribute(ATTRIBUTE_TIMESTAMP, JAVA_UTIL_DATE_FORMATTER.format(startTimeInUTC));
});
participant.getDuration().ifPresent(duration -> participantElement.addAttribute(ATTRIBUTE_DURATION, String.valueOf(duration.toMillis())));
});
}
}
public static void addSite(final Element parentElement, final Site site) {
final Element siteElement = parentElement.addElement("site");
site.getId().ifPresent(id -> siteElement.addAttribute("id", String.valueOf(id)));
site.isDefault().ifPresent(isDefault -> siteElement.addAttribute("default", String.valueOf(isDefault)));
site.getType().ifPresent(type -> siteElement.addAttribute("type", type.getLabel()));
site.getName().ifPresent(siteElement::setText);
}
public static Optional<Site> getSite(@Nonnull final Element parentElement, @Nonnull final String description, @Nonnull final List<String> parseErrors) {
final Element siteElement = parentElement.element("site");
if (siteElement == null) {
return Optional.empty();
}
final Site.Builder siteBuilder = Site.Builder.start()
.setName(siteElement.getText());
final Optional<Long> id = getLongAttribute(siteElement, "id", description, parseErrors);
id.ifPresent(siteBuilder::setId);
final Optional<Boolean> isDefaultSite = getBooleanAttribute(siteElement, OpenlinkXmppNamespace.TAG_DEFAULT, description, parseErrors);
isDefaultSite.ifPresent(siteBuilder::setDefault);
final Optional<Site.Type> type = Site.Type.from(getNullableStringAttribute(siteElement, "type", false, description, parseErrors));
type.ifPresent(siteBuilder::setType);
return Optional.of(siteBuilder.build(parseErrors));
}
private static List<PhoneNumber> getPhoneNumbers(@Nullable final Element parentElement, String attributeName) {
final Optional<String> e164String = getStringAttribute(parentElement, attributeName);
final List<PhoneNumber> phoneNumbers = new ArrayList<>();
e164String.ifPresent(string -> Arrays.stream(string.split(","))
.map(String::trim)
.map(PhoneNumber::from)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(phoneNumbers::add));
return phoneNumbers;
}
@SuppressWarnings("unchecked")
public static Optional<CallStatus> getCallStatus(@Nullable final Element parentElement, @Nonnull final String description, @Nonnull final List<String> parseErrors) {
final Element callStatusElement = getChildElement(parentElement, "callstatus");
if (callStatusElement == null) {
return Optional.empty();
}
final CallStatus.Builder builder = CallStatus.Builder.start();
TinderPacketUtil.getBooleanAttribute(callStatusElement, "busy", "callstatus busy attribute", parseErrors).ifPresent(builder::setCallStatusBusy);
final List<Element> callElements = callStatusElement.elements("call");
for (final Element callElement : callElements) {
final Element callerElement = getChildElement(callElement, "caller");
final Element calledElement = getChildElement(callElement, "called");
final Call.Builder callBuilder = Call.Builder.start();
CallId.from(getNullableChildElementString(callElement, "id")).ifPresent(callBuilder::setId);
TelephonyCallId.from(getNullableStringAttribute(getChildElement(callElement, "id"), "telephony")).ifPresent(callBuilder::setTelephonyCallId);
ConferenceId.from(getNullableChildElementString(callElement, "conference")).ifPresent(callBuilder::setConferenceId);
getSite(callElement, description, parseErrors).ifPresent(callBuilder::setSite);
ProfileId.from(getNullableChildElementString(callElement, ELEMENT_PROFILE)).ifPresent(callBuilder::setProfileId);
UserId.from(getNullableChildElementString(callElement, "user")).ifPresent(callBuilder::setUserId);
InterestId.from(getNullableChildElementString(callElement, "interest")).ifPresent(callBuilder::setInterestId);
Changed.from(getNullableChildElementString(callElement, "changed")).ifPresent(callBuilder::setChanged);
CallState.from(getNullableChildElementString(callElement, "state")).ifPresent(callBuilder::setState);
CallDirection.from(getNullableChildElementString(callElement, ATTRIBUTE_DIRECTION)).ifPresent(callBuilder::setDirection);
PhoneNumber.from(getNullableChildElementString(callerElement, ELEMENT_NUMBER)).ifPresent(callBuilder::setCallerNumber);
getOptionalChildElementString(callerElement, "name").ifPresent(callBuilder::setCallerName);
callBuilder.addCallerE164Numbers(getPhoneNumbers(getChildElement(callerElement, ELEMENT_NUMBER), "e164"));
PhoneNumber.from(getNullableChildElementString(calledElement, ELEMENT_NUMBER)).ifPresent(callBuilder::setCalledNumber);
getOptionalChildElementString(calledElement, "name").ifPresent(callBuilder::setCalledName);
PhoneNumber.from(getNullableStringAttribute(getChildElement(calledElement, ELEMENT_NUMBER), ATTRIBUTE_DESTINATION)).ifPresent(callBuilder::setCalledDestination);
callBuilder.addCalledE164Numbers(getPhoneNumbers(getChildElement(calledElement, ELEMENT_NUMBER), "e164"));
getOriginatorReferences(callElement).forEach(callBuilder::addOriginatorReference);
getChildElementISO8601(callElement, ATTRIBUTE_START_TIME, description, parseErrors).ifPresent(callBuilder::setStartTime);
getChildElementLong(callElement, ATTRIBUTE_DURATION, description, parseErrors).map(Duration::ofMillis).ifPresent(callBuilder::setDuration);
getActions(callElement, callBuilder, description, parseErrors);
getFeatures(callElement, callBuilder, description, parseErrors);
getParticipants(callElement, callBuilder, description, parseErrors);
builder.addCall(callBuilder.build(parseErrors));
}
return Optional.of(builder.build(parseErrors));
}
@SuppressWarnings("unchecked")
public static List<OriginatorReference> getOriginatorReferences(final Element parentElement) {
final List<OriginatorReference> originatorReferences = new ArrayList<>();
final Element originatorRefElement = getChildElement(parentElement, "originator-ref");
if (originatorRefElement != null) {
final List<Element> propertyElements = originatorRefElement.elements("property");
propertyElements.forEach(propertyElement -> {
final String key = getStringAttribute(propertyElement, "id").orElse("");
final String value = getOptionalChildElementString(propertyElement, "value").orElse("");
originatorReferences.add(new OriginatorReference(key, value));
});
}
return originatorReferences;
}
public static Optional<DeviceStatus> getDeviceStatus(@Nullable final Element deviceStatusElement, @Nonnull final String stanzaDescription, @Nonnull final List<String> parseErrors) {
final Element profileElement = getChildElement(deviceStatusElement, ELEMENT_PROFILE);
if (profileElement == null) {
return Optional.empty();
}
final DeviceStatus.Builder builder = DeviceStatus.Builder.start();
getBooleanAttribute(profileElement, "online", stanzaDescription, parseErrors).ifPresent(builder::setOnline);
getStringAttribute(profileElement, "devicenum", false, stanzaDescription, parseErrors).ifPresent(builder::setDeviceId);
ProfileId.from(getNullableChildElementString(deviceStatusElement, ELEMENT_PROFILE)).ifPresent(builder::setProfileId);
return Optional.of(builder.build(parseErrors));
}
@SuppressWarnings("unchecked")
private static void getFeatures(@Nonnull final Element callElement, @Nonnull final Call.Builder callBuilder, final String description, List<String> parseErrors) {
final Element featuresElement = callElement.element("features");
if (featuresElement != null) {
final List<Element> featureElements = featuresElement.elements("feature");
for (final Element featureElement : featureElements) {
final Optional<FeatureId> featureId = FeatureId.from(featureElement.attributeValue("id"));
Optional<String> label = Optional.ofNullable(featureElement.attributeValue("label"));
final Optional<FeatureType> featureType = FeatureType.from(featureElement.attributeValue("type"));
final Iterator<Element> elementIterator = featureElement.elementIterator();
final boolean hasChildElement = elementIterator.hasNext();
final CallFeature.AbstractCallFeatureBuilder callFeatureBuilder;
if (hasChildElement) {
final Element childElement = elementIterator.next();
final String childElementName = childElement.getName();
switch (childElementName) {
case "devicekeys":
final CallFeatureDeviceKey.Builder deviceKeyBuilder = CallFeatureDeviceKey.Builder.start();
DeviceKey.from(getNullableChildElementString(childElement, "key")).ifPresent(deviceKeyBuilder::setDeviceKey);
callFeatureBuilder = deviceKeyBuilder;
break;
case "speakerchannel":
final CallFeatureSpeakerChannel.Builder speakerChannelBuilder = CallFeatureSpeakerChannel.Builder.start();
getChildElementLong(childElement, "channel", description, parseErrors).ifPresent(speakerChannelBuilder::setChannel);
getChildElementBoolean(childElement, "microphone", description, parseErrors).ifPresent(speakerChannelBuilder::setMicrophoneActive);
getChildElementBoolean(childElement, "mute", description, parseErrors).ifPresent(speakerChannelBuilder::setMuteRequested);
callFeatureBuilder = speakerChannelBuilder;
break;
default:
// Assume it's a simple true/false call feature
final CallFeatureBoolean.Builder booleanBuilder = CallFeatureBoolean.Builder.start();
getBoolean(featureElement.getText(), description, parseErrors).ifPresent(booleanBuilder::setEnabled);
callFeatureBuilder = booleanBuilder;
break;
}
} else {
// It's a simple true/false call feature
final CallFeatureBoolean.Builder booleanBuilder = CallFeatureBoolean.Builder.start();
getBoolean(featureElement.getText(), description, parseErrors).ifPresent(booleanBuilder::setEnabled);
callFeatureBuilder = booleanBuilder;
}
featureId.ifPresent(callFeatureBuilder::setId);
label.ifPresent(callFeatureBuilder::setLabel);
featureType.ifPresent(callFeatureBuilder::setType);
callBuilder.addFeature(callFeatureBuilder.build(parseErrors));
}
}
}
@Nonnull
private static Optional<Boolean> getBoolean(@Nullable final String value, String description, List<String> parseErrors) {
if ("true".equalsIgnoreCase(value)) {
return Optional.of(Boolean.TRUE);
} else if ("false".equalsIgnoreCase(value)) {
return Optional.of(Boolean.FALSE);
}
if (value != null) {
parseErrors.add(String.format("Invalid %s: %s is neither true or false", description, value));
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
private static void getParticipants(@Nonnull final Element callElement, @Nonnull final Call.Builder callBuilder, @Nonnull final String description, @Nonnull final List<String> parseErrors) {
final Element participantsElement = callElement.element("participants");
if (participantsElement != null) {
final List<Element> participantElements = participantsElement.elements("participant");
for (final Element participantElement : participantElements) {
final Participant.Builder participantBuilder = Participant.Builder.start();
getStringAttribute(participantElement, "jid", false, description, parseErrors).ifPresent(participantBuilder::setJID);
getStringAttribute(participantElement, ATTRIBUTE_NUMBER, false, description, parseErrors).flatMap(PhoneNumber::from).ifPresent(participantBuilder::setNumber);
participantBuilder.addE164Numbers(getPhoneNumbers(participantElement, "e164Number"));
getStringAttribute(participantElement, ATTRIBUTE_DESTINATION, false, description, parseErrors).flatMap(PhoneNumber::from).ifPresent(participantBuilder::setDestinationNumber);
ParticipantType.from(getNullableStringAttribute(participantElement, "type")).ifPresent(participantBuilder::setType);
CallDirection.from(getNullableStringAttribute(participantElement, ATTRIBUTE_DIRECTION)).ifPresent(participantBuilder::setDirection);
final Optional<Instant> participantTimestamp = getJavaUtilDateAttribute(participantElement, ATTRIBUTE_TIMESTAMP, description, parseErrors);
participantTimestamp.ifPresent(participantBuilder::setStartTime);
final Optional<Instant> participantStartTime = getISO8601Attribute(participantElement, ATTRIBUTE_START_TIME, description, parseErrors);
participantStartTime.ifPresent(participantBuilder::setStartTime);
if (participantStartTime.isPresent() && participantTimestamp.isPresent() && !participantStartTime.equals(participantTimestamp)) {
parseErrors.add("Invalid participant; the legacy timestamp field does not match the start time field");
}
final Optional<Long> participantDuration = getLongAttribute(participantElement, ATTRIBUTE_DURATION, description, parseErrors);
participantDuration.ifPresent(millis -> participantBuilder.setDuration(Duration.ofMillis(millis)));
callBuilder.addParticipant(participantBuilder.build(parseErrors));
}
}
}
@SuppressWarnings("unchecked")
private static void getActions(@Nonnull final Element callElement, @Nonnull final Call.Builder callBuilder, @Nonnull final String description, @Nonnull final List<String> parseErrors) {
final Element actionsElement = callElement.element("actions");
if (actionsElement != null) {
final List<Element> actionElements = actionsElement.elements();
for (final Element actionElement : actionElements) {
final String actionString = actionElement.getName();
final Optional<RequestAction> action = RequestAction.from(actionString);
if (action.isPresent()) {
callBuilder.addAction(action.get());
} else {
parseErrors.add(String.format("Invalid %s: %s is not a valid action", description, actionString));
}
}
}
}
@Nonnull
public static Element addPubSubMetaData(@Nonnull final Element messageElement, @Nonnull final PubSubMessageBuilder<?, ?> builder) {
final Element eventElement = messageElement.addElement("event", OpenlinkXmppNamespace.XMPP_PUBSUB_EVENT.uri());
final Element itemsElement = eventElement.addElement("items");
builder.getPubSubNodeId().ifPresent(nodeId -> itemsElement.addAttribute("node", nodeId.value()));
final Element itemElement = itemsElement.addElement("item");
builder.getItemId().ifPresent(id -> itemElement.addAttribute("id", id.value()));
return itemElement;
}
public static void addDelay(@Nonnull final Element messageElement, @Nonnull final PubSubMessageBuilder<?, ?> builder) {
builder.getDelay().ifPresent(stamp -> messageElement.addElement("delay", "urn:xmpp:delay").addAttribute("stamp", stamp.toString()));
}
@Nullable
public static Element setPubSubMetaData(
@Nonnull final Message message,
@Nonnull PubSubMessageBuilder<?, JID> builder,
@Nonnull final String description,
@Nonnull final List<String> parseErrors) {
builder.setId(message.getID());
builder.setFrom(message.getFrom());
builder.setTo(message.getTo());
final Element itemsElement = message.getChildElement("event", "http://jabber.org/protocol/pubsub#event").element("items");
final Element itemElement = itemsElement.element("item");
final Element delayElement = message.getChildElement("delay", "urn:xmpp:delay");
PubSubNodeId.from(itemsElement.attributeValue("node")).ifPresent(builder::setPubSubNodeId);
ItemId.from(TinderPacketUtil.getNullableStringAttribute(itemElement, "id")).ifPresent(builder::setItemId);
final Optional<String> stampOptional = TinderPacketUtil.getStringAttribute(delayElement, "stamp");
if (stampOptional.isPresent()) {
final String stamp = stampOptional.get();
try {
builder.setDelay(Instant.parse(stamp));
} catch (final DateTimeParseException e) {
parseErrors.add(String.format("Invalid %s; invalid timestamp '%s'; format should be compliant with XEP-0082", description, stamp));
}
}
return itemElement;
}
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// Modifications:
// 2007 Jan 29: Indenting; implement the new ThresholdNetworkInterface used by ServiceThresholder. - dj@opennms.org
// 2003 Jan 31: Cleaned up some unused imports.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// 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.
// For more information contact:
package org.opennms.netmgt.threshd;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.PollOutagesConfigFactory;
import org.opennms.netmgt.config.threshd.Package;
import org.opennms.netmgt.config.threshd.Parameter;
import org.opennms.netmgt.config.threshd.Service;
import org.opennms.netmgt.model.events.EventProxy;
import org.opennms.netmgt.poller.IPv4NetworkInterface;
import org.opennms.netmgt.scheduler.LegacyScheduler;
import org.opennms.netmgt.scheduler.ReadyRunnable;
import org.opennms.netmgt.xml.event.Event;
final class ThresholdableService extends IPv4NetworkInterface implements ThresholdNetworkInterface, ReadyRunnable {
private static final long serialVersionUID = 2477161545461824755L;
/**
* Interface's parent node identifier
*/
private int m_nodeId;
/**
* The package information for this interface/service pair
*/
private Package m_package;
/**
* The service information for this interface/service pair
*/
private final Service m_service;
/**
* Last known/current status
*/
private int m_status;
/**
* The last time a threshold check occurred
*/
private long m_lastThresholdCheckTime;
/**
* The last time this service was scheduled for threshold checking.
*/
private long m_lastScheduledThresholdCheckTime;
/**
* The proxy used to send events.
*/
private final EventProxy m_proxy;
/**
* The scheduler for threshd
*/
private final LegacyScheduler m_scheduler;
/**
* Service updates
*/
private ThresholderUpdates m_updates;
private static final boolean ABORT_THRESHOLD_CHECK = true;
private ServiceThresholder m_thresholder;
/**
* The key used to lookup the service properties that are passed to the
* thresholder.
*/
private final String m_svcPropKey;
/**
* The map of service parameters. These parameters are mapped by the
* composite key <em>(package name, service name)</em>.
*/
private static Map<String,Map> SVC_PROP_MAP = Collections.synchronizedMap(new TreeMap<String,Map>());
private Threshd m_threshd;
/**
* Constructs a new instance of a ThresholdableService object.
*
* @param dbNodeId
* The database identifier key for the interfaces' node
* @param address
* InetAddress of the interface to collect from
* @param svcName
* Service name
* @param pkg
* The package containing parms for this collectable service.
*
*/
ThresholdableService(Threshd threshd, int dbNodeId, InetAddress address, String svcName, org.opennms.netmgt.config.threshd.Package pkg) {
super(address);
m_nodeId = dbNodeId;
m_package = pkg;
m_status = ServiceThresholder.THRESHOLDING_SUCCEEDED;
m_threshd = threshd;
m_proxy = threshd.getEventProxy();
m_scheduler = threshd.getScheduler();
m_thresholder = threshd.getServiceThresholder(svcName);
m_updates = new ThresholderUpdates();
// Initialize last scheduled threshold check and last threshold
// check times to current time.
m_lastScheduledThresholdCheckTime = System.currentTimeMillis();
m_lastThresholdCheckTime = System.currentTimeMillis();
// find the service matching the name
Service svc = null;
Enumeration esvc = m_package.enumerateService();
while (esvc.hasMoreElements()) {
Service s = (Service) esvc.nextElement();
if (s.getName().equalsIgnoreCase(svcName)) {
svc = s;
break;
}
}
if (svc == null)
throw new RuntimeException("Service name not part of package!");
// save reference to the service
m_service = svc;
// add property list for this service/package combination if
// it doesn't already exist in the service property map
m_svcPropKey = m_package.getName() + "." + m_service.getName();
synchronized (SVC_PROP_MAP) {
if (!SVC_PROP_MAP.containsKey(m_svcPropKey)) {
Map<String,String> m = Collections.synchronizedMap(new TreeMap<String,String>());
Enumeration<Parameter> ep = m_service.enumerateParameter();
while (ep.hasMoreElements()) {
Parameter p = ep.nextElement();
m.put(p.getKey(), p.getValue());
}
// Add configured service 'interval' attribute as
// a property as well. Needed by the ServiceThresholder
// check() method in order to generate the
// correct rrdtool fetch command.
m.put("interval", Integer.toString((int) m_service.getInterval()));
SVC_PROP_MAP.put(m_svcPropKey, m);
}
}
}
/**
* Returns node identifier
*/
public int getNodeId() {
return m_nodeId;
}
/**
* Set node identifier
*/
public void setNodeId(int nodeId) {
m_nodeId = nodeId;
}
/**
* Returns the service name
*/
public String getServiceName() {
return m_service.getName();
}
/**
* Returns the service name
*/
public String getPackageName() {
return m_package.getName();
}
/**
* Uses the existing package name to try and re-obtain the package from the threshd config factory.
* Should be called when the threshd config has been reloaded.
*/
public void refreshPackage() {
Package refreshedPackage=m_threshd.getPackage(getPackageName());
if(refreshedPackage!=null) {
this.m_package=refreshedPackage;
}
}
/**
* Returns updates object
*/
public ThresholderUpdates getThresholderUpdates() {
return m_updates;
}
/**
* This method is used to evaluate the status of this interface and service
* pair. If it is time to run the threshold check again then a value of true
* is returned. If the interface is not ready then a value of false is
* returned.
*/
public boolean isReady() {
boolean ready = false;
if (!m_threshd.isSchedulingCompleted())
return false;
if (m_service.getInterval() < 1) {
ready = true;
} else {
ready = ((m_service.getInterval() - (System.currentTimeMillis() - m_lastScheduledThresholdCheckTime)) < 1);
}
return ready;
}
/**
* Returns the service's configured thresholding interval.
*/
public long getInterval() {
return m_service.getInterval();
}
/**
* Generate event and send it to eventd via the event proxy.
*
* uei Universal event identifier of event to generate.
*/
private void sendEvent(String uei) {
ThreadCategory log = log();
Event event = new Event();
event.setUei(uei);
event.setNodeid((long) m_nodeId);
event.setInterface(m_address.getHostAddress());
event.setService("SNMP");
event.setSource("OpenNMS.Threshd");
try {
event.setHost(InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException ex) {
event.setHost("unresolved.host");
}
event.setTime(EventConstants.formatToString(new java.util.Date()));
// Send the event
try {
m_proxy.send(event);
} catch (Exception ex) {
log.error("Failed to send the event " + uei + " for interface " + m_address.getHostAddress(), ex);
}
if (log.isDebugEnabled())
log.debug("sendEvent: Sent event " + uei + " for " + m_nodeId + "/" + m_address.getHostAddress() + "/" + m_service.getName());
}
/**
* This is the main method of the class. An instance is normally enqueued on
* the scheduler which checks its <code>isReady</code> method to determine
* execution. If the instance is ready for execution then it is started with
* it's own thread context to execute the query. The last step in the method
* before it exits is to reschedule the interface.
*
*/
public void run() {
ThreadCategory log = log();
// Process any oustanding updates.
if (processUpdates() == ABORT_THRESHOLD_CHECK)
return;
// Update last scheduled poll time
m_lastScheduledThresholdCheckTime = System.currentTimeMillis();
// Check scheduled outages to see if any apply indicating
// that threshold checking should be skipped
if (scheduledOutage()) {
// Outage applied...reschedule the service and return
m_scheduler.schedule(this, m_service.getInterval());
return;
}
// Perform threshold checking
if (log.isDebugEnabled())
log.debug("run: starting new threshold check for " + m_address.getHostAddress());
int status = ServiceThresholder.THRESHOLDING_FAILED;
Map propertiesMap = SVC_PROP_MAP.get(m_svcPropKey);
try {
status = m_thresholder.check(this, m_proxy, propertiesMap);
} catch (Throwable t) {
log.error("run: An undeclared throwable was caught during SNMP thresholding for interface " + m_address.getHostAddress(), t);
}
// Update last threshold check time
m_lastThresholdCheckTime = System.currentTimeMillis();
// Any change in status?
if (status != m_status) {
// Generate transition events
if (log.isDebugEnabled())
log.debug("run: change in thresholding status, generating event.");
// Send the appropriate event
switch (status) {
case ServiceThresholder.THRESHOLDING_SUCCEEDED:
sendEvent(EventConstants.THRESHOLDING_SUCCEEDED_EVENT_UEI);
break;
case ServiceThresholder.THRESHOLDING_FAILED:
sendEvent(EventConstants.THRESHOLDING_FAILED_EVENT_UEI);
break;
default:
break;
}
}
// Set the new status
m_status = status;
// Reschedule ourselves
m_scheduler.schedule(this, this.getInterval());
return;
}
Map getPropertyMap() {
return (Map) SVC_PROP_MAP.get(m_svcPropKey);
}
/**
* Checks the package information for the thresholdable service and
* determines if any of the calendar outages associated with the package
* apply to the current time and the service's interface. If an outage
* applies true is returned...otherwise false is returned.
*
* @return false if no outage found (indicating thresholding may be
* performed) or true if applicable outage is found (indicating
* thresholding should be skipped).
*/
private boolean scheduledOutage() {
boolean outageFound = false;
PollOutagesConfigFactory outageFactory = PollOutagesConfigFactory.getInstance();
// Iterate over the outage names defined in the interface's package.
// For each outage...if the outage contains a calendar entry which
// applies to the current time and the outage applies to this
// interface then break and return true. Otherwise process the
// next outage.
Iterator iter = m_package.getOutageCalendarCollection().iterator();
while (iter.hasNext()) {
String outageName = (String) iter.next();
// Does the outage apply to the current time?
if (outageFactory.isCurTimeInOutage(outageName)) {
// Does the outage apply to this interface?
if ((outageFactory.isNodeIdInOutage((long)m_nodeId, outageName)) ||
(outageFactory.isInterfaceInOutage(m_address.getHostAddress(), outageName))) {
if (log().isDebugEnabled())
log().debug("scheduledOutage: configured outage '" + outageName + "' applies, interface " + m_address.getHostAddress() + " will not be thresholded for " + m_service);
outageFound = true;
break;
}
}
}
return outageFound;
}
/**
* Process any outstanding updates.
*
* @return true if update indicates that threshold check should be aborted
* (for example due to deletion flag being set), false otherwise.
*/
private boolean processUpdates() {
ThreadCategory log = log();
// All update processing takes place within synchronized block
// to ensure that no updates are missed.
synchronized (this) {
if (!m_updates.hasUpdates())
return !ABORT_THRESHOLD_CHECK;
if (m_updates.isDeletionFlagSet()) {
// Deletion flag is set, simply return without polling
// or rescheduling this collector.
if (log.isDebugEnabled())
log.debug("Collector for " + m_address.getHostAddress() + " is marked for deletion...skipping thresholding, will not reschedule.");
return ABORT_THRESHOLD_CHECK;
}
if (m_updates.isReinitializationFlagSet()) {
// Reinitialization flag is set, call initialize() to
// reinit the collector for this interface
if (log.isDebugEnabled())
log.debug("ReinitializationFlag set for " + m_address.getHostAddress());
try {
m_thresholder.release(this);
m_thresholder.initialize(this, this.getPropertyMap());
if (log.isDebugEnabled())
log.debug("Completed reinitializing SNMP collector for " + m_address.getHostAddress());
} catch (RuntimeException rE) {
log.warn("Unable to reschedule " + m_address.getHostAddress() + " for " + m_service.getName() + " thresholding, reason: " + rE.getMessage());
} catch (Throwable t) {
log.error("Uncaught exception, failed to reschedule interface " + m_address.getHostAddress() + " for " + m_service.getName() + " thresholding", t);
}
}
if (m_updates.isReparentingFlagSet()) {
if (log.isDebugEnabled())
log.debug("ReparentingFlag set for " + m_address.getHostAddress());
// Convert new nodeId to integer value
int newNodeId = -1;
try {
newNodeId = Integer.parseInt(m_updates.getReparentNewNodeId());
} catch (NumberFormatException nfE) {
log.warn("Unable to convert new nodeId value to an int while processing reparenting update: " + m_updates.getReparentNewNodeId());
}
// Set this collector's nodeId to the value of the interface's
// new parent nodeid.
m_nodeId = newNodeId;
// We must now reinitialize the thresholder for this interface,
// in order to update the NodeInfo object to reflect changes
// to the interface's parent node among other things.
try {
if (log.isDebugEnabled())
log.debug("Reinitializing SNMP thresholder for " + m_address.getHostAddress());
m_thresholder.release(this);
m_thresholder.initialize(this, this.getPropertyMap());
if (log.isDebugEnabled())
log.debug("Completed reinitializing SNMP thresholder for " + m_address.getHostAddress());
} catch (RuntimeException rE) {
log.warn("Unable to initialize " + m_address.getHostAddress() + " for " + m_service.getName() + " thresholding, reason: " + rE.getMessage());
} catch (Throwable t) {
log.error("Uncaught exception, failed to initialize interface " + m_address.getHostAddress() + " for " + m_service.getName() + " thresholding", t);
}
}
// Updates have been applied. Reset ThresholderUpdates object.
m_updates.reset();
} // end synchronized
return !ABORT_THRESHOLD_CHECK;
}
}
|
package org.mwc.debrief.lite.menu;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.geotools.swing.JMapPane;
import org.mwc.debrief.lite.DebriefLiteApp;
import org.mwc.debrief.lite.map.GeoToolMapRenderer;
import org.mwc.debrief.lite.util.DoSave;
import org.mwc.debrief.lite.util.DoSaveAs;
import org.pushingpixels.flamingo.api.ribbon.JRibbon;
import org.pushingpixels.flamingo.api.ribbon.JRibbonBand;
import org.pushingpixels.flamingo.api.ribbon.RibbonElementPriority;
import org.pushingpixels.flamingo.api.ribbon.RibbonTask;
import Debrief.GUI.Frames.Application;
import Debrief.GUI.Frames.Session;
import Debrief.ReaderWriter.XML.DebriefXMLReaderWriter;
public class DebriefRibbonFile
{
private static class CopyPlotAsPNG extends AbstractAction
{
private static final long serialVersionUID = 1L;
private final GeoToolMapRenderer mapRenderer;
public CopyPlotAsPNG(final GeoToolMapRenderer _geoMapRenderer)
{
mapRenderer = _geoMapRenderer;
}
@Override
public void actionPerformed(final ActionEvent e)
{
final JMapPane map = (JMapPane) mapRenderer.getMap();
final RenderedImage image = map.getBaseImage();
if (image != null)
{
final Transferable t = new Transferable()
{
@Override
public Object getTransferData(final DataFlavor flavor)
throws UnsupportedFlavorException, IOException
{
if (isDataFlavorSupported(flavor))
{
return image;
}
return null;
}
@Override
public DataFlavor[] getTransferDataFlavors()
{
return new DataFlavor[]
{DataFlavor.imageFlavor};
}
@Override
public boolean isDataFlavorSupported(final DataFlavor flavor)
{
if (flavor == DataFlavor.imageFlavor)
return true;
return false;
}
};
final ClipboardOwner co = new ClipboardOwner()
{
@Override
public void lostOwnership(final Clipboard clipboard,
final Transferable contents)
{
System.out.println("Copy to PNG: Lost Ownership");
}
};
final Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.setContents(t, co);
}
}
}
// Actions
private static class TODOAction extends AbstractAction
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
System.out.println("Not implemented yet");
}
}
private static class NewFileAction extends AbstractAction
{
private static final long serialVersionUID = 1L;
private final JFrame _theFrame;
private final Session _session;
private Runnable _doReset;
public NewFileAction(final JFrame theFrame, final Session session,
final Runnable doReset)
{
_theFrame = theFrame;
_session = session;
_doReset = doReset;
}
@Override
public void actionPerformed(final ActionEvent e)
{
// ask user whether to save, if file is dirty.
if (DebriefLiteApp.isDirty())
{
int res = JOptionPane.showConfirmDialog(null,
"Save changes before creating new file?");
if (res == JOptionPane.OK_OPTION)
{
if (DebriefLiteApp.currentFileName != null
&& DebriefLiteApp.currentFileName.endsWith(".rep"))
{
String newFileName = DebriefLiteApp.currentFileName.replaceAll(
".rep", ".dpf");
DebriefRibbonFile.saveChanges(newFileName, _session, _theFrame);
}
else
{
DebriefRibbonFile.saveChanges(DebriefLiteApp.currentFileName,
_session, _theFrame);
}
_doReset.run();
}
else if (res == JOptionPane.NO_OPTION)
{
_doReset.run();
}
else
{
// do nothing
}
}
else
{
_doReset.run();
}
}
}
protected static void addFileTab(final JRibbon ribbon,
final GeoToolMapRenderer geoMapRenderer, final Session session, final Runnable resetAction)
{
final JRibbonBand fileMenu = new JRibbonBand("File", null);
MenuUtils.addCommand("New", "images/16/new.png", new NewFileAction(
(JFrame) ribbon.getRibbonFrame(), session, resetAction), fileMenu,
RibbonElementPriority.MEDIUM);
MenuUtils.addCommand("Open Plot", "images/16/open.png", new TODOAction(),
fileMenu, RibbonElementPriority.MEDIUM);
fileMenu.startGroup();
MenuUtils.addCommand("Save", "images/16/save.png",
new DoSave(session,ribbon.getRibbonFrame()), fileMenu, RibbonElementPriority.MEDIUM);
MenuUtils.addCommand("Save as", "images/16/save-as.png",
new DoSaveAs(session,ribbon.getRibbonFrame()), fileMenu, RibbonElementPriority.MEDIUM);
fileMenu.setResizePolicies(MenuUtils.getStandardRestrictivePolicies(
fileMenu));
final JRibbonBand exitMenu = new JRibbonBand("Exit", null);
MenuUtils.addCommand("Exit", "images/16/exit.png", new AbstractAction()
{
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
System.exit(0);
}
}, exitMenu, RibbonElementPriority.MEDIUM);
exitMenu.setResizePolicies(MenuUtils.getStandardRestrictivePolicies(
exitMenu));
final JRibbonBand importMenu = new JRibbonBand("Import / Export", null);
MenuUtils.addCommand("Import Replay", "images/16/import.png",
new TODOAction(), importMenu, RibbonElementPriority.MEDIUM);
importMenu.setResizePolicies(MenuUtils.getStandardRestrictivePolicies(
importMenu));
MenuUtils.addCommand("Copy Plot to PNG", "images/16/import.png",
new CopyPlotAsPNG(geoMapRenderer), importMenu,
RibbonElementPriority.MEDIUM);
fileMenu.setPreferredSize(new Dimension(150, 50));
importMenu.setPreferredSize(new Dimension(50, 50));
final RibbonTask fileTask = new RibbonTask("File", fileMenu, importMenu,
exitMenu);
fileMenu.setPreferredSize(new Dimension(50, 50));
ribbon.addTask(fileTask);
}
public static void saveChanges(String currentFileName,Session session,JFrame theFrame)
{
File targetFile = new File(currentFileName);
if((targetFile!=null && targetFile.exists() && targetFile.canWrite())
|| (targetFile!=null && !targetFile.exists() && targetFile.getParentFile().canWrite()) )
{
//export to this file.
// if it already exists, check with rename/cancel
OutputStream stream = null;
try
{
stream = new FileOutputStream(targetFile.getAbsolutePath());
DebriefXMLReaderWriter.exportThis(session, stream);
}
catch (FileNotFoundException e1)
{
Application.logError2(Application.ERROR, "Can't find file", e1);
}
finally {
try
{
stream.close();
DebriefLiteApp.currentFileName = targetFile.getAbsolutePath();
DebriefLiteApp.setDirty(false);
}
catch (IOException e1)
{
//ignore
}
}
}
}
}
|
package org.smeup.sys.os.lib.base.api;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.smeup.sys.il.data.QCharacter;
import org.smeup.sys.il.data.QEnum;
import org.smeup.sys.il.data.QScroller;
import org.smeup.sys.il.data.annotation.DataDef;
import org.smeup.sys.il.data.annotation.Main;
import org.smeup.sys.il.data.annotation.Program;
import org.smeup.sys.il.memo.QResourceReader;
import org.smeup.sys.os.core.QExceptionManager;
import org.smeup.sys.os.core.jobs.QJob;
import org.smeup.sys.os.core.jobs.QJobLogManager;
import org.smeup.sys.os.lib.QLibrary;
import org.smeup.sys.os.lib.QLibraryManager;
import org.smeup.sys.os.lib.base.api.tools.CurrentLibraryChangeHelper;
@Program(name = "QLICHLIB")
public class LibraryListChanger {
public static enum QCPFMSG {
CPF2110
}
@Inject
private QExceptionManager exceptionManager;
@Inject
private QJob job;
@Inject
private QLibraryManager libraryManager;
@Inject
private QJobLogManager jobLogManager;
@Main
public void main(@DataDef(dimension = 250, length = 10) QScroller<QEnum<LIBRARIESFORCURRENTTHREADEnum, QCharacter>> librariesForCurrentThread,
@DataDef(length = 10) QEnum<CURRENTLIBRARYEnum, QCharacter> currentLibrary) {
switch (librariesForCurrentThread.first().asEnum()) {
case SAME:
break;
case NONE:
job.getLibraries().clear();
job.getLibraries().add(job.getSystem().getSystemLibrary());
break;
case OTHER: {
QResourceReader<QLibrary> libraryReader = libraryManager.getLibraryReader(job);
List<String> newLibList = new ArrayList<String>();
for (QEnum<LIBRARIESFORCURRENTTHREADEnum, QCharacter> libEnum : librariesForCurrentThread) {
String lib = libEnum.asData().trimR();
if (lib.isEmpty())
continue;
if(libraryReader.exists(lib))
newLibList.add(lib);
}
if (newLibList.size() > 0) {
job.getLibraries().clear();
job.getLibraries().add(job.getSystem().getSystemLibrary());
job.getLibraries().addAll(newLibList);
}
break;
}
}
new CurrentLibraryChangeHelper(job, libraryManager, jobLogManager, exceptionManager).changeCurrentLibrary(currentLibrary);
}
public static enum LIBRARIESFORCURRENTTHREADEnum {
SAME, NONE, OTHER
}
}
|
package org.smeup.sys.os.type.base.api;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.smeup.sys.dk.core.annotation.Supported;
import org.smeup.sys.il.core.QObjectIterator;
import org.smeup.sys.il.core.QObjectNameable;
import org.smeup.sys.il.data.QCharacter;
import org.smeup.sys.il.data.QEnum;
import org.smeup.sys.il.data.QScroller;
import org.smeup.sys.il.data.annotation.DataDef;
import org.smeup.sys.il.data.annotation.Entry;
import org.smeup.sys.il.data.annotation.Program;
import org.smeup.sys.il.data.annotation.Special;
import org.smeup.sys.os.core.Scope;
import org.smeup.sys.os.core.jobs.QJob;
import org.smeup.sys.os.core.resources.QResourceManager;
import org.smeup.sys.os.core.resources.QResourceReader;
import org.smeup.sys.os.core.resources.QResourceWriter;
import org.smeup.sys.os.type.QType;
import org.smeup.sys.os.type.QTypeRegistry;
import org.smeup.sys.os.type.QTypedObject;
@Program(name = "QLICRDUP")
public @Supported class ObjectDuplicator {
public static enum QCPFMSG {
CPF2130
}
@Inject
private QTypeRegistry typeRegistry;
@Inject
private QResourceManager resourceManager;
@Inject
private QJob job;
public @Entry void main(
@Supported @DataDef(length = 10) QEnum<FROMOBJECTEnum, QCharacter> fromObject,
@Supported @DataDef(length = 10) QEnum<FROMLIBRARYEnum, QCharacter> fromLibrary,
@Supported @DataDef(dimension=57,length=7) QEnum<OBJECTTYPEEnum, QScroller<QCharacter>> objectTypes,
@Supported @DataDef(length = 10) QEnum<TOLIBRARYEnum, QCharacter> toLibrary,
@Supported @DataDef(length = 10) QEnum<NEWOBJECTEnum, QCharacter> newObjectName,
@DataDef(length = 10) QEnum<FROMASPDEVICEEnum, QCharacter> fromASPDevice,
@DataDef(length = 10) QEnum<TOASPDEVICEEnum, QCharacter> toASPDevice,
@Supported @DataDef(length = 1) QEnum<DUPLICATEDATAEnum, QCharacter> duplicateData,
@DataDef(length = 1) QEnum<DUPLICATECONSTRAINTSEnum, QCharacter> duplicateConstraints,
@DataDef(length = 1) QEnum<DUPLICATETRIGGERSEnum, QCharacter> duplicateTriggers,
@DataDef(length = 1) QEnum<DUPLICATEFILEIDENTIFIERSEnum, QCharacter> duplicateFileIdentifiers) {
List<QType<?>> types = typesFrom(objectTypes);
for (QType<?> type : types) {
QResourceReader<?> resourceReader = null;
switch (fromLibrary.asEnum()) {
case CURLIB:
resourceReader = resourceManager.getResourceReader(job, type.getTypedClass(), Scope.CURRENT_LIBRARY);
break;
case LIBL:
resourceReader = resourceManager.getResourceReader(job, type.getTypedClass(), Scope.LIBRARY_LIST);
break;
case OTHER:
resourceReader = resourceManager.getResourceReader(job, type.getTypedClass(), fromLibrary.asData().trimR());
break;
}
QObjectIterator<? extends QObjectNameable> objectIterator = null;
switch (fromObject.asEnum()) {
case ALL:
objectIterator = resourceReader.find(null);
break;
case OTHER:
objectIterator = resourceReader.find(fromObject.asData().trimR());
break;
}
while (objectIterator.hasNext()) {
duplicate(toLibrary, newObjectName, type, (QTypedObject) objectIterator.next());
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void duplicate(QEnum<TOLIBRARYEnum, QCharacter> toLibrary, QEnum<NEWOBJECTEnum, QCharacter> newObjectName, QType<?> type, QTypedObject objToDuplicate) {
QResourceWriter resourceWriter = getWriter(toLibrary, type, objToDuplicate.getLibrary());
QTypedObject duplicatedObject = (QTypedObject) EcoreUtil.copy((EObject)objToDuplicate);
switch (newObjectName.asEnum()) {
case SAME:
case OBJ:
//Nulla
break;
case OTHER:
duplicatedObject.setName(newObjectName.asData().trimR());
break;
}
resourceWriter.save(duplicatedObject);
}
private QResourceWriter<? extends QTypedObject> getWriter(QEnum<TOLIBRARYEnum, QCharacter> toLibrary, QType<?> type, String sourceLibraryName) {
QResourceWriter<? extends QTypedObject> resourceWriter = null;
switch (toLibrary.asEnum()) {
case CURLIB:
resourceWriter = resourceManager.getResourceWriter(job, type.getTypedClass(), Scope.CURRENT_LIBRARY);
break;
case SAME:
case FROMLIB:
resourceWriter = resourceManager.getResourceWriter(job, type.getTypedClass(), sourceLibraryName);
break;
case OTHER:
resourceWriter = resourceManager.getResourceWriter(job, type.getTypedClass(), toLibrary.asData().trimR());
break;
}
return resourceWriter;
}
private List<QType<?>> typesFrom(QEnum<OBJECTTYPEEnum, QScroller<QCharacter>> objectTypes) {
List<QType<?>> result = new ArrayList<QType<?>>();
for(QCharacter type: objectTypes.asData()) {
String objectTypeString = type.trimR();
if (objectTypeString.equals("*ALL")) {
result.addAll(typeRegistry.list());
break;
} else {
QType<?> typeFound = typeRegistry.lookup("*" + objectTypeString);
if (typeFound != null) {
result.add(typeFound);
}
}
}
return result;
}
public static enum FROMOBJECTEnum {
ALL, OTHER
}
public static enum FROMLIBRARYEnum {
LIBL, CURLIB, OTHER
}
public static enum OBJECTTYPEEnum {
ALL,
@Special(value = "ALRTBL") ALRTBL,
@Special(value = "AUTL") AUTL, @Special(value = "BNDDIR")
BNDDIR, @Special(value = "CHTFMT")
CHTFMT, @Special(value = "CLD")
CLD, @Special(value = "CLS")
CLS, @Special(value = "CMD")
CMD, @Special(value = "CRQD")
CRQD, @Special(value = "CSI")
CSI, @Special(value = "CSPMAP")
CSPMAP, @Special(value = "CSPTBL")
CSPTBL, @Special(value = "DTAARA")
DTAARA, @Special(value = "FCT")
FCT, @Special(value = "FILE")
FILE, @Special(value = "FNTRSC")
FNTRSC, @Special(value = "FNTTBL")
FNTTBL, @Special(value = "FORMDF")
FORMDF, @Special(value = "FTR")
FTR, @Special(value = "GSS")
GSS, @Special(value = "IGCDCT")
IGCDCT, @Special(value = "IGCSRT")
IGCSRT, @Special(value = "JOBD")
JOBD, @Special(value = "JOBQ")
JOBQ, @Special(value = "LOCALE")
LOCALE, @Special(value = "MEDDFN")
MEDDFN, @Special(value = "MENU")
MENU, @Special(value = "MGTCOL")
MGTCOL, @Special(value = "MODULE")
MODULE, @Special(value = "MSGF")
MSGF, @Special(value = "MSGQ")
MSGQ, @Special(value = "M36CFG")
M36CFG, @Special(value = "NODGRP")
NODGRP, @Special(value = "NODL")
NODL, @Special(value = "OUTQ")
OUTQ, @Special(value = "OVL")
OVL, @Special(value = "PAGDFN")
PAGDFN, @Special(value = "PAGSEG")
PAGSEG, @Special(value = "PDFMAP")
PDFMAP, @Special(value = "PDG")
PDG, @Special(value = "PGM")
PGM, @Special(value = "PNLGRP")
PNLGRP, @Special(value = "PRDAVL")
PRDAVL, @Special(value = "PRDDFN")
PRDDFN, @Special(value = "PRDLOD")
PRDLOD, @Special(value = "PSFCFG")
PSFCFG, @Special(value = "QMFORM")
QMFORM, @Special(value = "QMQRY")
QMQRY, @Special(value = "QRYDFN")
QRYDFN, @Special(value = "SBSD")
SBSD, @Special(value = "SCHIDX")
SCHIDX, @Special(value = "SRVPGM")
SRVPGM, @Special(value = "SSND")
SSND, @Special(value = "TBL")
TBL, @Special(value = "USRIDX")
USRIDX, @Special(value = "USRSPC")
USRSPC, @Special(value = "VLDL")
VLDL, @Special(value = "WSCST")
WSCST
}
public static enum TOLIBRARYEnum {
@Special(value = "*SAME")
FROMLIB, SAME, CURLIB, OTHER
}
public static enum NEWOBJECTEnum {
@Special(value = "*SAME")
OBJ, SAME, OTHER
}
public static enum FROMASPDEVICEEnum {
@Special(value = "*")
TERM_STAR, CURASPGRP, SYSBAS, OTHER
}
public static enum TOASPDEVICEEnum {
ASPDEV, @Special(value = "*")
TERM_STAR, CURASPGRP, SYSBAS, OTHER
}
public static enum DUPLICATEDATAEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum DUPLICATECONSTRAINTSEnum {
@Special(value = "Y")
YES, @Special(value = "N")
NO
}
public static enum DUPLICATETRIGGERSEnum {
@Special(value = "Y")
YES, @Special(value = "N")
NO
}
public static enum DUPLICATEFILEIDENTIFIERSEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
}
|
package xtandem;
import interfaces.Peak;
/**
* The class is an implementation of the peak interface.
* It hold the peak m/z, the peak intensity and the peak charge.
*
* @author Thilo Muth
*
*/
public class MgfPeak implements Peak{
/**
* This variable holds the peak m/z.
*/
private double iPeakMz = 0;
/**
* This variable holds the peak intensity.
*/
private double iPeakIntensity = 0;
/**
* This variable holds the peak charge.
*/
private int iPeakCharge = 0;
/**
* The empty constructor for a mgfpeak object.
*/
public MgfPeak(){
}
/**
* Returns the m/z of the mgf peak.
* @return iPeakMz
*/
public double getMZ() {
return iPeakMz;
}
/**
* Returns the intensity of the mgf peak.
* @return iPeakIntensity
*/
public double getIntensity() {
return iPeakIntensity;
}
/**
* Returns the charge of the mgf peak.
* @return iPeakCharge
*/
public int getCharge() {
return iPeakCharge;
}
/**
* Sets the m/z of the mgf peak.
* @param aPeakMz
*/
public void setPeakMz(double aPeakMz) {
iPeakMz = aPeakMz;
}
/**
* Sets the intensity of the mgf peak.
* @param aPeakIntensity
*/
public void setPeakIntensity(double aPeakIntensity) {
iPeakIntensity = aPeakIntensity;
}
/**
* Sets the charge of the mgf peak.
* @param aPeakCharge
*/
public void setPeakCharge(int aPeakCharge) {
iPeakCharge = aPeakCharge;
}
}
|
package org.neo4j.helpers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import org.neo4j.helpers.collection.FilteringIterable;
import org.neo4j.helpers.collection.IterableWrapper;
import org.neo4j.helpers.collection.NestingIterable;
import org.neo4j.helpers.collection.PrefetchingIterator;
public abstract class Service
{
/**
* Designates that a class implements the specified service and should be
* added to the services listings file (META-INF/services/[service-name]).
*
* The annotation in itself does not provide any functionality for adding
* the implementation class to the services listings file. But it serves as
* a handle for an Annotation Processing Tool to utilize for performing that
* task.
*
* @author Tobias Ivarsson
*/
@Target( ElementType.TYPE )
@Retention( RetentionPolicy.SOURCE )
public @interface Implementation
{
/**
* The service(s) this class implements.
*
* @return the services this class implements.
*/
Class<?>[] value();
}
/**
* A base class for services, similar to {@link Service}, that compares keys
* using case insensitive comparison instead of exact comparison.
*
* @author Tobias Ivarsson
*/
public static abstract class CaseInsensitiveService extends Service
{
/**
* Create a new instance of a service implementation identified with the
* specified key(s).
*
* @param key the main key for identifying this service implementation
* @param altKeys alternative spellings of the identifier of this
* service implementation
*/
protected CaseInsensitiveService( String key, String... altKeys )
{
super( key, altKeys );
}
@Override
final boolean matches( String key )
{
for ( String id : keys )
{
if ( id.equalsIgnoreCase( key ) ) return true;
}
return false;
}
}
/**
* Load all implementations of a Service.
*
* @param <T> the type of the Service
* @param type the type of the Service to load
* @return all registered implementations of the Service
*/
public static <T> Iterable<T> load( Class<T> type )
{
Iterable<T> loader;
if ( null != ( loader = osgiLoader( type ) ) ) return loader;
if ( null != ( loader = java6Loader( type ) ) ) return loader;
if ( null != ( loader = sunJava5Loader( type ) ) ) return loader;
if ( null != ( loader = ourOwnLoader( type ) ) ) return loader;
return Collections.emptyList();
}
/**
* Load the Service implementation with the specified key.
*
* @param <T> the type of the Service
* @param type the type of the Service to load
* @param key the key that identifies the desired implementation
* @return the matching Service implementation
*/
public static <T extends Service> T load( Class<T> type, String key )
{
for ( T impl : load( type ) )
{
if ( impl.matches( key ) ) return impl;
}
throw new NoSuchElementException( String.format(
"Could not find any implementation of %s with a key=\"%s\"",
type.getName(), key ) );
}
final Set<String> keys;
/**
* Create a new instance of a service implementation identified with the
* specified key(s).
*
* @param key the main key for identifying this service implementation
* @param altKeys alternative spellings of the identifier of this service
* implementation
*/
protected Service( String key, String... altKeys )
{
if ( altKeys == null || altKeys.length == 0 )
{
this.keys = Collections.singleton( key );
}
else
{
this.keys = new HashSet<String>( Arrays.asList( altKeys ) );
this.keys.add( key );
}
}
@Override
public String toString()
{
return getClass().getSuperclass().getName() + "" + keys;
}
boolean matches( String key )
{
return keys.contains( key );
}
private static <T> Iterable<T> filterExceptions( final Iterable<T> iterable )
{
return new Iterable<T>()
{
public Iterator<T> iterator()
{
return new PrefetchingIterator<T>()
{
final Iterator<T> iterator = iterable.iterator();
@Override
protected T fetchNextOrNull()
{
while ( iterator.hasNext() )
{
try
{
return iterator.next();
}
catch ( Throwable e )
{
}
}
return null;
}
};
}
};
}
private static <T> Iterable<T> osgiLoader( Class<T> type )
{
// TODO: implement loading services in an OSGi environment
return null;
}
private static <T> Iterable<T> java6Loader( Class<T> type )
{
try
{
@SuppressWarnings( "unchecked" ) Iterable<T> result = (Iterable<T>) Class.forName(
"java.util.ServiceLoader" ).getMethod( "load", Class.class ).invoke(
null, type );
return filterExceptions( result );
}
catch ( Exception e )
{
return null;
}
catch ( LinkageError e )
{
return null;
}
}
private static <T> Iterable<T> sunJava5Loader( final Class<T> type )
{
final Method providers;
try
{
providers = Class.forName( "sun.misc.Service" ).getMethod(
"providers", Class.class );
}
catch ( Exception e )
{
return null;
}
catch ( LinkageError e )
{
return null;
}
return filterExceptions( new Iterable<T>()
{
public Iterator<T> iterator()
{
try
{
@SuppressWarnings( "unchecked" ) Iterator<T> result = (Iterator<T>) providers.invoke(
null, type );
return result;
}
catch ( Exception e )
{
throw new RuntimeException(
"Failed to invoke sun.misc.Service.providers(forClass)",
e );
}
}
} );
}
private static <T> Iterable<T> ourOwnLoader( final Class<T> type )
{
List<URL> urls = new LinkedList<URL>();
try
{
Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(
"META-INF/services/" + type.getName() );
while ( resources.hasMoreElements() )
{
urls.add( resources.nextElement() );
}
}
catch ( IOException e )
{
return null;
}
return new NestingIterable<T, BufferedReader>(
FilteringIterable.notNull( new IterableWrapper<BufferedReader, URL>(
urls )
{
@Override
protected BufferedReader underlyingObjectToObject( URL url )
{
try
{
return new BufferedReader( new InputStreamReader( url.openStream() ) );
}
catch ( IOException e )
{
return null;
}
}
} ) )
{
@Override
protected Iterator<T> createNestedIterator( final BufferedReader input )
{
return new PrefetchingIterator<T>()
{
@Override
protected T fetchNextOrNull()
{
try
{
String line;
while ( null != ( line = input.readLine() ) )
{
try
{
return type.cast( Class.forName( line ).newInstance() );
}
catch ( Exception e )
{
}
catch ( LinkageError e )
{
}
}
return null;
}
catch ( IOException e )
{
return null;
}
}
};
}
};
}
}
|
package foam.nanos.auth;
import foam.core.FObject;
import foam.core.X;
import foam.dao.*;
import foam.mlang.order.Comparator;
import foam.mlang.predicate.Predicate;
/**
* A DAO decorator to run authorization checks.
*/
public class AuthorizationDAO extends ProxyDAO {
public Authorizer authorizer_;
public AuthorizationDAO(X x, DAO delegate) {
this(x, delegate, AuthorizableAuthorizer.instance());
}
public AuthorizationDAO(X x, DAO delegate, Authorizer authorizer) {
setX(x);
setDelegate(delegate);
authorizer_ = authorizer;
}
@Override
public FObject put_(X x, FObject obj) throws AuthorizationException {
if ( obj == null ) throw new RuntimeException("Cannot put null.");
Object id = obj.getProperty("id");
FObject oldObj = getDelegate().inX(x).find(id);
boolean isCreate = id == null || oldObj == null;
if ( isCreate ) {
authorizer_.authorizeOnCreate(x, obj);
} else {
authorizer_.authorizeOnUpdate(x, oldObj, obj);
}
return super.put_(x, obj);
}
@Override
public FObject remove_(X x, FObject obj) {
Object id = obj.getProperty("id");
FObject oldObj = getDelegate().inX(x).find(id);
if ( id == null || oldObj == null ) return null;
authorizer_.authorizeOnDelete(x, oldObj);
return super.remove_(x, obj);
}
@Override
public FObject find_(X x, Object id) {
FObject obj = super.find_(x, id);
if ( id == null || obj == null ) return null;
authorizer_.authorizeOnRead(x, obj);
return obj;
}
@Override
public Sink select_(X x, Sink sink, long skip, long limit, Comparator order, Predicate predicate) {
super.select_(x, new AuthorizationSink(x, authorizer_, sink), skip, limit, order, predicate);
return sink;
}
@Override
public void removeAll_(X x, long skip, long limit, Comparator order, Predicate predicate) {
Sink authorizationSink = new AuthorizationSink(x, authorizer_, new RemoveSink(x, this));
this.select_(x, authorizationSink, skip, limit, order, predicate);
}
}
|
package be.digitalia.fosdem.db;
import java.util.ArrayList;
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 android.app.SearchManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.provider.BaseColumns;
import be.digitalia.fosdem.model.Day;
import be.digitalia.fosdem.model.Event;
import be.digitalia.fosdem.model.Link;
import be.digitalia.fosdem.model.Person;
import be.digitalia.fosdem.model.Track;
/**
* Here comes the badass SQL.
*
* @author Christophe Beyls
*
*/
public class DatabaseManager {
private static final Uri URI_SCHEDULE = Uri.parse("sqlite://be.digitalia.fosdem/schedule");
private static final Uri URI_BOOKMARKS = Uri.parse("sqlite://be.digitalia.fosdem/bookmarks");
private static final String DB_PREFS_FILE = "database";
private static final String LAST_UPDATE_TIME_PREF = "last_update_time";
private static DatabaseManager instance;
private Context context;
private DatabaseHelper helper;
public static void init(Context context) {
if (instance == null) {
instance = new DatabaseManager(context);
}
}
public static DatabaseManager getInstance() {
return instance;
}
private DatabaseManager(Context context) {
this.context = context;
helper = new DatabaseHelper(context);
}
private static final String[] countProjection = new String[] { "count(*)" };
private static long queryNumEntries(SQLiteDatabase db, String table, String selection, String[] selectionArgs) {
Cursor cursor = db.query(table, countProjection, selection, selectionArgs, null, null, null);
try {
cursor.moveToFirst();
return cursor.getLong(0);
} finally {
cursor.close();
}
}
private static final String TRACK_INSERT_STATEMENT = "INSERT INTO " + DatabaseHelper.TRACKS_TABLE_NAME + " (id, name, type) VALUES (?, ?, ?);";
private static final String EVENT_INSERT_STATEMENT = "INSERT INTO " + DatabaseHelper.EVENTS_TABLE_NAME
+ " (id, day_index, start_time, end_time, room_name, slug, track_id, abstract, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
private static final String EVENT_TITLES_INSERT_STATEMENT = "INSERT INTO " + DatabaseHelper.EVENTS_TITLES_TABLE_NAME
+ " (rowid, title, subtitle) VALUES (?, ?, ?);";
private static final String EVENT_PERSON_INSERT_STATEMENT = "INSERT INTO " + DatabaseHelper.EVENTS_PERSONS_TABLE_NAME
+ " (event_id, person_id) VALUES (?, ?);";
// Ignore conflicts in case of existing person
private static final String PERSON_INSERT_STATEMENT = "INSERT OR IGNORE INTO " + DatabaseHelper.PERSONS_TABLE_NAME + " (rowid, name) VALUES (?, ?);";
private static final String LINK_INSERT_STATEMENT = "INSERT INTO " + DatabaseHelper.LINKS_TABLE_NAME + " (event_id, url, description) VALUES (?, ?, ?);";
private static void bindString(SQLiteStatement statement, int index, String value) {
if (value == null) {
statement.bindNull(index);
} else {
statement.bindString(index, value);
}
}
private SharedPreferences getSharedPreferences() {
return context.getSharedPreferences(DB_PREFS_FILE, Context.MODE_PRIVATE);
}
public Date getLastUpdateTime() {
long time = getSharedPreferences().getLong(LAST_UPDATE_TIME_PREF, -1L);
return (time == -1L) ? null : new Date(time);
}
/**
* Stores the schedule to the database.
*
* @param events
* @return The number of events processed.
*/
public int storeSchedule(Iterable<Event> events) {
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
// 1: Delete the previous schedule
clearSchedule(db);
// Compile the insert statements for the big tables
final SQLiteStatement trackInsertStatement = db.compileStatement(TRACK_INSERT_STATEMENT);
final SQLiteStatement eventInsertStatement = db.compileStatement(EVENT_INSERT_STATEMENT);
final SQLiteStatement eventTitlesInsertStatement = db.compileStatement(EVENT_TITLES_INSERT_STATEMENT);
final SQLiteStatement eventPersonInsertStatement = db.compileStatement(EVENT_PERSON_INSERT_STATEMENT);
final SQLiteStatement personInsertStatement = db.compileStatement(PERSON_INSERT_STATEMENT);
final SQLiteStatement linkInsertStatement = db.compileStatement(LINK_INSERT_STATEMENT);
// 2: Insert the events
int totalEvents = 0;
Map<Track, Long> tracks = new HashMap<Track, Long>();
long nextTrackId = 0L;
Set<Day> days = new HashSet<Day>(2);
for (Event event : events) {
// 2a: Retrieve or insert Track
Track track = event.getTrack();
Long trackId = tracks.get(track);
if (trackId == null) {
// New track
nextTrackId++;
trackId = nextTrackId;
trackInsertStatement.clearBindings();
trackInsertStatement.bindLong(1, nextTrackId);
bindString(trackInsertStatement, 2, track.getName());
bindString(trackInsertStatement, 3, track.getType().name());
if (trackInsertStatement.executeInsert() != -1L) {
tracks.put(track, trackId);
}
}
// 2b: Insert main event
eventInsertStatement.clearBindings();
long eventId = event.getId();
eventInsertStatement.bindLong(1, eventId);
Day day = event.getDay();
days.add(day);
eventInsertStatement.bindLong(2, day.getIndex());
Date time = event.getStartTime();
if (time == null) {
eventInsertStatement.bindNull(3);
} else {
eventInsertStatement.bindLong(3, time.getTime());
}
time = event.getEndTime();
if (time == null) {
eventInsertStatement.bindNull(4);
} else {
eventInsertStatement.bindLong(4, time.getTime());
}
bindString(eventInsertStatement, 5, event.getRoomName());
bindString(eventInsertStatement, 6, event.getSlug());
eventInsertStatement.bindLong(7, trackId);
bindString(eventInsertStatement, 8, event.getAbstractText());
bindString(eventInsertStatement, 9, event.getDescription());
if (eventInsertStatement.executeInsert() != -1L) {
// 2c: Insert fulltext fields
eventTitlesInsertStatement.clearBindings();
eventTitlesInsertStatement.bindLong(1, eventId);
bindString(eventTitlesInsertStatement, 2, event.getTitle());
bindString(eventTitlesInsertStatement, 3, event.getSubTitle());
eventTitlesInsertStatement.executeInsert();
// 2d: Insert persons
for (Person person : event.getPersons()) {
eventPersonInsertStatement.clearBindings();
eventPersonInsertStatement.bindLong(1, eventId);
long personId = person.getId();
eventPersonInsertStatement.bindLong(2, personId);
eventPersonInsertStatement.executeInsert();
personInsertStatement.clearBindings();
personInsertStatement.bindLong(1, personId);
bindString(personInsertStatement, 2, person.getName());
try {
personInsertStatement.executeInsert();
} catch (SQLiteConstraintException e) {
// Older Android versions may not ignore an existing person
}
}
// 2e: Insert links
for (Link link : event.getLinks()) {
linkInsertStatement.clearBindings();
linkInsertStatement.bindLong(1, eventId);
bindString(linkInsertStatement, 2, link.getUrl());
bindString(linkInsertStatement, 3, link.getDescription());
linkInsertStatement.executeInsert();
}
}
totalEvents++;
}
// 3: Insert collected days
ContentValues values = new ContentValues();
for (Day day : days) {
values.clear();
values.put("_index", day.getIndex());
Date date = day.getDate();
values.put("date", (date == null) ? 0L : date.getTime());
db.insert(DatabaseHelper.DAYS_TABLE_NAME, null, values);
}
// TODO purge outdated bookmarks ?
db.setTransactionSuccessful();
// Set last update time
getSharedPreferences().edit().putLong(LAST_UPDATE_TIME_PREF, System.currentTimeMillis()).commit();
return totalEvents;
} finally {
db.endTransaction();
context.getContentResolver().notifyChange(URI_SCHEDULE, null);
context.getContentResolver().notifyChange(URI_BOOKMARKS, null);
}
}
public void clearSchedule() {
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
clearSchedule(db);
db.setTransactionSuccessful();
getSharedPreferences().edit().remove(LAST_UPDATE_TIME_PREF).commit();
} finally {
db.endTransaction();
}
}
private static void clearSchedule(SQLiteDatabase db) {
db.delete(DatabaseHelper.EVENTS_TABLE_NAME, null, null);
db.delete(DatabaseHelper.EVENTS_TITLES_TABLE_NAME, null, null);
db.delete(DatabaseHelper.PERSONS_TABLE_NAME, null, null);
db.delete(DatabaseHelper.EVENTS_PERSONS_TABLE_NAME, null, null);
db.delete(DatabaseHelper.LINKS_TABLE_NAME, null, null);
db.delete(DatabaseHelper.TRACKS_TABLE_NAME, null, null);
db.delete(DatabaseHelper.DAYS_TABLE_NAME, null, null);
}
/**
*
* @return The Days the events span to.
*/
public List<Day> getDays() {
Cursor cursor = helper.getReadableDatabase().rawQuery("SELECT _index, date" + " FROM " + DatabaseHelper.DAYS_TABLE_NAME + " ORDER BY _index ASC", null);
try {
List<Day> result = new ArrayList<Day>(cursor.getCount());
while (cursor.moveToNext()) {
Day day = new Day();
day.setIndex(cursor.getInt(0));
day.setDate(new Date(cursor.getLong(1)));
result.add(day);
}
return result;
} finally {
cursor.close();
}
}
public Cursor getTracks(Day day) {
String[] selectionArgs = new String[] { String.valueOf(day.getIndex()) };
Cursor cursor = helper.getReadableDatabase().rawQuery(
"SELECT t.id AS _id, t.name, t.type" + " FROM " + DatabaseHelper.TRACKS_TABLE_NAME + " t" + " JOIN " + DatabaseHelper.EVENTS_TABLE_NAME
+ " e ON t.id = e.track_id" + " WHERE e.day_index = ?" + " GROUP BY t.id" + " ORDER BY t.id ASC", selectionArgs);
cursor.setNotificationUri(context.getContentResolver(), URI_SCHEDULE);
return cursor;
}
public static Track toTrack(Cursor cursor, Track track) {
if (track == null) {
track = new Track();
}
track.setName(cursor.getString(1));
track.setType(Enum.valueOf(Track.Type.class, cursor.getString(2)));
return track;
}
public static Track toTrack(Cursor cursor) {
return toTrack(cursor, null);
}
public long getEventsCount() {
return queryNumEntries(helper.getReadableDatabase(), DatabaseHelper.EVENTS_TABLE_NAME, null, null);
}
/**
*
* @param day
* @param track
* @return A cursor to Events
*/
public Cursor getEvents(Day day, Track track) {
String[] selectionArgs = new String[] { String.valueOf(day.getIndex()), track.getName(), track.getType().name() };
Cursor cursor = helper
.getReadableDatabase()
.rawQuery(
"SELECT e.id AS _id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description, GROUP_CONCAT(p.name, ', '), e.day_index, d.date, t.name, t.type"
+ " FROM "
+ DatabaseHelper.EVENTS_TABLE_NAME
+ " e"
+ " JOIN "
+ DatabaseHelper.EVENTS_TITLES_TABLE_NAME
+ " et ON e.id = et.rowid"
+ " JOIN "
+ DatabaseHelper.DAYS_TABLE_NAME
+ " d ON e.day_index = d._index"
+ " JOIN "
+ DatabaseHelper.TRACKS_TABLE_NAME
+ " t ON e.track_id = t.id"
+ " JOIN "
+ DatabaseHelper.EVENTS_PERSONS_TABLE_NAME
+ " ep ON e.id = ep.event_id"
+ " JOIN "
+ DatabaseHelper.PERSONS_TABLE_NAME
+ " p ON ep.person_id = p.rowid"
+ " WHERE e.day_index = ? AND t.name = ? AND t.type = ?" + " GROUP BY e.id" + " ORDER BY e.start_time ASC", selectionArgs);
cursor.setNotificationUri(context.getContentResolver(), URI_SCHEDULE);
return cursor;
}
/**
* Returns the events presented by the specified person.
*
* @param person
* @return A cursor to Events
*/
public Cursor getEvents(Person person) {
String[] selectionArgs = new String[] { String.valueOf(person.getId()) };
Cursor cursor = helper
.getReadableDatabase()
.rawQuery(
"SELECT e.id AS _id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description, GROUP_CONCAT(p.name, ', '), e.day_index, d.date, t.name, t.type"
+ " FROM "
+ DatabaseHelper.EVENTS_TABLE_NAME
+ " e"
+ " JOIN "
+ DatabaseHelper.EVENTS_TITLES_TABLE_NAME
+ " et ON e.id = et.rowid"
+ " JOIN "
+ DatabaseHelper.DAYS_TABLE_NAME
+ " d ON e.day_index = d._index"
+ " JOIN "
+ DatabaseHelper.TRACKS_TABLE_NAME
+ " t ON e.track_id = t.id"
+ " JOIN "
+ DatabaseHelper.EVENTS_PERSONS_TABLE_NAME
+ " ep ON e.id = ep.event_id"
+ " JOIN "
+ DatabaseHelper.PERSONS_TABLE_NAME
+ " p ON ep.person_id = p.rowid"
+ " JOIN "
+ DatabaseHelper.EVENTS_PERSONS_TABLE_NAME
+ " ep2 ON e.id = ep2.event_id" + " WHERE ep2.person_id = ?" + " GROUP BY e.id" + " ORDER BY e.start_time ASC", selectionArgs);
cursor.setNotificationUri(context.getContentResolver(), URI_SCHEDULE);
return cursor;
}
/**
* Returns the bookmarks.
*
* @param futureOnly
* When true, only return the events that are not over yet.
* @return A cursor to Events
*/
public Cursor getBookmarks(boolean futureOnly) {
String whereCondition;
String[] selectionArgs;
if (futureOnly) {
whereCondition = " WHERE e.end_time > ?";
selectionArgs = new String[] { String.valueOf(System.currentTimeMillis()) };
} else {
whereCondition = "";
selectionArgs = null;
}
Cursor cursor = helper
.getReadableDatabase()
.rawQuery(
"SELECT e.id AS _id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description, GROUP_CONCAT(p.name, ', '), e.day_index, d.date, t.name, t.type"
+ " FROM "
+ DatabaseHelper.BOOKMARKS_TABLE_NAME
+ " b"
+ " JOIN "
+ DatabaseHelper.EVENTS_TABLE_NAME
+ " e ON b.event_id = e.id"
+ " JOIN "
+ DatabaseHelper.EVENTS_TITLES_TABLE_NAME
+ " et ON e.id = et.rowid"
+ " JOIN "
+ DatabaseHelper.DAYS_TABLE_NAME
+ " d ON e.day_index = d._index"
+ " JOIN "
+ DatabaseHelper.TRACKS_TABLE_NAME
+ " t ON e.track_id = t.id"
+ " JOIN "
+ DatabaseHelper.EVENTS_PERSONS_TABLE_NAME
+ " ep ON e.id = ep.event_id"
+ " JOIN "
+ DatabaseHelper.PERSONS_TABLE_NAME
+ " p ON ep.person_id = p.rowid" + whereCondition + " GROUP BY e.id" + " ORDER BY e.start_time ASC", selectionArgs);
cursor.setNotificationUri(context.getContentResolver(), URI_BOOKMARKS);
return cursor;
}
/**
* Search through matching titles, subtitles, track names, person names. We need to use an union of 3 sub-queries because a "match" condition can not be
* accompanied by other conditions in a "where" statement.
*
* @param query
* @return A cursor to Events
*/
public Cursor getSearchResults(String query) {
final String matchQuery = query + "*";
String[] selectionArgs = new String[] { matchQuery, "%" + query + "%", matchQuery };
Cursor cursor = helper
.getReadableDatabase()
.rawQuery(
"SELECT e.id AS _id, e.start_time, e.end_time, e.room_name, e.slug, et.title, et.subtitle, e.abstract, e.description, GROUP_CONCAT(p.name, ', '), e.day_index, d.date, t.name, t.type"
+ " FROM "
+ DatabaseHelper.EVENTS_TABLE_NAME
+ " e"
+ " JOIN "
+ DatabaseHelper.EVENTS_TITLES_TABLE_NAME
+ " et ON e.id = et.rowid"
+ " JOIN "
+ DatabaseHelper.DAYS_TABLE_NAME
+ " d ON e.day_index = d._index"
+ " JOIN "
+ DatabaseHelper.TRACKS_TABLE_NAME
+ " t ON e.track_id = t.id"
+ " JOIN "
+ DatabaseHelper.EVENTS_PERSONS_TABLE_NAME
+ " ep ON e.id = ep.event_id"
+ " JOIN "
+ DatabaseHelper.PERSONS_TABLE_NAME
+ " p ON ep.person_id = p.rowid"
+ " WHERE e.id IN ( "
+ "SELECT rowid"
+ " FROM "
+ DatabaseHelper.EVENTS_TITLES_TABLE_NAME
+ " WHERE "
+ DatabaseHelper.EVENTS_TITLES_TABLE_NAME
+ " MATCH ?"
+ " UNION "
+ "SELECT e.id"
+ " FROM "
+ DatabaseHelper.EVENTS_TABLE_NAME
+ " e"
+ " JOIN "
+ DatabaseHelper.TRACKS_TABLE_NAME
+ " t ON e.track_id = t.id"
+ " WHERE t.name LIKE ?"
+ " UNION "
+ "SELECT ep.event_id"
+ " FROM "
+ DatabaseHelper.EVENTS_PERSONS_TABLE_NAME
+ " ep"
+ " JOIN "
+ DatabaseHelper.PERSONS_TABLE_NAME
+ " p ON ep.person_id = p.rowid" + " WHERE p.name MATCH ?" + " )" + " GROUP BY e.id" + " ORDER BY e.start_time ASC",
selectionArgs);
cursor.setNotificationUri(context.getContentResolver(), URI_SCHEDULE);
return cursor;
}
/**
* Method called by SearchSuggestionProvider to return search results in the format expected by the search framework.
*
*/
public Cursor getSearchSuggestionResults(String query) {
final String matchQuery = query + "*";
String[] selectionArgs = new String[] { matchQuery, "%" + query + "%", matchQuery };
// Query is similar to getSearchResults but returns different columns, does not join the Day table and limits the result set to 5 entries.
Cursor cursor = helper.getReadableDatabase().rawQuery(
"SELECT e.id AS " + BaseColumns._ID + ", et.title AS " + SearchManager.SUGGEST_COLUMN_TEXT_1
+ ", GROUP_CONCAT(p.name, ', ') || ' - ' || t.name AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + " FROM "
+ DatabaseHelper.EVENTS_TABLE_NAME + " e" + " JOIN " + DatabaseHelper.EVENTS_TITLES_TABLE_NAME + " et ON e.id = et.rowid" + " JOIN "
+ DatabaseHelper.TRACKS_TABLE_NAME + " t ON e.track_id = t.id" + " JOIN " + DatabaseHelper.EVENTS_PERSONS_TABLE_NAME
+ " ep ON e.id = ep.event_id" + " JOIN " + DatabaseHelper.PERSONS_TABLE_NAME + " p ON ep.person_id = p.rowid" + " WHERE e.id IN ( "
+ "SELECT rowid" + " FROM " + DatabaseHelper.EVENTS_TITLES_TABLE_NAME + " WHERE " + DatabaseHelper.EVENTS_TITLES_TABLE_NAME
+ " MATCH ?" + " UNION " + "SELECT e.id" + " FROM " + DatabaseHelper.EVENTS_TABLE_NAME + " e" + " JOIN "
+ DatabaseHelper.TRACKS_TABLE_NAME + " t ON e.track_id = t.id" + " WHERE t.name LIKE ?" + " UNION " + "SELECT ep.event_id" + " FROM "
+ DatabaseHelper.EVENTS_PERSONS_TABLE_NAME + " ep" + " JOIN " + DatabaseHelper.PERSONS_TABLE_NAME + " p ON ep.person_id = p.rowid"
+ " WHERE p.name MATCH ?" + " )" + " GROUP BY e.id" + " ORDER BY e.start_time ASC LIMIT 5", selectionArgs);
cursor.setNotificationUri(context.getContentResolver(), URI_SCHEDULE);
return cursor;
}
public static Event toEvent(Cursor cursor, Event event) {
Day day;
Track track;
if (event == null) {
event = new Event();
day = new Day();
event.setDay(day);
track = new Track();
event.setTrack(track);
event.setStartTime(new Date(cursor.getLong(1)));
event.setEndTime(new Date(cursor.getLong(2)));
day.setDate(new Date(cursor.getLong(11)));
} else {
day = event.getDay();
track = event.getTrack();
event.getStartTime().setTime(cursor.getLong(1));
event.getEndTime().setTime(cursor.getLong(2));
day.getDate().setTime(cursor.getLong(11));
}
event.setId(cursor.getInt(0));
event.setRoomName(cursor.getString(3));
event.setSlug(cursor.getString(4));
event.setTitle(cursor.getString(5));
event.setSubTitle(cursor.getString(6));
event.setAbstractText(cursor.getString(7));
event.setDescription(cursor.getString(8));
event.setPersonsSummary(cursor.getString(9));
day.setIndex(cursor.getInt(10));
track.setName(cursor.getString(12));
track.setType(Enum.valueOf(Track.Type.class, cursor.getString(13)));
return event;
}
public static Event toEvent(Cursor cursor) {
return toEvent(cursor, null);
}
/**
* Returns all persons in alphabetical order.
*/
public Cursor getPersons() {
Cursor cursor = helper.getReadableDatabase().rawQuery("SELECT rowid AS _id, name" + " FROM " + DatabaseHelper.PERSONS_TABLE_NAME + " ORDER BY name ASC", null);
cursor.setNotificationUri(context.getContentResolver(), URI_SCHEDULE);
return cursor;
}
/**
* Returns persons presenting the specified event.
*/
public List<Person> getPersons(Event event) {
String[] selectionArgs = new String[] { String.valueOf(event.getId()) };
Cursor cursor = helper.getReadableDatabase().rawQuery(
"SELECT p.rowid AS _id, p.name" + " FROM " + DatabaseHelper.PERSONS_TABLE_NAME + " p" + " JOIN " + DatabaseHelper.EVENTS_PERSONS_TABLE_NAME
+ " ep ON p.rowid = ep.person_id" + " WHERE ep.event_id = ?" + " ORDER BY p.name ASC", selectionArgs);
try {
List<Person> result = new ArrayList<Person>(cursor.getCount());
while (cursor.moveToNext()) {
result.add(toPerson(cursor));
}
return result;
} finally {
cursor.close();
}
}
public static Person toPerson(Cursor cursor, Person person) {
if (person == null) {
person = new Person();
}
person.setId(cursor.getInt(0));
person.setName(cursor.getString(1));
return person;
}
public static Person toPerson(Cursor cursor) {
return toPerson(cursor, null);
}
public List<Link> getLinks(Event event) {
String[] selectionArgs = new String[] { String.valueOf(event.getId()) };
Cursor cursor = helper.getReadableDatabase().rawQuery(
"SELECT url, description" + " FROM " + DatabaseHelper.LINKS_TABLE_NAME + " WHERE event_id = ?" + " ORDER BY rowid ASC", selectionArgs);
try {
List<Link> result = new ArrayList<Link>(cursor.getCount());
while (cursor.moveToNext()) {
Link link = new Link();
link.setUrl(cursor.getString(0));
link.setDescription(cursor.getString(1));
result.add(link);
}
return result;
} finally {
cursor.close();
}
}
public boolean isBookmarked(Event event) {
String[] selectionArgs = new String[] { String.valueOf(event.getId()) };
return queryNumEntries(helper.getReadableDatabase(), DatabaseHelper.BOOKMARKS_TABLE_NAME, "event_id = ?", selectionArgs) > 0L;
}
public boolean addBookmark(Event event) {
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("event_id", event.getId());
long result = db.insert(DatabaseHelper.BOOKMARKS_TABLE_NAME, null, values);
// If the bookmark is already present
if (result == -1L) {
return false;
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
context.getContentResolver().notifyChange(URI_BOOKMARKS, null);
}
}
public boolean removeBookmark(Event event) {
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
try {
String[] whereArgs = new String[] { String.valueOf(event.getId()) };
int count = db.delete(DatabaseHelper.BOOKMARKS_TABLE_NAME, "event_id = ?", whereArgs);
if (count == 0) {
return false;
}
db.setTransactionSuccessful();
return true;
} finally {
db.endTransaction();
context.getContentResolver().notifyChange(URI_BOOKMARKS, null);
}
}
}
|
// ClassList.java
package loci.formats;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
import loci.common.*;
public class ClassList {
// -- Fields --
/** Base class to which all classes are assignable. */
private Class base;
/** List of classes. */
private Vector classes;
// -- Constructor --
/**
* Constructs a list of classes, initially empty.
* @param base Base class to which all classes are assignable.
*/
public ClassList(Class base) {
this.base = base;
classes = new Vector();
}
/**
* Constructs a list of classes from the given configuration file.
* @param file Configuration file containing the list of classes.
* @param base Base class to which all classes are assignable.
* @throws IOException if the file cannot be read.
*/
public ClassList(String file, Class base) throws IOException {
this(file, base, ClassList.class);
}
/**
* Constructs a list of classes from the given configuration file.
* @param file Configuration file containing the list of classes.
* @param base Base class to which all classes are assignable.
* @param location Class indicating which package to search for the file. If
* null, 'file' is interpreted as an absolute path name.
* @throws IOException if the file cannot be read.
*/
public ClassList(String file, Class base, Class location) throws IOException {
this.base = base;
classes = new Vector();
if (file == null) return;
// read classes from file
BufferedReader in = null;
if (location == null) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
}
else {
in = new BufferedReader(new InputStreamReader(
location.getResourceAsStream(file)));
}
while (true) {
String line = null;
line = in.readLine();
if (line == null) break;
// ignore characters following # sign (comments)
int ndx = line.indexOf("
if (ndx >= 0) line = line.substring(0, ndx);
line = line.trim();
if (line.equals("")) continue;
// load reader class
Class c = null;
try { c = Class.forName(line); }
catch (ClassNotFoundException exc) {
if (FormatHandler.debug) LogTools.trace(exc);
}
catch (NoClassDefFoundError err) {
if (FormatHandler.debug) LogTools.trace(err);
}
catch (ExceptionInInitializerError err) {
if (FormatHandler.debug) LogTools.trace(err);
}
catch (RuntimeException exc) {
// HACK: workaround for bug in Apache Axis2
String msg = exc.getMessage();
if (msg != null && msg.indexOf("ClassNotFound") < 0) throw exc;
if (FormatHandler.debug) LogTools.trace(exc);
}
if (c == null || (base != null && !base.isAssignableFrom(c))) {
LogTools.println("Error: \"" + line + "\" is not valid.");
continue;
}
classes.add(c);
}
in.close();
}
// -- ClassList API methods --
/**
* Adds the given class, which must be assignable
* to the base class, to the list.
*
* @throws FormatException if the class is not assignable to the base class.
*/
public void addClass(Class c) throws FormatException {
if (base != null && !base.isAssignableFrom(c)) {
throw new FormatException(
"Class is not assignable to the base class");
}
classes.add(c);
}
/** Removes the given class from the list. */
public void removeClass(Class c) {
classes.remove(c);
}
/** Gets the list of classes as an array. */
public Class[] getClasses() {
Class[] c = new Class[classes.size()];
classes.copyInto(c);
return c;
}
}
|
package com.github.neuralnetworks.test;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import com.github.neuralnetworks.architecture.Connections;
import com.github.neuralnetworks.architecture.Conv2DConnection;
import com.github.neuralnetworks.architecture.ConvGridLayer;
import com.github.neuralnetworks.architecture.GraphConnections;
import com.github.neuralnetworks.architecture.Layer;
import com.github.neuralnetworks.architecture.Matrix;
import com.github.neuralnetworks.architecture.NeuralNetworkImpl;
import com.github.neuralnetworks.architecture.Subsampling2DConnection;
import com.github.neuralnetworks.architecture.types.NNFactory;
import com.github.neuralnetworks.calculation.ConnectionCalculator;
import com.github.neuralnetworks.calculation.LayerCalculatorImpl;
import com.github.neuralnetworks.calculation.ValuesProvider;
import com.github.neuralnetworks.calculation.neuronfunctions.AparapiAveragePooling2D;
import com.github.neuralnetworks.calculation.neuronfunctions.AparapiConv2D;
import com.github.neuralnetworks.calculation.neuronfunctions.AparapiConv2DFF;
import com.github.neuralnetworks.calculation.neuronfunctions.AparapiMaxPooling2D;
import com.github.neuralnetworks.calculation.neuronfunctions.AparapiStochasticPooling2D;
import com.github.neuralnetworks.training.TrainerFactory;
import com.github.neuralnetworks.training.backpropagation.BackPropagationTrainer;
import com.github.neuralnetworks.training.backpropagation.BackpropagationAveragePooling2D;
import com.github.neuralnetworks.training.backpropagation.BackpropagationMaxPooling2D;
import com.github.neuralnetworks.util.Environment;
import com.github.neuralnetworks.util.KernelExecutionStrategy.SeqKernelExecution;
import com.github.neuralnetworks.util.Util;
/**
* Tests for convolutional networks
*/
public class CNNTest {
@Test
public void testDimensions() {
// convolution dimensions
Conv2DConnection conv = new Conv2DConnection(new ConvGridLayer(4, 4, 3), 2, 2, 2);
ConvGridLayer output = (ConvGridLayer) conv.getOutputLayer();
assertEquals(3, output.getFeatureMapColumns(), 0);
assertEquals(3, output.getFeatureMapRows(), 0);
assertEquals(2, output.getFilters(), 0);
// subsampling dimensions
Subsampling2DConnection sub = new Subsampling2DConnection(new ConvGridLayer(5, 5, 3), 2, 2);
output = (ConvGridLayer) sub.getOutputLayer();
assertEquals(2, output.getFeatureMapColumns(), 0);
assertEquals(2, output.getFeatureMapRows(), 0);
assertEquals(3, output.getFilters(), 0);
}
@Test
public void testCNNConstruction() {
NeuralNetworkImpl nn = NNFactory.convNN(new int[][] { { 32, 32, 1 }, { 5, 5, 6 }, { 2, 2 }, { 5, 5, 16 }, { 2, 2 }, { 5, 5, 120 }, {84}, {10} }, true);
assertEquals(13, nn.getLayers().size(), 0);
ConvGridLayer l = (ConvGridLayer) nn.getInputLayer().getConnections().get(0).getOutputLayer();
assertEquals(28, l.getFeatureMapRows(), 0);
assertEquals(28, l.getFeatureMapColumns(), 0);
assertEquals(6, l.getFilters(), 0);
l = (ConvGridLayer) l.getConnections().get(2).getOutputLayer();
assertEquals(14, l.getFeatureMapRows(), 0);
assertEquals(14, l.getFeatureMapColumns(), 0);
assertEquals(6, l.getFilters(), 0);
l = (ConvGridLayer) l.getConnections().get(1).getOutputLayer();
assertEquals(10, l.getFeatureMapRows(), 0);
assertEquals(10, l.getFeatureMapColumns(), 0);
assertEquals(16, l.getFilters(), 0);
l = (ConvGridLayer) l.getConnections().get(2).getOutputLayer();
assertEquals(5, l.getFeatureMapRows(), 0);
assertEquals(5, l.getFeatureMapColumns(), 0);
assertEquals(16, l.getFilters(), 0);
l = (ConvGridLayer) l.getConnections().get(1).getOutputLayer();
assertEquals(1, l.getFeatureMapRows(), 0);
assertEquals(1, l.getFeatureMapColumns(), 0);
assertEquals(120, l.getFilters(), 0);
GraphConnections cg = (GraphConnections) l.getConnections().get(2);
assertEquals(84, cg.getConnectionGraph().getRows(), 0);
GraphConnections cg2 = (GraphConnections) cg.getOutputLayer().getConnections().get(2);
assertEquals(10, cg2.getConnectionGraph().getRows(), 0);
}
@Test
public void testCNNConstruction2() {
NeuralNetworkImpl nn = NNFactory.convNN(new int[][] { { 28, 28, 1 }, { 5, 5, 20 }, { 2, 2 }, { 5, 5, 50 }, { 2, 2 }, {500}, {10} }, true);
assertEquals(11, nn.getLayers().size(), 0);
ConvGridLayer l = (ConvGridLayer) nn.getInputLayer().getConnections().get(0).getOutputLayer();
assertEquals(24, l.getFeatureMapRows(), 0);
assertEquals(24, l.getFeatureMapColumns(), 0);
assertEquals(20, l.getFilters(), 0);
l = (ConvGridLayer) l.getConnections().get(2).getOutputLayer();
assertEquals(12, l.getFeatureMapRows(), 0);
assertEquals(12, l.getFeatureMapColumns(), 0);
assertEquals(20, l.getFilters(), 0);
l = (ConvGridLayer) l.getConnections().get(1).getOutputLayer();
assertEquals(8, l.getFeatureMapRows(), 0);
assertEquals(8, l.getFeatureMapColumns(), 0);
assertEquals(50, l.getFilters(), 0);
l = (ConvGridLayer) l.getConnections().get(2).getOutputLayer();
assertEquals(4, l.getFeatureMapRows(), 0);
assertEquals(4, l.getFeatureMapColumns(), 0);
assertEquals(50, l.getFilters(), 0);
assertEquals(50 * 4 * 4, l.getConnections().get(0).getOutputUnitCount(), 0);
Layer layer = l.getConnections().get(1).getOutputLayer();
assertEquals(500, layer.getConnections().get(0).getOutputUnitCount(), 0);
layer = layer.getConnections().get(2).getOutputLayer();
assertEquals(10, layer.getConnections().get(0).getOutputUnitCount(), 0);
}
@Test
public void testConvolutions() {
NeuralNetworkImpl nn = new NeuralNetworkImpl();
Conv2DConnection c = new Conv2DConnection(new ConvGridLayer(3, 3, 2), 2, 2, 1);
nn.addConnection(c);
c.getWeights()[0] = 1;
c.getWeights()[1] = 2;
c.getWeights()[2] = 3;
c.getWeights()[3] = 4;
c.getWeights()[4] = 1;
c.getWeights()[5] = 2;
c.getWeights()[6] = 3;
c.getWeights()[7] = 4;
Matrix i1 = new Matrix(new float[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }, 1);
Matrix o = new Matrix(4, 1);
AparapiConv2D conv = new AparapiConv2DFF(c, 1);
conv.calculate(c, i1, o);
// most simple case
assertEquals(164, o.get(0, 0), 0);
assertEquals(184, o.get(0, 1), 0);
assertEquals(224, o.get(0, 2), 0);
assertEquals(244, o.get(0, 3), 0);
Util.fillArray(o.getElements(), 0);
}
@Test
public void testConvolutions2() {
Conv2DConnection c = new Conv2DConnection(new ConvGridLayer(3, 3, 2), 2, 2, 2);
c.getWeights()[0] = 1;
c.getWeights()[1] = 2;
c.getWeights()[2] = 3;
c.getWeights()[3] = 4;
c.getWeights()[4] = 1;
c.getWeights()[5] = 2;
c.getWeights()[6] = 3;
c.getWeights()[7] = 4;
c.getWeights()[8] = 1;
c.getWeights()[9] = 2;
c.getWeights()[10] = 3;
c.getWeights()[11] = 4;
c.getWeights()[12] = 1;
c.getWeights()[13] = 2;
c.getWeights()[14] = 3;
c.getWeights()[15] = 4;
Matrix i1 = new Matrix(new float[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }, 1);
Matrix o = new Matrix(8, 1);
AparapiConv2D conv = new AparapiConv2DFF(c, 1);
conv.calculate(c, i1, o);
assertEquals(164, o.get(0, 0), 0);
assertEquals(184, o.get(0, 1), 0);
assertEquals(224, o.get(0, 2), 0);
assertEquals(244, o.get(0, 3), 0);
assertEquals(164, o.get(0, 4), 0);
assertEquals(184, o.get(0, 5), 0);
assertEquals(224, o.get(0, 6), 0);
assertEquals(244, o.get(0, 7), 0);
Util.fillArray(o.getElements(), 0);
}
@Test
public void testSimpleCNN() {
NeuralNetworkImpl nn = NNFactory.convNN(new int[][] {{3, 3, 2}, {2, 2, 2}, {2, 2}}, false);
nn.setLayerCalculator(NNFactory.lcWeightedSum(nn, null));
NNFactory.lcMaxPooling(nn, (LayerCalculatorImpl) nn.getLayerCalculator());
Conv2DConnection c = (Conv2DConnection) nn.getInputLayer().getConnections().get(0);
c.getWeights()[0] = 1;
c.getWeights()[1] = 2;
c.getWeights()[2] = 3;
c.getWeights()[3] = 4;
c.getWeights()[4] = 1;
c.getWeights()[5] = 2;
c.getWeights()[6] = 3;
c.getWeights()[7] = 4;
c.getWeights()[8] = 1;
c.getWeights()[9] = 2;
c.getWeights()[10] = 3;
c.getWeights()[11] = 4;
c.getWeights()[12] = 1;
c.getWeights()[13] = 2;
c.getWeights()[14] = 3;
c.getWeights()[15] = 4;
Matrix i1 = new Matrix(new float[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }, 1);
ValuesProvider vp = new ValuesProvider();
vp.addValues(nn.getInputLayer(), i1);
Set<Layer> calculatedLayers = new HashSet<>();
calculatedLayers.add(nn.getInputLayer());
nn.getLayerCalculator().calculate(nn, nn.getOutputLayer(), calculatedLayers, vp);
Matrix o = vp.getValues(nn.getOutputLayer());
assertEquals(244, o.get(0, 0), 0);
assertEquals(244, o.get(1, 0), 0);
}
@Test
public void testMaxPooling() {
Subsampling2DConnection c = new Subsampling2DConnection(new ConvGridLayer(4, 4, 2), 2, 2);
Matrix i1 = new Matrix(new float[] { 0.5f, 1, 1, 2, 1.5f, 3, 2, 4, 2.5f, 5, 3, 6, 3.5f, 7, 4f, 8, 4.5f, 9, 5f, 10, 5.5f, 11, 6f, 12, 6.5f, 13, 7f, 14, 8f, 16, 7.5f, 15, 8.5f, 17, 9f, 18, 9.5f, 19, 10f, 20, 10.5f, 21, 11f, 22, 11.5f, 23, 12f, 24, 12.5f, 25, 13f, 26, 13.5f, 27, 14f, 28, 14.5f, 29, 15f, 30, 16f, 32, 15.5f, 31 }, 2);
List<Connections> connections = new ArrayList<Connections>();
connections.add(c);
ConnectionCalculator calc = new AparapiMaxPooling2D();
Matrix o = new Matrix(8, 2);
ValuesProvider vp = new ValuesProvider();
vp.addValues(c.getInputLayer(), i1);
vp.addValues(c.getOutputLayer(), o);
calc.calculate(connections, vp, c.getOutputLayer());
assertEquals(3, o.get(0, 0), 0);
assertEquals(4, o.get(1, 0), 0);
assertEquals(7, o.get(2, 0), 0);
assertEquals(8, o.get(3, 0), 0);
assertEquals(11, o.get(4, 0), 0);
assertEquals(12, o.get(5, 0), 0);
assertEquals(15, o.get(6, 0), 0);
assertEquals(16, o.get(7, 0), 0);
assertEquals(6, o.get(0, 1), 0);
assertEquals(8, o.get(1, 1), 0);
assertEquals(14, o.get(2, 1), 0);
assertEquals(16, o.get(3, 1), 0);
assertEquals(22, o.get(4, 1), 0);
assertEquals(24, o.get(5, 1), 0);
assertEquals(30, o.get(6, 1), 0);
assertEquals(32, o.get(7, 1), 0);
}
@Test
public void testAveragePooling() {
Subsampling2DConnection c = new Subsampling2DConnection(new ConvGridLayer(4, 4, 2), 2, 2);
Matrix i1 = new Matrix(new float[] { 0.5f, 1, 1, 2, 1.5f, 3, 2, 4, 2.5f, 5, 3, 6, 3.5f, 7, 4f, 8, 4.5f, 9, 5f, 10, 5.5f, 11, 6f, 12, 6.5f, 13, 7f, 14, 8f, 16, 7.5f, 15, 8.5f, 17, 9f, 18, 9.5f, 19, 10f, 20, 10.5f, 21, 11f, 22, 11.5f, 23, 12f, 24, 12.5f, 25, 13f, 26, 13.5f, 27, 14f, 28, 14.5f, 29, 15f, 30, 16f, 32, 15.5f, 31 }, 2);
List<Connections> connections = new ArrayList<Connections>();
connections.add(c);
AparapiAveragePooling2D calc = new AparapiAveragePooling2D();
Matrix o = new Matrix(8, 2);
ValuesProvider vp = new ValuesProvider();
vp.addValues(c.getInputLayer(), i1);
vp.addValues(c.getOutputLayer(), o);
calc.calculate(connections, vp, c.getOutputLayer());
assertEquals(1.75, o.get(0, 0), 0);
assertEquals(2.75, o.get(1, 0), 0);
assertEquals(5.75, o.get(2, 0), 0);
assertEquals(6.75, o.get(3, 0), 0);
assertEquals(9.75, o.get(4, 0), 0);
assertEquals(10.75, o.get(5, 0), 0);
assertEquals(13.75, o.get(6, 0), 0);
assertEquals(14.75, o.get(7, 0), 0);
assertEquals(3.5, o.get(0, 1), 0);
assertEquals(5.5, o.get(1, 1), 0);
assertEquals(11.5, o.get(2, 1), 0);
assertEquals(13.5, o.get(3, 1), 0);
assertEquals(19.5, o.get(4, 1), 0);
assertEquals(21.5, o.get(5, 1), 0);
assertEquals(27.5, o.get(6, 1), 0);
assertEquals(29.5, o.get(7, 1), 0);
}
@Test
public void testStochasticPooling() {
Subsampling2DConnection c = new Subsampling2DConnection(new ConvGridLayer(3, 3, 1), 3, 3);
Matrix i1 = new Matrix(new float[] { 1.6f, 1.6f, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.4f, 2.4f }, 2);
List<Connections> connections = new ArrayList<Connections>();
connections.add(c);
Matrix o = new Matrix(1, 2);
ValuesProvider vp = new ValuesProvider();
vp.addValues(c.getInputLayer(), i1);
vp.addValues(c.getOutputLayer(), o);
AparapiStochasticPooling2D calc = new AparapiStochasticPooling2D();
calc.calculate(connections, vp, c.getOutputLayer());
assertEquals(2.08, o.get(0, 0), 0.01);
assertEquals(2.08, o.get(0, 1), 0.01);
}
@Test
public void testMaxPoolingBackpropagation() {
Subsampling2DConnection c = new Subsampling2DConnection(new ConvGridLayer(4, 4, 2), 2, 2);
Matrix a1 = new Matrix(new float[] { 0.5f, 1, 1, 2, 1.5f, 3, 2, 4, 2.5f, 5, 3, 6, 3.5f, 7, 4f, 8, 4.5f, 9, 5f, 10, 5.5f, 11, 6f, 12, 6.5f, 13, 7f, 14, 8f, 16, 7.5f, 15, 8.5f, 17, 9f, 18, 9.5f, 19, 10f, 20, 10.5f, 21, 11f, 22, 11.5f, 23, 12f, 24, 12.5f, 25, 13f, 26, 13.5f, 27, 14f, 28, 14.5f, 29, 15f, 30, 16f, 32, 15.5f, 31 }, 2);
Matrix o = new Matrix(8, 2);
List<Connections> connections = new ArrayList<Connections>();
connections.add(c);
// max pooling
ValuesProvider vp = new ValuesProvider();
vp.addValues(c.getInputLayer(), a1);
vp.addValues(c.getOutputLayer(), o);
ConnectionCalculator calc = new AparapiMaxPooling2D();
calc.calculate(connections, vp, c.getOutputLayer());
ValuesProvider activations = new ValuesProvider();
activations.addValues(c.getInputLayer(), a1);
Matrix bpo = new Matrix(32, 2);
vp = new ValuesProvider();
vp.addValues(c.getOutputLayer(), o);
vp.addValues(c.getInputLayer(), bpo);
BackpropagationMaxPooling2D bp = new BackpropagationMaxPooling2D();
bp.setActivations(activations);
bp.calculate(connections, vp, c.getInputLayer());
assertEquals(true, bpo.get(5, 0) == a1.get(5, 0));
assertEquals(true, bpo.get(7, 0) == a1.get(7, 0));
assertEquals(true, bpo.get(13, 0) == a1.get(13, 0));
assertEquals(true, bpo.get(14, 0) == a1.get(14, 0));
assertEquals(true, bpo.get(5, 1) == a1.get(5, 1));
assertEquals(true, bpo.get(7, 1) == a1.get(7, 1));
assertEquals(true, bpo.get(13, 1) == a1.get(13, 1));
assertEquals(true, bpo.get(14, 1) == a1.get(14, 1));
}
@Test
public void testAveragePoolingBackpropagation() {
Environment.getInstance().setExecutionStrategy(new SeqKernelExecution());
Subsampling2DConnection c = new Subsampling2DConnection(new ConvGridLayer(4, 4, 2), 2, 2);
Matrix a1 = new Matrix(new float[] { 0.5f, 1, 1, 2, 1.5f, 3, 2, 4, 2.5f, 5, 3, 6, 3.5f, 7, 4f, 8, 4.5f, 9, 5f, 10, 5.5f, 11, 6f, 12, 6.5f, 13, 7f, 14, 8f, 16, 7.5f, 15, 8.5f, 17, 9f, 18, 9.5f, 19, 10f, 20, 10.5f, 21, 11f, 22, 11.5f, 23, 12f, 24, 12.5f, 25, 13f, 26, 13.5f, 27, 14f, 28, 14.5f, 29, 15f, 30, 16f, 32, 15.5f, 31 }, 2);
// max pooling
ConnectionCalculator calc = new AparapiAveragePooling2D();
List<Connections> connections = new ArrayList<Connections>();
connections.add(c);
ValuesProvider vp = new ValuesProvider();
vp.addValues(c.getInputLayer(), a1);
Matrix o = new Matrix(8, 2);
vp.addValues(c.getOutputLayer(), o);
calc.calculate(connections, vp, c.getOutputLayer());
ValuesProvider activations = new ValuesProvider();
activations.addValues(c.getInputLayer(), a1);
BackpropagationAveragePooling2D bp = new BackpropagationAveragePooling2D();
bp.setActivations(activations);
vp = new ValuesProvider();
vp.addValues(c.getOutputLayer(), o);
Matrix bpo = new Matrix(32, 2);
vp.addValues(c.getInputLayer(), bpo);
bp.calculate(connections, vp, c.getInputLayer());
assertEquals(true, bpo.get(0, 0) == o.get(0, 0) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(1, 0) == o.get(0, 0) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(4, 0) == o.get(0, 0) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(5, 0) == o.get(0, 0) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(10, 0) == o.get(3, 0) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(11, 0) == o.get(3, 0) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(14, 0) == o.get(3, 0) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(15, 0) == o.get(3, 0) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(0, 1) == o.get(0, 1) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(1, 1) == o.get(0, 1) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(4, 1) == o.get(0, 1) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(5, 1) == o.get(0, 1) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(10, 1) == o.get(3, 1) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(11, 1) == o.get(3, 1) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(14, 1) == o.get(3, 1) / c.getSubsamplingRegionLength());
assertEquals(true, bpo.get(15, 1) == o.get(3, 1) / c.getSubsamplingRegionLength());
}
@Test
public void testCNNBackpropagation() {
Environment.getInstance().setExecutionStrategy(new SeqKernelExecution());
NeuralNetworkImpl nn = NNFactory.convNN(new int[][] { { 3, 3, 2 }, { 2, 2, 1 } }, true);
nn.setLayerCalculator(NNFactory.lcSigmoid(nn, null));
Conv2DConnection c = (Conv2DConnection) nn.getInputLayer().getConnections().get(0);
c.setWeights(new float [] {0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f});
Conv2DConnection b = (Conv2DConnection) nn.getOutputLayer().getConnections().get(1);
b.setWeights(new float [] {-3f});
SimpleInputProvider ts = new SimpleInputProvider(new float[][] { { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1, 1.1f, 1.2f, 1.3f, 1.4f, 1.5f, 1.6f, 1.7f, 1.8f } }, new float[][] { { 1, 1, 1, 1 } }, 1, 1);
BackPropagationTrainer<?> t = TrainerFactory.backPropagation(nn, ts, null, null, null, 0.5f, 0f, 0f);
t.train();
assertEquals(0.11756, c.getWeights()[0], 0.00001);
assertEquals(0.22640, c.getWeights()[1], 0.00001);
assertEquals(0.34408, c.getWeights()[2], 0.00001);
assertEquals(0.45292, c.getWeights()[3], 0.00001);
assertEquals(0.59712, c.getWeights()[4], 0.00001);
assertEquals(0.70596, c.getWeights()[5], 0.00001);
assertEquals(0.82364, c.getWeights()[6], 0.00001);
assertEquals(0.93248, c.getWeights()[7], 0.00001);
assertEquals(-2.911599, b.getWeights()[0], 0.00001);
}
}
|
package cz.hobrasoft.pdfmu.operation.signature;
import com.itextpdf.text.pdf.security.TSAClient;
import com.itextpdf.text.pdf.security.TSAClientBouncyCastle;
import cz.hobrasoft.pdfmu.operation.OperationException;
import cz.hobrasoft.pdfmu.operation.args.ArgsConfiguration;
import cz.hobrasoft.pdfmu.operation.args.PasswordArgs;
import net.sourceforge.argparse4j.inf.ArgumentGroup;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
/**
* Parameters of timestamping process.
*
* @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a>
*/
public class TimestampParameters implements ArgsConfiguration {
/**
* Timestamp authority URL.
*/
public String url;
/**
* Timestamp authority login username.
*/
public String username;
private PasswordArgs passwordArgs = new PasswordArgs("TSA password");
private final KeystoreParameters sslTruststore = new KeystoreParameters(SslKeystore.TRUSTSTORE.getName());
@Override
public void addArguments(ArgumentParser parser) {
ArgumentGroup group = parser.addArgumentGroup("timestamp");
// TODO: Add description
group.addArgument("--tsa-url")
.help("timestamp authority URL (set to enable timestamp)")
.type(String.class);
group.addArgument("--tsa-username")
.help("timestamp authority username (set to enable TSA authorization)")
.type(String.class);
passwordArgs.passwordArgument = group.addArgument("--tsa-password")
.help("timestamp authority password (default: <none>)");
passwordArgs.environmentVariableArgument = group.addArgument("--tsa-password-envvar")
.help("timestamp authority password environment variable")
.setDefault("PDFMU_TSA_PASSWORD");
passwordArgs.finalizeArguments();
sslTruststore.fileArgument = group.addArgument("--ssl-truststore")
.help("Location of the keystore file containing the trusted certificates. Always uses forward slashes.");
sslTruststore.typeArgument = group.addArgument("--ssl-truststore-type")
.help("SSL TrustStore type")
.choices(new String[]{"jceks", "jks", "pkcs12"});
sslTruststore.passwordArgs.passwordArgument = group.addArgument("--ssl-truststore-password")
.help("SSL TrustStore password (default: <none>)");
sslTruststore.passwordArgs.environmentVariableArgument = group.addArgument("--ssl-truststore-password-envvar")
.help("SSL TrustStore password environment variable")
.setDefault("PDFMU_TRUSTSTORE_PASSWORD");
sslTruststore.finalizeArguments();
}
@Override
public void setFromNamespace(Namespace namespace) throws OperationException {
url = namespace.get("tsa_url");
username = namespace.getString("tsa_username");
passwordArgs.setFromNamespace(namespace);
sslTruststore.setFromNamespace(namespace);
sslTruststore.setSystemProperties(SslKeystore.TRUSTSTORE);
}
/**
* Returns the {@link TSAClient} that corresponds to these parameters.
*
* @return null if the timestamp authority has not been configured
*/
public TSAClient getTSAClient() {
if (url == null) {
return null;
}
return new TSAClientBouncyCastle(url, username, getPassword());
}
private String getPassword() {
assert passwordArgs != null;
return passwordArgs.getPassword();
}
}
|
package fr.tikione.steam.cleaner;
public class Version {
public static final int MAJOR = 2;
public static final int MINOR = 4;
public static final int PATCH = 4;
public static final String VERSION = MAJOR + "." + MINOR + "." + PATCH;
private Version() {
}
}
|
package cx2x.translator.transformation.loop;
import cx2x.translator.language.ClawLanguage;
import cx2x.xcodeml.helper.*;
import cx2x.xcodeml.xelement.*;
import cx2x.xcodeml.transformation.*;
import cx2x.xcodeml.exception.*;
/**
* A LoopFusion transformation is a dependent transformation. If two LoopFusion
* transformation units shared the same fusion group and the same loop iteration
* information, they can be merge together.
* The transformation consists of merging the body of the second do statement to
* the end of the first do statement.
*
* @author clementval
*/
public class LoopFusion extends Transformation<LoopFusion> {
// Contains the value of the group option
private String _groupLabel = null;
// The loop statement involved in the Transformation
private XdoStatement[] _loops = null;
/**
* Constructs a new LoopFusion triggered from a specific pragma.
* @param directive The directive that triggered the loop fusion
* transformation.
*/
public LoopFusion(ClawLanguage directive){
super(directive);
_groupLabel = directive.getGroupName();
}
/**
* LoopFusion ctor without pragma. Create a LoopFusion dynamically at runtime.
* @param loop The do statement to be merge by the loop fusion.
* @param group The group fusion option to apply during the loop fusion.
* @param lineNumber The line number that triggered the transformation.
*/
public LoopFusion(XdoStatement loop, String group, int lineNumber){
super(null);
_loops = new XdoStatement[] { loop };
_groupLabel = group;
setStartLine(lineNumber);
}
/**
* Loop fusion analysis:
* - Without collapse clause: find whether the pragma statement is followed
* by a do statement.
* - With collapse clause: Finf the i loops follwing the pragma.
* @param xcodeml The XcodeML on which the transformations are applied.
* @param transformer The transformer used to applied the transformations.
* @return True if a do statement is found. False otherwise.
*/
public boolean analyze(XcodeProgram xcodeml, Transformer transformer) {
// With collapse clause
if(_directive.hasCollapseClause() && _directive.getCollapseValue() > 0){
_loops = new XdoStatement[_directive.getCollapseValue()];
for(int i = 0; i < _directive.getCollapseValue(); ++i){
if(i == 0){ // Find the outter loop from pragma
_loops[0] = XelementHelper.
findNextDoStatement(_directive.getPragma());
} else { // Find the next i loops
_loops[i] = XelementHelper.
findDoStatement(_loops[i-1].getBody(), false);
}
if(_loops[i] == null){
xcodeml.addError("Cannot find loop at depth " + i +
" after directive", _directive.getPragma().getLineNo());
return false;
}
}
return true;
} else {
// Without collapse clause, just fin the first do statement from the
// pragma
XdoStatement loop = XelementHelper.
findNextDoStatement(_directive.getPragma());
if(loop == null){
xcodeml.addError("Cannot find loop after directive",
_directive.getPragma().getLineNo());
return false;
}
_loops = new XdoStatement[] { loop };
return true;
}
}
public void transform(XcodeProgram xcodeml, Transformer transformer,
LoopFusion loopFusionUnit)
throws IllegalTransformationException
{
// Apply different transformation if the collapse clause is used
if(_directive.hasCollapseClause() && _directive.getCollapseValue() > 0){
// Merge the most inner loop with the most inner loop of the other fusion
// unit
int innerLoopIdx = _directive.getCollapseValue() - 1;
if(_loops[innerLoopIdx] == null
|| loopFusionUnit.getLoop(innerLoopIdx) == null)
{
throw new IllegalTransformationException(
"Cannot apply transformation, one or both do stmt are invalid.",
_directive.getPragma().getLineNo()
);
}
_loops[innerLoopIdx].appendToBody(loopFusionUnit.getLoop(innerLoopIdx));
} else {
_loops[0].appendToBody(loopFusionUnit.getLoop(0));
}
loopFusionUnit.finalizeTransformation();
}
/**
* Call by the transform method of the master loop fusion unit on the slave
* loop fusion unit to finalize the transformation. Pragma and loop of the
* slave loop fusion unit are deleted.
*/
private void finalizeTransformation(){
// Delete the pragma of the transformed loop
if(_directive.getPragma() != null){
_directive.getPragma().delete();
}
// Delete the loop that was merged with the main one
if(_loops[0] != null){
_loops[0].delete();
}
this.transformed();
}
/**
* Check whether the loop fusion unit can be merged with the given loop fusion
* unit. To be able to be transformed together, the loop fusion units must
* share the same parent block, the same iteration range, the same group
* option and both units must be not transformed.
* @param otherLoopUnit The other loop fusion unit to be merge with this one.
* @return True if the two loop fusion unit can be merge together.
*/
public boolean canBeTransformedWith(LoopFusion otherLoopUnit){
// No loop is transformed already
if(this.isTransformed() || otherLoopUnit.isTransformed()){
return false;
}
// Loop must share the same group option
if(!hasSameGroupOption(otherLoopUnit)){
return false;
}
// Loops can only be merged if they are at the same level
if(!XelementHelper.hasSameParentBlock(_loops[0],
otherLoopUnit.getLoop(0)))
{
return false;
}
if(_directive.hasCollapseClause() && _directive.getCollapseValue() > 0){
for(int i = 0; i < _directive.getCollapseValue(); ++i){
if(!_loops[i].hasSameRangeWith(otherLoopUnit.getLoop(i))){
return false;
}
}
return true;
} else {
// Loop must share the same iteration range
return _loops[0].hasSameRangeWith(otherLoopUnit.getLoop(0));
}
}
/**
* Return the do statement associated with this loop fusion unit at given
* depth.
* @param depth Integer avlue representing the depth of the loop from the
* pragma statement.
* @return A do statement.
*/
private XdoStatement getLoop(int depth){
if(_directive.hasCollapseClause() &&
depth < _directive.getCollapseValue())
{
return _loops[depth];
}
return _loops[0];
}
/**
* Get the group option associated with this loop fusion unit.
* @return Group option value.
*/
private String getGroupOptionLabel(){
return _groupLabel;
}
/**
* Check whether the given loop fusion unit share the same group fusion option
* with this loop fusion unit.
* @param otherLoopUnit The other loop fusion unit to be check with this one.
* @return True if the two loop fusion units share the same group fusion
* option.
*/
private boolean hasSameGroupOption(LoopFusion otherLoopUnit){
return (otherLoopUnit.getGroupOptionLabel() == null
? getGroupOptionLabel() == null
: otherLoopUnit.getGroupOptionLabel().equals(getGroupOptionLabel()));
}
}
|
package game;
import com.aem.sticky.button.Button;
import com.aem.sticky.button.SimpleButton;
import com.aem.sticky.button.events.ClickListener;
import graphic.Background;
import handlers.SceneHandler;
import javafx.scene.effect.Bloom;
import org.newdawn.slick.*;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.BlobbyTransition;
import org.newdawn.slick.state.transition.CombinedTransition;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;
public class MenuState extends BasicGameState {
private SimpleButton btn;
private Background background;
private SceneHandler sceneHandler = SceneHandler.getInstance();
@Override
public int getID() {
return Game.STATE.MENU;
}
@Override
public void init(GameContainer gameContainer, final StateBasedGame stateBasedGame) throws SlickException {
btn = new SimpleButton(new Rectangle(50, 50, 200, 100), new Image("data/image/balloon.png"), new Image("data/image/balloon2.png"), new Sound("data/sound/critical.ogg"));
btn.addListener(new ClickListener() {
@Override
public void onClick(Button clicked, float mx, float my) {
stateBasedGame.enterState(Game.STATE.MAIN, new CombinedTransition(), new BlobbyTransition());
}
@Override
public void onRightClick(Button clicked, float mx, float my) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void onDoubleClick(Button clicked, float mx, float my) {
//To change body of implemented methods use File | Settings | File Templates.
}
});
background = new Background(0, 0, Game.SCREEN_WIDTH, Game.SCREEN_HEIGHT, "data/image/title.png", false);
}
@Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
background.render(gameContainer, graphics);
btn.render(gameContainer, graphics);
}
@Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int delta) throws SlickException {
btn.update(gameContainer, delta);
background.update(gameContainer, delta);
}
@Override
public void mouseClicked(int button, int x, int y, int clickCount) {
super.mouseClicked(button, x, y, clickCount);
btn.mouseClicked(button, x, y, clickCount);
}
}
|
package foundation.omni.tx;
import org.bitcoinj.core.ECKey;
import java.util.ArrayList;
import java.util.Random;
/**
* <p>Convert a stream of bytes to a list of ECKeys</p>
*
* <p>Currently Assumes steam length is a whole number multiple of EncodingClassB.chunkSize</p>
*
* @author msgilligan
* @author dexX7
*/
public class PubKeyConversion {
private static final int randSeed = 0x8987FEED; // TODO: Better seed
private static Random rand = new Random(randSeed); // TODO: Better generator?
public static ArrayList<ECKey> convert(byte[] message) {
ArrayList<ECKey> list = new ArrayList<ECKey>();
byte[] chunk = new byte[EncodingClassB.chunkSize];
int pos = 0;
int bytesLeft = message.length;
while (bytesLeft > 0) {
int bytesToCopy = Math.min(bytesLeft, EncodingClassB.chunkSize);
System.arraycopy(message, pos, chunk, 0, bytesToCopy);
bytesLeft -= bytesToCopy;
pos += bytesToCopy;
ECKey key = createPubKey(chunk);
list.add(key);
}
return list;
}
/**
* Convert a 31-byte byte array to a valid public key
*
* @param input
* @return
*/
private static ECKey createPubKey(byte[] input) {
if (input.length != EncodingClassB.chunkSize) {
throw new IllegalArgumentException("invalid input length");
}
byte[] pub = new byte[EncodingClassB.prefixPubKeySize];
// pub[0] = rand.nextBoolean() ? (byte) 0x02 : (byte) 0x03; // prefix
// Don't use random for now to make unit testing work -- TODO: Fix this
pub[0] = (byte) 0x03; // prefix
System.arraycopy(input, 0, pub, 1, EncodingClassB.chunkSize); // Data
ECKey key = findValidKey(pub);
return key;
}
/**
* Try nonce values for the last byte until a valid ECKey is found
*
* @param pub A candidate public key with the last byte not set
* @return
*/
private static ECKey findValidKey(byte[] pub) {
ECKey key;
boolean valid;
short nonce = 0;
do {
valid = true;
pub[EncodingClassB.pubKeySize] = (byte) nonce++;
try {
// Create a Bouncy Castle ECPoint to make sure this pubkey is valid. As of bitcoinj 0.15.10,
// ECKey itself is lazy and won't validate at construction, so we create the point first.
key = ECKey.fromPublicOnly(ECKey.CURVE.getCurve().decodePoint(pub), true);
} catch (IllegalArgumentException e) {
valid = false;
key = null;
}
} while (valid == false && nonce < 256);
if (nonce >= 256) {
throw new RuntimeException("couldn't create valid key");
}
return key;
}
}
|
package galileo.test.net;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import galileo.net.GalileoMessage;
import galileo.net.MessageListener;
import galileo.net.NetworkDestination;
import galileo.net.ServerMessageRouter;
public class ScaleTestServer implements MessageListener {
protected static final int PORT = 5050;
protected static final int QUERY_SIZE = 64;
protected static final int REPLY_SIZE = 4096;
private int connections;
private ServerMessageRouter messageRouter;
private BlockingQueue<GalileoMessage> eventQueue
= new LinkedBlockingQueue<>();
public void listen()
throws IOException {
messageRouter = new ServerMessageRouter();
messageRouter.addListener(this);
messageRouter.listen(PORT);
System.out.println("Listening...");
}
@Override
public void onConnect(NetworkDestination endpoint) {
System.out.println("Connections: " + (++connections));
}
@Override
public void onDisconnect(NetworkDestination endpoint) {
System.out.println("Connections: " + (--connections));
}
@Override
public void onMessage(GalileoMessage message) {
try {
eventQueue.put(message);
} catch (InterruptedException e) {
Thread.interrupted();
e.printStackTrace();
}
}
public void processMessages() throws Exception {
while (true) {
GalileoMessage message = eventQueue.take();
message.getContext().sendMessage(
new GalileoMessage(new byte[REPLY_SIZE]));
}
}
public static void main(String[] args) throws Exception {
ScaleTestServer sts = new ScaleTestServer();
sts.listen();
sts.processMessages();
}
}
|
package org.jetbrains.idea.devkit.inspections.internal;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtilBase;
import com.intellij.codeInsight.intention.AddAnnotationPsiFix;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.lang.jvm.JvmParameter;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.InheritanceUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.devkit.inspections.DevKitInspectionBase;
import java.util.Objects;
public class SerializableCtorInspection extends DevKitInspectionBase {
@Override
protected PsiElementVisitor buildInternalVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitClass(PsiClass aClass) {
if (!InheritanceUtil.isInheritor(aClass, "java.io.Serializable"))
return;
if (aClass.findFieldByName(HighlightUtilBase.SERIAL_VERSION_UID_FIELD_NAME, false) == null)
return;
PsiMethod[] constructors = aClass.getConstructors();
for (PsiMethod constructor : constructors) {
String fqn = "com.intellij.serialization.PropertyMapping";
if (constructor.getNameIdentifier() != null && constructor.getAnnotation(fqn) == null) {
StringBuilder builder = new StringBuilder("@PropertyMapping({");
JvmParameter[] parameters = constructor.getParameters();
for (int i = 0; i < parameters.length; i++) {
if (i > 0) builder.append(',');
String name = Objects.requireNonNull(parameters[i].getName());
if (aClass.findFieldByName(name, false) == null) {
name = "my" + StringUtil.capitalize(name);
}
if (aClass.findFieldByName(name, false) == null) {
name = "??" + name;
}
builder.append('"').append(name).append('"');
}
PsiAnnotation annotation = JavaPsiFacade.getElementFactory(aClass.getProject())
.createAnnotationFromText(builder.append("})").toString(), aClass);
holder.registerProblem(constructor.getNameIdentifier(), "Non-default ctor should be annotated with @PropertyMapping",
new AddAnnotationPsiFix(fqn, constructor, annotation.getParameterList().getAttributes()));
}
}
}
};
}
}
|
package org.jboss.reddeer.swt.impl.tree;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.hamcrest.Matcher;
import org.jboss.reddeer.common.exception.RedDeerException;
import org.jboss.reddeer.common.logging.Logger;
import org.jboss.reddeer.swt.api.Tree;
import org.jboss.reddeer.swt.api.TreeItem;
import org.jboss.reddeer.core.handler.TreeHandler;
import org.jboss.reddeer.core.handler.TreeItemHandler;
import org.jboss.reddeer.core.reference.ReferencedComposite;
import org.jboss.reddeer.swt.widgets.AbstractControl;
public abstract class AbstractTree extends AbstractControl<org.eclipse.swt.widgets.Tree> implements Tree {
private static final Logger logger = Logger.getLogger(AbstractTree.class);
protected AbstractTree(ReferencedComposite refComposite, int index, Matcher<?>... matchers){
super(org.eclipse.swt.widgets.Tree.class, refComposite, index, matchers);
}
protected AbstractTree(org.eclipse.swt.widgets.Tree tree){
super(tree);
}
/* (non-Javadoc)
* @see org.jboss.reddeer.swt.api.Tree#getAllItems()
*/
public List<TreeItem> getAllItems() {
List<TreeItem> list = new LinkedList<TreeItem>();
list.addAll(getAllItemsRecursive(getItems()));
return list;
}
/* (non-Javadoc)
* @see org.jboss.reddeer.swt.api.Tree#getItems()
*/
public List<TreeItem> getItems() {
LinkedList<TreeItem> items = new LinkedList<TreeItem>();
List<org.eclipse.swt.widgets.TreeItem> eclipseItems = TreeHandler.getInstance().getSWTItems(swtWidget);
for (org.eclipse.swt.widgets.TreeItem swtTreeItem : eclipseItems) {
DefaultTreeItem item = null;
try{
item = new DefaultTreeItem(swtTreeItem);
items.addLast(item);
} catch (RedDeerException e) {
if(TreeHandler.getInstance().isDisposed(swtTreeItem)){
continue;
}
throw e;
}
}
return items;
}
public void selectItems(final TreeItem... treeItems) {
// Tree items should be logged, however, the names needs to
// be retrieved in UI thread so it might be a performance issue
logger.info("Select specified tree items");
org.eclipse.swt.widgets.TreeItem[] items = new org.eclipse.swt.widgets.TreeItem[treeItems.length];
for (int i=0; i < treeItems.length; i++) {
items[i] = treeItems[i].getSWTWidget();
}
TreeItemHandler.getInstance().selectItems(items);
}
@Override
public List<TreeItem> getSelectedItems() {
List<TreeItem> selectedItems = new ArrayList<TreeItem>();
for (org.eclipse.swt.widgets.TreeItem swtItem : TreeHandler.getInstance().getSelection(swtWidget)) {
DefaultTreeItem item = null;
try{
item = new DefaultTreeItem(swtItem);
selectedItems.add(item);
} catch (RedDeerException e) {
if(TreeHandler.getInstance().isDisposed(swtItem)){
continue;
}
throw e;
}
}
return selectedItems;
}
/* (non-Javadoc)
* @see org.jboss.reddeer.swt.api.Tree#setFocus()
*/
public void setFocus() {
TreeHandler.getInstance().setFocus(swtWidget);
}
/**
* Gets the column count.
*
* @return the column count
* @see Tree#getColumnCount()
*/
public int getColumnCount() {
return TreeHandler.getInstance().getColumnCount(swtWidget);
}
/* (non-Javadoc)
* @see org.jboss.reddeer.swt.api.Tree#getHeaderColumns()
*/
public List<String> getHeaderColumns() {
return TreeHandler.getInstance().getHeaderColumns(swtWidget);
}
/* (non-Javadoc)
* @see org.jboss.reddeer.swt.api.Tree#unselectAllItems()
*/
public void unselectAllItems() {
logger.info("Unselect all tree items");
TreeHandler.getInstance().unselectAllItems(swtWidget);
}
private List<TreeItem> getAllItemsRecursive(List<TreeItem> parentItems) {
List<TreeItem> list = new LinkedList<TreeItem>();
for (TreeItem item : parentItems) {
list.add(item);
list.addAll(getAllItemsRecursive(item.getItems()));
}
return list;
}
}
|
package imagej.plugins.scripting.jruby;
import static org.junit.Assert.assertEquals;
import imagej.script.ScriptLanguage;
import imagej.script.ScriptModule;
import imagej.script.ScriptService;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.junit.Test;
import org.scijava.Context;
/**
* JRuby unit tests.
*
* @author Johannes Schindelin
*/
public class JRubyTest {
@Test
public void testBasic() throws InterruptedException, ExecutionException,
IOException, ScriptException
{
final Context context = new Context(ScriptService.class);
final ScriptService scriptService = context.getService(ScriptService.class);
final String script = "$x = 1 + 2;";
final ScriptModule m = scriptService.run("add.rb", script, true).get();
final ScriptEngine engine = (ScriptEngine) m.getReturnValue();
final Object result = engine.get("$x");
// NB: Result is of type org.jruby.RubyFixnum.
assertEquals("3", result.toString());
}
@Test
public void testLocals() throws ScriptException {
final Context context = new Context(ScriptService.class);
final ScriptService scriptService = context.getService(ScriptService.class);
final ScriptLanguage language = scriptService.getLanguageByExtension("rb");
final ScriptEngine engine = language.getScriptEngine();
assertEquals(JRubyScriptEngine.class, engine.getClass());
engine.put("$hello", 17);
assertEquals("17", engine.eval("$hello").toString());
assertEquals("17", engine.get("$hello").toString());
final Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.clear();
assertEquals("", engine.get("$hello").toString());
}
// FIXME: This test currently fails due to input injection failure.
// @Test
public void testParameters() throws InterruptedException, ExecutionException,
IOException, ScriptException
{
final Context context = new Context(ScriptService.class);
final ScriptService scriptService = context.getService(ScriptService.class);
final String script = "" +
"# @ScriptService ss\n" + //
"# @OUTPUT String language\n" + //
"language = ss.getLanguageByName(\"Ruby\").getLanguageName\n";
final ScriptModule m = scriptService.run("hello.rb", script, true).get();
final Object actual = m.getOutput("language");
final String expected =
scriptService.getLanguageByName("Ruby").getLanguageName();
assertEquals(expected, actual);
final Object result = m.getReturnValue();
assertEquals(expected, result);
}
}
|
package beast.app.beauti;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import beast.app.draw.InputEditor;
import beast.core.Input;
import beast.core.BEASTObject;
import beast.core.BEASTInterface;
import beast.evolution.alignment.Alignment;
import beast.evolution.alignment.FilteredAlignment;
import beast.evolution.alignment.Sequence;
import beast.evolution.alignment.Taxon;
import beast.evolution.alignment.TaxonSet;
public class TaxonSetInputEditor extends InputEditor.Base {
private static final long serialVersionUID = 1L;
List<Taxon> m_taxonset;
List<Taxon> m_lineageset;
Map<String, String> m_taxonMap;
JTable m_table;
DefaultTableModel m_model = new DefaultTableModel();
JTextField filterEntry;
String m_sFilter = ".*";
int m_sortByColumn = 0;
boolean m_bIsAscending = true;
public TaxonSetInputEditor(BeautiDoc doc) {
super(doc);
}
@Override
public Class<?> type() {
return TaxonSet.class;
}
@Override
public void init(Input<?> input, BEASTInterface plugin, int itemNr, ExpandOption bExpandOption, boolean bAddButtons) {
m_input = input;
m_plugin = plugin;
this.itemNr = itemNr;
TaxonSet taxonset = (TaxonSet) m_input.get();
if (taxonset == null) {
return;
}
List<Taxon> taxonsets = new ArrayList<Taxon>();
List<Taxon> taxa = taxonset.taxonsetInput.get();
for (Taxon taxon : taxa) {
taxonsets.add((TaxonSet) taxon);
}
add(getContent(taxonsets));
if (taxa.size() == 1 && taxa.get(0).getID().equals("Beauti2DummyTaxonSet") || taxa.size() == 0) {
taxa.clear();
try {
// species is first character of taxon
guessTaxonSets("(.).*", 0);
for (Taxon taxonset2 : m_taxonset) {
for (Taxon taxon : ((TaxonSet) taxonset2).taxonsetInput.get()) {
m_lineageset.add(taxon);
m_taxonMap.put(taxon.getID(), taxonset2.getID());
}
}
} catch (Exception e) {
e.printStackTrace();
}
taxonSetToModel();
modelToTaxonset();
}
}
private Component getContent(List<Taxon> taxonset) {
m_taxonset = taxonset;
m_taxonMap = new HashMap<String, String>();
m_lineageset = new ArrayList<Taxon>();
for (Taxon taxonset2 : m_taxonset) {
for (Taxon taxon : ((TaxonSet) taxonset2).taxonsetInput.get()) {
m_lineageset.add(taxon);
m_taxonMap.put(taxon.getID(), taxonset2.getID());
}
}
// set up table.
// special features: background shading of rows
// custom editor allowing only Date column to be edited.
m_model = new DefaultTableModel();
m_model.addColumn("Taxon");
m_model.addColumn("Species/Population");
taxonSetToModel();
m_table = new JTable(m_model) {
private static final long serialVersionUID = 1L;
// method that induces table row shading
@Override
public Component prepareRenderer(TableCellRenderer renderer, int Index_row, int Index_col) {
Component comp = super.prepareRenderer(renderer, Index_row, Index_col);
// even index, selected or not selected
if (isCellSelected(Index_row, Index_col)) {
comp.setBackground(Color.gray);
} else if (Index_row % 2 == 0) {
comp.setBackground(new Color(237, 243, 255));
} else {
comp.setBackground(Color.white);
}
return comp;
}
};
// set up editor that makes sure only doubles are accepted as entry
// and only the Date column is editable.
m_table.setDefaultEditor(Object.class, new TableCellEditor() {
JTextField m_textField = new JTextField();
int m_iRow
,
m_iCol;
@Override
public boolean stopCellEditing() {
m_table.removeEditor();
String sText = m_textField.getText();
System.err.println(sText);
m_model.setValueAt(sText, m_iRow, m_iCol);
// try {
// Double.parseDouble(sText);
// } catch (Exception e) {
// return false;
modelToTaxonset();
return true;
}
@Override
public boolean isCellEditable(EventObject anEvent) {
return m_table.getSelectedColumn() == 1;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int iRow,
int iCol) {
if (!isSelected) {
return null;
}
m_iRow = iRow;
m_iCol = iCol;
m_textField.setText((String) value);
return m_textField;
}
@Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}
@Override
public void removeCellEditorListener(CellEditorListener l) {
}
@Override
public Object getCellEditorValue() {
return null;
}
@Override
public void cancelCellEditing() {
}
@Override
public void addCellEditorListener(CellEditorListener l) {
}
});
m_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
m_table.getColumnModel().getColumn(0).setPreferredWidth(250);
m_table.getColumnModel().getColumn(1).setPreferredWidth(250);
JTableHeader header = m_table.getTableHeader();
header.addMouseListener(new ColumnHeaderListener());
JScrollPane pane = new JScrollPane(m_table);
Box tableBox = Box.createHorizontalBox();
tableBox.add(Box.createHorizontalGlue());
tableBox.add(pane);
tableBox.add(Box.createHorizontalGlue());
Box box = Box.createVerticalBox();
box.add(createFilterBox());
box.add(tableBox);
box.add(createButtonBox());
return box;
}
private Component createButtonBox() {
Box buttonBox = Box.createHorizontalBox();
JButton fillDownButton = new JButton("Fill down");
fillDownButton.setName("Fill down");
fillDownButton.setToolTipText("replaces all taxons in selection with the one that is selected at the top");
fillDownButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int[] rows = m_table.getSelectedRows();
if (rows.length < 2) {
return;
}
String sTaxon = (String) ((Vector<?>) m_model.getDataVector().elementAt(rows[0])).elementAt(1);
for (int i = 1; i < rows.length; i++) {
m_model.setValueAt(sTaxon, rows[i], 1);
}
modelToTaxonset();
}
});
JButton guessButton = new JButton("Guess");
guessButton.setName("Guess");
guessButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
guess();
}
});
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(fillDownButton);
buttonBox.add(Box.createHorizontalGlue());
buttonBox.add(guessButton);
buttonBox.add(Box.createHorizontalGlue());
return buttonBox;
}
public class ColumnHeaderListener extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
// The index of the column whose header was clicked
int vColIndex = m_table.getColumnModel().getColumnIndexAtX(evt.getX());
if (vColIndex == -1) {
return;
}
if (vColIndex != m_sortByColumn) {
m_sortByColumn = vColIndex;
m_bIsAscending = true;
} else {
m_bIsAscending = !m_bIsAscending;
}
taxonSetToModel();
}
}
private void guess() {
GuessPatternDialog dlg = new GuessPatternDialog(this, m_sPattern);
switch(dlg.showDialog("Guess taxon sets")) {
case canceled: return;
case pattern:
String sPattern = dlg.getPattern();
try {
guessTaxonSets(sPattern, 0);
m_sPattern = sPattern;
break;
} catch (Exception e) {
e.printStackTrace();
}
case trait:
String trait = dlg.getTrait();
parseTrait(trait);
break;
}
m_lineageset.clear();
for (Taxon taxonset2 : m_taxonset) {
for (Taxon taxon : ((TaxonSet) taxonset2).taxonsetInput.get()) {
m_lineageset.add(taxon);
m_taxonMap.put(taxon.getID(), taxonset2.getID());
}
}
taxonSetToModel();
modelToTaxonset();
}
/**
* guesses taxon sets based on pattern in sRegExp based on the taxa in
* m_rawData
*/
public int guessTaxonSets(String sRegexp, int nMinSize) throws Exception {
m_taxonset.clear();
HashMap<String, TaxonSet> map = new HashMap<String, TaxonSet>();
Pattern m_pattern = Pattern.compile(sRegexp);
Set<Taxon> taxa = new HashSet<Taxon>();
Set<String> taxonIDs = new HashSet<String>();
for (Alignment alignment : getDoc().alignments) {
for (String sID : alignment.getTaxaNames()) {
if (!taxonIDs.contains(sID)) {
Taxon taxon = new Taxon();
taxon.setID(sID);
taxa.add(taxon);
taxonIDs.add(sID);
}
}
for (Sequence sequence : alignment.sequenceInput.get()) {
String sID = sequence.taxonInput.get();
if (!taxonIDs.contains(sID)) {
Taxon taxon = new Taxon();
// ensure sequence and taxon do not get same ID
if (sequence.getID().equals(sequence.taxonInput.get())) {
sequence.setID("_" + sequence.getID());
}
taxon.setID(sequence.taxonInput.get());
taxa.add(taxon);
taxonIDs.add(sID);
}
}
}
for (Taxon taxon : taxa) {
if (!(taxon instanceof TaxonSet)) {
Matcher matcher = m_pattern.matcher(taxon.getID());
if (matcher.find()) {
String sMatch = matcher.group(1);
try {
if (map.containsKey(sMatch)) {
TaxonSet set = map.get(sMatch);
set.taxonsetInput.setValue(taxon, set);
} else {
TaxonSet set = new TaxonSet();
set.setID(sMatch);
set.taxonsetInput.setValue(taxon, set);
map.put(sMatch, set);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// add taxon sets
int nIgnored = 0;
for (TaxonSet set : map.values()) {
if (set.taxonsetInput.get().size() > nMinSize) {
m_taxonset.add(set);
} else {
nIgnored += set.taxonsetInput.get().size();
}
}
return nIgnored;
}
void parseTrait(String trait) {
Map<String,String> traitmap = new HashMap<String, String>();
for (String line : trait.split(",")) {
String [] strs = line.split("=");
if (strs.length == 2) {
traitmap.put(strs[0].trim(), strs[1].trim());
}
}
m_taxonset.clear();
Set<Taxon> taxa = new HashSet<Taxon>();
Set<String> taxonIDs = new HashSet<String>();
for (Alignment alignment : getDoc().alignments) {
if (alignment instanceof FilteredAlignment) {
alignment = ((FilteredAlignment)alignment).alignmentInput.get();
}
for (Sequence sequence : alignment.sequenceInput.get()) {
String sID = sequence.taxonInput.get();
if (!taxonIDs.contains(sID)) {
Taxon taxon = new Taxon();
// ensure sequence and taxon do not get same ID
if (sequence.getID().equals(sequence.taxonInput.get())) {
sequence.setID("_" + sequence.getID());
}
taxon.setID(sequence.taxonInput.get());
taxa.add(taxon);
taxonIDs.add(sID);
}
}
}
HashMap<String, TaxonSet> map = new HashMap<String, TaxonSet>();
for (Taxon taxon : taxa) {
if (!(taxon instanceof TaxonSet)) {
String sMatch = traitmap.get(taxon.getID());
if (sMatch != null) {
try {
if (map.containsKey(sMatch)) {
TaxonSet set = map.get(sMatch);
set.taxonsetInput.setValue(taxon, set);
} else {
TaxonSet set = new TaxonSet();
set.setID(sMatch);
set.taxonsetInput.setValue(taxon, set);
map.put(sMatch, set);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// add taxon sets
int nIgnored = 0;
for (TaxonSet set : map.values()) {
m_taxonset.add(set);
}
}
String m_sPattern = "^(.+)[-_\\. ](.*)$";
private Component createFilterBox() {
Box filterBox = Box.createHorizontalBox();
filterBox.add(new JLabel("filter: "));
// Dimension size = new Dimension(100,20);
filterEntry = new JTextField();
filterEntry.setColumns(20);
// filterEntry.setMinimumSize(size);
// filterEntry.setPreferredSize(size);
// filterEntry.setSize(size);
filterEntry.setToolTipText("Enter regular expression to match taxa");
filterEntry.setMaximumSize(new Dimension(1024, 20));
filterBox.add(filterEntry);
filterBox.add(Box.createHorizontalGlue());
filterEntry.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
processFilter();
}
@Override
public void insertUpdate(DocumentEvent e) {
processFilter();
}
@Override
public void changedUpdate(DocumentEvent e) {
processFilter();
}
private void processFilter() {
String sFilter = ".*" + filterEntry.getText() + ".*";
try {
// sanity check: make sure the filter is legit
sFilter.matches(sFilter);
m_sFilter = sFilter;
taxonSetToModel();
m_table.repaint();
} catch (PatternSyntaxException e) {
// ignore
}
}
});
return filterBox;
}
/**
* for convert taxon sets to table model *
*/
@SuppressWarnings("unchecked")
private void taxonSetToModel() {
// count number of lineages that match the filter
int i = 0;
for (String sLineageID : m_taxonMap.keySet()) {
if (sLineageID.matches(m_sFilter)) {
i++;
}
}
// clear table model
while (m_model.getRowCount() > 0) {
m_model.removeRow(0);
}
// fill table model with lineages matching the filter
for (String sLineageID : m_taxonMap.keySet()) {
if (sLineageID.matches(m_sFilter)) {
Object[] rowData = new Object[2];
rowData[0] = sLineageID;
rowData[1] = m_taxonMap.get(sLineageID);
m_model.addRow(rowData);
}
}
@SuppressWarnings("rawtypes")
Vector data = m_model.getDataVector();
Collections.sort(data, new Comparator<Vector<?>>() {
@Override
public int compare(Vector<?> v1, Vector<?> v2) {
String o1 = (String) v1.get(m_sortByColumn);
String o2 = (String) v2.get(m_sortByColumn);
if (o1.equals(o2)) {
o1 = (String) v1.get(1 - m_sortByColumn);
o2 = (String) v2.get(1 - m_sortByColumn);
}
if (m_bIsAscending) {
return o1.compareTo(o2);
} else {
return o2.compareTo(o1);
}
}
});
m_model.fireTableRowsInserted(0, m_model.getRowCount());
}
/**
* for convert table model to taxon sets *
*/
private void modelToTaxonset() {
// update map
for (int i = 0; i < m_model.getRowCount(); i++) {
String sLineageID = (String) ((Vector<?>) m_model.getDataVector().elementAt(i)).elementAt(0);
String sTaxonSetID = (String) ((Vector<?>) m_model.getDataVector().elementAt(i)).elementAt(1);
// new taxon set?
if (!m_taxonMap.containsValue(sTaxonSetID)) {
// create new taxon set
TaxonSet taxonset = new TaxonSet();
taxonset.setID(sTaxonSetID);
m_taxonset.add(taxonset);
}
m_taxonMap.put(sLineageID, sTaxonSetID);
}
// clear old taxon sets
for (Taxon taxon : m_taxonset) {
TaxonSet set = (TaxonSet) taxon;
set.taxonsetInput.get().clear();
doc.registerPlugin(set);
}
// group lineages with their taxon sets
for (String sLineageID : m_taxonMap.keySet()) {
for (Taxon taxon : m_lineageset) {
if (taxon.getID().equals(sLineageID)) {
String sTaxonSet = m_taxonMap.get(sLineageID);
for (Taxon taxon2 : m_taxonset) {
TaxonSet set = (TaxonSet) taxon2;
if (set.getID().equals(sTaxonSet)) {
try {
set.taxonsetInput.setValue(taxon, set);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
// remove unused taxon sets
for (int i = m_taxonset.size() - 1; i >= 0; i
if (((TaxonSet) m_taxonset.get(i)).taxonsetInput.get().size() == 0) {
doc.unregisterPlugin(m_taxonset.get(i));
m_taxonset.remove(i);
}
}
TaxonSet taxonset = (TaxonSet) m_input.get();
taxonset.taxonsetInput.get().clear();
for (Taxon taxon : m_taxonset) {
try {
taxonset.taxonsetInput.setValue(taxon, taxonset);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
import java.text.ParseException;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
public class Main extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.getRequestURI().endsWith("/db")) {
showDatabase(req, resp);
} else {
showHome(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isCreate;
if (request.getRequestURI().toLowerCase().equals("/api/new")) {
isCreate = true;
} else if (request.getRequestURI().toLowerCase().equals("/api/check")) {
isCreate = false;
} else {
throw new IllegalArgumentException("Invalid path for post message");
}
JSONObject jsonBody, jsonResponse = null;
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /* report an error */
}
try {
jsonBody = new JSONObject(jb.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
throw new IOException("Error parsing JSON request string");
}
try {
if (isCreate) {
jsonResponse = generateSchedule(jsonBody);
} else {
jsonResponse = checkSchedule(jsonBody);
}
} catch (JSONException e) {
throw new IOException("Encountered JSONexception");
}
response.getWriter().print(jsonResponse.toString());
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
private void showHome(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().printf("%s\tHello from Java!", req.getRequestURI());
}
private void showDatabase(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
String out = "Hello!\n";
while (rs.next()) {
out += "Read from DB: " + rs.getTimestamp("tick") + "\n";
}
resp.getWriter().print(out);
} catch (Exception e) {
resp.getWriter().print("There was an error: " + e.getMessage());
}
}
private JSONObject generateSchedule(JSONObject data) {
return data;
}
private JSONObject checkSchedule(JSONObject data) throws JSONException {
JSONObject res = new JSONObject();
res.put("unsatisfiedSoft", new ArrayList<String>());
res.put("unsatisfiedHard", new ArrayList<String>());
return res;
}
private Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
public static void main(String[] args) throws Exception {
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
|
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
public class Main extends HttpServlet{
private static String TABLE_CREATION = "CREATE TABLE IF NOT EXISTS profile (user_id SERIAL, name varchar(32), " +
"about_me varchar(1024), village varchar(32), zip_code int, phone_number varchar(16), email varchar(32));";
private static String TABLE_CREATION_2 = "CREATE TABLE IF NOT EXISTS Connections (requester_id int, target_id int, status varchar(32));";
/*
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Connection connection = null;
try {
connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate(TABLE_CREATION);
}
catch (Exception e) {
resp.setStatus(500);
resp.getWriter().print("Table creation error: " + e.getMessage());
}
finally {
try {
connection.close();
}
catch (SQLException e) {
resp.getWriter().print("Failed to close connection: " + getStackTrace(e));
}
}
}
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
Connection connection = null;
try {
connection = getConnection();
Statement stmt = connection.createStatement();
stmt.executeUpdate(TABLE_CREATION);
stmt.executeUpdate(TABLE_CREATION_2);
}
catch (Exception e) {
resp.setStatus(500);
resp.getWriter().print("Table creation error: " + e.getMessage());
}
StringBuffer jb = new StringBuffer();
String line;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
}
catch (IOException e) {
resp.setStatus(400);
resp.getWriter().print("Couldn't read in request body: " + getStackTrace(e));
}
try {
JSONObject jsonObject = new JSONObject(jb.toString());
if (req.getRequestURI().endsWith("/createAccount")) {
resp.setStatus(200);
resp.getWriter().print("Creating!");
String name = jsonObject.getString("name");
String about_me = jsonObject.getString("about_me");
String village = jsonObject.getString("village");
String zip_code = jsonObject.getString("zip_code");
String phone_number = jsonObject.getString("phone_number");
String email = jsonObject.getString("email");
String update_sql = "INSERT INTO profile (name, about_me, village, zip_code, phone_number, email) VALUES (?, ?, ?, ?, ?, ?)";
try {
PreparedStatement stmt = connection.prepareStatement(update_sql);
stmt.setString(1, name);
stmt.setString(2, about_me);
stmt.setString(3, village);
stmt.setString(4, zip_code);
stmt.setString(5, phone_number);
stmt.setString(6, email);
stmt.executeUpdate();
stmt.close();
}
catch (SQLException e) {
resp.getWriter().print("SQL ERROR @POST: " + getStackTrace(e));
}
}
else {
resp.setStatus(404);
}
}
catch (JSONException e1) {
resp.setStatus(400);
resp.getWriter().print("Error parsing request JSON: " + getStackTrace(e1));
}
catch (IOException e) {
resp.setStatus(500);
resp.getWriter().print("Error creating SQL statement: " + getStackTrace(e));
}
finally {
try {
connection.close();
}
catch (SQLException e) {
resp.getWriter().print("Failed to close connection: " + getStackTrace(e));
}
}
}
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
public static void main(String[] args) throws Exception {
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.