answer
stringlengths 17
10.2M
|
|---|
/*
* $Id: TestPlatformUtil.java,v 1.10 2012-08-08 07:11:25 tlipkis Exp $
*/
package org.lockss.util;
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import org.lockss.util.*;
import org.lockss.config.*;
import org.lockss.test.*;
/**
* test class for org.lockss.util.PlatformInfo
*/
public class TestPlatformUtil extends LockssTestCase {
PlatformUtil info;
public void setUp() throws Exception {
super.setUp();
info = PlatformUtil.getInstance();
}
public void testGetSystemTempDir() {
String javatmp = System.getProperty("java.io.tmpdir");
assertEquals(javatmp, PlatformUtil.getSystemTempDir());
String parmtmp = "/another/tmp/dir";
ConfigurationUtil.setFromArgs(ConfigManager.PARAM_TMPDIR, parmtmp);
assertEquals(new File(parmtmp, "dtmp").toString(),
PlatformUtil.getSystemTempDir());
}
public void testGetCwd() {
log.info("cwd: " + info.getCwd());
}
public void testGetUnfilteredTcpPorts() throws Exception {
assertEmpty(info.getUnfilteredTcpPorts());
ConfigurationUtil.setFromArgs(PlatformUtil.PARAM_UNFILTERED_TCP_PORTS, "9909");
assertEquals(ListUtil.list("9909"), info.getUnfilteredTcpPorts());
ConfigurationUtil.setFromArgs(PlatformUtil.PARAM_UNFILTERED_TCP_PORTS,
"9900;1234");
assertEquals(ListUtil.list("9900", "1234"), info.getUnfilteredTcpPorts());
ConfigurationUtil.setFromArgs(PlatformUtil.PARAM_UNFILTERED_TCP_PORTS,
"9900,1234,333");
assertEquals(ListUtil.list("9900", "1234", "333"),
info.getUnfilteredTcpPorts());
}
public void testDiskUsageNonexistentPath() throws Exception {
long du = info.getDiskUsage("/very_unlik_elyd_irect_oryname/4x2");
assertEquals(-1, du);
}
public void testDiskUsage() throws Exception {
long du;
File tmpdir = getTempDir();
du = info.getDiskUsage(tmpdir.toString());
assertTrue(du >= 0);
StringBuffer sb = new StringBuffer(1500);
while (sb.length() < 1200) {
sb.append("01234567890123456789012345678901234567890123456789");
}
FileTestUtil.writeFile(new File(tmpdir, "foobar"), sb.toString());
long du2 = info.getDiskUsage(tmpdir.toString());
assertTrue(du2 > du);
}
public void testNonexistentPathNullDF() throws Exception {
String javatmp = System.getProperty("java.io.tmpdir");
PlatformUtil.DF df =
info.getDF(javatmp);
assertNotNull(javatmp + " is null", df);
javatmp = "/very_unlik_elyd_irect_oryname/4x3";
df = info.getDF(javatmp);
assertNull(javatmp, df);
}
public void testMakeDF() throws Exception {
String str = "/dev/hda2 26667896 9849640 15463576 39% /";
PlatformUtil.DF df = info.makeDFFromLine("/mnt", str);
assertNotNull(df);
assertEquals("/mnt", df.getPath());
assertEquals(26667896, df.getSize());
assertEquals(9849640, df.getUsed());
assertEquals(15463576, df.getAvail());
assertEquals("39%", df.getPercentString());
assertEquals(.39, df.getPercent(), .0000001);
}
public void testMakeDFLong() throws Exception {
String str = "/dev/md0 2826607136 411558468 2269149176 16% /";
PlatformUtil.DF df = info.makeDFFromLine("/cache.wd3", str);
assertNotNull(df);
assertEquals("/cache.wd3", df.getPath());
assertEquals(2826607136L, df.getSize());
assertEquals(411558468, df.getUsed());
assertEquals(2269149176L, df.getAvail());
assertEquals("16%", df.getPercentString());
assertEquals(.16, df.getPercent(), .0000001);
}
public void testMakeDFIll1() throws Exception {
String str = "/dev/hda2 26667896 9849640 -1546 39% /";
PlatformUtil.DF df = info.makeDFFromLine("/mnt", str);
assertNotNull(df);
assertEquals("/mnt", df.getPath());
assertEquals(26667896, df.getSize());
assertEquals(9849640, df.getUsed());
assertEquals(-1546, df.getAvail());
assertEquals("39%", df.getPercentString());
assertEquals(.39, df.getPercent(), .0000001);
}
public void testMakeDFIll2() throws Exception {
// linux df running under linux emul on OpenBSD can produce this
String str = "- 26667896 9849640 4294426204 101% /";
PlatformUtil.DF df = info.makeDFFromLine("/mnt", str);
assertNotNull(df);
assertEquals("/mnt", df.getPath());
assertEquals(26667896, df.getSize());
assertEquals(9849640, df.getUsed());
assertEquals(4294426204L, df.getAvail());
assertEquals("101%", df.getPercentString());
assertEquals(1.01, df.getPercent(), .0000001);
}
PlatformUtil.DF makeThresh(int minFreeMB, double minFreePercent) {
return PlatformUtil.DF.makeThreshold(minFreeMB, minFreePercent);
}
public void testIsFullerThan() throws Exception {
String str = "/dev/hda2 26667896 9849640 15463576 73% /";
PlatformUtil.DF df = info.makeDFFromLine("/mnt", str);
assertFalse(df.isFullerThan(makeThresh(100, 0)));
assertFalse(df.isFullerThan(makeThresh(15000, 0)));
assertTrue(df.isFullerThan(makeThresh(16000, 0)));
assertTrue(df.isFullerThan(makeThresh(16000, .3)));
assertTrue(df.isFullerThan(makeThresh(100, .30)));
assertFalse(df.isFullerThan(makeThresh(100, .20)));
assertFalse(df.isFullerThan(makeThresh(0, 0)));
}
public void testisDiskFullError() throws Exception {
assertFalse(info.isDiskFullError(new IOException("jjjjj: No such file or directory")));
assertTrue(info.isDiskFullError(new IOException("No space left on device")));
assertTrue(info.isDiskFullError(new IOException("disk: No space left on device")));
}
public void xtestThreadDump() throws Exception {
info.threadDump(true);
}
boolean isBuggy(String str) {
return PlatformUtil.isBuggyDoubleString(str);
}
double parseDouble(String str) {
return PlatformUtil.parseDouble(str);
}
public void testIsBuggyDoubleString() {
assertTrue(isBuggy("2.2250738585072012e-308"));
assertTrue(isBuggy("0.00022250738585072012E-304"));
assertTrue(isBuggy("0.0000000022250738585072012E-299"));
assertTrue(isBuggy("0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072012"));
assertTrue(isBuggy("0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002225073858507201212345"));
assertTrue(isBuggy("22.250738585072012e-309"));
assertTrue(isBuggy("22.250738585072012e-0309"));
assertTrue(isBuggy("00000000002.2250738585072012e-308"));
assertTrue(isBuggy("2.225073858507201200000e-308"));
assertTrue(isBuggy("2.2250738585072012e-00308"));
assertTrue(isBuggy("2.2250738585072012997800001e-308"));
assertFalse(isBuggy("0"));
assertFalse(isBuggy("4.5"));
assertFalse(isBuggy("2.2e-308"));
assertFalse(isBuggy("2.2E-308"));
assertFalse(isBuggy("2.2250738585072011e-308"));
// BaseServletManager.CompressingFilterWrapper checks the
// Accept-Encoding: header without parsing out the qvalue
assertTrue(isBuggy("gzip;q=1.0, identity; q=2.2250738585072012997800001e-308, *;q=0"));
assertFalse(isBuggy("gzip;q=1.0, identity; q=2.2, *;q=0"));
}
public void testParseDouble() {
assertEquals(0.0, parseDouble("0"));
assertEquals(4.5, parseDouble("4.5"));
try {
parseDouble("2.2250738585072012e-308");
fail("should throw");
} catch (NumberFormatException e) {
}
try {
parseDouble("0.00022250738585072012E-304");
fail("should throw");
} catch (NumberFormatException e) {
}
}
}
|
package com.hoho.android.usbserial.driver;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Cp21xxSerialDriver implements UsbSerialDriver {
private static final String TAG = Cp21xxSerialDriver.class.getSimpleName();
private final UsbDevice mDevice;
private final List<UsbSerialPort> mPorts;
public Cp21xxSerialDriver(UsbDevice device) {
mDevice = device;
mPorts = new ArrayList<>();
for( int port = 0; port < device.getInterfaceCount(); port++) {
mPorts.add(new Cp21xxSerialPort(mDevice, port));
}
}
@Override
public UsbDevice getDevice() {
return mDevice;
}
@Override
public List<UsbSerialPort> getPorts() {
return mPorts;
}
public class Cp21xxSerialPort extends CommonUsbSerialPort {
private static final int DEFAULT_BAUD_RATE = 9600;
private static final int USB_WRITE_TIMEOUT_MILLIS = 5000;
/*
* Configuration Request Types
*/
private static final int REQTYPE_HOST_TO_DEVICE = 0x41;
/*
* Configuration Request Codes
*/
private static final int SILABSER_IFC_ENABLE_REQUEST_CODE = 0x00;
private static final int SILABSER_SET_BAUDDIV_REQUEST_CODE = 0x01;
private static final int SILABSER_SET_LINE_CTL_REQUEST_CODE = 0x03;
private static final int SILABSER_SET_MHS_REQUEST_CODE = 0x07;
private static final int SILABSER_SET_BAUDRATE = 0x1E;
private static final int SILABSER_FLUSH_REQUEST_CODE = 0x12;
private static final int SILABSER_SET_DTR_RTS_REQUEST_CODE = 0x07;
private static final int FLUSH_READ_CODE = 0x0a;
private static final int FLUSH_WRITE_CODE = 0x05;
/*
* SILABSER_IFC_ENABLE_REQUEST_CODE
*/
private static final int UART_ENABLE = 0x0001;
private static final int UART_DISABLE = 0x0000;
/*
* SILABSER_SET_BAUDDIV_REQUEST_CODE
*/
private static final int BAUD_RATE_GEN_FREQ = 0x384000;
/*
* SILABSER_SET_MHS_REQUEST_CODE
*/
private static final int MCR_DTR = 0x0001;
private static final int MCR_RTS = 0x0002;
private static final int MCR_ALL = 0x0003;
private static final int CONTROL_WRITE_DTR = 0x0100;
private static final int CONTROL_WRITE_RTS = 0x0200;
/*
* SILABSER_SET_DTR_RTS_REQUEST_CODE
*/
private static final int DTR_ENABLE = 0x101;
private static final int DTR_DISABLE = 0x100;
private static final int RTS_ENABLE = 0x202;
private static final int RTS_DISABLE = 0x200;
private boolean dtr = false;
private boolean rts = false;
// second port of Cp2105 has limited baudRate, dataBits, stopBits, parity
// unsupported baudrate returns error at controlTransfer(), other parameters are silently ignored
private boolean mIsRestrictedPort;
public Cp21xxSerialPort(UsbDevice device, int portNumber) {
super(device, portNumber);
}
@Override
public UsbSerialDriver getDriver() {
return Cp21xxSerialDriver.this;
}
private int setConfigSingle(int request, int value) throws IOException {
int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request, value,
mPortNumber, null, 0, USB_WRITE_TIMEOUT_MILLIS);
if (result != 0) {
throw new IOException("Setting baudrate failed: result=" + result);
}
return result;
}
@Override
public void open(UsbDeviceConnection connection) throws IOException {
if (mConnection != null) {
throw new IOException("Already open");
}
mConnection = connection;
boolean opened = false;
mIsRestrictedPort = mDevice.getInterfaceCount() == 2 && mPortNumber == 1;
try {
if(mPortNumber >= mDevice.getInterfaceCount()) {
throw new IOException("Unknown port number");
}
UsbInterface dataIface = mDevice.getInterface(mPortNumber);
if (!mConnection.claimInterface(dataIface, true)) {
throw new IOException("Could not claim interface " + mPortNumber);
}
for (int i = 0; i < dataIface.getEndpointCount(); i++) {
UsbEndpoint ep = dataIface.getEndpoint(i);
if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
mReadEndpoint = ep;
} else {
mWriteEndpoint = ep;
}
}
}
setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, MCR_ALL | CONTROL_WRITE_DTR | CONTROL_WRITE_RTS);
setConfigSingle(SILABSER_SET_BAUDDIV_REQUEST_CODE, BAUD_RATE_GEN_FREQ / DEFAULT_BAUD_RATE);
// setParameters(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY);
opened = true;
} finally {
if (!opened) {
close();
}
}
}
@Override
public void closeInt() {
try {
setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_DISABLE);
} catch (Exception ignored) {}
try {
mConnection.releaseInterface(mDevice.getInterface(mPortNumber));
} catch(Exception ignored) {}
}
private void setBaudRate(int baudRate) throws IOException {
byte[] data = new byte[] {
(byte) ( baudRate & 0xff),
(byte) ((baudRate >> 8 ) & 0xff),
(byte) ((baudRate >> 16) & 0xff),
(byte) ((baudRate >> 24) & 0xff)
};
int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE,
0, mPortNumber, data, 4, USB_WRITE_TIMEOUT_MILLIS);
if (ret < 0) {
throw new IOException("Error setting baud rate");
}
}
@Override
public void setParameters(int baudRate, int dataBits, int stopBits, int parity) throws IOException {
if(baudRate <= 0) {
throw new IllegalArgumentException("Invalid baud rate: " + baudRate);
}
setBaudRate(baudRate);
int configDataBits = 0;
switch (dataBits) {
case DATABITS_5:
if(mIsRestrictedPort)
throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
configDataBits |= 0x0500;
break;
case DATABITS_6:
if(mIsRestrictedPort)
throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
configDataBits |= 0x0600;
break;
case DATABITS_7:
if(mIsRestrictedPort)
throw new UnsupportedOperationException("Unsupported data bits: " + dataBits);
configDataBits |= 0x0700;
break;
case DATABITS_8:
configDataBits |= 0x0800;
break;
default:
throw new IllegalArgumentException("Invalid data bits: " + dataBits);
}
switch (parity) {
case PARITY_NONE:
break;
case PARITY_ODD:
configDataBits |= 0x0010;
break;
case PARITY_EVEN:
configDataBits |= 0x0020;
break;
case PARITY_MARK:
if(mIsRestrictedPort)
throw new UnsupportedOperationException("Unsupported parity: mark");
configDataBits |= 0x0030;
break;
case PARITY_SPACE:
if(mIsRestrictedPort)
throw new UnsupportedOperationException("Unsupported parity: space");
configDataBits |= 0x0040;
break;
default:
throw new IllegalArgumentException("Invalid parity: " + parity);
}
switch (stopBits) {
case STOPBITS_1:
break;
case STOPBITS_1_5:
throw new UnsupportedOperationException("Unsupported stop bits: 1.5");
case STOPBITS_2:
if(mIsRestrictedPort)
throw new UnsupportedOperationException("Unsupported stop bits: 2");
configDataBits |= 2;
break;
default:
throw new IllegalArgumentException("Invalid stop bits: " + stopBits);
}
setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configDataBits);
}
@Override
public boolean getCD() throws IOException {
return false;
}
@Override
public boolean getCTS() throws IOException {
return false;
}
@Override
public boolean getDSR() throws IOException {
return false;
}
@Override
public boolean getDTR() throws IOException {
return dtr;
}
@Override
public void setDTR(boolean value) throws IOException {
dtr = value;
setConfigSingle(SILABSER_SET_DTR_RTS_REQUEST_CODE, dtr ? DTR_ENABLE : DTR_DISABLE);
}
@Override
public boolean getRI() throws IOException {
return false;
}
@Override
public boolean getRTS() throws IOException {
return rts;
}
@Override
public void setRTS(boolean value) throws IOException {
rts = value;
setConfigSingle(SILABSER_SET_DTR_RTS_REQUEST_CODE, rts ? RTS_ENABLE : RTS_DISABLE);
}
@Override
public boolean purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException {
int value = (purgeReadBuffers ? FLUSH_READ_CODE : 0)
| (purgeWriteBuffers ? FLUSH_WRITE_CODE : 0);
if (value != 0) {
setConfigSingle(SILABSER_FLUSH_REQUEST_CODE, value);
}
return true;
}
}
public static Map<Integer, int[]> getSupportedDevices() {
final Map<Integer, int[]> supportedDevices = new LinkedHashMap<Integer, int[]>();
supportedDevices.put(UsbId.VENDOR_SILABS,
new int[] {
UsbId.SILABS_CP2102,
UsbId.SILABS_CP2105,
UsbId.SILABS_CP2108,
UsbId.SILABS_CP2110
});
return supportedDevices;
}
}
|
package com.peterphi.usermanager.ui.impl;
import com.google.inject.Inject;
import com.peterphi.std.guice.common.auth.annotations.AuthConstraint;
import com.peterphi.std.guice.web.HttpCallContext;
import com.peterphi.std.guice.web.rest.templating.TemplateCall;
import com.peterphi.std.guice.web.rest.templating.Templater;
import com.peterphi.usermanager.db.dao.hibernate.UserDaoImpl;
import com.peterphi.usermanager.db.entity.UserEntity;
import com.peterphi.usermanager.guice.authentication.UserAuthenticationService;
import com.peterphi.usermanager.guice.authentication.UserLogin;
import com.peterphi.usermanager.guice.nonce.SessionNonceStore;
import com.peterphi.usermanager.ui.api.LoginUIService;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import java.net.URI;
public class LoginUIServiceImpl implements LoginUIService
{
/**
* Approximately 1 year in seconds
*/
private static final int ONE_YEAR = 8765 * 60 * 60;
@Inject
Templater templater;
@Inject
UserDaoImpl accountDao;
@Inject
UserLogin login;
@Inject
UserAuthenticationService authenticationService;
@Inject
SessionNonceStore nonceStore;
@Override
@AuthConstraint(skip = true, comment = "login page")
public String getLogin(String returnTo, String errorText)
{
if (login.isLoggedIn())
{
throw new IllegalArgumentException("You are already logged in!");
}
else
{
TemplateCall call = templater.template("login");
call.set("returnTo", returnTo);
call.set("errorText", errorText);
call.set("nonce", nonceStore.allocate());
return call.process();
}
}
@AuthConstraint(skip = true, comment = "login page")
@Override
public Response doLogin(String nonce, String returnTo, String user, String password)
{
nonceStore.validate(nonce, true);
if (login.isLoggedIn())
{
throw new IllegalArgumentException("You are already logged in!");
}
else
{
final UserEntity account = authenticationService.authenticate(user, password, false);
if (account != null)
{
// Successful login
login.reload(account);
final Response.ResponseBuilder builder;
if (returnTo != null)
builder = Response.seeOther(URI.create(returnTo));
else
builder = Response.seeOther(URI.create("/"));
// If this account has a Session Reconnect Key we should give it to the browser
if (account.getSessionReconnectKey() != null)
{
// Mark the cookie as secure if the request arrived on a secure channel OR if the requestURL is https (the latter can happen with Azure App Service which has poor tomcat integration)
final boolean secure = (HttpCallContext.get().getRequest().isSecure() || HttpCallContext.get().getRequest().getRequestURL().indexOf("https:
NewCookie cookie = new NewCookie(UserLogin.SESSION_RECONNECT_COOKIE,
account.getSessionReconnectKey(),
null,
null,
null,
ONE_YEAR,
secure,
true);
builder.cookie(cookie);
}
return builder.build();
}
else
{
// Send the user back to the login page
final String page = getLogin(returnTo, "E-mail/password incorrect");
return Response.status(403).entity(page).build();
}
}
}
@Override
public Response doLogout(String returnTo)
{
// Change the session reconnect key (if one is used)
if (login.isLoggedIn())
accountDao.changeSessionReconnectKey(login.getId());
// Invalidate the current session
HttpSession session = HttpCallContext.get().getRequest().getSession(false);
if (session != null)
session.invalidate();
// Clear the login (in case the session isn't correctly invalidated)
login.clear();
if (StringUtils.isEmpty(returnTo))
return Response.seeOther(URI.create("/")).build();
else
return Response.seeOther(URI.create(returnTo)).build();
}
}
|
package nl.jpoint.vertx.mod.deploy.service;
import io.vertx.core.Vertx;
import io.vertx.rxjava.core.file.FileSystem;
import nl.jpoint.vertx.mod.deploy.DeployConfig;
import nl.jpoint.vertx.mod.deploy.command.RunApplication;
import nl.jpoint.vertx.mod.deploy.command.StopApplication;
import nl.jpoint.vertx.mod.deploy.request.DeployApplicationRequest;
import nl.jpoint.vertx.mod.deploy.request.DeployRequest;
import nl.jpoint.vertx.mod.deploy.util.LogConstants;
import nl.jpoint.vertx.mod.deploy.util.ProcessUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import static rx.Observable.just;
public class DeployApplicationService implements DeployService<DeployApplicationRequest, DeployApplicationRequest> {
private static final Logger LOG = LoggerFactory.getLogger(DeployApplicationService.class);
private final DeployConfig config;
private final Vertx vertx;
private final List<String> deployedApplicationsSuccess = new ArrayList<>();
private final Map<String, Object> deployedApplicationsFailed = new HashMap<>();
public DeployApplicationService(DeployConfig config, Vertx vertx) {
this.config = config;
this.vertx = vertx;
}
@Override
public Observable<DeployApplicationRequest> deployAsync(DeployApplicationRequest deployApplicationRequest) {
return resolveSnapShotVersion(deployApplicationRequest)
.flatMap(this::checkModuleState)
.flatMap(this::stopApplication)
.flatMap(this::startApplication)
.flatMap(this::registerApplication);
}
private Observable<DeployApplicationRequest> checkModuleState(DeployApplicationRequest deployApplicationRequest) {
new ProcessUtils(config).checkModuleRunning(deployApplicationRequest);
LOG.info("[{} - {}]: Module '{}' running : {}, sameVersion : {}.", LogConstants.DEPLOY_REQUEST, deployApplicationRequest.getId(), deployApplicationRequest.getModuleId(), deployApplicationRequest.isInstalled(), deployApplicationRequest.isInstalled());
return just(deployApplicationRequest);
}
private Observable<DeployApplicationRequest> stopApplication(DeployApplicationRequest deployApplicationRequest) {
if (deployApplicationRequest.isRunning() && !deployApplicationRequest.isInstalled()) {
StopApplication stopApplicationCommand = new StopApplication(vertx, config);
return stopApplicationCommand.executeAsync(deployApplicationRequest);
} else {
return just(deployApplicationRequest);
}
}
private Observable<DeployApplicationRequest> startApplication(DeployApplicationRequest deployApplicationRequest) {
if (!deployApplicationRequest.isRunning()) {
RunApplication runModCommand = new RunApplication(vertx, config);
return runModCommand.executeAsync(deployApplicationRequest);
} else {
return just(deployApplicationRequest);
}
}
private Observable<DeployApplicationRequest> registerApplication(DeployApplicationRequest
deployApplicationRequest) {
io.vertx.rxjava.core.Vertx rxVertx = new io.vertx.rxjava.core.Vertx(vertx);
return rxVertx.fileSystem()
.existsObservable(config.getRunDir() + deployApplicationRequest.getModuleId())
.flatMap(exists -> {
if (!exists) {
return rxVertx.fileSystem().createFileObservable(config.getRunDir() + deployApplicationRequest.getModuleId())
.flatMap(x -> just(deployApplicationRequest));
} else {
return just(deployApplicationRequest);
}
});
}
@Override
public DeployConfig getConfig() {
return config;
}
@Override
public Vertx getVertx() {
return vertx;
}
public Observable<Boolean> stopContainer() {
LOG.info("[{}]: Stopping all running modules", LogConstants.INVOKE_CONTAINER);
return Observable.from(new ProcessUtils(config).listInstalledAndRunningModules().entrySet())
.flatMap(entry -> {
StopApplication stopApplication = new StopApplication(vertx, config);
String[] mavenIds = entry.getKey().split(":", 2);
DeployApplicationRequest request = new DeployApplicationRequest(mavenIds[0], mavenIds[1], entry.getValue(), null, "jar");
request.setRunning(false);
request.setInstalled(false);
return stopApplication.executeAsync(request);
})
.toList()
.flatMap(x -> Observable.just(true));
}
public Observable<DeployRequest> cleanup(DeployRequest deployRequest) {
deployedApplicationsSuccess.clear();
deployedApplicationsFailed.clear();
return cleanup()
.flatMap(x -> just(deployRequest));
}
public Observable<?> cleanup() {
List<String> runningApplications = new ProcessUtils(config).listModules();
FileSystem fs = new io.vertx.rxjava.core.Vertx(vertx).fileSystem();
return fs.readDirObservable(config.getRunDir())
.flatMapIterable(x -> x)
.flatMap(s -> just(Pattern.compile("/").splitAsStream(s).reduce((a, b) -> b).orElse("")))
.filter(s -> !s.isEmpty() && !runningApplications.contains(s))
.flatMap(file -> fs.deleteObservable(config.getRunDir() + file))
.toList()
.flatMap(x -> just(null))
.doOnError(t -> LOG.error("Error during cleanup of run files {}", t.getMessage()));
}
public void addApplicationDeployResult(boolean succeeded, String message, String deploymentId) {
if (succeeded && !deployedApplicationsSuccess.contains(deploymentId)) {
deployedApplicationsSuccess.add(deploymentId);
}
if (!succeeded && !deployedApplicationsFailed.containsKey(deploymentId)) {
deployedApplicationsFailed.put(deploymentId, message != null ? message : "No reason provided by application.");
}
}
public List<String> getDeployedApplicationsSuccess() {
return deployedApplicationsSuccess;
}
public Map<String, Object> getDeployedApplicationsFailed() {
return deployedApplicationsFailed;
}
}
|
package edu.cornell.mannlib.vitro.webapp.controller.authenticate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.RequestIdentifiers;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount.Status;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.SelfEditingConfiguration;
import edu.cornell.mannlib.vitro.webapp.beans.UserAccount;
import edu.cornell.mannlib.vitro.webapp.controller.edit.Authenticate;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.UserAccountsDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.LoginEvent;
import edu.cornell.mannlib.vitro.webapp.dao.jena.LogoutEvent;
/**
* The "standard" implementation of Authenticator.
*/
public class BasicAuthenticator extends Authenticator {
private static final Log log = LogFactory.getLog(BasicAuthenticator.class);
private final HttpServletRequest request;
public BasicAuthenticator(HttpServletRequest request) {
this.request = request;
}
@Override
public UserAccount getAccountForInternalAuth(String emailAddress) {
UserAccountsDao userAccountsDao = getUserAccountsDao();
if (userAccountsDao == null) {
return null;
}
return userAccountsDao.getUserAccountByEmail(emailAddress);
}
@Override
public UserAccount getAccountForExternalAuth(String externalAuthId) {
UserAccountsDao userAccountsDao = getUserAccountsDao();
if (userAccountsDao == null) {
return null;
}
return userAccountsDao.getUserAccountByExternalAuthId(externalAuthId);
}
@Override
public boolean isCurrentPassword(UserAccount userAccount,
String clearTextPassword) {
if (userAccount == null) {
return false;
}
if (clearTextPassword == null) {
return false;
}
String encodedPassword = applyMd5Encoding(clearTextPassword);
return encodedPassword.equals(userAccount.getMd5Password());
}
@Override
public void recordNewPassword(UserAccount userAccount,
String newClearTextPassword) {
if (userAccount == null) {
log.error("Trying to change password on null user.");
return;
}
userAccount.setMd5Password(applyMd5Encoding(newClearTextPassword));
userAccount.setPasswordChangeRequired(false);
userAccount.setPasswordLinkExpires(0L);
getUserAccountsDao().updateUserAccount(userAccount);
}
@Override
public boolean accountRequiresEditing(UserAccount userAccount) {
if (userAccount == null) {
log.error("Trying to check for valid fields on a null user.");
return false;
}
if (userAccount.getFirstName().isEmpty()) {
return true;
}
if (userAccount.getLastName().isEmpty()) {
return true;
}
if (userAccount.getEmailAddress().isEmpty()) {
return true;
}
if (!isValidEmailAddress(userAccount.getEmailAddress())) {
return true;
}
return false;
}
@Override
public List<String> getAssociatedIndividualUris(UserAccount userAccount) {
List<String> uris = new ArrayList<String>();
if (userAccount == null) {
return uris;
}
uris.addAll(getUrisAssociatedBySelfEditorConfig(userAccount));
return uris;
}
@Override
public void recordLoginAgainstUserAccount(UserAccount userAccount,
AuthenticationSource authSource) {
if (userAccount == null) {
log.error("Trying to record the login of a null user. ");
return;
}
recordLoginOnUserRecord(userAccount);
HttpSession session = request.getSession();
createLoginStatusBean(userAccount.getUri(), authSource, session);
RequestIdentifiers.resetIdentifiers(request);
setSessionTimeoutLimit(userAccount, session);
recordInUserSessionMap(userAccount.getUri(), session);
notifyOtherUsers(userAccount.getUri(), session);
}
/**
* Update the user record to record the login.
*/
private void recordLoginOnUserRecord(UserAccount userAccount) {
userAccount.setLoginCount(userAccount.getLoginCount() + 1);
userAccount.setLastLoginTime(new Date().getTime());
userAccount.setStatus(Status.ACTIVE);
getUserAccountsDao().updateUserAccount(userAccount);
}
/**
* Put the login bean into the session.
*/
private void createLoginStatusBean(String userUri,
AuthenticationSource authSource, HttpSession session) {
LoginStatusBean lsb = new LoginStatusBean(userUri, authSource);
LoginStatusBean.setBean(session, lsb);
log.debug("Adding status bean: " + lsb);
}
/**
* Editors and other privileged users get a longer timeout interval.
*/
private void setSessionTimeoutLimit(UserAccount userAccount,
HttpSession session) {
RoleLevel role = RoleLevel.getRoleFromLoginStatus(request);
if (role == RoleLevel.EDITOR || role == RoleLevel.CURATOR
|| role == RoleLevel.DB_ADMIN) {
session.setMaxInactiveInterval(PRIVILEGED_TIMEOUT_INTERVAL);
} else if (userAccount.isRootUser()) {
session.setMaxInactiveInterval(PRIVILEGED_TIMEOUT_INTERVAL);
} else {
session.setMaxInactiveInterval(LOGGED_IN_TIMEOUT_INTERVAL);
}
}
/**
* Record the login in the user/session map.
*
* TODO What is this map used for?
*/
private void recordInUserSessionMap(String userUri, HttpSession session) {
Map<String, HttpSession> userURISessionMap = Authenticate
.getUserURISessionMapFromContext(session.getServletContext());
userURISessionMap.put(userUri, session);
}
/**
* Anyone listening to the model might need to know that another user is
* logged in.
*/
private void notifyOtherUsers(String userUri, HttpSession session) {
Authenticate.sendLoginNotifyEvent(new LoginEvent(userUri),
session.getServletContext(), session);
}
private List<String> getUrisAssociatedBySelfEditorConfig(UserAccount user) {
List<String> uris = new ArrayList<String>();
if (user == null) {
return uris;
}
IndividualDao iDao = getIndividualDao();
if (iDao == null) {
return uris;
}
List<Individual> associatedIndividuals = SelfEditingConfiguration
.getBean(request).getAssociatedIndividuals(iDao, user);
for (Individual ind : associatedIndividuals) {
uris.add(ind.getURI());
}
return uris;
}
@Override
public void recordUserIsLoggedOut() {
HttpSession session = request.getSession();
notifyOtherUsersOfLogout(session);
session.invalidate();
}
private void notifyOtherUsersOfLogout(HttpSession session) {
String userUri = LoginStatusBean.getBean(session).getUserURI();
if ((userUri == null) || userUri.isEmpty()) {
return;
}
Authenticate.sendLoginNotifyEvent(new LogoutEvent(userUri),
session.getServletContext(), session);
}
/**
* Get a reference to the UserAccountsDao, or null.
*/
private UserAccountsDao getUserAccountsDao() {
WebappDaoFactory wadf = getWebappDaoFactory();
if (wadf == null) {
return null;
}
UserAccountsDao userAccountsDao = wadf.getUserAccountsDao();
if (userAccountsDao == null) {
log.error("getUserAccountsDao: no UserAccountsDao");
}
return userAccountsDao;
}
/**
* Get a reference to the IndividualDao, or null.
*/
private IndividualDao getIndividualDao() {
WebappDaoFactory wadf = getWebappDaoFactory();
if (wadf == null) {
return null;
}
IndividualDao individualDao = wadf.getIndividualDao();
if (individualDao == null) {
log.error("getIndividualDao: no IndividualDao");
}
return individualDao;
}
/**
* Get a reference to the WebappDaoFactory, or null.
*/
private WebappDaoFactory getWebappDaoFactory() {
HttpSession session = request.getSession(false);
if (session == null) {
return null;
}
ServletContext servletContext = session.getServletContext();
WebappDaoFactory wadf = (WebappDaoFactory) servletContext
.getAttribute("webappDaoFactory");
if (wadf == null) {
log.error("no WebappDaoFactory");
return null;
}
return wadf;
}
}
|
package edu.cornell.mannlib.vitro.webapp.web.directives;
import freemarker.template.Configuration;
import freemarker.template.TemplateDirectiveModel;
public interface VitroTemplateDirectiveModel extends TemplateDirectiveModel {
public String help(Configuration config);
}
|
package won.matcher.siren.matcher;
import com.hp.hpl.jena.vocabulary.DC;
import com.sindicetech.siren.qparser.tree.dsl.*;
import org.apache.lucene.queryparser.flexible.core.QueryNodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import won.protocol.vocabulary.WON;
public class SirenQueryBuilder
{
private final Logger log = LoggerFactory.getLogger(getClass());
private AbstractBooleanQuery topQuery;
private ConciseQueryBuilder builder;
private int consideredQueryTokens;
private int usedQueryTokens;
private static final String DEMAND = WON.BASIC_NEED_TYPE_DEMAND.toString().toLowerCase();
private static final String SUPPLY = WON.BASIC_NEED_TYPE_SUPPLY.toString().toLowerCase();
private static final String DOTOGETHER = WON.BASIC_NEED_TYPE_DO_TOGETHER.toString().toLowerCase();
private static final String CRITIQUE = WON.BASIC_NEED_TYPE_CRITIQUE.toString().toLowerCase();
public SirenQueryBuilder(NeedObject needObject, int consideredQueryTokens) throws QueryNodeException {
this.consideredQueryTokens = consideredQueryTokens;
usedQueryTokens = 0;
builder = new ConciseQueryBuilder();
topQuery = builder.newBoolean();
//First of all, we have to consider the BasicNeedType
String matchNeedType = null;
if (DEMAND.equals(needObject.getBasicNeedType().toLowerCase())) {
matchNeedType = SUPPLY;
} else if (SUPPLY.equals(needObject.getBasicNeedType().toLowerCase())) {
matchNeedType = DEMAND;
} else if (DOTOGETHER.equals(needObject.getBasicNeedType().toLowerCase())) {
matchNeedType = DOTOGETHER;
} else if (CRITIQUE.equals(needObject.getBasicNeedType().toLowerCase())) {
matchNeedType = CRITIQUE;
}
TwigQuery twigBasicNeedType = builder.newTwig("@graph").with(builder.newTwig(WON.HAS_BASIC_NEED_TYPE.toString()).with(
builder.newNode("'" + matchNeedType + "'").setAttribute("@id")));
topQuery.with(twigBasicNeedType);
// retrieve only needs in state active
TwigQuery needState = builder.newTwig("@graph").with(builder.newTwig(WON.IS_IN_STATE.toString()).with(
builder.newNode("'" + WON.NEED_STATE_ACTIVE + "'").setAttribute("@id")));
topQuery.with(needState);
}
public void addTermsToTitleQuery(String[] terms, int boost) throws QueryNodeException {
addTermsToContentQuery(terms, DC.title.toString(), boost);
}
public void addTermsToDescriptionQuery(String[] terms, int boost) throws QueryNodeException {
addTermsToContentQuery(terms, WON.HAS_TEXT_DESCRIPTION.toString(), boost);
}
public void addTermsToTagQuery(String[] terms, int boost) throws QueryNodeException {
addTermsToContentQuery(terms, WON.HAS_TAG.toString(), boost);
}
public void addTermsToContentQuery(String[] terms, String contentAttribute, int boost) throws QueryNodeException {
if (terms == null || terms.length == 0) {
return;
}
if (usedQueryTokens + terms.length <= consideredQueryTokens) {
String queryTerms = String.join(" OR ", terms);
usedQueryTokens += terms.length;
topQuery.optional(builder.newTwig("@graph").with(builder.newTwig(WON.HAS_CONTENT.toString()).with(
builder.newNode(queryTerms).setAttribute(contentAttribute).setBoost(boost))));
} else {
log.warn("Cannot add more terms to the Solr query. Reached considered number of terms: " + consideredQueryTokens);
return;
}
}
public String build() {
return topQuery.toString();
}
}
|
package org.knowm.xchange.bittrex.service;
import static org.knowm.xchange.bittrex.BittrexResilience.GET_CLOSED_ORDERS_RATE_LIMITER;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.knowm.xchange.bittrex.BittrexAdapters;
import org.knowm.xchange.bittrex.BittrexAuthenticated;
import org.knowm.xchange.bittrex.BittrexConstants;
import org.knowm.xchange.bittrex.BittrexExchange;
import org.knowm.xchange.bittrex.BittrexUtils;
import org.knowm.xchange.bittrex.dto.batch.BatchResponse;
import org.knowm.xchange.bittrex.dto.batch.order.BatchOrder;
import org.knowm.xchange.bittrex.dto.batch.order.neworder.TimeInForce;
import org.knowm.xchange.bittrex.dto.trade.BittrexNewOrder;
import org.knowm.xchange.bittrex.dto.trade.BittrexOrder;
import org.knowm.xchange.bittrex.dto.trade.BittrexOrders;
import org.knowm.xchange.client.ResilienceRegistries;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams;
public class BittrexTradeServiceRaw extends BittrexBaseService {
/**
* Constructor
*
* @param exchange
*/
public BittrexTradeServiceRaw(
BittrexExchange exchange,
BittrexAuthenticated bittrex,
ResilienceRegistries resilienceRegistries) {
super(exchange, bittrex, resilienceRegistries);
}
public String placeBittrexLimitOrder(LimitOrder limitOrder) throws IOException {
return placeBittrexLimitOrder(limitOrder, TimeInForce.GOOD_TIL_CANCELLED);
}
public String placeBittrexLimitOrder(LimitOrder limitOrder, TimeInForce type) throws IOException {
BittrexNewOrder bittrexNewOrder =
new BittrexNewOrder(
BittrexUtils.toPairString(limitOrder.getCurrencyPair()),
OrderType.BID.equals(limitOrder.getType())
? BittrexConstants.BUY
: BittrexConstants.SELL,
BittrexConstants.LIMIT,
limitOrder.getRemainingAmount().toPlainString(),
null,
limitOrder.getLimitPrice().toPlainString(),
type.toString(),
null,
null);
return bittrexAuthenticated
.placeOrder(
apiKey, System.currentTimeMillis(), contentCreator, signatureCreator, bittrexNewOrder)
.getId();
}
public String placeBittrexMarketOrder(MarketOrder marketOrder) throws IOException {
return placeBittrexMarketOrder(marketOrder, TimeInForce.IMMEDIATE_OR_CANCEL);
}
public String placeBittrexMarketOrder(MarketOrder marketOrder, TimeInForce type) throws IOException {
BittrexNewOrder bittrexNewOrder =
new BittrexNewOrder(
BittrexUtils.toPairString(marketOrder.getCurrencyPair()),
OrderType.BID.equals(marketOrder.getType())
? BittrexConstants.BUY
: BittrexConstants.SELL,
BittrexConstants.MARKET,
marketOrder.getRemainingAmount().toPlainString(),
null,
null,
type.toString(),
null,
null);
return bittrexAuthenticated
.placeOrder(
apiKey, System.currentTimeMillis(), contentCreator, signatureCreator, bittrexNewOrder)
.getId();
}
public BittrexOrder cancelBittrexLimitOrder(String orderId) throws IOException {
return bittrexAuthenticated.cancelOrder(
apiKey, System.currentTimeMillis(), contentCreator, signatureCreator, orderId);
}
public List<BittrexOrder> getBittrexOpenOrders(OpenOrdersParams params) throws IOException {
return bittrexAuthenticated.getOpenOrders(
apiKey, System.currentTimeMillis(), contentCreator, signatureCreator);
}
public SequencedOpenOrders getBittrexSequencedOpenOrders(OpenOrdersParams params)
throws IOException {
BittrexOrders openOrders =
bittrexAuthenticated.getOpenOrders(
apiKey, System.currentTimeMillis(), contentCreator, signatureCreator);
return new SequencedOpenOrders(
openOrders.getSequence(), BittrexAdapters.adaptOpenOrders(openOrders));
}
public List<BittrexOrder> getBittrexUserTradeHistory(
CurrencyPair currencyPair, Date start, Date end) throws IOException {
return decorateApiCall(
() ->
bittrexAuthenticated.getClosedOrders(
apiKey,
System.currentTimeMillis(),
contentCreator,
signatureCreator,
BittrexUtils.toPairString(currencyPair),
200,
start,
end))
.withRetry(retry("getClosedOrders"))
.withRateLimiter(rateLimiter(GET_CLOSED_ORDERS_RATE_LIMITER))
.call();
}
public List<BittrexOrder> getBittrexUserTradeHistory(CurrencyPair currencyPair)
throws IOException {
return getBittrexUserTradeHistory(currencyPair, null, null);
}
public List<BittrexOrder> getBittrexUserTradeHistory() throws IOException {
return getBittrexUserTradeHistory(null);
}
public BittrexOrder getBittrexOrder(String orderId) throws IOException {
return bittrexAuthenticated.getOrder(
apiKey, System.currentTimeMillis(), contentCreator, signatureCreator, orderId);
}
public BatchResponse[] executeOrdersBatch(BatchOrder[] batchOrders) throws IOException {
return bittrexAuthenticated.executeOrdersBatch(
apiKey, System.currentTimeMillis(), contentCreator, signatureCreator, batchOrders);
}
@AllArgsConstructor
@Getter
public static class SequencedOpenOrders {
private final String sequence;
private final List<LimitOrder> openOrders;
}
}
|
package org.springframework.orm.hibernate;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import javax.transaction.Status;
import javax.transaction.UserTransaction;
import junit.framework.TestCase;
import net.sf.hibernate.FlushMode;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Interceptor;
import net.sf.hibernate.JDBCException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import org.easymock.MockControl;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.JtaTransactionTestSuite;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.jta.JtaTransactionManager;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
/**
* @author Juergen Hoeller
*/
public class HibernateTransactionManagerTests extends TestCase {
public void testTransactionCommit() throws SQLException, HibernateException {
MockControl dsControl = MockControl.createControl(DataSource.class);
final DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
MockControl queryControl = MockControl.createControl(Query.class);
Query query = (Query) queryControl.getMock();
final List list = new ArrayList();
list.add("test");
con.getTransactionIsolation();
conControl.setReturnValue(Connection.TRANSACTION_READ_COMMITTED);
con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
conControl.setVoidCallable(1);
con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
conControl.setVoidCallable(1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
sf.openSession();
sfControl.setReturnValue(session, 1);
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
session.connection();
sessionControl.setReturnValue(con, 4);
session.createQuery("some query string");
sessionControl.setReturnValue(query, 1);
query.setTimeout(10);
queryControl.setReturnValue(query, 1);
query.list();
queryControl.setReturnValue(list, 1);
session.close();
sessionControl.setReturnValue(null, 1);
tx.commit();
txControl.setVoidCallable(1);
dsControl.replay();
conControl.replay();
sfControl.replay();
sessionControl.replay();
txControl.replay();
queryControl.replay();
HibernateTransactionManager tm = new HibernateTransactionManager();
tm.setSessionFactory(sf);
tm.setDataSource(ds);
TransactionTemplate tt = new TransactionTemplate(tm);
tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
tt.setTimeout(10);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
Object result = tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
HibernateTemplate ht = new HibernateTemplate(sf);
return ht.find("some query string");
}
});
assertTrue("Correct result list", result == list);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
dsControl.verify();
conControl.verify();
sfControl.verify();
sessionControl.verify();
txControl.verify();
queryControl.verify();
}
public void testTransactionRollback() throws HibernateException, SQLException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
session.close();
sessionControl.setReturnValue(null, 1);
tx.rollback();
txControl.setVoidCallable(1);
session.connection();
sessionControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
sfControl.replay();
sessionControl.replay();
txControl.replay();
PlatformTransactionManager tm = new HibernateTransactionManager(sf);
TransactionTemplate tt = new TransactionTemplate(tm);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
try {
tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
HibernateTemplate ht = new HibernateTemplate(sf);
return ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) {
throw new RuntimeException("application exception");
}
});
}
});
fail("Should have thrown RuntimeException");
}
catch (RuntimeException ex) {
// expected
}
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
sfControl.verify();
sessionControl.verify();
txControl.verify();
}
public void testTransactionRollbackOnly() throws HibernateException, SQLException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
session.flush();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setReturnValue(null, 1);
tx.rollback();
txControl.setVoidCallable(1);
session.connection();
sessionControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
sfControl.replay();
sessionControl.replay();
txControl.replay();
PlatformTransactionManager tm = new HibernateTransactionManager(sf);
TransactionTemplate tt = new TransactionTemplate(tm);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
HibernateTemplate ht = new HibernateTemplate(sf);
ht.setFlushMode(HibernateTemplate.FLUSH_EAGER);
ht.execute(new HibernateCallback() {
public Object doInHibernate(Session session) {
return null;
}
});
status.setRollbackOnly();
return null;
}
});
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
sfControl.verify();
sessionControl.verify();
txControl.verify();
}
public void testNestedTransactionCommit() throws HibernateException, SQLException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
session.flush();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setReturnValue(null, 1);
tx.commit();
txControl.setVoidCallable(1);
session.connection();
sessionControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
sfControl.replay();
sessionControl.replay();
txControl.replay();
PlatformTransactionManager tm = new HibernateTransactionManager(sf);
final TransactionTemplate tt = new TransactionTemplate(tm);
final List l = new ArrayList();
l.add("test");
Object result = tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
return tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
HibernateTemplate ht = new HibernateTemplate(sf);
ht.setFlushMode(HibernateTemplate.FLUSH_EAGER);
return ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) {
return l;
}
});
}
});
}
});
assertTrue("Correct result list", result == l);
sfControl.verify();
sessionControl.verify();
txControl.verify();
}
public void testNestedTransactionRollback() throws HibernateException, SQLException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
session.close();
sessionControl.setReturnValue(null, 1);
tx.rollback();
txControl.setVoidCallable(1);
session.connection();
sessionControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
sfControl.replay();
sessionControl.replay();
txControl.replay();
PlatformTransactionManager tm = new HibernateTransactionManager(sf);
final TransactionTemplate tt = new TransactionTemplate(tm);
try {
tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
return tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
HibernateTemplate ht = new HibernateTemplate(sf);
ht.setFlushMode(HibernateTemplate.FLUSH_EAGER);
return ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) {
throw new RuntimeException("application exception");
}
});
}
});
}
});
fail("Should not thrown RuntimeException");
}
catch (RuntimeException ex) {
// expected
}
sfControl.verify();
sessionControl.verify();
txControl.verify();
}
public void testNestedTransactionRollbackOnly() throws HibernateException, SQLException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
session.close();
sessionControl.setReturnValue(null, 1);
tx.rollback();
txControl.setVoidCallable(1);
session.connection();
sessionControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
sfControl.replay();
sessionControl.replay();
txControl.replay();
PlatformTransactionManager tm = new HibernateTransactionManager(sf);
final TransactionTemplate tt = new TransactionTemplate(tm);
final List l = new ArrayList();
l.add("test");
tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
return tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
HibernateTemplate ht = new HibernateTemplate(sf);
ht.execute(new HibernateCallback() {
public Object doInHibernate(Session session) {
return l;
}
});
status.setRollbackOnly();
return null;
}
});
}
});
sfControl.verify();
sessionControl.verify();
txControl.verify();
}
public void testJtaTransactionCommit() throws Exception {
MockControl utControl = MockControl.createControl(UserTransaction.class);
UserTransaction ut = (UserTransaction) utControl.getMock();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.begin();
utControl.setVoidCallable(1);
ut.commit();
utControl.setVoidCallable(1);
utControl.replay();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
final MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
sfControl.replay();
sessionControl.replay();
TransactionTemplate tt = JtaTransactionTestSuite.getTransactionTemplateForJta(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, ut);
final List l = new ArrayList();
l.add("test");
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
Object result = tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
try {
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
HibernateTemplate ht = new HibernateTemplate(sf);
List htl = ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session sess) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
assertEquals(session, sess);
return l;
}
});
ht = new HibernateTemplate(sf);
htl = ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session sess) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
assertEquals(session, sess);
return l;
}
});
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
sessionControl.verify();
sessionControl.reset();
try {
session.flush();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setReturnValue(null, 1);
}
catch (HibernateException e) {
}
sessionControl.replay();
return htl;
}
catch (Error err) {
err.printStackTrace();
throw err;
}
}
});
assertTrue("Correct result list", result == l);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
utControl.verify();
sfControl.verify();
sessionControl.verify();
}
public void testJtaTransactionRollback() throws Exception {
MockControl utControl = MockControl.createControl(UserTransaction.class);
UserTransaction ut = (UserTransaction) utControl.getMock();
ut.getStatus();
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
ut.begin();
utControl.setVoidCallable(1);
ut.rollback();
utControl.setVoidCallable(1);
utControl.replay();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
final MockControl sessionControl = MockControl.createControl(Session.class);
final Session session = (Session) sessionControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
sfControl.replay();
sessionControl.replay();
TransactionTemplate tt = JtaTransactionTestSuite.getTransactionTemplateForJta(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, ut);
final List l = new ArrayList();
l.add("test");
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
Object result = tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
try {
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
HibernateTemplate ht = new HibernateTemplate(sf);
List htl = ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) {
return l;
}
});
status.setRollbackOnly();
sessionControl.verify();
sessionControl.reset();
try {
session.close();
}
catch (HibernateException ex) {
}
sessionControl.setReturnValue(null, 1);
sessionControl.replay();
return htl;
}
catch (Error err) {
err.printStackTrace();
throw err;
}
}
});
assertTrue("Correct result list", result == l);
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
utControl.verify();
sfControl.verify();
sessionControl.verify();
}
public void testTransactionWithPropagationSupports() throws HibernateException, SQLException {
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.flush();
sessionControl.setVoidCallable(1);
session.close();
sessionControl.setReturnValue(null, 1);
sfControl.replay();
sessionControl.replay();
PlatformTransactionManager tm = new HibernateTransactionManager(sf);
TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("Is not new transaction", !status.isNewTransaction());
HibernateTemplate ht = new HibernateTemplate(sf);
ht.setFlushMode(HibernateTemplate.FLUSH_EAGER);
ht.execute(new HibernateCallback() {
public Object doInHibernate(Session session) {
return null;
}
});
return null;
}
});
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
sfControl.verify();
sessionControl.verify();
}
public void testTransactionCommitWithPreBound() throws HibernateException, SQLException {
MockControl dsControl = MockControl.createControl(DataSource.class);
final DataSource ds = (DataSource) dsControl.getMock();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
session.getFlushMode();
sessionControl.setReturnValue(FlushMode.NEVER);
session.setFlushMode(FlushMode.AUTO);
sessionControl.setVoidCallable(1);
session.setFlushMode(FlushMode.NEVER);
sessionControl.setVoidCallable(1);
session.connection();
sessionControl.setReturnValue(con, 4);
con.getTransactionIsolation();
conControl.setReturnValue(Connection.TRANSACTION_READ_COMMITTED);
con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
conControl.setVoidCallable(1);
con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
conControl.setVoidCallable(1);
tx.commit();
txControl.setVoidCallable(1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
dsControl.replay();
conControl.replay();
sfControl.replay();
sessionControl.replay();
txControl.replay();
HibernateTransactionManager tm = new HibernateTransactionManager();
tm.setSessionFactory(sf);
tm.setDataSource(ds);
TransactionTemplate tt = new TransactionTemplate(tm);
tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
final List l = new ArrayList();
l.add("test");
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
Object result = tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
assertTrue("Has thread transaction", sessionHolder.getTransaction() != null);
HibernateTemplate ht = new HibernateTemplate(sf);
return ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
return l;
}
});
}
});
assertTrue("Correct result list", result == l);
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf);
assertTrue("Hasn't thread transaction", sessionHolder.getTransaction() == null);
TransactionSynchronizationManager.unbindResource(sf);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
dsControl.verify();
conControl.verify();
sfControl.verify();
sessionControl.verify();
txControl.verify();
conControl.verify();
}
public void testTransactionCommitWithEntityInterceptor() throws HibernateException, SQLException {
MockControl interceptorControl = MockControl.createControl(net.sf.hibernate.Interceptor.class);
Interceptor entityInterceptor = (Interceptor) interceptorControl.getMock();
interceptorControl.replay();
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
sf.openSession(entityInterceptor);
sfControl.setReturnValue(session, 1);
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
session.close();
sessionControl.setReturnValue(null, 1);
tx.commit();
txControl.setVoidCallable(1);
session.connection();
sessionControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
sfControl.replay();
sessionControl.replay();
txControl.replay();
conControl.replay();
HibernateTransactionManager tm = new HibernateTransactionManager(sf);
tm.setEntityInterceptor(entityInterceptor);
TransactionTemplate tt = new TransactionTemplate(tm);
final List l = new ArrayList();
l.add("test");
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
Object result = tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
HibernateTemplate ht = new HibernateTemplate(sf);
return ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
return l;
}
});
}
});
assertTrue("Correct result list", result == l);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
sfControl.verify();
sessionControl.verify();
txControl.verify();
conControl.verify();
}
public void testTransactionCommitWithReadOnly() throws HibernateException, SQLException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
session.setFlushMode(FlushMode.NEVER);
sessionControl.setVoidCallable(1);
session.connection();
sessionControl.setReturnValue(con, 2);
session.close();
sessionControl.setReturnValue(null, 1);
tx.commit();
txControl.setVoidCallable(1);
con.setReadOnly(true);
conControl.setVoidCallable(1);
con.isReadOnly();
conControl.setReturnValue(true, 1);
con.setReadOnly(false);
conControl.setVoidCallable(1);
sfControl.replay();
sessionControl.replay();
txControl.replay();
conControl.replay();
HibernateTransactionManager tm = new HibernateTransactionManager(sf);
TransactionTemplate tt = new TransactionTemplate(tm);
tt.setReadOnly(true);
final List l = new ArrayList();
l.add("test");
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
Object result = tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
HibernateTemplate ht = new HibernateTemplate(sf);
return ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
return l;
}
});
}
});
assertTrue("Correct result list", result == l);
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
sfControl.verify();
sessionControl.verify();
txControl.verify();
conControl.verify();
}
public void testTransactionCommitWithFlushingFailure() throws HibernateException, SQLException {
MockControl conControl = MockControl.createControl(Connection.class);
Connection con = (Connection) conControl.getMock();
MockControl sfControl = MockControl.createControl(SessionFactory.class);
final SessionFactory sf = (SessionFactory) sfControl.getMock();
MockControl sessionControl = MockControl.createControl(Session.class);
Session session = (Session) sessionControl.getMock();
MockControl txControl = MockControl.createControl(Transaction.class);
Transaction tx = (Transaction) txControl.getMock();
sf.openSession();
sfControl.setReturnValue(session, 1);
session.beginTransaction();
sessionControl.setReturnValue(tx, 1);
tx.commit();
txControl.setThrowable(new JDBCException(new SQLException("argh", "27")), 1);
session.close();
sessionControl.setReturnValue(null, 1);
tx.rollback();
txControl.setVoidCallable(1);
session.connection();
sessionControl.setReturnValue(con, 1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
sfControl.replay();
sessionControl.replay();
txControl.replay();
conControl.replay();
HibernateTransactionManager tm = new HibernateTransactionManager(sf);
TransactionTemplate tt = new TransactionTemplate(tm);
final List l = new ArrayList();
l.add("test");
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
try {
tt.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
HibernateTemplate ht = new HibernateTemplate(sf);
return ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
return l;
}
});
}
});
fail("Should have thrown DataIntegrityViolationException");
}
catch (DataIntegrityViolationException ex) {
// expected
}
assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
sfControl.verify();
sessionControl.verify();
txControl.verify();
conControl.verify();
}
protected void tearDown() {
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
}
|
package com.cosylab.logging.client.cache;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import com.cosylab.logging.engine.log.ILogEntry;
public class LogMultiFileCache implements ILogMap {
/**
* The name of the property defining the max size of each fileof the cache
*/
public static final String FILEMAXSIZE_PROPERTY_NAME = "jlog.cache.fileMaxSize";
/**
* The default max size of each file of the cache
*/
public static final long DEFAULT_FILEMAXSIZE = 10000000;
/**
* Flag activating some info prints
*/
private boolean debugTrace=false;
/**
* This vector implement a table whose records are specified by the
* class LogFileTableRecord.
*/
private long fileMaxSize;
/**
* The vector of objects describing the buffers on disk
*/
private Vector<MultiFileTableRecord> logFileTable= new Vector<MultiFileTableRecord>();
/**
* The number of logs in cache
*/
private final AtomicInteger logsInCache=new AtomicInteger(0);
/**
* The ID (i.e. the key) identifying each log
*/
private int ID=-1;
/**
* Get the max size of the file out of the system properties or
* uses the default value if the property does not exist
*/
private static long getDefaultMaxFileSize() {
Integer fileSizeFromProperty = Integer.getInteger(FILEMAXSIZE_PROPERTY_NAME);
if (fileSizeFromProperty != null) {
return fileSizeFromProperty.longValue();
}
return DEFAULT_FILEMAXSIZE;
}
/**
* Prints trace info if traceDebug flag is true
*
*/
private void printDebugTrace(String traceInfo) {
if (debugTrace) {
System.out.println(traceInfo);
}
}
/**
* Creates a new record for the log file table : min/max log indexes are
* initialized according to the total number of received logs.
*
* The create <code>LogFileTableRecord</code> is added to the table of file records.
*
*/
private MultiFileTableRecord createNewFileRecord() throws LogCacheException {
MultiFileTableRecord newFileRec=new MultiFileTableRecord();
// Add new record to vector
logFileTable.add(newFileRec);
return newFileRec;
}
/**
* Looks in the log file table in which file buffered cache the log has
* been stored.
*
* The search is made by checking the min and max key of the logs contained in each record
* against the key of the searched log.
* As a consequence the record returned by this method is the only one record that <B>can</B>
* contain this log but it could be that the log is not there (for example it has been deleted)
*
* @param logKey The key of the log to look for
* @return The record containing the log
* @throws LogCacheException If no record is found or an error happened
*/
private MultiFileTableRecord searchFileLogTable(Integer logKey) throws LogCacheException {
// Check for key validity
if (logKey == null || logKey < 0 ) {
throw new IllegalArgumentException("Invalid or null log key "+logKey);
}
// Check if log file table empty
if (logFileTable.isEmpty()) {
throw new LogCacheException("Empty log file table");
}
for (MultiFileTableRecord record: logFileTable) {
if (logKey>=record.getMinLogIdx() && logKey<=record.getMaxLogIdx()) {
return record;
}
}
throw new LogCacheException("Log record containing "+logKey+" not found");
}
/**
* Builds a LogMultiFileCache objects setting the maximum size of the
* cache files
*
* @param fileSize The maximum size of cache files
*/
public LogMultiFileCache(long fileSize) throws LogCacheException {
if (fileSize<=0) {
throw new IllegalArgumentException("Invalid size for logFile "+fileSize);
}
fileMaxSize = fileSize;
printDebugTrace("LogMultiFileCache uses file of max size: "+fileMaxSize);
}
/**
* Constructor
*
* The maximum size of the files is read from the system properties.
* If the property is not found a default value is used.
*/
public LogMultiFileCache() throws LogCacheException {
this(getDefaultMaxFileSize());
}
/**
* Retrieves a log by means of its keyword.
*
* @param pos The key of the log to retrieve
*/
public ILogEntry getLog(Integer logKey) throws LogCacheException {
MultiFileTableRecord fileRecord = searchFileLogTable(logKey);
return fileRecord.getLog(logKey);
}
/**
* Add a log to the cache
*
* @param log The log to add to the cache
*
*/
public synchronized int add(ILogEntry log) throws LogCacheException {
if (log==null) {
throw new LogCacheException("Trying to add a null log to the buffer");
}
// Check if file size exceeds fileMaxSize
MultiFileTableRecord fileRecord;
if (logFileTable.size()>0) {
fileRecord=logFileTable.get(logFileTable.size() - 1);
} else {
fileRecord = createNewFileRecord();
}
long actualSize;
try {
actualSize = fileRecord.getFileSize();
} catch (IOException e) {
throw new LogCacheException("Error getting the size of the file",e);
}
if (actualSize >= fileMaxSize) {
// Move logs from internal buffer to file
fileRecord.flushBuffer();
printDebugTrace("LogMultiFileCache log file : fileSize "+actualSize+" logs = "+fileRecord.getNumOfLogs()+
" Range keys = "+fileRecord.getMinLogIdx()+" "+fileRecord.getMaxLogIdx());
// Replace old file record with new one.
fileRecord= createNewFileRecord();
}
fileRecord.addLog(log, ++ID);
logsInCache.incrementAndGet();
return ID;
}
/**
* Delete a log with the given key.
*
* @param pos The key of the log to delete
*/
public synchronized void deleteLog(Integer logKey) throws LogCacheException {
if (logKey==null) {
throw new IllegalArgumentException("The key can't be null");
}
MultiFileTableRecord fileRecord = searchFileLogTable(logKey);
int idx = logFileTable.indexOf(fileRecord);
if (idx==-1) {
throw new IllegalStateException("The record is not in the vector");
}
// Delete log in the LogBufferedFile cache
fileRecord.deleteLog(logKey);
// Update table record
logsInCache.decrementAndGet();
printDebugTrace("\n Delete log key = "+logKey+" from record "+idx+
" Tot. Logs "+ logsInCache +
" Range keys = "+fileRecord.getMinLogIdx()+" "+fileRecord.getMaxLogIdx());
// Remove file and element from the vector only if this is not
// the logFile we are using to add logs.
if (fileRecord.getNumOfLogs()==0) {
fileRecord.clear();
printDebugTrace("Delete log file: recId " + idx + " num. of logs = "+fileRecord.getNumOfLogs()+ " Range keys = ["
+fileRecord.getMinLogIdx()+", "+fileRecord.getMaxLogIdx()+"] files in table "+logFileTable.size());
// Remove vector element
logFileTable.remove(fileRecord);
}
}
/**
*
* @return The number of logs in the map
* @see com.cosylab.logging.client.cache.ILogMap
*/
public int getSize() {
return logsInCache.get();
}
/**
* Return the key of the last valid log (FIFO)
* The key of the last log is the key of the last inserted log
* but it can change if such log has been deleted
*
* @return The key of the last inserted log
* null if the cache is empty
* @see com.cosylab.logging.client.cache.ILogMap
*/
public Integer getLastLog() {
if (logsInCache.get()==0) {
return null;
}
MultiFileTableRecord lastRecord = logFileTable.lastElement();
Integer key = lastRecord.getLastLog();
if (key==null) {
throw new IllegalStateException("The cache is not empty but the last log does not exist?!?!");
}
return key;
}
/**
* Return the key of the first valid log (FIFO).
* The key of the first log is 0 but it can change if the log 0 has
* been deleted.
*
* @return The key of the first log
* null if the cache is empty
* @see com.cosylab.logging.client.cache.ILogMap
* @throws In case of error getting the first log
*/
public Integer getFirstLog() {
if (logsInCache.get()==0) {
return null;
}
MultiFileTableRecord firstRecord = logFileTable.get(0);
Integer key = firstRecord.getFirstLog();
if (key==null) {
throw new IllegalStateException("The cache is not empty but the last log does not exist?!?!");
}
return key;
}
/**
* Delete a set of logs
*
* @param keys The keys of logs to delete
* @see com.cosylab.logging.client.cache.ILogMap
*/
public void deleteLogs(Collection<Integer> keys) throws LogCacheException {
if (keys==null || keys.size()==0) {
return;
}
for (Integer key: keys) {
deleteLog(key);
}
}
/**
* Clear the Map i.e. remove all the logs and keys from the map
*
* @throws LogCacheException
* @see com.cosylab.logging.client.cache.ILogMap
*/
public synchronized void clear() throws LogCacheException {
for (MultiFileTableRecord record: logFileTable) {
record.clear();
}
logFileTable.clear();
logsInCache.set(0);
}
/**
* Replace the log in the given position with the new one
* @param position The position of the log to replace
* @param log The key (identifier) of the log
* @see com.cosylab.logging.client.cache.ILogMap
*/
public void replaceLog(Integer key, ILogEntry log) throws LogCacheException {
MultiFileTableRecord tableRecord=searchFileLogTable(key);
tableRecord.replaceLog(key, log);
}
/**
* Return an Iterator to browse the logs in the map.
* The order the iterator returns the logs is that of the keys.
*
* @return an Iterator over the elements in this map
* @see com.cosylab.logging.client.cache.ILogMap
*/
public Iterator<ILogEntry> iterator() {
return new LogIterator(this);
}
/**
* The keys in the map
*
* @return The key in the map
* @see com.cosylab.logging.client.cache.ILogMap
*/
public Set<Integer> keySet() {
HashSet<Integer> ret = new HashSet<Integer>();
for (MultiFileTableRecord record: logFileTable) {
ret.addAll(record.keySet());
}
return ret;
}
/**
* Append at most n keys from the first valid logs to the collection.
* First here means first in the FIFO policy.
*
* The number of added keys can be less then n if the cache doesn't
* contain enough logs.
*
* @param n The desired number of keys of first logs
* @param keys The collection to add they keys to
* @return The number of keys effectively added
* @see com.cosylab.logging.client.cache.ILogMap
*/
public int getFirstLogs(int n, Collection<Integer> keys) {
int ret=0;
Vector<Integer>temp = new Vector<Integer>();
for (MultiFileTableRecord record: logFileTable) {
temp.clear();
ret+=record.getFirstLogs(n-ret, temp);
for (int t=0; t<temp.size(); t++) {
temp.set(t, temp.get(t)+record.getMinLogIdx());
}
keys.addAll(temp);
if (ret==n) {
break;
}
}
return ret;
}
/**
* Return the size of the last log file used by the cache
* (it is here for testing purposes)
*
* @see
*/
public long getLogFileSize() throws LogCacheException {
if (logFileTable.isEmpty()) {
return 0;
}
MultiFileTableRecord lastRecord = logFileTable.lastElement();
if (lastRecord == null) {
throw new LogCacheException("Null file record");
}
long fileSize;
try {
fileSize = lastRecord.getFileSize();
} catch (IOException ioe) {
throw new LogCacheException(ioe);
}
return fileSize;
}
/**
* Return the disk space used by all the files of the cache.
*
* @return The disk space used by all the files of the cache
* @throws IOException In case of error getting the size of one of
* the files
*/
public synchronized long getFilesSize() throws IOException {
long ret=0;
for (MultiFileTableRecord mftb: logFileTable) {
ret+=mftb.getFileSize();
}
return ret;
}
/**
* Return the current maximum size of the log file
*
* @see
*/
public long getMaxFileSize() throws LogCacheException {
return fileMaxSize;
}
/**
* Return the current maximum size of the log file
*
* @see
*/
public void setDebugTrace(boolean flag) throws LogCacheException {
debugTrace = flag;
return;
}
/**
* Return the current maximum size of the log file
*
* @see
*/
public void printFileTableInfo() throws LogCacheException {
int idx;
System.out.println("\nlogFileTable : total logs = "+ logsInCache);
for (idx = 0; idx < logFileTable.size(); idx ++) {
MultiFileTableRecord fr = logFileTable.get(idx);
long actualSize;
try {
actualSize = fr.getFileSize();
} catch (IOException e) {
throw new LogCacheException("Error getting the size of the file",e);
}
System.out.println("logFile "+idx+": log counter = "+ fr.getNumOfLogs()+
" Range Keys [" + fr.getMinLogIdx() + " " + fr.getMaxLogIdx()+
"] file size " + actualSize);
}
System.out.println("\n");
return;
}
/**
* @return the number of the files used by the cache
*/
public int getNumberOfCacheFiles() {
return logFileTable.size();
}
}
|
package com.navigation.reactnative;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import com.facebook.common.executors.UiThreadImmediateExecutorService;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.image.CloseableBitmap;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.uimanager.PixelUtil;
class IconResolver {
private static final String PROP_ICON_URI = "uri";
private static final String PROP_ICON_WIDTH = "width";
private static final String PROP_ICON_HEIGHT = "height";
private static class DrawableWithIntrinsicSize extends BitmapDrawable {
private int width;
private int height;
DrawableWithIntrinsicSize(Resources resources, Bitmap bitmap, ReadableMap source) {
super(resources, bitmap);
if (source.hasKey(PROP_ICON_WIDTH)) {
width = Math.round(PixelUtil.toPixelFromDIP(source.getInt(PROP_ICON_WIDTH)));
} else {
width = bitmap.getWidth();
}
if (source.hasKey(PROP_ICON_HEIGHT)) {
height = Math.round(PixelUtil.toPixelFromDIP(source.getInt(PROP_ICON_HEIGHT)));
} else {
height = bitmap.getHeight();
}
}
@Override
public int getIntrinsicWidth() {
return width;
}
@Override
public int getIntrinsicHeight() {
return height;
}
}
interface IconResolverListener {
void setDrawable(Drawable d);
}
static void setIconSource(final ReadableMap source, final IconResolverListener iconResolverListener, final Context context) {
String uri = source != null ? source.getString(PROP_ICON_URI) : null;
if (uri == null) {
iconResolverListener.setDrawable(null);
} else if (uri.startsWith("http:
ImagePipeline imagePipeline = Fresco.getImagePipeline();
ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uri));
ImageRequest request = builder.build();
DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(request, context);
dataSource.subscribe(new BaseDataSubscriber<CloseableReference<CloseableImage>>() {
@Override
protected void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
if (!dataSource.isFinished()) {
return;
}
CloseableReference<CloseableImage> imageRef = dataSource.getResult();
if (imageRef != null) {
CloseableImage image = imageRef.get();
try {
if (image instanceof CloseableBitmap) {
Bitmap bitmap = (((CloseableBitmap) image).getUnderlyingBitmap());
if (bitmap != null && !bitmap.isRecycled()) {
Bitmap bitmapCopy = bitmap.copy(bitmap.getConfig(), true);
Drawable drawable = new DrawableWithIntrinsicSize(context.getResources(), bitmapCopy, source);
iconResolverListener.setDrawable(drawable);
}
}
} finally {
imageRef.close();
}
}
}
@Override
protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
}
}, UiThreadImmediateExecutorService.getInstance());
} else {
int drawableResId = context.getResources().getIdentifier(uri, "drawable", context.getPackageName());
if (drawableResId != 0)
iconResolverListener.setDrawable(context.getResources().getDrawable(drawableResId));
}
}
}
|
package com.hubspot.singularity.mesos;
import com.google.inject.Inject;
import com.hubspot.mesos.JavaUtils;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SingularitySchedulerLock {
private static final Logger LOG = LoggerFactory.getLogger(
SingularitySchedulerLock.class
);
private final ReentrantLock stateLock;
private final ReentrantLock offersLock;
private final ConcurrentHashMap<String, ReentrantLock> requestLocks;
@Inject
public SingularitySchedulerLock() {
this.stateLock = new ReentrantLock();
this.offersLock = new ReentrantLock();
this.requestLocks = new ConcurrentHashMap<>();
}
private long lock(String requestId, String name) {
final long start = System.currentTimeMillis();
LOG.trace("{} - Locking {}", name, requestId);
ReentrantLock lock = requestLocks.computeIfAbsent(
requestId,
r -> new ReentrantLock()
);
lock.lock();
LOG.trace(
"{} - Acquired lock on {} ({})",
name,
requestId,
JavaUtils.duration(start)
);
return System.currentTimeMillis();
}
/** Returns start time of lock if successful, -1 otherwise. */
private long tryLock(String requestId, String name, long timeout, TimeUnit timeunit) {
try {
final long start = System.currentTimeMillis();
LOG.trace("{} - Trying Locking {}", name, requestId);
ReentrantLock lock = requestLocks.computeIfAbsent(
requestId,
r -> new ReentrantLock()
);
boolean locked = lock.tryLock(timeout, timeunit);
if (locked) {
LOG.trace(
"{} - Acquired lock on {} ({})",
name,
requestId,
JavaUtils.duration(start)
);
return start;
} else {
LOG.info(
"{} - Failed to acquire lock on {} ({})",
name,
requestId,
JavaUtils.duration(start)
);
return -1;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private void unlock(String requestId, String name, long start) {
long duration = System.currentTimeMillis() - start;
if (duration > 1000) {
LOG.debug("{} - Unlocking {} after {}ms", name, requestId, duration);
} else {
LOG.trace("{} - Unlocking {} after {}ms", name, requestId, duration);
}
ReentrantLock lock = requestLocks.computeIfAbsent(
requestId,
r -> new ReentrantLock()
);
lock.unlock();
}
public void runWithRequestLock(Runnable function, String requestId, String name) {
long start = lock(requestId, name);
try {
function.run();
} finally {
unlock(requestId, name, start);
}
}
public void tryRunWithRequestLock(
Runnable function,
String requestId,
String name,
long timeout,
TimeUnit timeunit
) {
long start = tryLock(requestId, name, timeout, timeunit);
if (start > 0) {
try {
function.run();
} finally {
unlock(requestId, name, start);
}
}
}
public <T> T runWithRequestLockAndReturn(
Callable<T> function,
String requestId,
String name
) {
long start = lock(requestId, name);
try {
return function.call();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
unlock(requestId, name, start);
}
}
void runWithStateLock(Runnable function, String name) {
long start = lockState(name);
try {
function.run();
} finally {
unlockState(name, start);
}
}
private long lockState(String name) {
final long start = System.currentTimeMillis();
LOG.info("{} - Locking state lock", name);
stateLock.lock();
LOG.info("{} - Acquired state lock ({})", name, JavaUtils.duration(start));
return System.currentTimeMillis();
}
private void unlockState(String name, long start) {
LOG.info("{} - Unlocking state lock ({})", name, JavaUtils.duration(start));
stateLock.unlock();
}
public void runWithOffersLock(Runnable function, String name) {
long start = lockOffers(name);
try {
function.run();
} finally {
unlockOffers(name, start);
}
}
public void runWithOffersLockAndtimeout(
Function<Boolean, Void> function,
String name,
long timeoutMillis
) {
final long start = System.currentTimeMillis();
LOG.debug("{} - Locking offers lock", name);
try {
boolean acquired = offersLock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS);
LOG.debug(
"{} - Acquired offers lock ({}) ({})",
name,
acquired,
JavaUtils.duration(start)
);
long functionStart = System.currentTimeMillis();
try {
function.apply(acquired);
} finally {
if (acquired) {
unlockOffers(name, functionStart);
}
}
} catch (InterruptedException ie) {
LOG.warn("Interrupted waiting for offer lock", ie);
}
}
private long lockOffers(String name) {
final long start = System.currentTimeMillis();
LOG.debug("{} - Locking offers lock", name);
offersLock.lock();
LOG.debug("{} - Acquired offers lock ({})", name, JavaUtils.duration(start));
return System.currentTimeMillis();
}
private void unlockOffers(String name, long start) {
LOG.debug("{} - Unlocking offers lock ({})", name, JavaUtils.duration(start));
offersLock.unlock();
}
}
|
package org.spine3.examples.todolist.c.aggregates;
import com.google.common.base.Throwables;
import com.google.protobuf.Message;
import com.google.protobuf.StringValue;
import com.google.protobuf.Timestamp;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.spine3.base.CommandContext;
import org.spine3.change.ValueMismatch;
import org.spine3.examples.todolist.DescriptionUpdateFailed;
import org.spine3.examples.todolist.PriorityUpdateFailed;
import org.spine3.examples.todolist.TaskDefinition;
import org.spine3.examples.todolist.TaskDueDateUpdateFailed;
import org.spine3.examples.todolist.TaskId;
import org.spine3.examples.todolist.TaskPriority;
import org.spine3.examples.todolist.TaskPriorityValue;
import org.spine3.examples.todolist.c.commands.CompleteTask;
import org.spine3.examples.todolist.c.commands.CreateBasicTask;
import org.spine3.examples.todolist.c.commands.CreateDraft;
import org.spine3.examples.todolist.c.commands.DeleteTask;
import org.spine3.examples.todolist.c.commands.FinalizeDraft;
import org.spine3.examples.todolist.c.commands.ReopenTask;
import org.spine3.examples.todolist.c.commands.UpdateTaskDescription;
import org.spine3.examples.todolist.c.commands.UpdateTaskDueDate;
import org.spine3.examples.todolist.c.commands.UpdateTaskPriority;
import org.spine3.examples.todolist.c.events.TaskCompleted;
import org.spine3.examples.todolist.c.events.TaskCreated;
import org.spine3.examples.todolist.c.events.TaskDeleted;
import org.spine3.examples.todolist.c.events.TaskDescriptionUpdated;
import org.spine3.examples.todolist.c.events.TaskDraftCreated;
import org.spine3.examples.todolist.c.events.TaskDueDateUpdated;
import org.spine3.examples.todolist.c.events.TaskPriorityUpdated;
import org.spine3.examples.todolist.c.failures.CannotCompleteTask;
import org.spine3.examples.todolist.c.failures.CannotDeleteTask;
import org.spine3.examples.todolist.c.failures.CannotFinalizeDraft;
import org.spine3.examples.todolist.c.failures.CannotReopenTask;
import org.spine3.examples.todolist.c.failures.CannotUpdateTaskDescription;
import org.spine3.examples.todolist.c.failures.CannotUpdateTaskDueDate;
import org.spine3.examples.todolist.c.failures.CannotUpdateTaskPriority;
import org.spine3.examples.todolist.c.failures.CannotUpdateTaskWithInappropriateDescription;
import org.spine3.examples.todolist.c.failures.Failures;
import org.spine3.protobuf.Timestamps;
import org.spine3.test.CommandTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.spine3.examples.todolist.TaskStatus.COMPLETED;
import static org.spine3.examples.todolist.TaskStatus.DELETED;
import static org.spine3.examples.todolist.TaskStatus.DRAFT;
import static org.spine3.examples.todolist.TaskStatus.FINALIZED;
import static org.spine3.examples.todolist.TaskStatus.OPEN;
import static org.spine3.examples.todolist.testdata.TestCommandContextFactory.createCommandContext;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.DESCRIPTION;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.DUE_DATE;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.TASK_ID;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.completeTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.createDraftInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.createTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.deleteTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.finalizeDraftInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.reopenTaskInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.updateTaskDescriptionInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.updateTaskDueDateInstance;
import static org.spine3.examples.todolist.testdata.TestTaskCommandFactory.updateTaskPriorityInstance;
import static org.spine3.protobuf.AnyPacker.unpack;
/**
* @author Illia Shepilov
*/
public class TaskDefinitionPartTest {
private static final CommandContext COMMAND_CONTEXT = createCommandContext();
private TaskDefinitionPart aggregate;
private static final String EXPECTED_DESCRIPTION = "description";
@Nested
@DisplayName("CreateBasicTask command")
class CreateBasicTaskCommand extends CommandTest<CreateBasicTask> {
@Override
protected void setUp() {
}
@Test
@DisplayName("produces TaskCreated event")
public void producesEvent() {
final CreateBasicTask createTaskCmd = createTaskInstance();
final List<? extends com.google.protobuf.Message> messageList =
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
assertNotNull(aggregate.getState()
.getCreated());
assertNotNull(aggregate.getId());
final int expectedListSize = 1;
assertEquals(expectedListSize, messageList.size());
assertEquals(TaskCreated.class, messageList.get(0)
.getClass());
final TaskCreated taskCreated = (TaskCreated) messageList.get(0);
assertEquals(TASK_ID, taskCreated.getId());
assertEquals(DESCRIPTION, taskCreated.getDetails()
.getDescription());
}
@Test
public void record_modification_timestamp() throws InterruptedException {
CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
TaskDefinition state = aggregate.getState();
final Timestamp firstStateCreationTime = state.getCreated();
assertEquals(TASK_ID, state.getId());
Thread.sleep(1000);
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
state = aggregate.getState();
final Timestamp secondStateCreationTime = state.getCreated();
assertEquals(TASK_ID, state.getId());
assertTrue(Timestamps.isLaterThan(secondStateCreationTime, firstStateCreationTime));
}
}
@Nested
@DisplayName("UpdateTaskDescription command")
class UpdateTaskDescriptionCommand extends CommandTest<UpdateTaskDescription> {
@Override
protected void setUp() {
}
@Test
@DisplayName("produces TaskDescriptionUpdated event")
public void producesEvent() {
final CreateBasicTask createBasicTask = createTaskInstance();
aggregate.dispatchForTest(createBasicTask, COMMAND_CONTEXT);
final UpdateTaskDescription updateTaskDescriptionCmd = updateTaskDescriptionInstance();
final List<? extends Message> messageList =
aggregate.dispatchForTest(updateTaskDescriptionCmd, COMMAND_CONTEXT);
final int expectedListSize = 1;
assertEquals(expectedListSize, messageList.size());
assertEquals(TaskDescriptionUpdated.class, messageList.get(0)
.getClass());
final TaskDescriptionUpdated taskDescriptionUpdated = (TaskDescriptionUpdated) messageList.get(0);
assertEquals(TASK_ID, taskDescriptionUpdated.getTaskId());
final String newDescription = taskDescriptionUpdated.getDescriptionChange()
.getNewValue();
assertEquals(DESCRIPTION, newDescription);
}
@Test
@DisplayName("")
public void catch_exception_when_handle_update_task_description_when_description_contains_one_symbol() {
try {
final UpdateTaskDescription updateTaskDescriptionCmd = updateTaskDescriptionInstance(TASK_ID, "", ".");
aggregate.dispatchForTest(updateTaskDescriptionCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskWithInappropriateDescription);
}
}
@Test
public void catch_exception_when_handle_update_task_description_when_task_is_deleted() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final DeleteTask deleteTaskCmd = deleteTaskInstance();
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
final UpdateTaskDescription updateTaskDescriptionCmd = updateTaskDescriptionInstance();
assertThrows(CannotUpdateTaskDescription.class, () -> aggregate.dispatchForTest(updateTaskDescriptionCmd, COMMAND_CONTEXT));
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskDescription);
}
}
@Test
public void catch_exception_handle_update_task_description_when_task_is_completed() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final CompleteTask completeTaskCmd = completeTaskInstance();
aggregate.dispatchForTest(completeTaskCmd, COMMAND_CONTEXT);
final UpdateTaskDescription updateTaskDescriptionCmd = updateTaskDescriptionInstance();
aggregate.dispatchForTest(updateTaskDescriptionCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskDescription);
}
}
@Test
public void update_current_state_task_description_after_dispatch_command() {
final String newDescription = "new description.";
final CreateBasicTask createBasicTask = createTaskInstance();
aggregate.dispatchForTest(createBasicTask, COMMAND_CONTEXT);
final UpdateTaskDescription updateTaskDescriptionCmd =
updateTaskDescriptionInstance(TASK_ID, DESCRIPTION, newDescription);
aggregate.dispatchForTest(updateTaskDescriptionCmd, COMMAND_CONTEXT);
final TaskDefinition state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(newDescription, state.getDescription());
}
@Test
public void emit_cannot_update_task_description_failure_upon_update_task_description_command() {
final CreateBasicTask createBasicTask = createTaskInstance();
aggregate.dispatchForTest(createBasicTask, COMMAND_CONTEXT);
final String expectedValue = EXPECTED_DESCRIPTION;
final String newValue = "update description";
final String actualValue = createBasicTask.getDescription();
try {
final UpdateTaskDescription updateTaskDescription =
updateTaskDescriptionInstance(TASK_ID, expectedValue, newValue);
aggregate.dispatchForTest(updateTaskDescription, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskDescription);
@SuppressWarnings("ConstantConditions")
final Failures.CannotUpdateTaskDescription failure = ((CannotUpdateTaskDescription) cause).getFailure();
final DescriptionUpdateFailed descriptionUpdateFailed = failure.getUpdateFailed();
final TaskId actualTaskId = descriptionUpdateFailed.getFailedCommand()
.getTaskId();
assertEquals(TASK_ID, actualTaskId);
final StringValue expectedStringValue = StringValue.newBuilder()
.setValue(expectedValue)
.build();
final StringValue actualStringValue = StringValue.newBuilder()
.setValue(actualValue)
.build();
final StringValue newStringValue = StringValue.newBuilder()
.setValue(newValue)
.build();
final ValueMismatch mismatch = descriptionUpdateFailed.getDescriptionMismatch();
assertEquals(expectedStringValue, unpack(mismatch.getExpected()));
assertEquals(actualStringValue, unpack(mismatch.getActual()));
assertEquals(newStringValue, unpack(mismatch.getNewValue()));
}
}
}
@Nested
class UpdateTaskDueDateCommand extends CommandTest<UpdateTaskDueDate> {
@Override
protected void setUp() {
}
@Test
public void catch_exception_when_handle_update_task_due_date_when_task_is_completed() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final CompleteTask completeTaskCmd = completeTaskInstance();
aggregate.dispatchForTest(completeTaskCmd, COMMAND_CONTEXT);
final UpdateTaskDueDate updateTaskDueDateCmd = updateTaskDueDateInstance();
aggregate.dispatchForTest(updateTaskDueDateCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskDueDate);
}
}
@Test
public void catch_exception_when_handle_update_task_due_date_when_task_is_deleted() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final DeleteTask deleteTaskCmd = deleteTaskInstance();
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
final UpdateTaskDueDate updateTaskDueDateCmd = updateTaskDueDateInstance();
aggregate.dispatchForTest(updateTaskDueDateCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskDueDate);
}
}
@Test
public void emit_task_due_date_updated_event_upon_update_task_due_date_command() {
final UpdateTaskDueDate updateTaskDueDateCmd = updateTaskDueDateInstance();
final List<? extends com.google.protobuf.Message> messageList =
aggregate.dispatchForTest(updateTaskDueDateCmd, COMMAND_CONTEXT);
final int expectedListSize = 1;
assertEquals(expectedListSize, messageList.size());
assertEquals(TaskDueDateUpdated.class, messageList.get(0)
.getClass());
final TaskDueDateUpdated taskDueDateUpdated = (TaskDueDateUpdated) messageList.get(0);
assertEquals(TASK_ID, taskDueDateUpdated.getTaskId());
final Timestamp newDueDate = taskDueDateUpdated.getDueDateChange()
.getNewValue();
assertEquals(DUE_DATE, newDueDate);
}
@Test
public void update_current_state_task_due_date_after_dispatch_command() {
final Timestamp updatedDueDate = Timestamps.getCurrentTime();
final CreateBasicTask createBasicTask = createTaskInstance();
aggregate.dispatchForTest(createBasicTask, COMMAND_CONTEXT);
final UpdateTaskDueDate updateTaskDueDateCmd =
updateTaskDueDateInstance(TASK_ID, Timestamp.getDefaultInstance(), updatedDueDate);
aggregate.dispatchForTest(updateTaskDueDateCmd, COMMAND_CONTEXT);
final TaskDefinition state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(updatedDueDate, state.getDueDate());
}
@Test
public void emit_cannot_update_task_due_date_failure_upon_update_task_due_date_command() {
final CreateBasicTask createBasicTask = createTaskInstance();
aggregate.dispatchForTest(createBasicTask, COMMAND_CONTEXT);
final Timestamp expectedDueDate = Timestamps.getCurrentTime();
final Timestamp newDueDate = Timestamps.getCurrentTime();
try {
final UpdateTaskDueDate updateTaskDueDate =
updateTaskDueDateInstance(TASK_ID, expectedDueDate, newDueDate);
final List<? extends com.google.protobuf.Message> messageList =
aggregate.dispatchForTest(updateTaskDueDate, COMMAND_CONTEXT);
final int expectedListSize = 1;
assertEquals(expectedListSize, messageList.size());
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskDueDate);
@SuppressWarnings("ConstantConditions")
final Failures.CannotUpdateTaskDueDate cannotUpdateTaskDueDate =
((CannotUpdateTaskDueDate) cause).getFailure();
final TaskDueDateUpdateFailed dueDateUpdateFailed = cannotUpdateTaskDueDate.getUpdateFailed();
final TaskId actualTaskId = dueDateUpdateFailed.getFailedCommand()
.getTaskId();
assertEquals(TASK_ID, actualTaskId);
final ValueMismatch mismatch = dueDateUpdateFailed.getDueDateMismatch();
assertEquals(newDueDate, unpack(mismatch.getNewValue()));
assertEquals(expectedDueDate, unpack(mismatch.getExpected()));
final Timestamp actualDueDate = Timestamp.getDefaultInstance();
assertEquals(actualDueDate, unpack(mismatch.getActual()));
}
}
}
@Nested
@DisplayName("UpdateTaskPriority command")
class UpdateTaskPriorityCommand extends CommandTest<UpdateTaskPriority> {
@Override
protected void setUp() {
}
@Test
public void catch_exception_handle_update_task_priority_when_task_is_deleted() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final DeleteTask deleteTaskCmd = deleteTaskInstance();
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
final UpdateTaskPriority updateTaskPriorityCmd = updateTaskPriorityInstance();
aggregate.dispatchForTest(updateTaskPriorityCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskPriority);
}
}
@Test
public void catch_exception_handle_update_task_priority_when_task_is_completed() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final CompleteTask completeTaskCmd = completeTaskInstance();
aggregate.dispatchForTest(completeTaskCmd, COMMAND_CONTEXT);
final UpdateTaskPriority updateTaskPriorityCmd = updateTaskPriorityInstance();
aggregate.dispatchForTest(updateTaskPriorityCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskPriority);
}
}
@Test
public void emit_task_priority_updated_event_upon_update_task_priority_command() {
final CreateBasicTask createBasicTask = createTaskInstance();
aggregate.dispatchForTest(createBasicTask, COMMAND_CONTEXT);
final UpdateTaskPriority updateTaskPriorityCmd = updateTaskPriorityInstance();
final List<? extends com.google.protobuf.Message> messageList =
aggregate.dispatchForTest(updateTaskPriorityCmd, COMMAND_CONTEXT);
final int expectedListSize = 1;
assertEquals(expectedListSize, messageList.size());
assertEquals(TaskPriorityUpdated.class, messageList.get(0)
.getClass());
final TaskPriorityUpdated taskPriorityUpdated = (TaskPriorityUpdated) messageList.get(0);
assertEquals(TASK_ID, taskPriorityUpdated.getTaskId());
final TaskPriority newPriority = taskPriorityUpdated.getPriorityChange()
.getNewValue();
assertEquals(TaskPriority.HIGH, newPriority);
}
@Test
public void update_current_state_task_priority_after_dispatch_command() {
final TaskPriority updatedPriority = TaskPriority.HIGH;
final CreateBasicTask createBasicTask = createTaskInstance();
aggregate.dispatchForTest(createBasicTask, COMMAND_CONTEXT);
final UpdateTaskPriority updateTaskPriorityCmd =
updateTaskPriorityInstance(TASK_ID, TaskPriority.TP_UNDEFINED, updatedPriority);
aggregate.dispatchForTest(updateTaskPriorityCmd, COMMAND_CONTEXT);
final TaskDefinition state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(updatedPriority, state.getPriority());
}
@Test
public void emit_cannot_update_task_priority_failure_upon_update_task_priority_command() {
try {
final UpdateTaskPriority updateTaskPriority =
updateTaskPriorityInstance(TASK_ID, TaskPriority.LOW, TaskPriority.HIGH);
aggregate.dispatchForTest(updateTaskPriority, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotUpdateTaskPriority);
@SuppressWarnings("ConstantConditions")
final Failures.CannotUpdateTaskPriority cannotUpdateTaskPriority =
((CannotUpdateTaskPriority) cause).getFailure();
final PriorityUpdateFailed priorityUpdateFailed = cannotUpdateTaskPriority.getUpdateFailed();
final TaskId actualTaskId = priorityUpdateFailed.getFailedCommand()
.getTaskId();
assertEquals(TASK_ID, actualTaskId);
final ValueMismatch mismatch = priorityUpdateFailed.getPriorityMismatch();
final TaskPriorityValue expectedValue = TaskPriorityValue.newBuilder()
.setPriorityValue(TaskPriority.LOW)
.build();
final TaskPriorityValue actualValue = TaskPriorityValue.newBuilder()
.setPriorityValue(TaskPriority.TP_UNDEFINED)
.build();
final TaskPriorityValue newValue = TaskPriorityValue.newBuilder()
.setPriorityValue(TaskPriority.HIGH)
.build();
assertEquals(actualValue, unpack(mismatch.getActual()));
assertEquals(expectedValue, unpack(mismatch.getExpected()));
assertEquals(newValue, unpack(mismatch.getNewValue()));
}
}
}
@Nested
@DisplayName("CompleteTask command")
class CompleteTaskCommand extends CommandTest<CompleteTask> {
@Override
protected void setUp() {
}
@Test
public void emit_task_completed_event_upon_complete_task_command() {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final CompleteTask completeTaskCmd = completeTaskInstance();
final List<? extends com.google.protobuf.Message> messageList =
aggregate.dispatchForTest(completeTaskCmd, COMMAND_CONTEXT);
final int expectedListSize = 1;
assertEquals(expectedListSize, messageList.size());
assertEquals(TaskCompleted.class, messageList.get(0)
.getClass());
final TaskCompleted taskCompleted = (TaskCompleted) messageList.get(0);
assertEquals(TASK_ID, taskCompleted.getTaskId());
}
@Test
public void change_task_status_state_when_task_is_completed() {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final CompleteTask completeTaskCmd = completeTaskInstance();
aggregate.dispatchForTest(completeTaskCmd, COMMAND_CONTEXT);
final TaskDefinition state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(COMPLETED, state.getTaskStatus());
}
@Test
public void catch_exception_when_handle_complete_task_command_when_task_is_deleted() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final DeleteTask deleteTaskCmd = deleteTaskInstance();
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
final CompleteTask completeTaskCmd = completeTaskInstance();
aggregate.dispatchForTest(completeTaskCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotCompleteTask);
}
}
@Test
public void catch_exception_when_handle_complete_task_command_when_task_in_draft_state() {
try {
final CreateDraft createDraftCmd = createDraftInstance();
aggregate.dispatchForTest(createDraftCmd, COMMAND_CONTEXT);
final CompleteTask completeTaskCmd = completeTaskInstance();
aggregate.dispatchForTest(completeTaskCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotCompleteTask);
}
}
}
@Nested
@DisplayName("DeleteTask command")
class DeleteTaskCommand extends CommandTest<DeleteTask> {
@Override
protected void setUp() {
}
@Test
public void change_task_status_state_when_task_is_deleted() {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final DeleteTask deleteTaskCmd = deleteTaskInstance();
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
final TaskDefinition state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(DELETED, state.getTaskStatus());
}
@Test
public void emit_task_created_and_task_deleted_events_upon_create_basic_task_and_delete_task_commands() {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
assertNotEquals(DELETED, aggregate.getState()
.getTaskStatus());
final DeleteTask deleteTaskCmd = deleteTaskInstance();
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
assertEquals(DELETED, aggregate.getState()
.getTaskStatus());
}
@Test
public void catch_exception_when_handle_delete_task_command_when_task_is_already_deleted() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final DeleteTask deleteTaskCmd = deleteTaskInstance();
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotDeleteTask);
}
}
@Test
public void emit_task_deleted_event_upon_delete_task_command() {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final DeleteTask deleteTaskCmd = deleteTaskInstance();
final List<? extends com.google.protobuf.Message> messageList =
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
final int expectedListSize = 1;
assertEquals(expectedListSize, messageList.size());
assertEquals(TaskDeleted.class, messageList.get(0)
.getClass());
final TaskDeleted taskDeleted = (TaskDeleted) messageList.get(0);
assertEquals(TASK_ID, taskDeleted.getTaskId());
}
}
@Nested
@DisplayName("FinalizeDraft command")
class FinalizeDraftCommand extends CommandTest<FinalizeDraft> {
@Override
protected void setUp() {
}
@Test
public void emit_task_draft_finalized_event_upon_finalize_draft_command() {
final CreateDraft createDraftCmd = createDraftInstance();
aggregate.dispatchForTest(createDraftCmd, COMMAND_CONTEXT);
final FinalizeDraft finalizeDraftCmd = finalizeDraftInstance();
TaskDefinition state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(DRAFT, state.getTaskStatus());
aggregate.dispatchForTest(finalizeDraftCmd, COMMAND_CONTEXT);
state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(FINALIZED, state.getTaskStatus());
}
@Test
public void catch_exception_when_handle_finalized_draft_command_when_task_is_deleted() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final DeleteTask deleteTaskCmd = deleteTaskInstance();
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
final FinalizeDraft finalizeDraftCmd = finalizeDraftInstance();
aggregate.dispatchForTest(finalizeDraftCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotFinalizeDraft);
}
}
@Test
public void catch_exception_when_handle_finalized_draft_command_when_task_not_in_the_draft_state() {
try {
final FinalizeDraft finalizeDraftCmd = finalizeDraftInstance();
aggregate.dispatchForTest(finalizeDraftCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotFinalizeDraft);
}
}
}
@Nested
@DisplayName("CreateDraft command")
class CreateDraftCommand extends CommandTest<CreateDraft> {
@Override
protected void setUp() {
}
@Test
public void emit_task_draft_created_event_upon_create_draft_task_command() {
final CreateDraft createDraftCmd = createDraftInstance();
final List<? extends com.google.protobuf.Message> messageList =
aggregate.dispatchForTest(createDraftCmd, COMMAND_CONTEXT);
final int expectedListSize = 1;
assertEquals(expectedListSize, messageList.size());
assertEquals(TaskDraftCreated.class, messageList.get(0)
.getClass());
final TaskDraftCreated taskDraftCreated = (TaskDraftCreated) messageList.get(0);
assertEquals(TASK_ID, taskDraftCreated.getId());
}
@Test
public void emit_task_draft_created_event_upon_create_task_draft_command() {
final CreateDraft createDraftCmd = createDraftInstance();
aggregate.dispatchForTest(createDraftCmd, COMMAND_CONTEXT);
final TaskDefinition state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(DRAFT, state.getTaskStatus());
}
}
@Nested
@DisplayName("ReopenTask command")
class ReopenTaskCommand extends CommandTest<ReopenTask> {
@Override
protected void setUp() {
}
@Test
public void catch_exception_when_handle_reopen_task_command_when_task_created() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final ReopenTask reopenTaskCmd = reopenTaskInstance();
aggregate.dispatchForTest(reopenTaskCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotReopenTask);
}
}
@Test
public void emit_task_completed_and_task_reopened_events_upon_complete_and_reopen_task_command() {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final CompleteTask completeTaskCmd = completeTaskInstance();
aggregate.dispatchForTest(completeTaskCmd, COMMAND_CONTEXT);
TaskDefinition state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(COMPLETED, state.getTaskStatus());
final ReopenTask reopenTaskCmd = reopenTaskInstance();
aggregate.dispatchForTest(reopenTaskCmd, COMMAND_CONTEXT);
state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(OPEN, state.getTaskStatus());
}
@Test
public void catch_exception_when_handle_reopen_task_command_when_task_is_created() {
try {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final ReopenTask reopenTaskCmd = reopenTaskInstance();
aggregate.dispatchForTest(reopenTaskCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotReopenTask);
}
}
@Test
public void emit_task_reopened_event_when_handle_reopen_task_command_when_task_is_deleted() {
final CreateBasicTask createTaskCmd = createTaskInstance();
aggregate.dispatchForTest(createTaskCmd, COMMAND_CONTEXT);
final DeleteTask deleteTaskCmd = deleteTaskInstance();
aggregate.dispatchForTest(deleteTaskCmd, COMMAND_CONTEXT);
final ReopenTask reopenTaskCmd = reopenTaskInstance();
aggregate.dispatchForTest(reopenTaskCmd, COMMAND_CONTEXT);
final TaskDefinition state = aggregate.getState();
assertEquals(TASK_ID, state.getId());
assertEquals(OPEN, state.getTaskStatus());
}
@Test
public void catch_exception_when_handle_reopen_task_command_when_task_in_draft_state() {
try {
final CreateDraft createDraftCmd = createDraftInstance();
aggregate.dispatchForTest(createDraftCmd, COMMAND_CONTEXT);
final ReopenTask reopenTaskCmd = reopenTaskInstance();
aggregate.dispatchForTest(reopenTaskCmd, COMMAND_CONTEXT);
} catch (Throwable e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") // We need it for checking.
final Throwable cause = Throwables.getRootCause(e);
assertTrue(cause instanceof CannotReopenTask);
}
}
}
}
|
package com.sebaslogen.blendletje.ui.activities.recyclerview;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.graphics.ColorUtils;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.florent37.picassopalette.PicassoPalette;
import com.sebaslogen.blendletje.R;
import com.sebaslogen.blendletje.domain.model.Article;
import com.sebaslogen.blendletje.domain.model.ArticleImage;
import com.sebaslogen.blendletje.domain.model.ImageMetadata;
import com.sebaslogen.blendletje.domain.model.ListItem;
import com.sebaslogen.blendletje.ui.utils.ImageLoader;
import java.util.List;
import rx.exceptions.OnErrorNotImplementedException;
import rx.functions.Func4;
import static com.sebaslogen.blendletje.ui.utils.TextUtils.getMarkupStrippedString;
public class ItemsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final short VIEW_TYPE_ARTICLE = 0;
private static final short VIEW_TYPE_ADVERTISEMENT = 1;
private final ImageLoader mImageLoader;
private final Func4<View, String, String, String, Void> mItemClick;
private final DecelerateInterpolator mDecelerateInterpolator = new DecelerateInterpolator();
private List<ListItem> mItemsList;
private int mLastPosition = -1; // Remember the last item shown on screen for animations
/**
* Constructor of an adapter for a list of items to bind and display in a recyclerView
*
* @param itemsList List of items
*/
public ItemsListAdapter(final List<ListItem> itemsList, final ImageLoader imageLoader,
final Func4<View, String, String, String, Void> itemClick) {
mItemsList = itemsList;
mImageLoader = imageLoader;
mItemClick = itemClick;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final View view;
switch (viewType) {
case VIEW_TYPE_ARTICLE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.article_item, parent, false);
return new ArticleItemViewHolder(view);
case VIEW_TYPE_ADVERTISEMENT:
default:
// TODO: Implement advertisement items
// view = LayoutInflater.from(parent.getContext()).inflate(...
// return new AdvertisementItemViewHolder(view);
throw new OnErrorNotImplementedException(new Throwable("TODO: Implement advertisement items"));
}
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final int viewType = holder.getItemViewType();
final ListItem listItem = mItemsList.get(position);
switch (viewType) {
case VIEW_TYPE_ARTICLE:
bindArticleItem((Article) listItem, (ArticleItemViewHolder) holder);
break;
case VIEW_TYPE_ADVERTISEMENT:
// TODO: Implement advertisement items biding
// bindAdvertisementItem((Advertisement) listItem, (AdvertisementItemViewHolder) holder);
throw new OnErrorNotImplementedException(new Throwable("TODO: Implement advertisement items biding"));
// break;
default:
throw new IllegalArgumentException("View holder contains an unknown item type");
}
setAnimation(((ViewHolderAnimations) holder), position);
}
@Override
public void onViewDetachedFromWindow(final RecyclerView.ViewHolder holder) {
((ViewHolderAnimations) holder).clearAnimation();
}
private void setAnimation(final ViewHolderAnimations view, final int position) {
if (position > mLastPosition) {
final Animation animation = AnimationUtils.loadAnimation(view.getContext(), R.anim.card_appears);
animation.setStartOffset(300);
animation.setInterpolator(mDecelerateInterpolator);
view.startAnimation(animation);
mLastPosition = position;
}
}
private void bindArticleItem(final Article article, final ArticleItemViewHolder holder) {
final String title = article.contents().title();
holder.setTitle(title);
final List<ArticleImage> images = article.images();
String imageUrl = null;
if (images.isEmpty()) {
holder.clearImage();
} else {
final ArticleImage articleImage = images.get(0);
final ImageMetadata image = articleImage.large();
imageUrl = image.url();
holder.setImage(imageUrl, image.height(), articleImage.caption());
}
holder.setClickAction(mItemClick, article.id(), title, imageUrl);
}
@Override
public int getItemCount() {
return mItemsList.size();
}
@Override
public int getItemViewType(final int position) {
return (mItemsList.get(position) instanceof Article) ? VIEW_TYPE_ARTICLE : VIEW_TYPE_ADVERTISEMENT;
}
public void overwriteList(final List<ListItem> newList) {
mItemsList = newList;
notifyDataSetChanged();
}
private interface ViewHolderAnimations {
Context getContext();
void startAnimation(Animation animation);
void clearAnimation();
}
private class ArticleItemViewHolder extends RecyclerView.ViewHolder implements ViewHolderAnimations {
private final CardView mContainer;
private final TextView mTitle;
private final ImageView mImageView;
private final String mDefaultImageContentDescription;
private final FrameLayout.LayoutParams mDefaultLayoutParams;
ArticleItemViewHolder(final View view) {
super(view);
mContainer = (CardView) view.findViewById(R.id.cv_item_container);
mTitle = (TextView) view.findViewById(R.id.tv_title);
mImageView = (ImageView) view.findViewById(R.id.iv_image);
mDefaultImageContentDescription = view.getResources().getString(R.string.article_image_description);
mDefaultLayoutParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
void setTitle(final String text) {
mTitle.setText(getMarkupStrippedString(text));
}
void setImage(final String imageUrl, final int height, final String caption) {
mImageView.setContentDescription(caption);
mImageView.setLayoutParams(new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
height)); // Prepare container size so it's already correct before image is loaded
mImageLoader.cancelRequest(mImageView);
mImageLoader.load(imageUrl)
.placeholder(R.drawable.empty)
.error(R.drawable.empty)
.into(mImageView, PicassoPalette.with(imageUrl, mImageView)
.use(PicassoPalette.Profile.MUTED_DARK)
.intoCallBack(palette -> {
final Palette.Swatch swatch = palette.getDarkMutedSwatch();
if (swatch != null) {
mTitle.setBackgroundColor(
ColorUtils.setAlphaComponent(swatch.getRgb(), 200));
}
}));
}
void setClickAction(final Func4<View, String, String, String, Void> itemClick,
final String id, final String title, @Nullable final String imageUrl) {
itemView.setOnClickListener(view -> itemClick.call(view, id, title, imageUrl));
}
void clearImage() {
mImageLoader.cancelRequest(mImageView);
mImageView.setLayoutParams(mDefaultLayoutParams);
mImageView.setContentDescription(mDefaultImageContentDescription);
mImageView.setImageDrawable(null);
}
@Override
public Context getContext() {
return mContainer.getContext();
}
@Override
public void startAnimation(final Animation animation) {
mContainer.startAnimation(animation);
}
@Override
public void clearAnimation() {
mContainer.clearAnimation();
}
}
}
|
package link.standen.michael.fatesheets.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.DeletableStringArrayAdapter;
import link.standen.michael.fatesheets.layout.AdapterLinearLayout;
import link.standen.michael.fatesheets.model.Character;
/**
* A fragment for managing a characters aspects.
*/
public class CharacterEditAspectsFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.character_edit_aspects, container, false);
}
@Override
public void onViewCreated(View rootView, Bundle savedInstanceState) {
final Character character = getCharacter();
// High Concept
TextView view = (TextView) rootView.findViewById(R.id.high_concept);
view.setText(character.getHighConcept());
view.setOnKeyListener(new View.OnKeyListener(){
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
character.setHighConcept(((TextView)v).getText().toString());
return false;
}
});
// Trouble
view = (TextView) rootView.findViewById(R.id.trouble);
view.setText(character.getTrouble());
view.setOnKeyListener(new View.OnKeyListener(){
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
character.setTrouble(((TextView)v).getText().toString());
return false;
}
});
// Aspects
Fragment childFragment = new AspectFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.aspect_container, childFragment).commit();
}
/**
* Class for managing aspects.
*/
public static class AspectFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Character character = getCharacter();
View rootView = inflater.inflate(R.layout.character_edit_aspects_aspect, container, false);
// Aspects
final DeletableStringArrayAdapter aspectListAdapter = new DeletableStringArrayAdapter(getContext(),
R.layout.character_edit_aspects_list_item, getCharacter().getAspects());
((AdapterLinearLayout) rootView.findViewById(R.id.aspect_list)).setAdapter(aspectListAdapter);
rootView.findViewById(R.id.add_aspect).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
character.getAspects().add("");
aspectListAdapter.notifyDataSetChanged();
}
});
return rootView;
}
}
}
|
package me.devsaki.hentoid.notification.download;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import java.util.Locale;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.activities.QueueActivity;
import me.devsaki.hentoid.util.notification.Notification;
public class DownloadProgressNotification implements Notification {
private final String title;
private final int progress;
private final int max;
public DownloadProgressNotification(String title, int progress, int max) {
this.title = title;
this.progress = progress;
this.max = max;
}
@NonNull
@Override
public android.app.Notification onCreateNotification(Context context) {
return new NotificationCompat.Builder(context, DownloadNotificationChannel.ID)
.setSmallIcon(R.drawable.ic_stat_hentoid)
.setContentTitle(context.getString(R.string.downloading))
.setContentText(title)
.setContentInfo(getProgressString())
.setProgress(max, progress, false)
.setColor(ContextCompat.getColor(context, R.color.accent))
.setContentIntent(getDefaultIntent(context))
.setLocalOnly(true)
.setOngoing(true)
.build();
}
private PendingIntent getDefaultIntent(Context context) {
Intent resultIntent = new Intent(context, QueueActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
return PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private String getProgressString() {
return String.format(Locale.US, " %.2f%%", progress * 100.0 / max);
}
}
|
package com.apptentive.android.sdk.module.messagecenter;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import com.apptentive.android.sdk.ApptentiveInternal;
import com.apptentive.android.sdk.ApptentiveLog;
import com.apptentive.android.sdk.R;
import com.apptentive.android.sdk.comm.ApptentiveClient;
import com.apptentive.android.sdk.comm.ApptentiveHttpResponse;
import com.apptentive.android.sdk.conversation.Conversation;
import com.apptentive.android.sdk.module.messagecenter.model.ApptentiveMessage;
import com.apptentive.android.sdk.module.messagecenter.model.ApptentiveToastNotification;
import com.apptentive.android.sdk.module.messagecenter.model.CompoundMessage;
import com.apptentive.android.sdk.module.messagecenter.model.MessageCenterListItem;
import com.apptentive.android.sdk.module.messagecenter.model.MessageFactory;
import com.apptentive.android.sdk.module.metric.MetricModule;
import com.apptentive.android.sdk.storage.MessageStore;
import com.apptentive.android.sdk.util.Util;
import com.apptentive.android.sdk.util.threading.DispatchQueue;
import com.apptentive.android.sdk.util.threading.DispatchTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
public class MessageManager {
// The reason of pause message sending
public static int SEND_PAUSE_REASON_ACTIVITY_PAUSE = 0;
public static int SEND_PAUSE_REASON_NETWORK = 1;
public static int SEND_PAUSE_REASON_SERVER = 2;
private static int TOAST_TYPE_UNREAD_MESSAGE = 1;
private WeakReference<Activity> currentForegroundApptentiveActivity;
private WeakReference<AfterSendMessageListener> afterSendMessageListener;
private final List<WeakReference<OnNewIncomingMessagesListener>> internalNewMessagesListeners = new ArrayList<WeakReference<OnNewIncomingMessagesListener>>();
/* UnreadMessagesListener is set by external hosting app, and its lifecycle is managed by the app.
* Use WeakReference to prevent memory leak
*/
private final List<WeakReference<UnreadMessagesListener>> hostUnreadMessagesListeners = new ArrayList<WeakReference<UnreadMessagesListener>>();
AtomicBoolean appInForeground = new AtomicBoolean(false);
private Handler uiHandler;
private MessagePollingWorker pollingWorker;
private final MessageDispatchTask toastMessageNotifierTask = new MessageDispatchTask() {
@Override
protected void execute(CompoundMessage message) {
showUnreadMessageToastNotification(message);
}
};
private final MessageCountDispatchTask hostMessageNotifierTask = new MessageCountDispatchTask() {
@Override
protected void execute(int messageCount) {
notifyHostUnreadMessagesListeners(messageCount);
}
};
public MessageManager() {
}
// init() will start polling worker.
public void init() {
if (uiHandler == null) {
uiHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case UI_THREAD_MESSAGE_ON_TOAST_NOTIFICATION: {
CompoundMessage msgToShow = (CompoundMessage) msg.obj;
showUnreadMessageToastNotification(msgToShow);
break;
}
default:
super.handleMessage(msg);
}
}
};
}
if (pollingWorker == null) {
pollingWorker = new MessagePollingWorker(this);
/* Set SharePreference to indicate Message Center feature is desired. It will always be checked
* during Apptentive initialization.
*/
Conversation conversation = ApptentiveInternal.getInstance().getConversation();
if (conversation != null) {
conversation.setMessageCenterFeatureUsed(true);
}
}
}
/*
* Starts an AsyncTask to pre-fetch messages. This is to be called as part of Push notification action
* when push is received on the device.
*/
public void startMessagePreFetchTask() {
// Defer message polling thread creation, if not created yet and host app receives a new message push
init();
AsyncTask<Object, Void, Void> task = new AsyncTask<Object, Void, Void>() {
private Exception e = null;
@Override
protected Void doInBackground(Object... params) {
boolean updateMC = (Boolean) params[0];
try {
fetchAndStoreMessages(updateMC, false);
} catch (Exception e) {
this.e = e;
}
return null;
}
@Override
protected void onPostExecute(Void v) {
if (e != null) {
ApptentiveLog.w("Unhandled Exception thrown from fetching new message asyncTask", e);
MetricModule.sendError(e, null, null);
}
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, isMessageCenterInForeground());
} else {
task.execute(isMessageCenterInForeground());
}
}
/**
* Performs a request against the server to check for messages in the conversation since the latest message we already have.
* This method will either be run on MessagePollingThread or as an asyncTask when Push is received.
*
* @return true if messages were returned, else false.
*/
public synchronized boolean fetchAndStoreMessages(boolean isMessageCenterForeground, boolean showToast) {
if (ApptentiveInternal.getInstance().getConversation().getConversationToken() == null) {
ApptentiveLog.d("Can't fetch messages because the conversation has not yet been initialized.");
return false;
}
if (!Util.isNetworkConnectionPresent()) {
ApptentiveLog.d("Can't fetch messages because a network connection is not present.");
return false;
}
// Fetch the messages.
List<ApptentiveMessage> messagesToSave = null;
try {
Future<String> future = getMessageStore().getLastReceivedMessageId();
messagesToSave = fetchMessages(future.get());
} catch (Exception e) {
ApptentiveLog.e("Error retrieving last received message id from worker thread");
}
CompoundMessage messageOnToast = null;
if (messagesToSave != null && messagesToSave.size() > 0) {
ApptentiveLog.d("Messages retrieved.");
// Also get the count of incoming unread messages.
int incomingUnreadMessages = 0;
// Mark messages from server where sender is the app user as read.
for (final ApptentiveMessage apptentiveMessage : messagesToSave) {
if (apptentiveMessage.isOutgoingMessage()) {
apptentiveMessage.setRead(true);
} else {
if (messageOnToast == null) {
if (apptentiveMessage.getType() == ApptentiveMessage.Type.CompoundMessage) {
messageOnToast = (CompoundMessage) apptentiveMessage;
}
}
incomingUnreadMessages++;
// for every new message received, notify Message Center
DispatchQueue.mainQueue().dispatchAsync(new DispatchTask() {
@Override
protected void execute() {
notifyInternalNewMessagesListeners((CompoundMessage) apptentiveMessage);
}
});
}
}
getMessageStore().addOrUpdateMessages(messagesToSave.toArray(new ApptentiveMessage[messagesToSave.size()]));
if (incomingUnreadMessages > 0) {
// Show toast notification only if the foreground activity is not already message center activity
if (!isMessageCenterForeground && showToast) {
DispatchQueue.mainQueue().dispatchAsyncOnce(toastMessageNotifierTask.setMessage(messageOnToast));
}
}
// Send message to notify host app, such as unread message badge
DispatchQueue.mainQueue()
.dispatchAsyncOnce(hostMessageNotifierTask.setMessageCount(getUnreadMessageCount()));
return incomingUnreadMessages > 0;
}
return false;
}
public List<MessageCenterListItem> getMessageCenterListItems() {
List<MessageCenterListItem> messagesToShow = new ArrayList<MessageCenterListItem>();
try {
List<ApptentiveMessage> messagesAll = getMessageStore().getAllMessages().get();
// Do not display hidden messages on Message Center
for (ApptentiveMessage message : messagesAll) {
if (!message.isHidden()) {
messagesToShow.add(message);
}
}
} catch (Exception e) {
ApptentiveLog.e("Error getting all messages in worker thread");
}
return messagesToShow;
}
public void sendMessage(ApptentiveMessage apptentiveMessage) {
getMessageStore().addOrUpdateMessages(apptentiveMessage);
ApptentiveInternal.getInstance().getApptentiveTaskManager().addPayload(apptentiveMessage);
}
/**
* This doesn't need to be run during normal program execution. Testing only.
*/
public void deleteAllMessages(Context context) {
ApptentiveLog.d("Deleting all messages.");
getMessageStore().deleteAllMessages();
}
private List<ApptentiveMessage> fetchMessages(String afterId) {
ApptentiveLog.d("Fetching messages newer than: %s", (afterId == null) ? "0" : afterId);
ApptentiveHttpResponse response = ApptentiveClient.getMessages(null, afterId, null);
List<ApptentiveMessage> ret = new ArrayList<ApptentiveMessage>();
if (!response.isSuccessful()) {
return ret;
}
try {
ret = parseMessagesString(response.getContent());
} catch (JSONException e) {
ApptentiveLog.e("Error parsing messages JSON.", e);
} catch (Exception e) {
ApptentiveLog.e("Unexpected error parsing messages JSON.", e);
}
return ret;
}
public void updateMessage(ApptentiveMessage apptentiveMessage) {
getMessageStore().updateMessage(apptentiveMessage);
}
public List<ApptentiveMessage> parseMessagesString(String messageString) throws JSONException {
List<ApptentiveMessage> ret = new ArrayList<ApptentiveMessage>();
JSONObject root = new JSONObject(messageString);
if (!root.isNull("items")) {
JSONArray items = root.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
String json = items.getJSONObject(i).toString();
ApptentiveMessage apptentiveMessage = MessageFactory.fromJson(json);
// Since these came back from the server, mark them saved before updating them in the DB.
if (apptentiveMessage != null) {
apptentiveMessage.setState(ApptentiveMessage.State.saved);
ret.add(apptentiveMessage);
}
}
}
return ret;
}
public void resumeSending() {
if (afterSendMessageListener != null && afterSendMessageListener.get() != null) {
afterSendMessageListener.get().onResumeSending();
}
}
public void pauseSending(int reason_code) {
if (afterSendMessageListener != null && afterSendMessageListener.get() != null) {
afterSendMessageListener.get().onPauseSending(reason_code);
}
}
public void onSentMessage(ApptentiveMessage apptentiveMessage, ApptentiveHttpResponse response) {
if (response.isRejectedPermanently() || response.isBadPayload()) {
if (apptentiveMessage instanceof CompoundMessage) {
apptentiveMessage.setCreatedAt(Double.MIN_VALUE);
getMessageStore().updateMessage(apptentiveMessage);
if (afterSendMessageListener != null && afterSendMessageListener.get() != null) {
afterSendMessageListener.get().onMessageSent(response, apptentiveMessage);
}
}
return;
}
if (response.isRejectedTemporarily()) {
pauseSending(SEND_PAUSE_REASON_SERVER);
return;
}
if (response.isSuccessful()) {
// Don't store hidden messages once sent. Delete them.
if (apptentiveMessage.isHidden()) {
((CompoundMessage) apptentiveMessage).deleteAssociatedFiles();
getMessageStore().deleteMessage(apptentiveMessage.getNonce());
return;
}
try {
JSONObject responseJson = new JSONObject(response.getContent());
apptentiveMessage.setState(ApptentiveMessage.State.sent);
apptentiveMessage.setId(responseJson.getString(ApptentiveMessage.KEY_ID));
apptentiveMessage.setCreatedAt(responseJson.getDouble(ApptentiveMessage.KEY_CREATED_AT));
} catch (JSONException e) {
ApptentiveLog.e("Error parsing sent apptentiveMessage response.", e);
}
getMessageStore().updateMessage(apptentiveMessage);
if (afterSendMessageListener != null && afterSendMessageListener.get() != null) {
afterSendMessageListener.get().onMessageSent(response, apptentiveMessage);
}
}
}
private MessageStore getMessageStore() {
return ApptentiveInternal.getInstance().getApptentiveTaskManager();
}
public int getUnreadMessageCount() {
int msgCount = 0;
try {
msgCount = getMessageStore().getUnreadMessageCount().get();
} catch (Exception e) {
ApptentiveLog.e("Error getting unread messages count in worker thread");
}
return msgCount;
}
// Listeners
public interface AfterSendMessageListener {
void onMessageSent(ApptentiveHttpResponse response, ApptentiveMessage apptentiveMessage);
void onPauseSending(int reason);
void onResumeSending();
}
public interface OnNewIncomingMessagesListener {
void onNewMessageReceived(final CompoundMessage apptentiveMsg);
}
public void setAfterSendMessageListener(AfterSendMessageListener listener) {
if (listener != null) {
afterSendMessageListener = new WeakReference<AfterSendMessageListener>(listener);
} else {
afterSendMessageListener = null;
}
}
public void addInternalOnMessagesUpdatedListener(OnNewIncomingMessagesListener newlistener) {
if (newlistener != null) {
init();
for (Iterator<WeakReference<OnNewIncomingMessagesListener>> iterator = internalNewMessagesListeners.iterator(); iterator.hasNext(); ) {
WeakReference<OnNewIncomingMessagesListener> listenerRef = iterator.next();
OnNewIncomingMessagesListener listener = listenerRef.get();
if (listener != null && listener == newlistener) {
return;
} else if (listener == null) {
iterator.remove();
}
}
internalNewMessagesListeners.add(new WeakReference<>(newlistener));
}
}
public void clearInternalOnMessagesUpdatedListeners() {
internalNewMessagesListeners.clear();
}
public void notifyInternalNewMessagesListeners(final CompoundMessage apptentiveMsg) {
for (WeakReference<OnNewIncomingMessagesListener> listenerRef : internalNewMessagesListeners) {
OnNewIncomingMessagesListener listener = listenerRef.get();
if (listener != null) {
listener.onNewMessageReceived(apptentiveMsg);
}
}
}
@Deprecated
public void setHostUnreadMessagesListener(UnreadMessagesListener listener) {
clearHostUnreadMessagesListeners();
if (listener != null) {
hostUnreadMessagesListeners.add(new WeakReference<>(listener));
}
}
public void addHostUnreadMessagesListener(UnreadMessagesListener newListener) {
if (newListener != null) {
// Defer message polling thread creation, if not created yet, and host app adds an unread message listener
init();
for (Iterator<WeakReference<UnreadMessagesListener>> iterator = hostUnreadMessagesListeners.iterator(); iterator.hasNext(); ) {
WeakReference<UnreadMessagesListener> listenerRef = iterator.next();
UnreadMessagesListener listener = listenerRef.get();
if (listener != null && listener == newListener) {
return;
} else if (listener == null) {
iterator.remove();
}
}
hostUnreadMessagesListeners.add(new WeakReference<>(newListener));
}
}
public void clearHostUnreadMessagesListeners() {
hostUnreadMessagesListeners.clear();
}
public void notifyHostUnreadMessagesListeners(int unreadMessages) {
for (WeakReference<UnreadMessagesListener> listenerRef : hostUnreadMessagesListeners) {
UnreadMessagesListener listener = listenerRef.get();
if (listener != null) {
listener.onUnreadMessageCountChanged(unreadMessages);
}
}
}
// Set when Activity.onStart() and onStop() are called
public void setCurrentForegroundActivity(Activity activity) {
if (activity != null) {
currentForegroundApptentiveActivity = new WeakReference<Activity>(activity);
} else {
ApptentiveToastNotificationManager manager = ApptentiveToastNotificationManager.getInstance(null, false);
if (manager != null) {
manager.cleanUp();
}
currentForegroundApptentiveActivity = null;
}
}
public void setMessageCenterInForeground(boolean bInForeground) {
pollingWorker.setMessageCenterInForeground(bInForeground);
}
public boolean isMessageCenterInForeground() {
return pollingWorker.messageCenterInForeground.get();
}
private void showUnreadMessageToastNotification(final CompoundMessage apptentiveMsg) {
if (currentForegroundApptentiveActivity != null && currentForegroundApptentiveActivity.get() != null) {
Activity foreground = currentForegroundApptentiveActivity.get();
if (foreground != null) {
PendingIntent pendingIntent = ApptentiveInternal.prepareMessageCenterPendingIntent(foreground.getApplicationContext());
if (pendingIntent != null) {
final ApptentiveToastNotificationManager manager = ApptentiveToastNotificationManager.getInstance(foreground, true);
final ApptentiveToastNotification.Builder builder = new ApptentiveToastNotification.Builder(foreground);
builder.setContentTitle(foreground.getResources().getString(R.string.apptentive_message_center_title))
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
.setSmallIcon(R.drawable.avatar).setContentText(apptentiveMsg.getBody())
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, false);
foreground.runOnUiThread(new Runnable() {
public void run() {
ApptentiveToastNotification notification = builder.buildApptentiveToastNotification();
notification.setAvatarUrl(apptentiveMsg.getSenderProfilePhoto());
manager.notify(TOAST_TYPE_UNREAD_MESSAGE, notification);
}
}
);
}
}
}
}
public void appWentToForeground() {
appInForeground.set(true);
if (pollingWorker != null) {
pollingWorker.appWentToForeground();
}
}
public void appWentToBackground() {
appInForeground.set(false);
if (pollingWorker != null) {
pollingWorker.appWentToBackground();
}
}
//region Message Dispatch Task
private abstract static class MessageDispatchTask extends DispatchTask
{
private CompoundMessage message;
protected abstract void execute(CompoundMessage message);
@Override
protected void execute() {
try {
execute(message);
} finally {
message = null;
}
}
MessageDispatchTask setMessage(CompoundMessage message) {
this.message = message;
return this;
}
}
private abstract static class MessageCountDispatchTask extends DispatchTask
{
private int messageCount;
protected abstract void execute(int messageCount);
@Override
protected void execute() {
execute(messageCount);
}
MessageCountDispatchTask setMessageCount(int messageCount) {
this.messageCount = messageCount;
return this;
}
}
//endregion
}
|
package org.ovirt.engine.core.bll;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.ovirt.engine.core.dal.VdcBllMessages.NETWORK_BOND_PARAMETERS_INVALID;
import static org.ovirt.engine.core.dal.VdcBllMessages.NETWORK_INTERFACE_NAME_ALREADY_IN_USE;
import static org.ovirt.engine.core.dal.VdcBllMessages.NETWORK_INTERFACE_NOT_EXISTS;
import static org.ovirt.engine.core.dal.VdcBllMessages.NETWROK_ALREADY_ATTACHED_TO_INTERFACE;
import static org.ovirt.engine.core.dal.VdcBllMessages.NETWROK_NOT_EXISTS;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.ovirt.engine.core.common.action.SetupNetworksParameters;
import org.ovirt.engine.core.common.businessentities.Entities;
import org.ovirt.engine.core.common.businessentities.VdsNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.NetworkUtils;
public class SetupNetworksHelper {
private SetupNetworksParameters params;
private List<network> clusterNetworks;
private List<VdcBllMessages> violations = new ArrayList<VdcBllMessages>();
private List<VdsNetworkInterface> vdsInterfaces;
private List<network> networks;
private List<network> removeNetworks;
private List<VdsNetworkInterface> bonds;
private List<VdsNetworkInterface> removedBonds;
public SetupNetworksHelper(SetupNetworksParameters parameters, Guid vdsGroupId) {
params = parameters;
clusterNetworks = DbFacade.getInstance().getNetworkDAO().getAllForCluster(vdsGroupId);
vdsInterfaces = DbFacade.getInstance().getInterfaceDAO().getAllInterfacesForVds(params.getVdsId());
}
/**
* validate and extract data from the list of interfaces sent. The general flow is:
* <ul>
* <li>create mapping of existing the current topology - interfaces and logical networks.
* <li>create maps for networks bonds and bonds-slaves.
* <li>iterate over the interfaces and extract network/bond/slave info as we go.
* <li>validate the extracted information by using the pre-build mappings of the current topology.
* <li>store and encapsulate the extracted lists to later be fetched by the calling command.
* <li>error messages are aggregated
* </ul>
* TODO add fail-fast to exist on the first validation error.
*
* @return
*/
public List<VdcBllMessages> validate() {
Set<String> ifaceNames = new HashSet<String>();
Map<String, VdsNetworkInterface> existingIfaces = Entities.entitiesByName(vdsInterfaces);
Map<String, network> clusterNetworksMap = Entities.entitiesByName(clusterNetworks);
// key = bond name, value = interface
Map<String, VdsNetworkInterface> bonds = new HashMap<String, VdsNetworkInterface>();
// key = master bond name, value = list of interfaces
Map<String, List<VdsNetworkInterface>> bondSlaves = new HashMap<String, List<VdsNetworkInterface>>();
// key = network name, vale = interface
Map<String, network> networks = new HashMap<String, network>();
for (VdsNetworkInterface iface : params.getInterfaces()) {
String name = iface.getName();
String networkName = iface.getNetworkName();
String bondName = iface.getBondName();
boolean bonded = isBond(iface);
if (ifaceNames.contains(name)) {
violations.add(NETWORK_INTERFACE_NAME_ALREADY_IN_USE);
continue;
} else {
ifaceNames.add(name);
}
// if its a bond extract to bonds map
if (bonded) {
extractBond(bonds, iface, name);
} else {
if (isNotBlank(bondName)) {
extractBondSlave(bondSlaves, iface, bondName);
}
// validate the nic exists on host
if (!existingIfaces.containsKey(NetworkUtils.StripVlan(name))) {
violations.add(NETWORK_INTERFACE_NOT_EXISTS);
}
}
// validate and extract to network map
if (isNotBlank(networkName)) {
extractNetwork(clusterNetworksMap, networks, iface, networkName);
}
}
validateBonds(bonds, bondSlaves);
this.networks = new ArrayList<network>(networks.values());
this.removeNetworks =
extractRemoveNetworks(networks.keySet(),
clusterNetworksMap,
getExisitingHostNetworkNames(existingIfaces));
this.bonds = new ArrayList<VdsNetworkInterface>(bonds.values());
this.removedBonds = extractRemovedBonds(bonds, existingIfaces);
return violations;
}
private List<String> getExisitingHostNetworkNames(Map<String, VdsNetworkInterface> existingIfaces) {
List<String> list = new ArrayList<String>(existingIfaces.size());
for (VdsNetworkInterface iface : existingIfaces.values()) {
if (isNotBlank(iface.getNetworkName())) {
list.add(iface.getNetworkName());
}
}
return list;
}
/**
* extracting a network is done by matching the desired network name with the network details from db on
* clusterNetworksMap. The desired network is just a key and actual network configuration is taken from the db
* entity.
*
* @param clusterNetworksMap
* map of the stored network names -> network
* @param networks
* map of aggregated networks to add
* @param iface
* current iterated interface
* @param networkName
* the current network name of iface
*/
public void extractNetwork(Map<String, network> clusterNetworksMap,
Map<String, network> networks,
VdsNetworkInterface iface,
String networkName) {
List<String> networksOverBond = new ArrayList<String>();
// check if network exists on cluster
if (clusterNetworksMap.containsKey(networkName)) {
// prevent attaching 2 interfaces to 1 network
if (networks.containsKey(networkName) && networksOverBond.contains(networkName) && isBond(iface)) {
violations.add(NETWROK_ALREADY_ATTACHED_TO_INTERFACE);
} else {
networks.put(networkName, clusterNetworksMap.get(networkName));
if (isBond(iface)) {
networksOverBond.add(networkName);
}
}
} else {
violations.add(VdcBllMessages.NETWORK_NOT_EXISTS_IN_CURRENT_CLUSTER);
}
}
private boolean isBond(VdsNetworkInterface iface) {
return Boolean.TRUE.equals(iface.getBonded());
}
/**
* build mapping of the bond name - > list of slaves. slaves are interfaces with a pointer to the master bond by
* bondName.
* @param bondSlaves
* @param iface
* @param bondName
*/
public void extractBondSlave(Map<String, List<VdsNetworkInterface>> bondSlaves,
VdsNetworkInterface iface,
String bondName) {
List<VdsNetworkInterface> value = new ArrayList<VdsNetworkInterface>();
value.add(iface);
if (bondSlaves.containsKey(bondName)) {
value.addAll(bondSlaves.get(bondName));
}
bondSlaves.put(bondName, value);
}
public void extractBond(Map<String, VdsNetworkInterface> bonds, VdsNetworkInterface iface, String name) {
if (isBlank(iface.getNetworkName())) {
violations.add(NETWROK_NOT_EXISTS);
} else {
if (bonds.containsKey(name)) {
violations.add(VdcBllMessages.NETWORK_BOND_NAME_EXISTS);
} else {
bonds.put(name, iface);
}
}
}
public List<VdsNetworkInterface> extractRemovedBonds(Map<String, VdsNetworkInterface> bonds,
Map<String, VdsNetworkInterface> existingIfaces) {
List<VdsNetworkInterface> removedBonds = new ArrayList<VdsNetworkInterface>();
for (Entry<String, VdsNetworkInterface> e : existingIfaces.entrySet()) {
if (isBond(e.getValue())) {
if (!bonds.containsKey(e.getKey())) {
removedBonds.add(e.getValue());
}
}
}
return removedBonds;
}
public boolean validateBonds(Map<String, VdsNetworkInterface> bonds,
Map<String, List<VdsNetworkInterface>> bondSlaves) {
boolean returnValue = true;
for (String bondName : bonds.keySet()) {
if (bondSlaves.containsKey(bondName)) {
if (bondSlaves.get(bondName).size() < 2) {
returnValue = false;
violations.add(NETWORK_BOND_PARAMETERS_INVALID);
}
}
}
return returnValue;
}
public List<network> extractRemoveNetworks(Set<String> networkNames,
Map<String, network> clusterNetworksMap,
List<String> exisitingHostNetworksNames) {
Map<String, network> removedNetworks = new HashMap<String, network>(clusterNetworksMap);
for (String name : networkNames) {
removedNetworks.remove(name);
}
// exclude networks which already the host anyway doesn't have
for (Iterator<Entry<String, network>> iterator = removedNetworks.entrySet().iterator(); iterator.hasNext();) {
Entry<String, network> entry = iterator.next();
if (!exisitingHostNetworksNames.contains(entry.getKey())) {
iterator.remove();
}
}
return new ArrayList<network>(removedNetworks.values());
}
public List<VdcBllMessages> getViolations() {
return violations;
}
public List<network> getNetworks() {
return networks;
}
public List<network> getRemoveNetworks() {
return removeNetworks;
}
public List<VdsNetworkInterface> getBonds() {
return bonds;
}
public List<VdsNetworkInterface> getRemovedBonds() {
return removedBonds;
}
}
|
package org.biojava.bio.structure.align.gui.jmol;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JComboBox;
import org.biojava.bio.structure.Atom;
import org.biojava.bio.structure.Group;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureTools;
import org.biojava.bio.structure.align.ce.AbstractUserArgumentProcessor;
import org.biojava.bio.structure.align.gui.JPrintPanel;
import org.biojava.bio.structure.align.gui.jmol.MyJmolStatusListener;
import org.biojava.bio.structure.domain.ProteinDomainParser;
import org.biojava.bio.structure.domain.pdp.Domain;
import org.biojava.bio.structure.domain.pdp.Segment;
import org.biojava.bio.structure.gui.util.color.ColorUtils;
import org.biojava.bio.structure.scop.ScopDatabase;
import org.biojava.bio.structure.scop.ScopDomain;
import org.biojava.bio.structure.scop.ScopInstallation;
import org.jmol.adapter.smarter.SmarterJmolAdapter;
import org.jmol.api.JmolAdapter;
import org.jmol.api.JmolStatusListener;
import org.jmol.api.JmolViewer;
public class JmolPanel
extends JPrintPanel
implements ActionListener
{
private static final long serialVersionUID = -3661941083797644242L;
private JmolViewer viewer;
private JmolAdapter adapter;
JmolStatusListener statusListener;
final Dimension currentSize = new Dimension();
final Rectangle rectClip = new Rectangle();
Structure structure;
public JmolPanel() {
super();
statusListener = new MyJmolStatusListener();
adapter = new SmarterJmolAdapter();
viewer = JmolViewer.allocateViewer(this,
adapter,
null,null,null,null,
statusListener);
}
public void paint(Graphics g) {
getSize(currentSize);
g.getClipBounds(rectClip);
viewer.renderScreenImage(g, currentSize, rectClip);
}
public void evalString(String rasmolScript){
viewer.evalString(rasmolScript);
}
public void openStringInline(String pdbFile){
viewer.openStringInline(pdbFile);
}
public JmolViewer getViewer() {
return viewer;
}
public JmolAdapter getAdapter(){
return adapter;
}
public JmolStatusListener getStatusListener(){
return statusListener;
}
public void executeCmd(String rasmolScript) {
viewer.evalString(rasmolScript);
}
public void setStructure(Structure s)
{
this.structure = s;
String pdb = s.toPDB();
viewer.openStringInline(pdb);
evalString("save STATE state_1");
}
/** assign a custom color to the Jmol chains command.
*
*/
public void jmolColorByChain(){
String script =
"function color_by_chain(objtype, color_list) {"+ String.format("%n") +
""+ String.format("%n") +
" if (color_list) {"+ String.format("%n") +
" if (color_list.type == \"string\") {"+ String.format("%n") +
" color_list = color_list.split(\",\").trim();"+ String.format("%n") +
" }"+ String.format("%n") +
" } else {"+ String.format("%n") +
" color_list = [\"104BA9\",\"AA00A2\",\"C9F600\",\"FFA200\",\"284A7E\",\"7F207B\",\"9FB82E\",\"BF8B30\",\"052D6E\",\"6E0069\",\"83A000\",\"A66A00\",\"447BD4\",\"D435CD\",\"D8FA3F\",\"FFBA40\",\"6A93D4\",\"D460CF\",\"E1FA71\",\"FFCC73\"];"+ String.format("%n") +
" }"+ String.format("%n") +
" var cmd2 = \"\";"+ String.format("%n") +
" if (!objtype) {"+ String.format("%n") +
" var type_list = [ \"backbone\",\"cartoon\",\"dots\",\"halo\",\"label\",\"meshribbon\",\"polyhedra\",\"rocket\",\"star\",\"strand\",\"strut\",\"trace\"];"+ String.format("%n") +
" cmd2 = \"color \" + type_list.join(\" none; color \") + \" none;\";"+ String.format("%n") +
" objtype = \"atoms\";"+ String.format("%n") +
" }"+ String.format("%n") +
" var chain_list = script(\"show chain\").trim().lines;"+ String.format("%n") +
" var chain_count = chain_list.length;"+ String.format("%n") +
" var color_count = color_list.length;"+ String.format("%n") +
" var sel = {selected};"+ String.format("%n") +
" var cmds = \"\";"+ String.format("%n") +
" for (var chain_number=1; chain_number<=chain_count; chain_number++) {"+ String.format("%n") +
" // remember, Jmol arrays start with 1, but % can return 0"+ String.format("%n") +
" cmds += \"select sel and :\" + chain_list[chain_number] + \";color \" + objtype + \" [x\" + color_list[(chain_number-1) % color_count + 1] + \"];\" + cmd2;"+ String.format("%n") +
" }"+ String.format("%n") +
" script INLINE @{cmds + \"select sel\"}"+ String.format("%n") +
"}";
executeCmd(script);
}
/** The user selected one of the Combo boxes...
*
* @param event an ActionEvent
*/
public void actionPerformed(ActionEvent event) {
JComboBox source = (JComboBox) event.getSource();
String value = source.getSelectedItem().toString();
String selectLigand = "select ligand;wireframe 0.16;spacefill 0.5; color cpk ;";
if ( value.equals("Cartoon")){
String script = "hide null; select all; spacefill off; wireframe off; backbone off;" +
" cartoon on; " +
" select ligand; wireframe 0.16;spacefill 0.5; color cpk; " +
" select *.FE; spacefill 0.7; color cpk ; " +
" select *.CU; spacefill 0.7; color cpk ; " +
" select *.ZN; spacefill 0.7; color cpk ; " +
" select all; ";
this.executeCmd(script);
} else if (value.equals("Backbone")){
String script = "hide null; select all; spacefill off; wireframe off; backbone 0.4;" +
" cartoon off; " +
" select ligand; wireframe 0.16;spacefill 0.5; color cpk; " +
" select *.FE; spacefill 0.7; color cpk ; " +
" select *.CU; spacefill 0.7; color cpk ; " +
" select *.ZN; spacefill 0.7; color cpk ; " +
" select all; ";
this.executeCmd(script);
} else if (value.equals("CPK")){
String script = "hide null; select all; spacefill off; wireframe off; backbone off;" +
" cartoon off; cpk on;" +
" select ligand; wireframe 0.16;spacefill 0.5; color cpk; " +
" select *.FE; spacefill 0.7; color cpk ; " +
" select *.CU; spacefill 0.7; color cpk ; " +
" select *.ZN; spacefill 0.7; color cpk ; " +
" select all; ";
this.executeCmd(script);
} else if (value.equals("Ligands")){
this.executeCmd("restrict ligand; cartoon off; wireframe on; display selected;");
} else if (value.equals("Ligands and Pocket")){
this.executeCmd(" select within (6.0,ligand); cartoon off; wireframe on; backbone off; display selected; ");
} else if ( value.equals("Ball and Stick")){
String script = "hide null; restrict not water; wireframe 0.2; spacefill 25%;" +
" cartoon off; backbone off; " +
" select ligand; wireframe 0.16; spacefill 0.5; color cpk; " +
" select *.FE; spacefill 0.7; color cpk ; " +
" select *.CU; spacefill 0.7; color cpk ; " +
" select *.ZN; spacefill 0.7; color cpk ; " +
" select all; ";
this.executeCmd(script);
} else if ( value.equals("By Chain")){
jmolColorByChain();
String script = "hide null; select all;set defaultColors Jmol; color_by_chain(\"cartoon\"); color_by_chain(\"\"); " + selectLigand + "; select all; ";
this.executeCmd(script);
} else if ( value.equals("Rainbow")) {
this.executeCmd("hide null; select all; set defaultColors Jmol; color group; color cartoon group; " + selectLigand + "; select all; " );
} else if ( value.equals("Secondary Structure")){
this.executeCmd("hide null; select all; set defaultColors Jmol; color structure; color cartoon structure;" + selectLigand + "; select all; " );
} else if ( value.equals("By Element")){
this.executeCmd("hide null; select all; set defaultColors Jmol; color cpk; color cartoon cpk; " + selectLigand + "; select all; ");
} else if ( value.equals("By Amino Acid")){
this.executeCmd("hide null; select all; set defaultColors Jmol; color amino; color cartoon amino; " + selectLigand + "; select all; " );
} else if ( value.equals("Hydrophobicity") ){
this.executeCmd("hide null; set defaultColors Jmol; select hydrophobic; color red; color cartoon red; select not hydrophobic ; color blue ; color cartoon blue; "+ selectLigand+"; select all; ");
} else if ( value.equals("Suggest Domains")){
colorByPDP();
} else if ( value.equals("Show SCOP Domains")){
colorBySCOP();
}
}
private void colorBySCOP() {
if ( structure == null)
return;
String pdbId = structure.getPDBCode();
if ( pdbId == null)
return;
String pdbLocation = System.getProperty(AbstractUserArgumentProcessor.PDB_DIR);
ScopDatabase scop = new ScopInstallation(pdbLocation);
List<ScopDomain> domains = scop.getDomainsForPDB(pdbId);
if ( domains == null) {
System.err.println("No SCOP domains found for " + pdbId);
return;
}
int i = -1;
for ( ScopDomain domain : domains){
i++;
if ( i >= ColorUtils.colorWheel.length)
i = 0;
Color c1 = ColorUtils.colorWheel[i];
List<String>ranges = domain.getRanges();
for (String range : ranges){
System.out.println(range);
String[] spl = range.split(":");
String script = " select ";
if ( spl.length > 1 )
script += spl[1]+":"+spl[0] +"/1;";
else
script += "*" + spl[0]+"/1;";
script += " color [" + c1.getRed() + ","+c1.getGreen() + "," +c1.getBlue()+"];";
script += " color cartoon [" + c1.getRed() + ","+c1.getGreen() + "," +c1.getBlue()+"] ;";
System.out.println(script);
evalString(script);
}
}
}
private void colorByPDP() {
System.out.println("colorByPDP");
if ( structure == null)
return;
try {
Atom[] ca = StructureTools.getAtomCAArray(structure);
List<Domain> domains = ProteinDomainParser.suggestDomains(ca);
int i = -1;
for ( Domain dom : domains){
i++;
if ( i > ColorUtils.colorWheel.length)
i = 0;
//System.out.println("DOMAIN:" + i + " size:" + dom.size + " " + dom.score);
List<Segment> segments = dom.getSegments();
Color c1 = ColorUtils.colorWheel[i];
float fraction = 0f;
for ( Segment s : segments){
//System.out.println(" Segment: " + s);
//Color c1 = ColorUtils.rotateHue(c, fraction);
fraction += 1.0/(float)segments.size();
int start = s.from;
int end = s.to;
Group startG = ca[start].getGroup();
Group endG = ca[end].getGroup();
System.out.println(" Segment: " +startG.getResidueNumber() +":" + startG.getChainId() + " - " + endG.getResidueNumber()+":"+endG.getChainId() + " " + s);
String j1 = startG.getResidueNumber()+"";
String j2 = endG.getResidueNumber()+":"+endG.getChainId();
String script = " select " +j1 +"-" +j2 +"/1;";
script += " color [" + c1.getRed() + ","+c1.getGreen() + "," +c1.getBlue()+"];";
script += " color cartoon [" + c1.getRed() + ","+c1.getGreen() + "," +c1.getBlue()+"] ;";
//System.out.println(script);
evalString(script);
}
}
} catch (Exception e){
e.printStackTrace();
}
}
}
|
package gov.nih.nci.cabig.caaers.api.impl;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.api.AbstractImportService;
import gov.nih.nci.cabig.caaers.api.ProcessingOutcome;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.dao.query.StudyQuery;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.domain.repository.StudyRepository;
import gov.nih.nci.cabig.caaers.integration.schema.common.CaaersServiceResponse;
import gov.nih.nci.cabig.caaers.integration.schema.common.OrganizationType;
import gov.nih.nci.cabig.caaers.integration.schema.common.ServiceResponse;
import gov.nih.nci.cabig.caaers.integration.schema.study.Studies;
import gov.nih.nci.cabig.caaers.integration.schema.study.StudySiteType;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome.Message;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome.Severity;
import gov.nih.nci.cabig.caaers.service.StudyImportServiceImpl;
import gov.nih.nci.cabig.caaers.service.migrator.OrganizationConverter;
import gov.nih.nci.cabig.caaers.service.migrator.StudyConverter;
import gov.nih.nci.cabig.caaers.service.synchronizer.StudySynchronizer;
import gov.nih.nci.cabig.caaers.validation.validator.DomainObjectValidator;
import gov.nih.nci.security.util.StringUtilities;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* The implementation will manage (create/update) {@link Study}
* @author Monish Dombla
* @author Biju Joseph
* @author Ion C. Olaru
*/
public class StudyProcessorImpl extends AbstractImportService implements ApplicationContextAware,MessageSourceAware {
private static Log logger = LogFactory.getLog(StudyProcessorImpl.class);
//Injected through spring
private StudyImportServiceImpl studyImportService;
private StudyDao studyDao;
private StudyRepository studyRepository;
private StudyConverter studyConverter;
private StudySynchronizer studySynchronizer;
private ApplicationContext applicationContext;
private DomainObjectValidator domainObjectValidator;
private MessageSource messageSource;
private OrganizationManagementServiceImpl oms;
private OrganizationConverter organizationConverter;
public StudyProcessorImpl() {
}
public StudyImportServiceImpl getStudyImportService() {
return studyImportService;
}
public void setStudyImportService(StudyImportServiceImpl studyImportService) {
this.studyImportService = studyImportService;
}
public StudyDao getStudyDao() {
return studyDao;
}
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
public StudyConverter getStudyConverter() {
return studyConverter;
}
public void setStudyConverter(StudyConverter studyConverter) {
this.studyConverter = studyConverter;
}
public StudySynchronizer getStudySynchronizer() {
return studySynchronizer;
}
public void setStudySynchronizer(StudySynchronizer studySynchronizer) {
this.studySynchronizer = studySynchronizer;
}
/**
* Method exisits only to be called from ImportController
* @param studyDto
*/
public DomainObjectImportOutcome<Study> importStudy(gov.nih.nci.cabig.caaers.integration.schema.study.Study studyDto) {
logger.info("Entering processStudy() in StudyProcessorImpl");
DomainObjectImportOutcome<Study> studyImportOutcome = null;
Study study = new LocalStudy();
//Convert JAXB StudyType to Domain Study
try{
studyConverter.convertStudyDtoToStudyDomain(studyDto, study);
logger.info("StudyDto converted to Study");
}catch(CaaersSystemException caEX){
studyImportOutcome = new DomainObjectImportOutcome<Study>();
logger.error("StudyDto to StudyDomain Conversion Failed " , caEX);
studyImportOutcome.addErrorMessage("StudyDto to StudyDomain Conversion Failed " , DomainObjectImportOutcome.Severity.ERROR);
}
if(studyImportOutcome == null){
studyImportOutcome = studyImportService.importStudy(study);
if(studyImportOutcome.isSavable()){
//Check if Study Exists; If Exists then update
Study dbStudy = fetchStudy(studyImportOutcome.getImportedDomainObject());
if(dbStudy != null){
logger.info("Study with Long Title -- "+ dbStudy.getLongTitle() + " -- Exists in caAERS trying to Update");
studySynchronizer.migrate(dbStudy, studyImportOutcome.getImportedDomainObject(), studyImportOutcome);
studyImportOutcome.setImportedDomainObject(dbStudy);
logger.info("Study "+ dbStudy.getLongTitle() + " in caAERS Updated");
}else{
logger.info("New Study with Long Title -- "+ studyImportOutcome.getImportedDomainObject().getLongTitle() + " -- being Created");
}
}
}
return studyImportOutcome;
}
private List<Organization> searchForOrganization(OrganizationType org) {
if (!StringUtilities.isBlank(org.getNciInstituteCode())) {
return getAuthorizedOrganizationsByNameOrNciId(null, org.getNciInstituteCode());
} else {
return getAuthorizedOrganizationsByNameOrNciId(org.getName(), null);
}
}
private String checkAuthorizedOrganizations(gov.nih.nci.cabig.caaers.integration.schema.study.Study studyDto) {
List<OrganizationType> orgs = new ArrayList<OrganizationType>();
orgs.add(studyDto.getCoordinatingCenter().getStudyCoordinatingCenter().getOrganization());
orgs.add(studyDto.getFundingSponsor().getStudyFundingSponsor().getOrganization());
gov.nih.nci.cabig.caaers.integration.schema.study.Study.StudyOrganizations so = studyDto.getStudyOrganizations();
if (so != null) {
for (StudySiteType sst: so.getStudySite()) {
orgs.add(sst.getOrganization());
}
}
// ToDo Code that persists the new organization should be moved to StudyOrganizationMigrator class
for (OrganizationType org:orgs) {
List foundOrgs = searchForOrganization(org);
if (foundOrgs.size() < 1) {
// Persist the organization
Organization domainOrganization = new LocalOrganization();
organizationConverter.convertOrganizationDtoToDomainOrganization(org, domainOrganization);
oms.createOrUpdateOrganization(domainOrganization);
// return messageSource.getMessage("WS_AEMS_028", new String[]{org.getNciInstituteCode() + " : " + org.getName()}, "", Locale.getDefault());
}
}
return "ALL_ORGS_AUTH";
}
public CaaersServiceResponse createOrUpdate(gov.nih.nci.cabig.caaers.integration.schema.study.Studies xmlStudies) {
gov.nih.nci.cabig.caaers.integration.schema.study.Study studyDto = xmlStudies.getStudy().get(0);
CaaersServiceResponse caaersServiceResponse = Helper.createResponse();
// ToDo Merge createStudy & updateStudy into this method
return caaersServiceResponse;
}
public CaaersServiceResponse createStudy(gov.nih.nci.cabig.caaers.integration.schema.study.Studies xmlStudies) {
gov.nih.nci.cabig.caaers.integration.schema.study.Study studyDto = xmlStudies.getStudy().get(0);
CaaersServiceResponse caaersServiceResponse = Helper.createResponse();
logger.info("Study Short Title: " + studyDto.getShortTitle());
logger.info("Study Long Title:" + studyDto.getLongTitle());
String errorMsg = checkAuthorizedOrganizations(studyDto);
if (!errorMsg.equals("ALL_ORGS_AUTH")) {
return Helper.populateError(caaersServiceResponse, "WS_AEMS_028", errorMsg);
}
DomainObjectImportOutcome<Study> studyImportOutcome = null;
Study study = new LocalStudy();
//Convert JAXB StudyType to Domain Study
try {
logger.info("Converting StudyDto to Study");
studyConverter.convertStudyDtoToStudyDomain(studyDto, study);
logger.info("StudyDto converted to Study");
} catch (CaaersSystemException caEX) {
studyImportOutcome = new DomainObjectImportOutcome<Study>();
logger.error("StudyDto to StudyDomain Conversion Failed ", caEX);
studyImportOutcome.addErrorMessage("StudyDto to StudyDomain Conversion Failed ", DomainObjectImportOutcome.Severity.ERROR);
Helper.populateError(caaersServiceResponse, "WS_GEN_000", "StudyDto to StudyDomain Conversion Failed");
}
if(studyImportOutcome == null){
studyImportOutcome = studyImportService.importStudy(study);
//Check if Study Exists
Study dbStudy = checkDuplicateStudy(studyImportOutcome.getImportedDomainObject());
if(dbStudy != null){
studyImportOutcome.addErrorMessage(study.getClass().getSimpleName() + " identifier already exists. ", Severity.ERROR);
Helper.populateError(caaersServiceResponse, "WS_STU_001", messageSource.getMessage("WS_STU_001", new Object[]{dbStudy.getShortTitle(),
studyImportOutcome.getImportedDomainObject().getShortTitle()}, "Another study is using the identifier provided", Locale.getDefault()));
}else{
List<String> errors = domainObjectValidator.validate(studyImportOutcome.getImportedDomainObject());
if(studyImportOutcome.isSavable() && errors.size() == 0){
try {
Study theStudy = studyImportOutcome.getImportedDomainObject();
studyRepository.synchronizeStudyPersonnel(theStudy);
studyRepository.save(theStudy);
ProcessingOutcome processingOutcome = Helper.createOutcome(Study.class, theStudy.getFundingSponsorIdentifierValue(),
String.valueOf(theStudy.getId()), false,"Study with Short Title \""
+ theStudy.getShortTitle()
+ "\" Created in caAERS" ) ;
Helper.populateProcessingOutcome(caaersServiceResponse, processingOutcome);
Helper.populateMessage(caaersServiceResponse, "Study with Short Title \""
+ theStudy.getShortTitle()
+ "\" Created in caAERS");
logger.info("Study Created");
} catch (Exception e) {
Helper.populateError(caaersServiceResponse, "WS_GEN_000", "Study Creation Failed " + e.getMessage());
logger.error("Error processing study : " + e.getMessage(), e);
}
}else{
for(String errMsg : errors){
studyImportOutcome.addErrorMessage(errMsg, Severity.ERROR);
}
List<String> messages = new ArrayList<String>();
for(Message message : studyImportOutcome.getMessages()){
messages.add(message.getMessage());
}
for(String errMsg : errors){
messages.add(errMsg);
}
String msg = "Study with Short Title \"" + studyImportOutcome.getImportedDomainObject().getShortTitle()+ "\" could not be created in caAERS. "
+ messages.toString();
String messageWithoutShortTitle = "Study could not be created in caAERS because " +messages.toString();
Helper.populateError(caaersServiceResponse, "WS_GEN_000", msg);
Helper.populateProcessingOutcome(caaersServiceResponse, Helper.createOutcome(Study.class,
studyImportOutcome.getImportedDomainObject().getFundingSponsorIdentifierValue(), true, messageWithoutShortTitle ));
logger.debug(">>> ERR:" + msg);
}
}
}
logger.info("Leaving createStudy() in StudyProcessorImpl");
return caaersServiceResponse;
}
@Transactional(readOnly = false)
public CaaersServiceResponse updateStudy(gov.nih.nci.cabig.caaers.integration.schema.study.Studies xmlStudies) {
gov.nih.nci.cabig.caaers.integration.schema.study.Study studyDto = xmlStudies.getStudy().get(0);
CaaersServiceResponse caaersServiceResponse = Helper.createResponse();
logger.info("Study Short Title --- " + studyDto.getShortTitle());
logger.info("Study Long Title --- " + studyDto.getLongTitle());
String errorMsg = checkAuthorizedOrganizations(studyDto);
if (!errorMsg.equals("ALL_ORGS_AUTH")) {
Helper.populateError(caaersServiceResponse, "WS_AEMS_028", errorMsg);
return caaersServiceResponse;
}
DomainObjectImportOutcome<Study> studyImportOutcome = null;
Study study = new LocalStudy();
//Convert JAXB StudyType to Domain Study
try {
studyConverter.convertStudyDtoToStudyDomain(studyDto, study);
logger.info("StudyDto converted to Study");
} catch (CaaersSystemException caEX) {
studyImportOutcome = new DomainObjectImportOutcome<Study>();
logger.error("StudyDto to StudyDomain Conversion Failed ", caEX);
studyImportOutcome.addErrorMessage("StudyDto to StudyDomain Conversion Failed ", DomainObjectImportOutcome.Severity.ERROR);
Helper.populateError(caaersServiceResponse, "WS_GEN_000", "StudyDto to StudyDomain Conversion Failed");
return caaersServiceResponse;
}
if (studyImportOutcome == null) {
studyImportOutcome = studyImportService.importStudy(study);
List<String> errors = domainObjectValidator.validate(studyImportOutcome.getImportedDomainObject());
if(studyImportOutcome.isSavable() && errors.size() == 0){
Study dbStudy = fetchStudy(studyImportOutcome.getImportedDomainObject());
if(dbStudy == null){
Helper.populateError(caaersServiceResponse, "WS_GEN_000", "Study with Short Title \""
+ studyImportOutcome.getImportedDomainObject().getShortTitle()
+ "\" does not exist in caAERS");
studyImportOutcome.addErrorMessage("Study with Short Title \""
+ studyImportOutcome.getImportedDomainObject().getShortTitle()
+ "\" does not exist in caAERS" , DomainObjectImportOutcome.Severity.ERROR);
return caaersServiceResponse;
}
studySynchronizer.migrate(dbStudy, studyImportOutcome.getImportedDomainObject(), studyImportOutcome);
studyImportOutcome.setImportedDomainObject(dbStudy);
//check if another study exist?
Study anotherStudy = checkDuplicateStudy(studyImportOutcome.getImportedDomainObject());
if(anotherStudy != null){
String errorDescription = messageSource.getMessage("WS_STU_001", new Object[]{anotherStudy.getShortTitle(),
studyImportOutcome.getImportedDomainObject().getShortTitle()},
"Another study is using the identifier provided", Locale.getDefault());
Helper.populateError(caaersServiceResponse, "WS_GEN_000", errorDescription);
studyImportOutcome.addErrorMessage(errorDescription, DomainObjectImportOutcome.Severity.ERROR);
return caaersServiceResponse;
}
try {
Study theStudy = studyImportOutcome.getImportedDomainObject();
studyRepository.synchronizeStudyPersonnel(theStudy);
studyRepository.save(theStudy);
ProcessingOutcome processingOutcome = Helper.createOutcome(Study.class, theStudy.getFundingSponsorIdentifierValue(),
String.valueOf(theStudy.getId()), false,"Study with Short Title \""
+ studyImportOutcome.getImportedDomainObject().getShortTitle()
+ "\" updated in caAERS" ) ;
Helper.populateProcessingOutcome(caaersServiceResponse, processingOutcome);
Helper.populateMessage(caaersServiceResponse, "Study with Short Title \""
+ studyImportOutcome.getImportedDomainObject().getShortTitle()
+ "\" updated in caAERS");
caaersServiceResponse.getServiceResponse().getResponsecode();
logger.info("Study Updated");
} catch (Exception e) {
logger.error("Error while saving the study :" + e.getMessage(), e);
String msg = "Cannot process study : " + e.getMessage();
Helper.populateError(caaersServiceResponse, "WS_GEN_000", msg);
Helper.populateProcessingOutcome(caaersServiceResponse, Helper.createOutcome(Study.class,
studyImportOutcome.getImportedDomainObject().getFundingSponsorIdentifierValue(), true, msg));
}
}else {
List<String> messages = new ArrayList<String>();
for(Message message : studyImportOutcome.getMessages()){
messages.add(message.getMessage());
}
for(String errMsg : errors){
messages.add(errMsg);
}
Helper.populateError(caaersServiceResponse, "WS_GEN_000", "Study with Short Title \""
+ studyImportOutcome.getImportedDomainObject().getShortTitle()
+ "\" could not be updated in caAERS. " + messages.toString());
}
}
logger.info("Leaving updateStudy() in StudyProcessor");
return caaersServiceResponse;
}
/**
* This method fetches a Study from the DB based identifiers.
* @param importedStudy
* @return
*/
private Study fetchStudy(Study importedStudy){
Study dbStudy = null;
for (Identifier identifier : importedStudy.getIdentifiers()) {
dbStudy = studyDao.getStudyDesignByIdentifier(identifier);
if(dbStudy != null){
break;
}
studyDao.evict(dbStudy);
}
return dbStudy;
}
/**
* Will retrieve from DB a study that is having the same identifier as that of the study parameter.
* @param study
* @return
*/
public Study checkDuplicateStudy(Study study){
for(Identifier id : study.getIdentifiers()){
StudyQuery query = new StudyQuery();
query.joinIdentifier();
query.filterByIdentifier(id);
if(study.getId() != null) query.ignoreStudyById(study.getId());
List<Study> existingStudies = studyDao.find(query);
if(CollectionUtils.isNotEmpty(existingStudies)){
return existingStudies.get(0);
}
}
return null;
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
public void setDomainObjectValidator(DomainObjectValidator domainObjectValidator) {
this.domainObjectValidator = domainObjectValidator;
}
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
public void setStudyRepository(StudyRepository studyRepository) {
this.studyRepository = studyRepository;
}
public OrganizationManagementServiceImpl getOrganizationManagementServiceImpl() {
return oms;
}
public void setOrganizationManagementServiceImpl(OrganizationManagementServiceImpl oms) {
this.oms = oms;
}
public OrganizationConverter getOrganizationConverter() {
return organizationConverter;
}
public void setOrganizationConverter(OrganizationConverter organizationConverter) {
this.organizationConverter = organizationConverter;
}
}
|
package com.badlogic.gdx.maps.tiled;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.zip.DataFormatException;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetLoaderParameters;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.SynchronousAssetLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.ImageResolver;
import com.badlogic.gdx.maps.ImageResolver.AssetManagerImageResolver;
import com.badlogic.gdx.maps.ImageResolver.DirectImageResolver;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.objects.EllipseMapObject;
import com.badlogic.gdx.maps.objects.PolygonMapObject;
import com.badlogic.gdx.maps.objects.PolylineMapObject;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile;
import com.badlogic.gdx.math.Polygon;
import com.badlogic.gdx.math.Polyline;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Base64Coder;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.XmlReader;
import com.badlogic.gdx.utils.XmlReader.Element;
/**
* @brief synchronous loader for TMX maps created with the Tiled tool
*/
public class TmxMapLoader extends SynchronousAssetLoader<TiledMap, TmxMapLoader.Parameters> {
public static class Parameters extends AssetLoaderParameters<TiledMap> {
/** Whether to load the map for a y-up coordinate system */
boolean yUp = true;
}
protected static final int FLAG_FLIP_HORIZONTALLY = 0x80000000;
protected static final int FLAG_FLIP_VERTICALLY = 0x40000000;
protected static final int FLAG_FLIP_DIAGONALLY = 0x20000000;
protected static final int MASK_CLEAR = 0xE0000000;
protected XmlReader xml = new XmlReader();
protected Element root;
protected boolean yUp;
protected int mapWidthInPixels;
protected int mapHeightInPixels;
public TmxMapLoader() {
super(new InternalFileHandleResolver());
}
/**
* Creates loader
*
* @param resolver
*/
public TmxMapLoader(FileHandleResolver resolver) {
super(resolver);
}
/**
* Loads the {@link TiledMap} from the given file. The file is
* resolved via the {@link FileHandleResolver} set in the constructor
* of this class. By default it will resolve to an internal file. The
* map will be loaded for a y-up coordinate system.
* @param fileName the filename
* @return the TiledMap
*/
public TiledMap load(String fileName) {
return load(fileName, true);
}
/**
* Loads the {@link TiledMap} from the given file. The file is
* resolved via the {@link FileHandleResolver} set in the constructor
* of this class. By default it will resolve to an internal file.
* @param fileName the filename
* @param yUp whether to load the map for a y-up coordinate system
* @return the TiledMap
*/
public TiledMap load(String fileName, boolean yUp) {
try {
this.yUp = yUp;
FileHandle tmxFile = resolve(fileName);
root = xml.parse(tmxFile);
ObjectMap<String, Texture> textures = new ObjectMap<String, Texture>();
for(FileHandle textureFile: loadTilesets(root, tmxFile)) {
textures.put(textureFile.path(), new Texture(textureFile));
}
DirectImageResolver imageResolver = new DirectImageResolver(textures);
TiledMap map = loadTilemap(root, tmxFile, imageResolver);
map.setOwnedTextures(textures.values().toArray());
return map;
} catch(IOException e) {
throw new GdxRuntimeException("Couldn't load tilemap '" + fileName + "'", e);
}
}
@Override
public TiledMap load(AssetManager assetManager, String fileName, Parameters parameter) {
FileHandle tmxFile = resolve(fileName);
if (parameter != null) {
yUp = parameter.yUp;
} else {
yUp = true;
}
try {
return loadTilemap(root, tmxFile, new AssetManagerImageResolver(assetManager));
} catch (Exception e) {
throw new GdxRuntimeException("Couldn't load tilemap '" + fileName + "'", e);
}
}
/**
* Retrieves TiledMap resource dependencies
*
* @param fileName
* @param parameter not used for now
* @return dependencies for the given .tmx file
*/
@Override
public Array<AssetDescriptor> getDependencies(String fileName, Parameters parameter) {
Array<AssetDescriptor> dependencies = new Array<AssetDescriptor>();
try {
FileHandle tmxFile = resolve(fileName);
root = xml.parse(tmxFile);
for(FileHandle image: loadTilesets(root, tmxFile)) {
dependencies.add(new AssetDescriptor(image.path(), Texture.class));
}
return dependencies;
} catch (IOException e) {
throw new GdxRuntimeException("Couldn't load tilemap '" + fileName + "'", e);
}
}
/**
* Loads the map data, given the XML root element and an {@link ImageResolver} used
* to return the tileset Textures
* @param root the XML root element
* @param tmxFile the Filehandle of the tmx file
* @param imageResolver the {@link ImageResolver}
* @return the {@link TiledMap}
*/
protected TiledMap loadTilemap(Element root, FileHandle tmxFile, ImageResolver imageResolver) {
TiledMap map = new TiledMap();
String mapOrientation = root.getAttribute("orientation", null);
int mapWidth = root.getIntAttribute("width", 0);
int mapHeight = root.getIntAttribute("height", 0);
int tileWidth = root.getIntAttribute("tilewidth", 0);
int tileHeight = root.getIntAttribute("tileheight", 0);
String mapBackgroundColor = root.getAttribute("backgroundcolor", null);
MapProperties mapProperties = map.getProperties();
if (mapOrientation != null) {
mapProperties.put("orientation", mapBackgroundColor);
}
mapProperties.put("width", mapWidth);
mapProperties.put("height", mapHeight);
mapProperties.put("tilewidth", tileWidth);
mapProperties.put("tileheight", tileHeight);
if (mapBackgroundColor != null) {
mapProperties.put("backgroundcolor", mapBackgroundColor);
}
mapWidthInPixels = mapWidth * tileWidth;
mapHeightInPixels = mapHeight * tileHeight;
Element properties = root.getChildByName("properties");
if (properties != null) {
loadProperties(map.getProperties(), properties);
}
Array<Element> tilesets = root.getChildrenByName("tileset");
for (Element element : tilesets) {
loadTileSet(map, element, tmxFile, imageResolver);
root.removeChild(element);
}
for (int i = 0, j = root.getChildCount(); i < j; i++) {
Element element = root.getChild(i);
String name = element.getName();
if (name.equals("layer")) {
loadTileLayer(map, element);
} else if (name.equals("objectgroup")) {
loadObjectGroup(map, element);
}
}
return map;
}
/**
* Loads the tilesets
* @param root the root XML element
* @return a list of filenames for images containing tiles
* @throws IOException
*/
protected Array<FileHandle> loadTilesets(Element root, FileHandle tmxFile) throws IOException {
Array<FileHandle> images = new Array<FileHandle>();
for (Element tileset : root.getChildrenByName("tileset")) {
String source = tileset.getAttribute("source", null);
FileHandle image = null;
if (source != null) {
FileHandle tsx = getRelativeFileHandle(tmxFile, source);
tileset = xml.parse(tsx);
String imageSource = tileset.getChildByName("image").getAttribute("source");
image = getRelativeFileHandle(tsx, imageSource);
} else {
String imageSource = tileset.getChildByName("image").getAttribute("source");
image = getRelativeFileHandle(tmxFile, imageSource);
}
images.add(image);
}
return images;
}
protected void loadTileSet(TiledMap map, Element element, FileHandle tmxFile, ImageResolver imageResolver) {
if (element.getName().equals("tileset")) {
String name = element.get("name", null);
int firstgid = element.getIntAttribute("firstgid", 1);
int tilewidth = element.getIntAttribute("tilewidth", 0);
int tileheight = element.getIntAttribute("tileheight", 0);
int spacing = element.getIntAttribute("spacing", 0);
int margin = element.getIntAttribute("margin", 0);
String source = element.getAttribute("source", null);
FileHandle image = null;
if (source != null) {
FileHandle tsx = getRelativeFileHandle(tmxFile, source);
try {
element = xml.parse(tsx);
name = element.get("name", null);
tilewidth = element.getIntAttribute("tilewidth", 0);
tileheight = element.getIntAttribute("tileheight", 0);
spacing = element.getIntAttribute("spacing", 0);
margin = element.getIntAttribute("margin", 0);
String imageSource = element.getChildByName("image").getAttribute("source");
image = getRelativeFileHandle(tsx, imageSource);
} catch (IOException e) {
throw new GdxRuntimeException("Error parsing external tileset.");
}
} else {
String imageSource = element.getChildByName("image").getAttribute("source");
image = getRelativeFileHandle(tmxFile, imageSource);
}
TextureRegion texture = imageResolver.getImage(image.path());
TiledMapTileSet tileset = new TiledMapTileSet();
tileset.setName(name);
int stopWidth = texture.getRegionWidth() - tilewidth;
int stopHeight = texture.getRegionHeight() - tileheight;
int id = firstgid;
for (int y = margin; y <= stopHeight; y += tileheight + spacing) {
for (int x = margin; x <= stopWidth; x += tilewidth + spacing) {
TextureRegion tileRegion = new TextureRegion(new TextureRegion(texture, x, y, tilewidth, tileheight));
if (!yUp) {
tileRegion.flip(false, true);
}
TiledMapTile tile = new StaticTiledMapTile(tileRegion);
tile.setId(id);
tileset.putTile(id++, tile);
}
}
Array<Element> tileElements = element.getChildrenByName("tile");
for (Element tileElement : tileElements) {
int localtid = tileElement.getIntAttribute("id", 0);
TiledMapTile tile = tileset.getTile(firstgid + localtid);
if (tile!= null) {
Element properties = tileElement.getChildByName("properties");
if (properties != null) {
loadProperties(tile.getProperties(), properties);
}
}
}
Element properties = element.getChildByName("properties");
if (properties != null) {
loadProperties(tileset.getProperties(), properties);
}
map.getTileSets().addTileSet(tileset);
}
}
protected void loadTileLayer(TiledMap map, Element element) {
if (element.getName().equals("layer")) {
String name = element.getAttribute("name", null);
int width = element.getIntAttribute("width", 0);
int height = element.getIntAttribute("height", 0);
int tileWidth = element.getParent().getIntAttribute("tilewidth", 0);
int tileHeight = element.getParent().getIntAttribute("tileheight", 0);
boolean visible = element.getIntAttribute("visible", 1) == 1;
float opacity = element.getFloatAttribute("opacity", 1.0f);
TiledMapTileLayer layer = new TiledMapTileLayer(width, height, tileWidth, tileHeight);
layer.setVisible(visible);
layer.setOpacity(opacity);
layer.setName(name);
TiledMapTileSets tilesets = map.getTileSets();
Element data = element.getChildByName("data");
String encoding = data.getAttribute("encoding", null);
String compression = data.getAttribute("compression", null);
if (encoding.equals("csv")) {
String[] array = data.getText().split(",");
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int id = (int) Long.parseLong(array[y * width + x].trim());
final boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0);
final boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0);
final boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0);
id = id & ~MASK_CLEAR;
tilesets.getTile(id);
TiledMapTile tile = tilesets.getTile(id);
if (tile != null) {
Cell cell = new Cell();
if (flipDiagonally) {
if (flipHorizontally && flipVertically) {
cell.setFlipHorizontally(true);
cell.setRotation(Cell.ROTATE_270);
} else if (flipHorizontally) {
cell.setRotation(Cell.ROTATE_270);
} else if (flipVertically) {
cell.setRotation(Cell.ROTATE_90);
} else {
cell.setFlipVertically(true);
cell.setRotation(Cell.ROTATE_270);
}
} else {
cell.setFlipHorizontally(flipHorizontally);
cell.setFlipVertically(flipVertically);
}
cell.setTile(tile);
layer.setCell(x, yUp ? height - 1 - y : y, cell);
}
}
}
} else {
if(encoding.equals("base64")) {
byte[] bytes = Base64Coder.decode(data.getText());
if (compression == null) {
int read = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int id =
unsignedByteToInt(bytes[read++]) |
unsignedByteToInt(bytes[read++]) << 8 |
unsignedByteToInt(bytes[read++]) << 16 |
unsignedByteToInt(bytes[read++]) << 24;
final boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0);
final boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0);
final boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0);
id = id & ~MASK_CLEAR;
tilesets.getTile(id);
TiledMapTile tile = tilesets.getTile(id);
if (tile != null) {
Cell cell = new Cell();
if (flipDiagonally) {
if (flipHorizontally && flipVertically) {
cell.setFlipHorizontally(true);
cell.setRotation(Cell.ROTATE_270);
} else if (flipHorizontally) {
cell.setRotation(Cell.ROTATE_270);
} else if (flipVertically) {
cell.setRotation(Cell.ROTATE_90);
} else {
cell.setFlipVertically(true);
cell.setRotation(Cell.ROTATE_270);
}
} else {
cell.setFlipHorizontally(flipHorizontally);
cell.setFlipVertically(flipVertically);
}
cell.setTile(tile);
layer.setCell(x, yUp ? height - 1 - y : y, cell);
}
}
}
} else if (compression.equals("gzip")) {
GZIPInputStream GZIS = null;
try {
GZIS = new GZIPInputStream(new ByteArrayInputStream(bytes), bytes.length);
} catch (IOException e) {
throw new GdxRuntimeException("Error Reading TMX Layer Data - IOException: " + e.getMessage());
}
byte[] temp = new byte[4];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
try {
GZIS.read(temp, 0, 4);
int id =
unsignedByteToInt(temp[0]) |
unsignedByteToInt(temp[1]) << 8 |
unsignedByteToInt(temp[2]) << 16 |
unsignedByteToInt(temp[3]) << 24;
final boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0);
final boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0);
final boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0);
id = id & ~MASK_CLEAR;
tilesets.getTile(id);
TiledMapTile tile = tilesets.getTile(id);
if (tile != null) {
Cell cell = new Cell();
if (flipDiagonally) {
if (flipHorizontally && flipVertically) {
cell.setFlipHorizontally(true);
cell.setRotation(Cell.ROTATE_270);
} else if (flipHorizontally) {
cell.setRotation(Cell.ROTATE_270);
} else if (flipVertically) {
cell.setRotation(Cell.ROTATE_90);
} else {
cell.setFlipVertically(true);
cell.setRotation(Cell.ROTATE_270);
}
} else {
cell.setFlipHorizontally(flipHorizontally);
cell.setFlipVertically(flipVertically);
}
cell.setTile(tile);
layer.setCell(x, yUp ? height - 1 - y : y, cell);
}
} catch (IOException e) {
throw new GdxRuntimeException("Error Reading TMX Layer Data.", e);
}
}
}
} else if (compression.equals("zlib")) {
Inflater zlib = new Inflater();
byte[] temp = new byte[4];
zlib.setInput(bytes, 0, bytes.length);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
try {
zlib.inflate(temp, 0, 4);
int id =
unsignedByteToInt(temp[0]) |
unsignedByteToInt(temp[1]) << 8 |
unsignedByteToInt(temp[2]) << 16 |
unsignedByteToInt(temp[3]) << 24;
final boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0);
final boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0);
final boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0);
id = id & ~MASK_CLEAR;
tilesets.getTile(id);
TiledMapTile tile = tilesets.getTile(id);
if (tile != null) {
Cell cell = new Cell();
if (flipDiagonally) {
if (flipHorizontally && flipVertically) {
cell.setFlipHorizontally(true);
cell.setRotation(Cell.ROTATE_270);
} else if (flipHorizontally) {
cell.setRotation(Cell.ROTATE_270);
} else if (flipVertically) {
cell.setRotation(Cell.ROTATE_90);
} else {
cell.setFlipVertically(true);
cell.setRotation(Cell.ROTATE_270);
}
} else {
cell.setFlipHorizontally(flipHorizontally);
cell.setFlipVertically(flipVertically);
}
cell.setTile(tile);
layer.setCell(x, yUp ? height - 1 - y : y, cell);
}
} catch (DataFormatException e) {
throw new GdxRuntimeException("Error Reading TMX Layer Data.", e);
}
}
}
}
}
}
Element properties = element.getChildByName("properties");
if (properties != null) {
loadProperties(layer.getProperties(), properties);
}
map.getLayers().addLayer(layer);
}
}
protected void loadObjectGroup(TiledMap map, Element element) {
if (element.getName().equals("objectgroup")) {
String name = element.getAttribute("name", null);
MapLayer layer = new MapLayer();
layer.setName(name);
Element properties = element.getChildByName("properties");
if (properties != null) {
loadProperties(layer.getProperties(), properties);
}
for (Element objectElement : element.getChildrenByName("object")) {
loadObject(layer, objectElement);
}
map.getLayers().addLayer(layer);
}
}
protected void loadObject(MapLayer layer, Element element) {
if (element.getName().equals("object")) {
MapObject object = null;
int x = element.getIntAttribute("x", 0);
int y = (yUp ? mapHeightInPixels - element.getIntAttribute("y", 0) : element.getIntAttribute("y", 0));
int width = element.getIntAttribute("width", 0);
int height = element.getIntAttribute("height", 0);
if (element.getChildCount() > 0) {
Element child = null;
if ((child = element.getChildByName("polygon")) != null) {
String[] points = child.getAttribute("points").split(" ");
float[] vertices = new float[points.length * 2];
for (int i = 0; i < points.length; i++) {
String[] point = points[i].split(",");
vertices[i * 2] = Integer.parseInt(point[0]);
vertices[i * 2 + 1] = Integer.parseInt(point[1]);
if (yUp) {
vertices[i * 2 + 1] *= -1;
}
}
Polygon polygon = new Polygon(vertices);
polygon.setPosition(x, y);
object = new PolygonMapObject(polygon);
} else if ((child = element.getChildByName("polyline")) != null) {
String[] points = child.getAttribute("points").split(" ");
float[] vertices = new float[points.length * 2];
for (int i = 0; i < points.length; i++) {
String[] point = points[i].split(",");
vertices[i * 2] = Integer.parseInt(point[0]);
vertices[i * 2 + 1] = Integer.parseInt(point[1]);
if (yUp) {
vertices[i * 2 + 1] *= -1;
}
}
Polyline polyline = new Polyline(vertices);
polyline.setPosition(x, y);
object = new PolylineMapObject(polyline);
} else if ((child = element.getChildByName("ellipse")) != null) {
object = new EllipseMapObject(x, yUp ? y - height : y, width, height);
}
}
if (object == null) {
object = new RectangleMapObject(x, yUp ? y - height : y, width, height);
}
object.setName(element.getAttribute("name", null));
String type = element.getAttribute("type", null);
if (type != null) {
object.getProperties().put("type", type);
}
object.setVisible(element.getIntAttribute("visible", 1) == 1);
Element properties = element.getChildByName("properties");
if (properties != null) {
loadProperties(object.getProperties(), properties);
}
layer.getObjects().addObject(object);
}
}
protected void loadProperties(MapProperties properties, Element element) {
if (element.getName().equals("properties")) {
for (Element property : element.getChildrenByName("property")) {
String name = property.getAttribute("name", null);
String value = property.getAttribute("value", null);
if (value == null) {
value = property.getText();
}
properties.put(name, value);
}
}
}
protected static FileHandle getRelativeFileHandle(FileHandle file, String path) {
StringTokenizer tokenizer = new StringTokenizer(path, "\\/");
FileHandle result = file.parent();
while (tokenizer.hasMoreElements()) {
String token = tokenizer.nextToken();
if (token.equals(".."))
result = result.parent();
else {
result = result.child(token);
}
}
return result;
}
protected static int unsignedByteToInt (byte b) {
return (int) b & 0xFF;
}
}
|
package org.gbif.checklistbank.authorship;
import org.gbif.api.model.checklistbank.ParsedName;
import org.gbif.api.vocabulary.Rank;
import org.gbif.nameparser.NameParser;
import org.gbif.nameparser.UnparsableException;
import org.gbif.utils.file.csv.CSVReader;
import org.gbif.utils.file.csv.CSVReaderFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class BasionymSorterTest {
private final NameParser parser = new NameParser();
private final BasionymSorter sorter = new BasionymSorter();
@Test
public void testGroupPlantBasionyms() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add(parser.parse("Gymnolomia microcephala var. abbreviata (B.L.Rob. & Greenm.) B.L.Rob. & Greenm.", null));
names.add(parser.parse("Leucheria abbreviata (Bertero) Steud.", null));
names.add(parser.parse("Centaurea phrygia subsp. abbreviata (K. Koch) Dostál", null));
names.add(parser.parse("Centaurea abbreviata (K.Koch) Hand.-Mazz.", null));
names.add(parser.parse("Jacea abbreviata (K.Koch) Soják", null));
names.add(parser.parse("Artemisia abbreviata (Krasch. ex Korobkov) Krasnob.", null));
names.add(parser.parse("Artemisia lagopus subsp. abbreviata Krasch. ex Korobkov", null));
names.add(parser.parse("Bigelowia leiosperma var. abbreviata M.E.Jones", null));
names.add(parser.parse("Brickellia oblongifolia var. abbreviata A.Gray", null));
names.add(parser.parse("Calea abbreviata Pruski & Urbatsch", null));
names.add(parser.parse("Centaurea salicifolia subsp. abbreviata K. Koch", null));
names.add(parser.parse("Chabraea abbreviata Colla ex Bertero", null));
names.add(parser.parse("Chaetanthera stuebelii Hieron. var. abbreviata Cabrera", null));
names.add(parser.parse("Conyza abbreviata Wall.", null));
names.add(parser.parse("Cousinia abbreviata Tscherneva", null));
names.add(parser.parse("Gymnolomia patens var. abbreviata B.L.Rob. & Greenm.", null));
names.add(parser.parse("Gynura abbreviata F.G.Davies", null));
names.add(parser.parse("Jacea abbreviata subsp. abbreviata", null));
names.add(parser.parse("Nassauvia abbreviata Dusén", null));
names.add(parser.parse("Nassauvia abbreviata var. abbreviata", null));
names.add(parser.parse("Scorzonera latifolia var. abbreviata Lipsch.", null));
names.add(parser.parse("Vernonia abbreviata DC.", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(4, groups.size());
for (BasionymGroup<ParsedName> g : groups) {
assertFalse(g.getRecombinations().isEmpty());
switch (g.getRecombinations().get(0).getBracketAuthorship()) {
case "B.L.Rob. & Greenm.":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "Bertero":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "K. Koch":
assertEquals(3, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "Krasch. ex Korobkov":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
default:
fail("Unknown basionym group " + g.getRecombinations().get(0));
}
}
}
@Test
public void testGroupPlantBasionyms2() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add(parser.parse("Triniteurybia aberrans (A. Nelson) Brouillet, Urbatsch & R.P. Roberts", null));
names.add(parser.parse("Haplopappus aberrans (A.Nelson) H.M.Hall", null));
names.add(parser.parse("Sideranthus aberrans (A.Nelson) Rydb.", null));
names.add(parser.parse("Tonestus aberrans (A.Nelson) G.L.Nesom & D.R.Morgan", null));
names.add(parser.parse("Hysterionica aberrans (Cabrera) Cabrera", null));
names.add(parser.parse("Antennaria luzuloides ssp. aberrans (E.E. Nelson) Bayer & Stebbins", null));
names.add(parser.parse("Logfia aberrans (Wagenitz) Anderb.", null));
names.add(parser.parse("Antennaria argentea subsp. aberrans", null));
names.add(parser.parse("Filago aberrans Wagenitz", null));
names.add(parser.parse("Hysterionica aberrans var. aberrans", null));
names.add(parser.parse("Hysterionica bakeri var. aberrans Cabrera", null));
names.add(parser.parse("Macronema aberrans A.Nelson", null));
names.add(parser.parse("Senecio aberrans Greenm.", null));
names.add(parser.parse("Taraxacum aberrans Hagend. & al.", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(4, groups.size());
for (BasionymGroup<ParsedName> g : groups) {
assertFalse(g.getRecombinations().isEmpty());
switch (g.getRecombinations().get(0).getBracketAuthorship()) {
case "A. Nelson":
assertEquals(4, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "Cabrera":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "E.E. Nelson":
assertEquals(1, g.getRecombinations().size());
assertNull(g.getBasionym());
break;
case "Wagenitz":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
default:
fail("Unknown basionym group " + g.getRecombinations().get(0));
}
}
}
@Test
public void testGroupPlantBasionyms3() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add( parser.parse("Negundo aceroides subsp. violaceus (G.Kirchn.) W.A.Weber", null) );
names.add( parser.parse("Negundo aceroides subsp. violaceus (Kirchner) W.A. Weber", null) );
names.add(parser.parse("Negundo aceroides subsp. violaceum (Booth ex G.Kirchn.) Holub", null));
names.add(parser.parse("Negundo aceroides subsp. violaceum (Booth ex Kirchn.) Holub", null));
names.add(parser.parse("Negundo aceroides var. violaceum G.Kirchn. in Petzold & G.Kirchn.", null));
names.add(parser.parse("Acer violaceum (Kirchn.) Simonkai", null));
names.add(parser.parse("Acer negundo var. violaceum (G. Kirchn.) H. Jaeger", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(1, groups.size());
BasionymGroup<ParsedName> g = groups.iterator().next();
assertFalse(g.getRecombinations().isEmpty());
assertEquals(6, g.getRecombinations().size());
assertNotNull(g.getBasionym());
assertEquals("G.Kirchn. in Petzold & G.Kirchn.", g.getBasionym().authorshipComplete());
}
@Test
public void testGroupWithDifferentInitials() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add(parser.parse("Negundo aceroides subsp. violaceum (Booth ex G.Kirchn.) Holub", null));
names.add(parser.parse("Negundo aceroides subsp. violaceum (Booth ex Kirchn.) Holub", null));
names.add(parser.parse("Negundo aceroides var. violaceum G.Kirchn. in Petzold & G.Kirchn.", null));
names.add(parser.parse("Acer violaceum (T.Kirchn.) Simonkai", null));
names.add(parser.parse("Acer negundo var. violaceum (G. Kirchn.) H. Jaeger", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(2, groups.size());
for (BasionymGroup<ParsedName> g : groups) {
assertFalse(g.getRecombinations().isEmpty());
switch (g.getRecombinations().get(0).getBracketAuthorship()) {
case "Booth ex G.Kirchn.":
assertEquals(3, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "T.Kirchn.":
// author comparison has to be very strict and must treat different initials as relevant
assertEquals(1, g.getRecombinations().size());
assertNull(g.getBasionym());
break;
default:
fail("Unknown basionym group " + g.getRecombinations().get(0));
}
}
}
@Test
public void testGroupAuthorTeams() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add(parser.parse("Negundo aceroides var. californicum (Torr. & A.Gray) Sarg.", null));
names.add(parser.parse("Acer negundo var. californicum (Torr. & Gray) Sarg.", null));
names.add(parser.parse("Acer californicum Torr et Gray", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(1, groups.size());
BasionymGroup<ParsedName> g = groups.iterator().next();
assertEquals(2, g.getRecombinations().size());
assertEquals("Acer californicum Torr et Gray", g.getBasionym().getScientificName());
}
@Test
public void testAtrocincta() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add(parser.parse("Anthophora atrocincta Lepeletier, 1841", Rank.SPECIES));
names.add(parser.parse("Amegilla atrocincta (Lepeletier)", Rank.SPECIES));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(1, groups.size());
BasionymGroup<ParsedName> g = groups.iterator().next();
assertEquals(1, g.getRecombinations().size());
assertEquals("Anthophora atrocincta Lepeletier, 1841", g.getBasionym().getScientificName());
}
@Test
public void testPlumipes() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add(parser.parse("Anthophora plumipes (Fabricius)", Rank.SPECIES));
names.add(parser.parse("Apis plumipes Fabricius, 1781", Rank.SPECIES));
names.add(parser.parse("Centris plumipes (Fabricius)", Rank.SPECIES));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(1, groups.size());
BasionymGroup<ParsedName> g = groups.iterator().next();
assertEquals(2, g.getRecombinations().size());
assertEquals("Apis plumipes Fabricius, 1781", g.getBasionym().getScientificName());
}
/**
* Test what happens if a group contains 2 or more basionyms.
*/
@Test
public void testMultipleBasionyms() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add(parser.parse("Negundo violaceum G.Kirchn.", null));
names.add(parser.parse("Negundo aceroides var. violaceum G.Kirchn. in Petzold & G.Kirchn.", null));
names.add(parser.parse("Acer violaceum (G Kirchn.) Simonkai", null));
names.add(parser.parse("Acer negundo var. violaceum (G. Kirchn.) H. Jaeger", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertTrue(groups.isEmpty());
}
@Test
public void testGroupAnimalBasionyms() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add(parser.parse("Microtus parvulus (A. H. Howell, 1916)", null));
names.add(parser.parse("Microtus pinetorum parvulus (A. H. Howell, 1916)", null));
names.add(parser.parse("Pitymys parvulus A. H. Howell, 1916", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(1, groups.size());
BasionymGroup<ParsedName> g = groups.iterator().next();
assertEquals(2, g.getRecombinations().size());
assertNotNull(g.getBasionym());
assertEquals("A. H. Howell", g.getBasionym().getAuthorship());
assertEquals("1916", g.getBasionym().getYear());
}
@Test
public void testGroupAnimalBasionyms2() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add(parser.parse("Heliodoxa rubinoides aequatorialis (Gould, 1860)", null));
names.add(parser.parse("Androdon aequatorialis Gould, 1863", null));
names.add(parser.parse("Campylopterus largipennis aequatorialis Gould, 1861", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
// multiple basionyms, no clear group!
assertEquals(0, groups.size());
}
@Test
/**
* create test files from current nub with this SQL:
* \copy (select coalesce(infra_specific_epithet, specific_epithet) as epi, scientific_name from name_usage u join name n on name_fk=n.id where u.dataset_key='d7dddbf4-2cf0-4f39-9b2a-bb099caae36c' and u.family_fk=5386 order by 1,2) to 'fabaceae.txt'
* \copy (select coalesce(infra_specific_epithet, specific_epithet) as epi, scientific_name from name_usage u join name n on name_fk=n.id where u.dataset_key='d7dddbf4-2cf0-4f39-9b2a-bb099caae36c' and u.family_fk=3065 order by 1,2) to 'asteraceae.txt'
* \copy (select coalesce(infra_specific_epithet, specific_epithet) as epi, scientific_name from name_usage u join name n on name_fk=n.id where u.dataset_key='d7dddbf4-2cf0-4f39-9b2a-bb099caae36c' and u.family_fk=212 order by 1,2) to 'aves.txt'
* \copy (select coalesce(infra_specific_epithet, specific_epithet) as epi, scientific_name from name_usage u join name n on name_fk=n.id where u.dataset_key='d7dddbf4-2cf0-4f39-9b2a-bb099caae36c' and u.family_fk=5719 order by 1,2) to 'molossidae.txt'
* \copy (select coalesce(infra_specific_epithet, specific_epithet) as epi, scientific_name from name_usage u join name n on name_fk=n.id where u.dataset_key='d7dddbf4-2cf0-4f39-9b2a-bb099caae36c' and u.family_fk=5510 order by 1,2) to 'muridae.txt'
*/
public void testGroupBasionymFiles() throws Exception {
assertEquals(80, testGroupBasionymFile("names/molossidae.txt"));
assertEquals(460, testGroupBasionymFile("names/muridae.txt"));
assertEquals(10188, testGroupBasionymFile("names/aves.txt"));
assertEquals(14521, testGroupBasionymFile("names/fabaceae.txt"));
assertEquals(22331, testGroupBasionymFile("names/asteraceae.txt"));
}
private int testGroupBasionymFile(String filename) throws Exception {
int epithets = 0;
int basionyms = 0;
EpithetGroupIterator iter = new EpithetGroupIterator(Resources.getResource(filename).openStream());
while (iter.hasNext()) {
List<ParsedName> names = iter.next();
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
//String epithet = names.get(0).getInfraSpecificEpithet() == null ? names.get(0).getSpecificEpithet() : names.get(0).getInfraSpecificEpithet();
//System.out.println(groups.size() + " groups for " + epithet);
epithets++;
basionyms = basionyms + groups.size();
}
System.out.println("\n\n" + basionyms + " basionym groups found in " + epithets + " epithet groups for file " + filename);
return basionyms;
}
class EpithetGroupIterator implements Iterator<List<ParsedName>> {
private final CSVReader reader;
private List<ParsedName> next;
private String[] lastRow = null;
EpithetGroupIterator(InputStream names) throws IOException {
reader = CSVReaderFactory.buildTabReader(names, "UTF8", 0);
next = readNextGroup();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public List<ParsedName> next() {
List<ParsedName> curr = next;
next = readNextGroup();
return curr;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private List<ParsedName> readNextGroup() {
List<ParsedName> names = Lists.newArrayList();
String epithet = null;
while (reader.hasNext() || lastRow != null) {
String[] row;
if (lastRow != null) {
row = lastRow;
lastRow = null;
} else {
row = reader.next();
}
if (row == null || row.length < 2 || row[1].startsWith("?")) {
// ignore basionym placeholders (?)
continue;
}
try {
ParsedName p = parser.parse(row[1], null);
if (epithet != null && !epithet.trim().equalsIgnoreCase(row[0])) {
// a new group, store this row for next call
lastRow = row;
return names.isEmpty() ? null : names;
}
if (epithet == null) {
epithet = row[0];
}
names.add(p);
} catch (UnparsableException e) {
if (e.type.isParsable()) {
throw new RuntimeException(e);
}
}
}
return null;
}
}
}
|
package etomica.atom.iterator;
import java.io.Serializable;
import etomica.atom.AtomAddressManager;
import etomica.atom.IAtom;
import etomica.box.Box;
import etomica.species.Species;
/**
* Gives pairs formed from the molecules of a species in a box, taking one
* molecule the species with all of its other molecules. Species is specified at
* construction and cannot be changed afterwards.
*/
public class ApiIntraspecies1A extends ApiSequence1A implements
AtomsetIteratorPDT, Serializable {
/**
* @param species
* species whose molecules will form the pair iterates
*/
public ApiIntraspecies1A(Species species) {
this(new Species[] { species, species });
}
public ApiIntraspecies1A(Species[] species) {
super();
if (species.length != 2)
throw new IllegalArgumentException(
"Constructor of ApiIntraspecies1A requires two references to the same species instance");
if (species == null || species[0] == null || species[1] == null)
throw new NullPointerException(
"Constructor of ApiIntraspecies1A requires two non-null species references to the same instance");
if (species[0] != species[1])
throw new IllegalArgumentException(
"Constructor of ApiIntraspecies1A requires references to the same species instance");
this.species = species[0];
}
/**
* Configures iterator to return molecules from the set species in the given
* box.
* @throws NullPointerException if the Box is null
*/
public void setBox(Box box) {
if (box == null) {
throw new IllegalArgumentException("You are a bad person. I didn't even care about the box, but since you passed null, I'm going to quit.");
}
}
/**
* Sets the target molecule with which all pairs are formed. Molecule is
* determined from the atom specified by the atomSet (which must have
* count() == 1), which may be the molecule itself or an atom that is part
* of it. If the atom is not in the species given at
* construction, no iterates will be returned.
*
* @throws NullPointerException
* if targetAtom is null
*/
public void setTarget(IAtom newTargetAtom) {
if (newTargetAtom == null) {
throw new NullPointerException("target atom must not be null");
}
targetAtom = newTargetAtom;
}
public void reset() {
identifyTargetMolecule();
super.reset();
}
/**
* Finds target molecule as indicated by the target atom. Sets target
* molecule to null if target atom is null, box is null, or atom is not
* part of either species.
*/
private void identifyTargetMolecule() {
if (targetAtom == null) {
targetMolecule = null;
} else {
targetMolecule = targetAtom;
while (targetMolecule.getType().getDepth() > AtomAddressManager.MOLECULE_DEPTH) {
targetMolecule = targetMolecule.getParentGroup();
}
if (targetMolecule.getType().getSpecies() != species) {
targetMolecule = null;
}
}
//targetMolecule may be null here
setAtom(targetMolecule);
}
private static final long serialVersionUID = 2L;
private final Species species;
private IAtom targetAtom, targetMolecule;
}
|
package org.gbif.checklistbank.authorship;
import org.gbif.api.model.checklistbank.ParsedName;
import org.gbif.nameparser.NameParser;
import org.gbif.nameparser.UnparsableException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
public class BasionymSorterTest {
private final NameParser parser = new NameParser();
private final BasionymSorter sorter = new BasionymSorter();
@Test
public void testGroupPlantBasionyms() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add( parser.parse("Gymnolomia microcephala var. abbreviata (B.L.Rob. & Greenm.) B.L.Rob. & Greenm.", null) );
names.add( parser.parse("Leucheria abbreviata (Bertero) Steud.", null) );
names.add( parser.parse("Centaurea phrygia subsp. abbreviata (K. Koch) Dostál", null) );
names.add( parser.parse("Centaurea abbreviata (K.Koch) Hand.-Mazz.", null) );
names.add( parser.parse("Jacea abbreviata (K.Koch) Soják", null) );
names.add( parser.parse("Artemisia abbreviata (Krasch. ex Korobkov) Krasnob.", null) );
names.add( parser.parse("Artemisia lagopus subsp. abbreviata Krasch. ex Korobkov", null) );
names.add( parser.parse("Bigelowia leiosperma var. abbreviata M.E.Jones", null) );
names.add( parser.parse("Brickellia oblongifolia var. abbreviata A.Gray", null) );
names.add( parser.parse("Calea abbreviata Pruski & Urbatsch", null) );
names.add( parser.parse("Centaurea salicifolia subsp. abbreviata K. Koch", null) );
names.add( parser.parse("Chabraea abbreviata Bertero ex Colla", null) );
names.add( parser.parse("Chaetanthera stuebelii Hieron. var. abbreviata Cabrera", null) );
names.add( parser.parse("Conyza abbreviata Wall.", null) );
names.add( parser.parse("Cousinia abbreviata Tscherneva", null) );
names.add( parser.parse("Gymnolomia patens var. abbreviata B.L.Rob. & Greenm.", null) );
names.add( parser.parse("Gynura abbreviata F.G.Davies", null) );
names.add( parser.parse("Jacea abbreviata subsp. abbreviata", null) );
names.add( parser.parse("Nassauvia abbreviata Dusén", null) );
names.add( parser.parse("Nassauvia abbreviata var. abbreviata", null) );
names.add( parser.parse("Scorzonera latifolia var. abbreviata Lipsch.", null) );
names.add(parser.parse("Vernonia abbreviata DC.", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(4, groups.size());
for (BasionymGroup<ParsedName> g : groups) {
assertFalse(g.getRecombinations().isEmpty());
switch (g.getRecombinations().get(0).getBracketAuthorship()) {
case "B.L.Rob. & Greenm.":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "Bertero":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "K. Koch":
assertEquals(3, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "Krasch. ex Korobkov":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
default:
fail("Unknown basionym group " + g.getRecombinations().get(0));
}
}
}
@Test
public void testGroupPlantBasionyms2() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add( parser.parse("Triniteurybia aberrans (A. Nelson) Brouillet, Urbatsch & R.P. Roberts", null) );
names.add( parser.parse("Haplopappus aberrans (A.Nelson) H.M.Hall", null) );
names.add( parser.parse("Sideranthus aberrans (A.Nelson) Rydb.", null) );
names.add( parser.parse("Tonestus aberrans (A.Nelson) G.L.Nesom & D.R.Morgan", null) );
names.add( parser.parse("Hysterionica aberrans (Cabrera) Cabrera", null) );
names.add( parser.parse("Antennaria luzuloides ssp. aberrans (E.E. Nelson) Bayer & Stebbins", null) );
names.add( parser.parse("Logfia aberrans (Wagenitz) Anderb.", null) );
names.add( parser.parse("Antennaria argentea subsp. aberrans", null) );
names.add( parser.parse("Filago aberrans Wagenitz", null) );
names.add( parser.parse("Hysterionica aberrans var. aberrans", null) );
names.add( parser.parse("Hysterionica bakeri var. aberrans Cabrera", null) );
names.add( parser.parse("Macronema aberrans A.Nelson", null) );
names.add( parser.parse("Senecio aberrans Greenm.", null) );
names.add( parser.parse("Taraxacum aberrans Hagend. & al.", null) );
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(4, groups.size());
for (BasionymGroup<ParsedName> g : groups) {
assertFalse(g.getRecombinations().isEmpty());
switch (g.getRecombinations().get(0).getBracketAuthorship()) {
case "A. Nelson":
assertEquals(4, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "Cabrera":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
case "E.E. Nelson":
assertEquals(1, g.getRecombinations().size());
assertNull(g.getBasionym());
break;
case "Wagenitz":
assertEquals(1, g.getRecombinations().size());
assertNotNull(g.getBasionym());
break;
default:
fail("Unknown basionym group " + g.getRecombinations().get(0));
}
}
}
@Test
public void testGroupAnimalBasionyms() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add( parser.parse("Microtus parvulus (A. H. Howell, 1916)", null) );
names.add( parser.parse("Microtus pinetorum parvulus (A. H. Howell, 1916)", null) );
names.add(parser.parse("Pitymys parvulus A. H. Howell, 1916", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(1, groups.size());
BasionymGroup<ParsedName> g = groups.iterator().next();
assertEquals(2, g.getRecombinations().size());
assertNotNull(g.getBasionym());
assertEquals("A. H. Howell", g.getBasionym().getAuthorship());
assertEquals("1916", g.getBasionym().getYear());
}
@Test
public void testGroupAnimalBasionyms2() throws Exception {
List<ParsedName> names = Lists.newArrayList();
names.add( parser.parse("Heliodoxa rubinoides aequatorialis (Gould, 1860)", null) );
names.add( parser.parse("Androdon aequatorialis Gould, 1863", null) );
names.add(parser.parse("Campylopterus largipennis aequatorialis Gould, 1861", null));
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
assertEquals(1, groups.size());
BasionymGroup<ParsedName> g = groups.iterator().next();
assertEquals(1, g.getRecombinations().size());
assertNull(g.getBasionym());
assertEquals("1860", g.getRecombinations().get(0).getBracketYear());
}
@Test
public void testGroupBasionymFiles() throws Exception {
assertEquals(52, testGroupBasionymFile("molossidae.txt"));
assertEquals(317, testGroupBasionymFile("muridae.txt"));
assertEquals(2840, testGroupBasionymFile("curculionidae.txt"));
assertEquals(5901, testGroupBasionymFile("aves.txt"));
assertEquals(22010, testGroupBasionymFile("asteraceae.txt"));
}
private int testGroupBasionymFile(String filename) throws Exception {
int epithets = 0;
int basionyms = 0;
EpithetGroupIterator iter = new EpithetGroupIterator(Resources.getResource(filename).openStream());
while (iter.hasNext()) {
List<ParsedName> names = iter.next();
Collection<BasionymGroup<ParsedName>> groups = sorter.groupBasionyms(names);
//String epithet = names.get(0).getInfraSpecificEpithet() == null ? names.get(0).getSpecificEpithet() : names.get(0).getInfraSpecificEpithet();
//System.out.println(groups.size() + " groups for " + epithet);
epithets++;
basionyms = basionyms+groups.size();
}
System.out.println("\n\n" + basionyms + " basionym groups found in " + epithets + " epithet groups for file " + filename);
return basionyms;
}
class EpithetGroupIterator implements Iterator<List<ParsedName>> {
private final BufferedReader br;
private List<ParsedName> next;
EpithetGroupIterator(InputStream names) {
br = new BufferedReader(new InputStreamReader(names));
next = readNextGroup();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public List<ParsedName> next() {
List<ParsedName> curr = next;
next = readNextGroup();
return curr;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private List<ParsedName> readNextGroup() {
List<ParsedName> names = Lists.newArrayList();
try {
String line;
while ((line = br.readLine()) != null) {
if (StringUtils.isBlank(line)) {
continue;
}
if (line.startsWith("
if (names.isEmpty()) {
continue;
}
return names;
}
try {
ParsedName p = parser.parse(line, null);
names.add(p);
} catch (UnparsableException e) {
throw new RuntimeException(e);
}
}
return names.isEmpty() ? null : names;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
package edu.duke.cabig.c3pr.web.registration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections15.functors.InstantiateFactory;
import org.apache.commons.collections15.list.LazyList;
import edu.duke.cabig.c3pr.constants.EpochType;
import edu.duke.cabig.c3pr.constants.RegistrationWorkFlowStatus;
import edu.duke.cabig.c3pr.constants.ScheduledEpochWorkFlowStatus;
import edu.duke.cabig.c3pr.domain.OffEpochReason;
import edu.duke.cabig.c3pr.domain.OffTreatmentReason;
import edu.duke.cabig.c3pr.domain.Reason;
import edu.duke.cabig.c3pr.domain.ScheduledEpoch;
import edu.duke.cabig.c3pr.domain.StudySubject;
import edu.duke.cabig.c3pr.domain.StudySubjectConsentVersion;
import edu.duke.cabig.c3pr.domain.StudyVersion;
import edu.duke.cabig.c3pr.utils.StringUtils;
/**
* @author Himanshu
*
*/
public class StudySubjectWrapper {
private StudySubject studySubject ;
// used for displaying participant data in UI
private Object participant;
private List<Integer> waiveEligibilityCrieteria = new ArrayList<Integer>();
private Reason[] reasons;
private List<StudySubjectConsentVersion> reConsentingStudySubjectConsentVersions =
new ArrayList<StudySubjectConsentVersion>();
public List<StudySubjectConsentVersion> getReConsentingStudySubjectConsentVersions() {
return reConsentingStudySubjectConsentVersions;
}
public String getTimeLineDescriptionsOfRegistrationDetails() {
StringBuffer sb = new StringBuffer();
sb.append("Subject is officially enrolled.");
if(studySubject.getTreatingPhysician() !=null){
sb.append("<br> Treating Physican: " + studySubject.getTreatingPhysicianFullName());
}
if(studySubject.getOtherTreatingPhysician() !=null){
sb.append("<br> Treating physican: " + studySubject.getOtherTreatingPhysician());
}
if(studySubject.getDiseaseHistory().getIcd9DiseaseSite() !=null){
sb.append("<br> Disease site: " + studySubject.getDiseaseHistory().getIcd9DiseaseSite().getName());
}
if(!StringUtils.isBlank(studySubject.getPaymentMethod())){
sb.append("<br> Payment method: " + studySubject.getPaymentMethod());
}
return sb.toString();
}
public String getTimelineDescriptionOfOffStudyReasons() {
StringBuffer sb = new StringBuffer();
if(studySubject.getOffStudyDate() != null) {
sb.append("Subject is Off-Study");
if(studySubject.getOffStudyReasons().size() > 0){
sb.append("<br> Off Study reason(s): ");
for(int i =0; i< studySubject.getOffStudyReasons().size(); i ++){
sb.append(" " + i+1 + ". " + studySubject.getOffStudyReasons().get(i).getReason().getDescription());
}
}
}
return sb.toString();
}
public List<String> getTimeLineDescriptionsOfScheduledEpochs(){
List<String> timeLineDescriptionsOfScheduledEpochs = new ArrayList<String>();
for(ScheduledEpoch scheduledEpoch : studySubject.getScheduledEpochs()){
StringBuffer sb = new StringBuffer();
sb.append("Epoch type: " + scheduledEpoch.getEpoch().getType().getDisplayName());
sb.append("<br>Scheduled epoch status: " +scheduledEpoch.getScEpochWorkflowStatus().getDisplayName());
if(scheduledEpoch.getStratumGroupNumber() !=null){
sb.append("<br> Stratum group: " + scheduledEpoch.getStratumGroupNumber());
}
if(scheduledEpoch.getScheduledArm() !=null && scheduledEpoch.getScheduledArm().getArm()!=null){
sb.append("<br> Arm assigned: " + scheduledEpoch.getScheduledArm().getArm().getName());
}
if(scheduledEpoch.getOffEpochReasons().size() > 0){
sb.append("<br> Off Epoch reason(s): ");
for(int i =0; i< scheduledEpoch.getOffEpochReasons().size(); i ++){
sb.append(" " + i+1 + ". " + scheduledEpoch.getOffEpochReasons().get(i).getReason().getDescription());
}
}
timeLineDescriptionsOfScheduledEpochs.add(sb.toString());
}
return timeLineDescriptionsOfScheduledEpochs;
}
public List<String> getTimeLineDescriptionsOfSignedConsents(){
List<String> timeLineDescriptionsOfSignedConsents = new ArrayList<String>();
for(StudySubjectConsentVersion studySubjectConsentVersion : studySubject.getAllSignedConsents()){
StringBuffer sb = new StringBuffer();
sb.append("Mandatory: " + (studySubjectConsentVersion.getConsent().getMandatoryIndicator()?"Yes":"No"));
if(studySubjectConsentVersion.getConsentPresenter() !=null){
sb.append("<br> Consent presenter: " + studySubjectConsentVersion.getConsentPresenter());
}
if(studySubjectConsentVersion.getConsentDeliveryDate() !=null){
sb.append("<br> Delivery date: " + studySubjectConsentVersion.getConsentDeliveryDateStr());
}
if(studySubjectConsentVersion.getConsentingMethod() !=null){
sb.append("<br> Consenting method: " + studySubjectConsentVersion.getConsentingMethod().getDisplayName());
}
timeLineDescriptionsOfSignedConsents.add(sb.toString());
}
return timeLineDescriptionsOfSignedConsents;
}
public void setReConsentingStudySubjectConsentVersons(
List<StudySubjectConsentVersion> reConsentingStudySubjectConsentVersons) {
this.reConsentingStudySubjectConsentVersions = reConsentingStudySubjectConsentVersons;
}
public void addReConsentingStudySubjectConsentVersion(StudySubjectConsentVersion studySubjectConsentVersion){
this.getReConsentingStudySubjectConsentVersions().add(studySubjectConsentVersion);
}
public void removeReConsentingStudySubjectConsentVersion(StudySubjectConsentVersion studySubjectConsentVersion){
this.getReConsentingStudySubjectConsentVersions().remove(studySubjectConsentVersion);
}
private List<OffEpochReason> offEpochReasons = LazyList.decorate(new ArrayList<OffEpochReason>(), new InstantiateFactory<OffEpochReason>(OffEpochReason.class){
@Override
public OffEpochReason create() {
OffEpochReason offEpochReason = super.create();
offEpochReason.setReason(new OffTreatmentReason());
return offEpochReason;
}
});
private Date offEpochDate;
private StudyVersion reConsentingVersion;
public StudyVersion getReConsentingVersion() {
return reConsentingVersion;
}
public void setReConsentingVersion(StudyVersion reConsentingVersion) {
this.reConsentingVersion = reConsentingVersion;
}
public Object getParticipant() {
return participant;
}
public void setParticipant(Object participant) {
this.participant = participant;
}
public StudySubject getStudySubject() {
return studySubject;
}
public void setStudySubject(StudySubject studySubject) {
this.studySubject = studySubject;
}
public Boolean getShouldReserve() {
if (!this.studySubject.getDataEntryStatus()) {
return false;
}
return (this.studySubject.getScheduledEpoch().getEpoch().getType() == EpochType.RESERVING
&& (this.studySubject.getScheduledEpoch().getScEpochWorkflowStatus() == ScheduledEpochWorkFlowStatus.PENDING_ON_EPOCH)
&& (this.studySubject.getRegWorkflowStatus() == RegistrationWorkFlowStatus.PENDING));
}
public Boolean getShouldRegister(){
if(!this.studySubject.getDataEntryStatus()){
return false;
}
boolean reservationIndicator = this.studySubject.getScheduledEpoch().getEpoch().getType() == EpochType.RESERVING ;
boolean enrollmentIndicator = this.studySubject.getScheduledEpoch().getEpoch().getEnrollmentIndicator() ;
if(this.studySubject.getParentStudySubject() != null){
if((reservationIndicator || enrollmentIndicator) && this.studySubject.getParentStudySubject().getRegWorkflowStatus() == RegistrationWorkFlowStatus.ON_STUDY){
return false;
}else{
return true;
}
}
return !this.studySubject.getWorkPendingOnMandatoryCompanionRegistrations() && !enrollmentIndicator ;
}
public Boolean getShouldEnroll(){
if(!this.studySubject.getDataEntryStatus()){
return false;
}
if(this.studySubject.getStartDate() == null){
return false;
}
boolean enrollmentIndicator = this.studySubject.getScheduledEpoch().getEpoch().getEnrollmentIndicator() ;
if(this.studySubject.getParentStudySubject() != null && enrollmentIndicator){
if(this.studySubject.getParentStudySubject().getRegWorkflowStatus() == RegistrationWorkFlowStatus.ON_STUDY){
return true ;
}else{
return false ;
}
}
return(!this.studySubject.getWorkPendingOnMandatoryCompanionRegistrations() && enrollmentIndicator);
}
public Boolean getShouldRandomize(){
if(!this.studySubject.getDataEntryStatus()){
return false;
}
if(this.studySubject.getStartDate() == null){
return false;
}
Boolean requiresRandomization = this.getStudySubject().getScheduledEpoch().getRequiresRandomization();
if(this.studySubject.getParentStudySubject() != null && requiresRandomization){
if(this.studySubject.getParentStudySubject().getRegWorkflowStatus() == RegistrationWorkFlowStatus.ON_STUDY){
return true ;
}else{
return false ;
}
}
return requiresRandomization;
}
public Boolean getShouldTransfer(){
if (this.studySubject.getRegWorkflowStatus()==RegistrationWorkFlowStatus.ON_STUDY){
if(this.studySubject.getDataEntryStatus()){
return true;
}
}
return false;
}
public Boolean getCanReConsent(){
return getReConsentableStudyVersions().size() > 0;
}
public List<StudyVersion> getReConsentableStudyVersions(){
List<StudyVersion> reConsentableStudyVersions = new ArrayList<StudyVersion>();
for(StudyVersion studyVersion : this.studySubject.getStudySite().getStudy().getStudyVersions()){
if (this.studySubject.canReConsent(studyVersion.getName())){
reConsentableStudyVersions.add(studyVersion);
}
}
return reConsentableStudyVersions;
}
public boolean getCanAllowEligibilityWaiver(){
return this.studySubject.canAllowEligibilityWaiver();
}
public List<Integer> getWaiveEligibilityCrieteria() {
return waiveEligibilityCrieteria;
}
public void setWaiveEligibilityCrieteria(List<Integer> waiveEligibilityCrieteria) {
this.waiveEligibilityCrieteria = waiveEligibilityCrieteria;
}
public Reason[] getReasons() {
return reasons;
}
public void setReasons(Reason[] reasons) {
this.reasons = reasons;
}
public Date getOffEpochDate() {
return offEpochDate;
}
public void setOffEpochDate(Date offEpochDate) {
this.offEpochDate = offEpochDate;
}
public List<OffEpochReason> getOffEpochReasons() {
return offEpochReasons;
}
public void setOffEpochReasons(List<OffEpochReason> offEpochReasons) {
this.offEpochReasons = offEpochReasons;
}
}
|
package gw.lang;
import gw.lang.init.ClasspathToGosuPathEntryUtil;
import gw.lang.init.GosuInitialization;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.gs.BytecodeOptions;
import gw.test.Suite;
import gw.test.TestEnvironment;
import junit.framework.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Typical JVM args:
* -Dgw.tests.skip.knownbreak=true
* -DcheckedArithmetic=true
*/
public class GosuScratchSuite extends Suite
{
public static Test suite()
{
BytecodeOptions.enableAggressiveVerification();
return new GosuScratchSuite()
.withTestEnvironment( new ScratchTestEnvironment() )
.withTest( "gw.internal.gosu.parser.classTests.gwtest.dynamic.JsonTest" )
}
private static class ScratchTestEnvironment extends TestEnvironment
{
@Override
public void initializeTypeSystem()
{
List<File> classpath = constructClasspathFromSystemClasspath();
for( File file : new ArrayList<File>(classpath) )
{
if( file.getName().endsWith( "classes" ) )
{
classpath.add( new File( file.getParentFile(), "test-classes" ) );
}
}
GosuInitialization.instance( TypeSystem.getExecutionEnvironment() )
.initializeRuntime( ClasspathToGosuPathEntryUtil.convertClasspathToGosuPathEntries( classpath ) );
}
}
}
|
package org.neo4j.unsafe.impl.batchimport;
import java.util.Iterator;
import org.neo4j.kernel.impl.store.AbstractDynamicStore;
import org.neo4j.kernel.impl.store.AbstractRecordStore;
import org.neo4j.kernel.impl.store.PropertyStore;
import org.neo4j.kernel.impl.store.PropertyType;
import org.neo4j.kernel.impl.store.record.DynamicRecord;
import org.neo4j.kernel.impl.store.record.PrimitiveRecord;
import org.neo4j.kernel.impl.store.record.PropertyBlock;
import org.neo4j.kernel.impl.store.record.PropertyRecord;
import org.neo4j.kernel.impl.transaction.state.PropertyCreator;
import org.neo4j.kernel.impl.util.ReusableIteratorCostume;
import org.neo4j.unsafe.impl.batchimport.input.InputEntity;
import org.neo4j.unsafe.impl.batchimport.staging.BatchSender;
import org.neo4j.unsafe.impl.batchimport.staging.ProcessorStep;
import org.neo4j.unsafe.impl.batchimport.staging.StageControl;
import org.neo4j.unsafe.impl.batchimport.store.BatchingPageCache.WriterFactory;
import org.neo4j.unsafe.impl.batchimport.store.BatchingPropertyRecordAccess;
import org.neo4j.unsafe.impl.batchimport.store.io.IoMonitor;
import static java.lang.Math.max;
/**
* Writes {@link RecordBatch entity batches} to the underlying stores. Also makes final composition of the
* {@link BatchEntity entities} before writing, such as clumping up {@link PropertyBlock properties} into
* {@link PropertyRecord property records}.
*
* @param <RECORD> type of entities.
* @param <INPUT> type of input.
*/
public class EntityStoreUpdaterStep<RECORD extends PrimitiveRecord,INPUT extends InputEntity>
extends ProcessorStep<Batch<INPUT,RECORD>>
{
private final AbstractRecordStore<RECORD> entityStore;
private final PropertyStore propertyStore;
private final IoMonitor monitor;
private final WriterFactory writerFactory;
private final PropertyCreator propertyCreator;
// Reusable instances for less GC
private final BatchingPropertyRecordAccess propertyRecords = new BatchingPropertyRecordAccess();
private final ReusableIteratorCostume<PropertyBlock> blockIterator = new ReusableIteratorCostume<>();
EntityStoreUpdaterStep( StageControl control, Configuration config,
AbstractRecordStore<RECORD> entityStore,
PropertyStore propertyStore, IoMonitor monitor, WriterFactory writerFactory )
{
super( control, "v", config, 1, monitor );
this.entityStore = entityStore;
this.propertyStore = propertyStore;
this.writerFactory = writerFactory;
this.propertyCreator = new PropertyCreator( propertyStore, null );
this.monitor = monitor;
this.monitor.reset();
}
@Override
protected void process( Batch<INPUT,RECORD> batch, BatchSender sender )
{
// Clear reused data structures
propertyRecords.close();
// Write the entity records, and at the same time allocate property records for its property blocks.
long highestId = 0;
RECORD[] records = batch.records;
int propertyBlockCursor = 0;
for ( int i = 0; i < records.length; i++ )
{
RECORD record = records[i];
int propertyBlockCount = batch.propertyBlocksLengths[i];
if ( record != null )
{
INPUT input = batch.input[i];
if ( input.hasFirstPropertyId() )
{
record.setNextProp( input.firstPropertyId() );
}
else
{
if ( propertyBlockCount > 0 )
{
reassignDynamicRecordIds( batch.propertyBlocks, propertyBlockCursor, propertyBlockCount );
long firstProp = propertyCreator.createPropertyChain( record,
blockIterator.dressArray( batch.propertyBlocks, propertyBlockCursor, propertyBlockCount ),
propertyRecords );
record.setNextProp( firstProp );
}
}
highestId = max( highestId, record.getId() );
entityStore.updateRecord( record );
}
else
{ // Here we have a relationship that refers to missing nodes. It's within the tolerance levels
// of number of bad relationships. Just don't import this relationship.
}
propertyBlockCursor += propertyBlockCount;
}
entityStore.setHighestPossibleIdInUse( highestId );
// Write all the created property records.
for ( PropertyRecord propertyRecord : propertyRecords.records() )
{
propertyStore.updateRecord( propertyRecord );
}
}
private void reassignDynamicRecordIds( PropertyBlock[] blocks, int offset, int length )
{
// OK, so here we have property blocks, potentially referring to DynamicRecords. The DynamicRecords
// have ids that we need to re-assign in here, because the ids are generated by multiple property encoders,
// and so we let each one of the encoders generate their own bogus ids and we re-assign those ids here,
// where we know we have a single thread doing this.
for ( int i = 0; i < length; i++ )
{
PropertyBlock block = blocks[offset+i];
PropertyType type = block.getType();
switch ( type )
{
case STRING:
reassignDynamicRecordIds( block, type, propertyStore.getStringStore() );
break;
case ARRAY:
reassignDynamicRecordIds( block, type, propertyStore.getArrayStore() );
break;
default: // No need to do anything be default, we only need to relink for dynamic records
}
}
}
private void reassignDynamicRecordIds( PropertyBlock block, PropertyType type, AbstractDynamicStore store )
{
Iterator<DynamicRecord> dynamicRecords = block.getValueRecords().iterator();
long newId = store.nextId();
block.getValueBlocks()[0] = PropertyStore.singleBlockLongValue( block.getKeyIndexId(), type, newId );
while ( dynamicRecords.hasNext() )
{
DynamicRecord dynamicRecord = dynamicRecords.next();
dynamicRecord.setId( newId );
if ( dynamicRecords.hasNext() )
{
dynamicRecord.setNextBlock( newId = store.nextId() );
}
}
}
@Override
protected void done()
{
super.done();
// Stop the I/O monitor, since the stats in there is based on time passed since the start
// and bytes written. NodeStage and CalculateDenseNodesStage can be run in parallel so if
// NodeStage completes before CalculateDenseNodesStage then we want to stop the time in the I/O monitor.
monitor.stop();
}
// Below we override the "parallizable" methods to go directly towards the I/O writer, since
// this step is very cheap and not parallelizable, except for the I/O part which is all handled by the writer.
@Override
public int numberOfProcessors()
{
return writerFactory.numberOfProcessors();
}
@Override
public boolean incrementNumberOfProcessors()
{
return writerFactory.incrementNumberOfProcessors();
}
@Override
public boolean decrementNumberOfProcessors()
{
return writerFactory.decrementNumberOfProcessors();
}
}
|
package org.jboss.as.connector.subsystems.datasources;
import static org.jboss.as.connector.ConnectorLogger.SUBSYSTEM_DATASOURCES_LOGGER;
import static org.jboss.as.connector.ConnectorMessages.MESSAGES;
import static org.jboss.as.connector.subsystems.datasources.Constants.JNDINAME;
import static org.jboss.as.connector.subsystems.datasources.DataSourceModelNodeUtil.from;
import static org.jboss.as.connector.subsystems.datasources.DataSourceModelNodeUtil.xaFrom;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ENABLED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import java.util.List;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.ServiceVerificationHandler;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.dmr.ModelNode;
import org.jboss.jca.common.api.validator.ValidateException;
import org.jboss.msc.service.AbstractServiceListener;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.ServiceTarget;
/**
* Operation handler responsible for disabling an existing data-source.
*
* @author John Bailey
*/
public class DataSourceDisable implements OperationStepHandler {
static final DataSourceDisable LOCAL_INSTANCE = new DataSourceDisable(false);
static final DataSourceDisable XA_INSTANCE = new DataSourceDisable(true);
private final boolean xa;
public DataSourceDisable(boolean xa) {
super();
this.xa = xa;
}
public void execute(OperationContext context, ModelNode operation) {
final ModelNode model = context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS).getModel();
model.get(ENABLED).set(false);
if (context.getType() == OperationContext.Type.SERVER) {
//if (context.isResourceServiceRestartAllowed()) {
if (true) {
context.addStep(new OperationStepHandler() {
public void execute(final OperationContext context, ModelNode operation) throws OperationFailedException {
final ModelNode address = operation.require(OP_ADDR);
final String dsName = PathAddress.pathAddress(address).getLastElement().getValue();
final String jndiName = model.get(JNDINAME.getName()).asString();
final ServiceRegistry registry = context.getServiceRegistry(true);
final ServiceName dataSourceServiceName = AbstractDataSourceService.SERVICE_NAME_BASE.append(jndiName);
final ServiceController<?> dataSourceController = registry.getService(dataSourceServiceName);
if (dataSourceController != null) {
if (ServiceController.State.UP.equals(dataSourceController.getState())) {
dataSourceController.setMode(ServiceController.Mode.NEVER);
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceNotEnabled("Data-source", dsName)));
}
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceNotAvailable("Data-source", dsName)));
}
final ServiceName referenceServiceName = DataSourceReferenceFactoryService.SERVICE_NAME_BASE.append(dsName);
final ServiceController<?> referenceController = registry.getService(referenceServiceName);
if (referenceController != null ) {
context.removeService(referenceController);
}
final ServiceName binderServiceName = ContextNames.bindInfoFor(jndiName).getBinderServiceName();
final ServiceController<?> binderController = registry.getService(binderServiceName);
if (binderController != null ) {
context.removeService(binderController);
}
final ServiceName dataSourceConfigServiceName = DataSourceConfigService.SERVICE_NAME_BASE.append(dsName);
final ServiceController<?> dataSourceConfigController = registry.getService(dataSourceConfigServiceName);
final List<ServiceName> serviceNames = registry.getServiceNames();
final ServiceName xaDataSourceConfigServiceName = XADataSourceConfigService.SERVICE_NAME_BASE.append(dsName);
final ServiceController<?> xaDataSourceConfigController = registry.getService(xaDataSourceConfigServiceName);
for (ServiceName name : serviceNames) {
if (dataSourceConfigServiceName.append("connection-properties").isParentOf(name)) {
final ServiceController<?> connProperyController = registry.getService(name);
if (connProperyController != null) {
if (ServiceController.State.UP.equals(connProperyController.getState())) {
connProperyController.setMode(ServiceController.Mode.NEVER);
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceAlreadyStarted("Data-source.connectionProperty", name)));
}
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceNotAvailable("Data-source.connectionProperty", name)));
}
}
if (xaDataSourceConfigServiceName.append("xa-datasource-properties").isParentOf(name)) {
final ServiceController<?> xaConfigProperyController = registry.getService(name);
if (xaConfigProperyController != null) {
if (ServiceController.State.UP.equals(xaConfigProperyController.getState())) {
xaConfigProperyController.setMode(ServiceController.Mode.NEVER);
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceAlreadyStarted("Data-source.xa-config-property", name)));
}
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceNotAvailable("Data-source.xa-config-property", name)));
}
}
}
if (xaDataSourceConfigController != null) {
context.removeService(xaDataSourceConfigController);
}
if (dataSourceConfigController != null) {
context.removeService(dataSourceConfigController);
}
context.completeStep(new OperationContext.RollbackHandler() {
@Override
public void handleRollback(OperationContext context, ModelNode operation) {
try {
reEnable(context,operation, model);
} catch (OperationFailedException e) {
}
}
});
}
}, OperationContext.Stage.RUNTIME);
} else {
context.restartRequired();
}
}
context.completeStep();
}
public void reEnable(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
if (context.getType() == OperationContext.Type.SERVER) {
final ServiceTarget serviceTarget = context.getServiceTarget();
final ServiceVerificationHandler verificationHandler = new ServiceVerificationHandler();
final ModelNode address = operation.require(OP_ADDR);
final String dsName = PathAddress.pathAddress(address).getLastElement().getValue();
final String jndiName = model.get(JNDINAME.getName()).asString();
final ServiceRegistry registry = context.getServiceRegistry(true);
final List<ServiceName> serviceNames = registry.getServiceNames();
if (isXa()) {
final ModifiableXaDataSource dataSourceConfig;
try {
dataSourceConfig = xaFrom(context, model, dsName);
} catch (ValidateException e) {
throw new OperationFailedException(e, new ModelNode().set(MESSAGES.failedToCreate("XaDataSource", operation, e.getLocalizedMessage())));
}
final ServiceName xaDataSourceConfigServiceName = XADataSourceConfigService.SERVICE_NAME_BASE.append(dsName);
final XADataSourceConfigService xaDataSourceConfigService = new XADataSourceConfigService(dataSourceConfig);
final ServiceBuilder<?> builder = serviceTarget.addService(xaDataSourceConfigServiceName, xaDataSourceConfigService);
builder.addListener(verificationHandler);
for (ServiceName name : serviceNames) {
if (xaDataSourceConfigServiceName.append("xa-datasource-properties").isParentOf(name)) {
final ServiceController<?> xaConfigProperyController = registry.getService(name);
XaDataSourcePropertiesService xaPropService = (XaDataSourcePropertiesService) xaConfigProperyController.getService();
if (xaConfigProperyController != null) {
if (!ServiceController.State.UP.equals(xaConfigProperyController.getState())) {
xaConfigProperyController.setMode(ServiceController.Mode.ACTIVE);
builder.addDependency(name, String.class, xaDataSourceConfigService.getXaDataSourcePropertyInjector(xaPropService.getName()));
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceAlreadyStarted("Data-source.xa-config-property", name)));
}
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceNotAvailable("Data-source.xa-config-property", name)));
}
}
}
builder.install();
} else {
final ModifiableDataSource dataSourceConfig;
try {
dataSourceConfig = from(context, model, dsName);
} catch (ValidateException e) {
throw new OperationFailedException(e, new ModelNode().set(MESSAGES.failedToCreate("DataSource", operation, e.getLocalizedMessage())));
}
final ServiceName dataSourceCongServiceName = DataSourceConfigService.SERVICE_NAME_BASE.append(dsName);
final DataSourceConfigService configService = new DataSourceConfigService(dataSourceConfig);
final ServiceBuilder<?> builder = serviceTarget.addService(dataSourceCongServiceName, configService);
builder.addListener(verificationHandler);
for (ServiceName name : serviceNames) {
if (dataSourceCongServiceName.append("connection-properties").isParentOf(name)) {
final ServiceController<?> dataSourceController = registry.getService(name);
ConnectionPropertiesService connPropService = (ConnectionPropertiesService) dataSourceController.getService();
if (dataSourceController != null) {
if (!ServiceController.State.UP.equals(dataSourceController.getState())) {
dataSourceController.setMode(ServiceController.Mode.ACTIVE);
builder.addDependency(name, String.class, configService.getConnectionPropertyInjector(connPropService.getName()));
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceAlreadyStarted("Data-source.connectionProperty", name)));
}
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceNotAvailable("Data-source.connectionProperty", name)));
}
}
}
builder.install();
}
context.completeStep();
final ServiceName dataSourceServiceName = AbstractDataSourceService.SERVICE_NAME_BASE.append(jndiName);
final ServiceController<?> dataSourceController = registry.getService(dataSourceServiceName);
if (dataSourceController != null) {
if (!ServiceController.State.UP.equals(dataSourceController.getState())) {
dataSourceController.setMode(ServiceController.Mode.ACTIVE);
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceAlreadyStarted("Data-source", dsName)));
}
} else {
throw new OperationFailedException(new ModelNode().set(MESSAGES.serviceNotAvailable("Data-source", dsName)));
}
final DataSourceReferenceFactoryService referenceFactoryService = new DataSourceReferenceFactoryService();
final ServiceName referenceFactoryServiceName = DataSourceReferenceFactoryService.SERVICE_NAME_BASE
.append(dsName);
final ServiceBuilder<?> referenceBuilder = serviceTarget.addService(referenceFactoryServiceName,
referenceFactoryService).addDependency(dataSourceServiceName, javax.sql.DataSource.class,
referenceFactoryService.getDataSourceInjector());
referenceBuilder.install();
final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(jndiName);
final BinderService binderService = new BinderService(bindInfo.getBindName());
final ServiceBuilder<?> binderBuilder = serviceTarget
.addService(bindInfo.getBinderServiceName(), binderService)
.addDependency(referenceFactoryServiceName, ManagedReferenceFactory.class, binderService.getManagedObjectInjector())
.addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()).addListener(new AbstractServiceListener<Object>() {
public void transition(final ServiceController<? extends Object> controller, final ServiceController.Transition transition) {
switch (transition) {
case STARTING_to_UP: {
SUBSYSTEM_DATASOURCES_LOGGER.boundDataSource(jndiName);
break;
}
case START_REQUESTED_to_DOWN: {
SUBSYSTEM_DATASOURCES_LOGGER.unboundDataSource(jndiName);
break;
}
case REMOVING_to_REMOVED: {
SUBSYSTEM_DATASOURCES_LOGGER.debugf("Removed JDBC Data-source [%s]", jndiName);
break;
}
}
}
});
binderBuilder.setInitialMode(ServiceController.Mode.ACTIVE)
.addListener(verificationHandler);
binderBuilder.install();
context.completeStep();
}
context.completeStep();
}
public boolean isXa() {
return xa;
}
}
|
package org.csstudio.platform.ui.dialogs;
import org.csstudio.platform.ui.CSSPlatformUiPlugin;
import org.csstudio.platform.ui.internal.dialogs.ResourceAndContainerGroup;
import org.csstudio.platform.ui.internal.localization.Messages;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
/**
* A standard "Save As" dialog which solicits a path from the user. The
* <code>getResult</code> method returns the path. Note that the folder at the
* specified path might not exist and might need to be created.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* <p>
* <b>Code is based upon <code>org.eclipse.ui.dialogs.SaveAsDialog</code> in
* plugin <code>org.eclipse.ui.ide</code>.</b>
* </p>
*
* @author Alexander Will
* @version $Revision$
*
*/
public final class SaveAsDialog extends TitleAreaDialog {
/**
* The key to store the dialog settings.
*/
private static final String DIALOG_SETTINGS_SECTION = "SaveAsDialogSettings"; //$NON-NLS-1$
/**
* The original file.
*/
private IFile _originalFile = null;
/**
* The original file name.
*/
private String _originalName = null;
/**
* The result file.
*/
private IPath _result;
/**
* The container selection group.
*/
private ResourceAndContainerGroup _resourceGroup;
/**
* The OK button.
*/
private Button _okButton;
/**
* The default file extension.
*/
private String _fileExtension = ""; //$NON-NLS-1$
/**
* Creates a new Save As dialog for no specific file.
*
* @param parentShell
* the parent shell
*/
public SaveAsDialog(final Shell parentShell) {
super(parentShell);
setShellStyle(getShellStyle() | SWT.RESIZE);
}
/**
* {@inheritDoc}
*/
protected void configureShell(final Shell shell) {
super.configureShell(shell);
shell.setText(Messages.getString("SaveAsDialog.TITLE")); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
protected Control createContents(final Composite parent) {
Control contents = super.createContents(parent);
initializeControls();
validatePage();
_resourceGroup.setFileExtension(_fileExtension);
_resourceGroup.setFocus();
setTitle(Messages.getString("SaveAsDialog.TITLE")); //$NON-NLS-1$
setMessage(Messages.getString("SaveAsDialog.MESSAGE")); //$NON-NLS-1$
return contents;
}
/**
* {@inheritDoc}
*/
protected void createButtonsForButtonBar(final Composite parent) {
_okButton = createButton(parent, IDialogConstants.OK_ID,
IDialogConstants.OK_LABEL, true);
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false);
}
/**
* {@inheritDoc}
*/
protected Control createDialogArea(final Composite parent) {
// top level composite
Composite parentComposite = (Composite) super.createDialogArea(parent);
// create a composite with standard margins and spacing
Composite composite = new Composite(parentComposite, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
composite.setFont(parentComposite.getFont());
Listener listener = new Listener() {
public void handleEvent(final Event event) {
setDialogComplete(validatePage());
}
};
_resourceGroup = new ResourceAndContainerGroup(
composite,
listener,
Messages.getString("SaveAsDialog.FILE_LABEL"), Messages.getString("SaveAsDialog.FILE")); //$NON-NLS-1$ //$NON-NLS-2$
_resourceGroup.setAllowExistingResources(true);
return parentComposite;
}
/**
* Returns the full path entered by the user.
* <p>
* Note that the file and container might not exist and would need to be
* created. See the <code>IFile.create</code> method and the
* <code>ContainerGenerator</code> class.
* </p>
*
* @return the path, or <code>null</code> if Cancel was pressed
*/
public IPath getResult() {
return _result;
}
/**
* Initializes the controls of this dialog.
*/
private void initializeControls() {
if (_originalFile != null) {
_resourceGroup.setContainerFullPath(_originalFile.getParent()
.getFullPath());
_resourceGroup.setResource(_originalFile.getName());
} else if (_originalName != null) {
_resourceGroup.setResource(_originalName);
}
setDialogComplete(validatePage());
}
/**
* {@inheritDoc}
*/
protected void okPressed() {
// Get new path.
IPath path = _resourceGroup.getContainerFullPath().append(
_resourceGroup.getResource());
// If the user does not supply a file extension and if the save
// as dialog was provided a default file name append the extension
// of the default filename to the new name
if (path.getFileExtension() == null) {
if (_originalFile != null
&& _originalFile.getFileExtension() != null) {
path = path.addFileExtension(_originalFile.getFileExtension());
} else if (_originalName != null) {
int pos = _originalName.lastIndexOf('.');
if (++pos > 0 && pos < _originalName.length()) {
path = path.addFileExtension(_originalName.substring(pos));
}
}
}
// If the path already exists then confirm overwrite.
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
if (file.exists()) {
String[] buttons = new String[] { IDialogConstants.YES_LABEL,
IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL };
String question = NLS.bind(Messages
.getString("SaveAsDialog.OVERWRITE_QUESTION"), //$NON-NLS-1$
path.toOSString());
MessageDialog d = new MessageDialog(getShell(), Messages
.getString("SaveAsDialog.QUESTION"), null, //$NON-NLS-1$
question, MessageDialog.QUESTION, buttons, 0);
int overwrite = d.open();
switch (overwrite) {
case 0: // Yes
break;
case 1:
return;
case 2: // Cancel
default:
cancelPressed();
return;
}
}
// Store path and close.
_result = path;
close();
}
/**
* Sets the completion state of this dialog and adjusts the enable state of
* the Ok button accordingly.
*
* @param value
* <code>true</code> if this dialog is compelete, and
* <code>false</code> otherwise
*/
protected void setDialogComplete(final boolean value) {
_okButton.setEnabled(value);
}
/**
* Sets the original file to use.
*
* @param originalFile
* the original file
*/
public void setOriginalFile(final IFile originalFile) {
_originalFile = originalFile;
}
/**
* Set the original file name to use. Used instead of
* <code>setOriginalFile</code> when the original resource is not an
* IFile. Must be called before <code>create</code>.
*
* @param originalName
* default file name
*/
public void setOriginalName(final String originalName) {
_originalName = originalName;
}
/**
* Set the file extension.
*
* @param fileExtension
* The file extension to set
*/
public void setFileExtension(final String fileExtension) {
_fileExtension = fileExtension;
}
/**
* Returns whether this page's visual components all contain valid values.
*
* @return <code>true</code> if valid, and <code>false</code> otherwise
*/
private boolean validatePage() {
if (!_resourceGroup.areAllValuesValid()) {
if (!_resourceGroup.getResource().equals("")) { //$NON-NLS-1$
setErrorMessage(_resourceGroup.getProblemMessage());
} else {
setErrorMessage(null);
}
return false;
}
setErrorMessage(null);
return true;
}
/**
* {@inheritDoc}
*/
protected IDialogSettings getDialogBoundsSettings() {
IDialogSettings settings = CSSPlatformUiPlugin.getDefault()
.getDialogSettings();
IDialogSettings section = settings.getSection(DIALOG_SETTINGS_SECTION);
if (section == null) {
section = settings.addNewSection(DIALOG_SETTINGS_SECTION);
}
return section;
}
}
|
package de.peeeq.wurstscript.intermediateLang.optimizer;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Iterator;
import java.util.Locale;
import de.peeeq.wurstscript.WurstOperator;
import de.peeeq.wurstscript.jassIm.ImBoolVal;
import de.peeeq.wurstscript.jassIm.ImExitwhen;
import de.peeeq.wurstscript.jassIm.ImExpr;
import de.peeeq.wurstscript.jassIm.ImIf;
import de.peeeq.wurstscript.jassIm.ImIntVal;
import de.peeeq.wurstscript.jassIm.ImOperatorCall;
import de.peeeq.wurstscript.jassIm.ImProg;
import de.peeeq.wurstscript.jassIm.ImRealVal;
import de.peeeq.wurstscript.jassIm.ImReturn;
import de.peeeq.wurstscript.jassIm.ImStmt;
import de.peeeq.wurstscript.jassIm.ImStmts;
import de.peeeq.wurstscript.jassIm.JassIm;
import de.peeeq.wurstscript.jassIm.JassImElement;
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
public class SimpleRewrites {
private final ImProg prog;
private final ImTranslator trans;
public SimpleRewrites(ImTranslator trans) {
this.prog = trans.getImProg();
this.trans = trans;
}
public void optimize() {
optimizeElement(prog);
// we need to flatten the program, because we introduced new
// StatementExprs
prog.flatten(trans);
removeUnreachableCode(prog);
}
private void removeUnreachableCode(ImProg prog) {
prog.accept(new ImProg.DefaultVisitor() {
@Override
public void visit(ImStmts stmts) {
removeUnreachableCode(stmts);
}
});
}
private void removeUnreachableCode(ImStmts stmts) {
Iterator<ImStmt> it = stmts.iterator();
boolean reachable = true;
while (it.hasNext()) {
ImStmt s = it.next();
if (reachable) {
if (s instanceof ImReturn) {
reachable = false;
} else if (s instanceof ImExitwhen) {
ImExitwhen imExitwhen = (ImExitwhen) s;
ImExpr expr = imExitwhen.getCondition();
if (expr instanceof ImBoolVal) {
boolean b = ((ImBoolVal) expr).getValB();
if (b) {
// found "exitwhen true"
reachable = false;
}
}
}
} else {
// it.remove();
}
}
}
/** Recursively optimizes the element */
private void optimizeElement(JassImElement elem) {
// optimize children:
for (int i = 0; i < elem.size(); i++) {
optimizeElement(elem.get(i));
}
if (elem instanceof ImOperatorCall) {
ImOperatorCall opc = (ImOperatorCall) elem;
optimizeOpCall(opc);
} else if (elem instanceof ImIf) {
ImIf imIf = (ImIf) elem;
optimizeIf(imIf);
} else if (elem instanceof ImExitwhen) {
ImExitwhen imExitwhen = (ImExitwhen) elem;
optimizeExitwhen(imExitwhen);
}
}
private void optimizeExitwhen(ImExitwhen imExitwhen) {
ImExpr expr = imExitwhen.getCondition();
if (expr instanceof ImBoolVal) {
boolean b = ((ImBoolVal) expr).getValB();
if (!b) {
imExitwhen.replaceWith(JassIm.ImNull());
}
}
}
private void optimizeOpCall(ImOperatorCall opc) {
// Binary
if (opc.getArguments().size() > 1) {
ImExpr left = opc.getArguments().get(0);
ImExpr right = opc.getArguments().get(1);
if (left instanceof ImBoolVal && right instanceof ImBoolVal) {
boolean b1 = ((ImBoolVal) left).getValB();
boolean b2 = ((ImBoolVal) right).getValB();
boolean result;
switch (opc.getOp()) {
case OR:
result = b1 || b2;
break;
case AND:
result = b1 && b2;
break;
case EQ:
result = b1 == b2;
break;
case NOTEQ:
result = b1 != b2;
break;
default:
result = false;
break;
}
opc.replaceWith(JassIm.ImBoolVal(result));
} else if (left instanceof ImIntVal && right instanceof ImIntVal) {
int i1 = ((ImIntVal) left).getValI();
int i2 = ((ImIntVal) right).getValI();
boolean isConditional = false;
boolean isArithmetic = false;
boolean result = false;
int resultVal = 0;
switch (opc.getOp()) {
case GREATER:
result = i1 > i2;
isConditional = true;
break;
case GREATER_EQ:
result = i1 >= i2;
isConditional = true;
break;
case LESS:
result = i1 < i2;
isConditional = true;
break;
case LESS_EQ:
result = i1 <= i2;
isConditional = true;
break;
case EQ:
result = i1 == i2;
isConditional = true;
break;
case NOTEQ:
result = i1 != i2;
isConditional = true;
break;
case PLUS:
resultVal = i1 + i2;
isArithmetic = true;
break;
case MINUS:
resultVal = i1 - i2;
isArithmetic = true;
break;
case MULT:
resultVal = i1 * i2;
isArithmetic = true;
break;
case MOD_INT:
if (i2 != 0) {
resultVal = i1 % i2;
isArithmetic = true;
}
break;
case MOD_REAL:
float f1 = i1;
float f2 = i2;
if (f2 != 0) {
float resultF = f1 % f2;
opc.replaceWith(JassIm.ImRealVal(String.valueOf(resultF)));
}
break;
case DIV_INT:
if (i2 != 0) {
resultVal = i1 / i2;
isArithmetic = true;
}
break;
case DIV_REAL:
float f3 = i1;
float f4 = i2;
if (f4 != 0) {
float resultF = f3 / f4;
opc.replaceWith(JassIm.ImRealVal(String.valueOf(resultF)));
}
break;
default:
result = false;
isConditional = false;
isArithmetic = false;
break;
}
if (isConditional) {
opc.replaceWith(JassIm.ImBoolVal(result));
} else if (isArithmetic) {
opc.replaceWith(JassIm.ImIntVal(resultVal));
}
} else if (left instanceof ImRealVal && right instanceof ImRealVal) {
float f1 = Float.parseFloat(((ImRealVal) left).getValR());
float f2 = Float.parseFloat(((ImRealVal) right).getValR());
boolean isConditional = false;
boolean isArithmetic = false;
boolean result = false;
float resultVal = 0;
switch (opc.getOp()) {
case GREATER:
result = f1 > f2;
isConditional = true;
break;
case GREATER_EQ:
result = f1 >= f2;
isConditional = true;
break;
case LESS:
result = f1 < f2;
isConditional = true;
break;
case LESS_EQ:
result = f1 <= f2;
isConditional = true;
break;
case EQ:
result = f1 == f2;
isConditional = true;
break;
case NOTEQ:
result = f1 != f2;
isConditional = true;
break;
case PLUS:
resultVal = f1 + f2;
isArithmetic = true;
break;
case MINUS:
resultVal = f1 - f2;
isArithmetic = true;
break;
case MULT:
resultVal = f1 * f2;
isArithmetic = true;
break;
case MOD_REAL:
if (f2 != 0) {
resultVal = f1 % f2;
isArithmetic = true;
}
break;
case DIV_INT:
if (f2 != 0) {
resultVal = f1 / f2;
isArithmetic = true;
}
break;
case DIV_REAL:
if (f2 != 0) {
resultVal = f1 / f2;
isArithmetic = true;
}
break;
default:
result = false;
isConditional = false;
isArithmetic = false;
break;
}
if (isConditional) {
opc.replaceWith(JassIm.ImBoolVal(result));
} else if (isArithmetic) {
// convert result to string, using 4 decimal digits
String s = floatToStringWith4decimalDigits(resultVal);
// String s = new BigDecimal(resultVal).toPlainString();
// check if the string representation is exact
if (Float.parseFloat(s) == resultVal) {
opc.replaceWith(JassIm.ImRealVal(s));
}
}
}
}
// Unary
else {
ImExpr expr = opc.getArguments().get(0);
if (expr instanceof ImBoolVal) {
boolean b1 = ((ImBoolVal) expr).getValB();
boolean result;
switch (opc.getOp()) {
case NOT:
result = !b1;
break;
default:
result = false;
break;
}
opc.replaceWith(JassIm.ImBoolVal(result));
} else if (opc.getOp() == WurstOperator.NOT && expr instanceof ImOperatorCall) {
// optimize negation of some operators
ImOperatorCall inner = (ImOperatorCall) expr;
switch (inner.getOp()) {
case NOT:
opc.replaceWith(inner.getArguments().remove(0));
break;
case EQ:
case NOTEQ:
case LESS:
case LESS_EQ:
case GREATER:
case GREATER_EQ:
opc.replaceWith(JassIm.ImOperatorCall(oppositeOperator(inner.getOp()),
JassIm.ImExprs(inner.getArguments().removeAll())));
break;
}
}
}
}
/** returns the opposite of an operator */
private WurstOperator oppositeOperator(WurstOperator op) {
switch (op) {
case EQ:
return WurstOperator.NOTEQ;
case GREATER:
return WurstOperator.LESS_EQ;
case GREATER_EQ:
return WurstOperator.LESS;
case LESS:
return WurstOperator.GREATER_EQ;
case LESS_EQ:
return WurstOperator.GREATER;
case NOTEQ:
return WurstOperator.EQ;
default:
throw new Error("operator " + op + " does not have an opposite.");
}
}
private static String floatToStringWith4decimalDigits(float resultVal) {
DecimalFormat format = new DecimalFormat();
// use a fixed locale, so that it does not randomly replace a dot by
// comma on German PCs
// hope this works
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(4);
format.setMinimumFractionDigits(0);
format.setGroupingUsed(false);
String s = format.format(resultVal);
return s;
}
private void optimizeIf(ImIf imIf) {
if (imIf.getThenBlock().isEmpty() && imIf.getElseBlock().isEmpty()) {
imIf.replaceWith(imIf.getCondition().copy());
} else if (imIf.getCondition() instanceof ImBoolVal) {
ImBoolVal boolVal = (ImBoolVal) imIf.getCondition();
if (boolVal.getValB()) {
// we have something like 'if true ...'
// replace the if statement with the then-block
// we have to use ImStatementExpr to get multiple statements
// into one statement as needed
// for the replaceWith function
// we need to copy the thenBlock because otherwise it would have
// two parents (we have not removed it from the old if-block)
imIf.replaceWith(JassIm.ImStatementExpr(imIf.getThenBlock().copy(), JassIm.ImNull()));
} else {
if (!imIf.getElseBlock().isEmpty()) {
imIf.replaceWith(JassIm.ImStatementExpr(imIf.getElseBlock().copy(), JassIm.ImNull()));
} else {
imIf.replaceWith(JassIm.ImNull());
}
}
}
}
}
|
package io.debezium.connector.oracle;
import java.io.IOException;
import java.sql.SQLRecoverableException;
import io.debezium.connector.base.ChangeEventQueue;
import io.debezium.pipeline.ErrorHandler;
import oracle.net.ns.NetException;
/**
* Error handle for Oracle.
*
* @author Chris Cranford
*/
public class OracleErrorHandler extends ErrorHandler {
public OracleErrorHandler(String logicalName, ChangeEventQueue<?> queue) {
super(OracleConnector.class, logicalName, queue);
}
@Override
protected boolean isRetriable(Throwable throwable) {
if (throwable.getMessage() == null || throwable.getCause() == null) {
return false;
}
return throwable.getMessage().startsWith("ORA-03135") || // connection lost
throwable.getMessage().startsWith("ORA-12543") || // TNS:destination host unreachable
throwable.getMessage().startsWith("ORA-00604") || // error occurred at recursive SQL level 1
throwable.getMessage().startsWith("ORA-01089") || // Oracle immediate shutdown in progress
throwable.getCause() instanceof IOException ||
throwable instanceof SQLRecoverableException ||
throwable.getMessage().toUpperCase().startsWith("NO MORE DATA TO READ FROM SOCKET") ||
(throwable.getCause() != null && throwable.getCause().getCause() instanceof NetException);
}
}
|
package org.jnosql.diana.column.query;
import jakarta.nosql.QueryException;
import jakarta.nosql.column.ColumnEntity;
import jakarta.nosql.column.ColumnFamilyManager;
import jakarta.nosql.column.ColumnObserverParser;
import jakarta.nosql.column.ColumnPreparedStatement;
import jakarta.nosql.column.ColumnQueryParser;
import java.util.Objects;
import java.util.stream.Stream;
/**
* The default implementation of {@link ColumnQueryParser}
*/
public final class DefaultColumnQueryParser implements ColumnQueryParser {
private final DefaultSelectQueryConverter select = new DefaultSelectQueryConverter();
private final DefaultDeleteQueryConverter delete = new DefaultDeleteQueryConverter();
private final InsertQueryParser insert = new InsertQueryParser();
private final UpdateQueryParser update = new UpdateQueryParser();
@Override
public Stream<ColumnEntity> query(String query, ColumnFamilyManager manager, ColumnObserverParser observer) {
validation(query, manager, observer);
String command = query.substring(0, 6);
switch (command) {
case "select":
return select.query(query, manager, observer);
case "delete":
return delete.query(query, manager, observer);
case "insert":
return insert.query(query, manager, observer);
case "update":
return update.query(query, manager, observer);
default:
throw new QueryException(String.format("The command was not recognized at the query %s ", query));
}
}
@Override
public ColumnPreparedStatement prepare(String query, ColumnFamilyManager manager, ColumnObserverParser observer) {
validation(query, manager, observer);
String command = query.substring(0, 6);
switch (command) {
case "select":
return select.prepare(query, manager, observer);
case "delete":
return delete.prepare(query, manager, observer);
case "insert":
return insert.prepare(query, manager, observer);
case "update":
return update.prepare(query, manager, observer);
default:
throw new QueryException(String.format("The command was not recognized at the query %s ", query));
}
}
private void validation(String query, ColumnFamilyManager manager, ColumnObserverParser observer) {
Objects.requireNonNull(query, "query is required");
Objects.requireNonNull(manager, "manager is required");
Objects.requireNonNull(observer, "manager is observer");
if (query.length() < 6) {
throw new QueryException(String.format("The query %s is invalid", query));
}
}
}
|
package org.cytoscape.ding.impl;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.RootPaneContainer;
import javax.swing.Timer;
import org.cytoscape.ding.DVisualLexicon;
import org.cytoscape.ding.PrintLOD;
import org.cytoscape.ding.debug.DebugCallback;
import org.cytoscape.ding.icon.VisualPropertyIconFactory;
import org.cytoscape.ding.impl.canvas.CompositeGraphicsCanvas;
import org.cytoscape.ding.impl.canvas.MainRenderComponent;
import org.cytoscape.ding.impl.canvas.NetworkImageBuffer;
import org.cytoscape.ding.impl.canvas.NetworkTransform;
import org.cytoscape.ding.impl.cyannotator.AnnotationFactoryManager;
import org.cytoscape.ding.impl.cyannotator.CyAnnotator;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.event.DebounceTimer;
import org.cytoscape.graph.render.stateful.EdgeDetails;
import org.cytoscape.graph.render.stateful.GraphLOD;
import org.cytoscape.graph.render.stateful.GraphLOD.RenderEdges;
import org.cytoscape.graph.render.stateful.NodeDetails;
import org.cytoscape.graph.render.stateful.RenderDetailFlags;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.session.events.SessionAboutToBeSavedListener;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.CyNetworkViewListener;
import org.cytoscape.view.model.CyNetworkViewSnapshot;
import org.cytoscape.view.model.View;
import org.cytoscape.view.model.VisualProperty;
import org.cytoscape.view.model.events.UpdateNetworkPresentationEvent;
import org.cytoscape.view.model.spacial.SpacialIndex2D;
import org.cytoscape.view.presentation.RenderingEngine;
import org.cytoscape.view.presentation.property.BasicVisualLexicon;
import org.cytoscape.view.presentation.property.values.HandleFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class acts as a controller for rendering one CyNetworkView.
* It initializes all the classes needed for rendering and acts as a bridge
* between them.
*
*/
public class DRenderingEngine implements RenderingEngine<CyNetwork>, Printable, CyNetworkViewListener {
private static final Logger logger = LoggerFactory.getLogger(DRenderingEngine.class);
protected static int DEF_SNAPSHOT_SIZE = 400;
public enum UpdateType {
ALL_FAST, // Render a fast frame
ALL_FULL, // Render a fast frame, then start rendering a full frame async
JUST_ANNOTATIONS, // Just render annotations fast
JUST_EDGES
}
private final CyServiceRegistrar serviceRegistrar;
private final CyEventHelper eventHelper;
private final DVisualLexicon lexicon;
private final CyNetworkView viewModel;
private CyNetworkViewSnapshot viewModelSnapshot;
// Common object lock used for state synchronization
final DingLock dingLock = new DingLock();
private final NodeDetails nodeDetails;
private final EdgeDetails edgeDetails;
private final DingGraphLODAll dingGraphLODAll = new DingGraphLODAll();
private final DingGraphLOD dingGraphLOD;
private MainRenderComponent renderComponent;
private NetworkPicker picker;
// Snapshot of current view. Will be updated by CONTENT_CHANGED event.
private BufferedImage snapshotImage;
// Represents current snapshot is latest version or not.
private boolean latestSnapshot;
private final Properties props;
private final CyAnnotator cyAnnotator;
//Flag that indicates that the content has changed and the graph needs to be redrawn.
private volatile boolean contentChanged = true;
private final List<ContentChangeListener> contentChangeListeners = new CopyOnWriteArrayList<>();
private final List<ThumbnailChangeListener> thumbnailChangeListeners = new CopyOnWriteArrayList<>();
private Timer animationTimer;
private final Timer checkDirtyTimer;
private final DebounceTimer eventFireTimer;
private final BendStore bendStore;
private InputHandlerGlassPane inputHandler = null;
private DebugCallback debugCallback;
// This is Ding's own rendering thread. All rendering is single-threaded, but off the EDT
private final ExecutorService singleThreadExecutor;
public DRenderingEngine(
final CyNetworkView view,
final DVisualLexicon dingLexicon,
final AnnotationFactoryManager annMgr,
final DingGraphLOD dingGraphLOD,
final HandleFactory handleFactory,
final CyServiceRegistrar registrar
) {
this.serviceRegistrar = registrar;
this.eventHelper = registrar.getService(CyEventHelper.class);
this.props = new Properties();
this.viewModel = view;
this.lexicon = dingLexicon;
this.dingGraphLOD = dingGraphLOD;
this.singleThreadExecutor = Executors.newSingleThreadExecutor(r -> {
Thread thread = Executors.defaultThreadFactory().newThread(r);
thread.setName("ding-" + thread.getName());
return thread;
});
this.bendStore = new BendStore(this, eventHelper, handleFactory);
nodeDetails = new DNodeDetails(this, registrar);
edgeDetails = new DEdgeDetails(this);
// Finally, intialize our annotations
cyAnnotator = new CyAnnotator(this, annMgr, registrar);
registrar.registerService(cyAnnotator, SessionAboutToBeSavedListener.class, new Properties());
renderComponent = new MainRenderComponent(this, dingGraphLOD);
picker = new NetworkPicker(this, null);
// Updating the snapshot for nested networks
addContentChangeListener(() -> latestSnapshot = false);
viewModelSnapshot = viewModel.createSnapshot();
eventFireTimer = new DebounceTimer(240);
// Check if the view model has changed approximately 30 times per second
checkDirtyTimer = new Timer(30, e -> checkModelIsDirty());
checkDirtyTimer.setRepeats(true);
checkDirtyTimer.start();
renderComponent.addTransformChangeListener(() -> {
fireThumbnailChanged(null);
});
}
public void install(RootPaneContainer rootPane) {
InputHandlerGlassPane glassPane = getInputHandlerGlassPane();
rootPane.setGlassPane(glassPane);
rootPane.setContentPane(renderComponent);
glassPane.setVisible(true);
}
public void install(JComponent component) {
component.setLayout(new BorderLayout());
component.add(renderComponent, BorderLayout.CENTER);
}
public void setDebugCallback(DebugCallback callback) {
this.debugCallback = callback;
}
public DebugCallback getDebugCallback() {
return debugCallback;
}
public Image getImage() {
return renderComponent.getImage();
}
public ExecutorService getSingleThreadExecutorService() {
return singleThreadExecutor;
}
public Rectangle getComponentBounds() {
return renderComponent.getBounds();
}
public Point getComponentCenter() {
var bounds = renderComponent.getBounds();
int centerX = bounds.x + bounds.width / 2;
int centerY = bounds.y + bounds.height / 2;
return new Point(centerX, centerY);
}
public NetworkPicker getPicker() {
return picker;
}
public NetworkTransform getTransform() {
return renderComponent.getTransform();
}
public GraphLOD getGraphLOD() {
return dingGraphLOD;
}
/**
* TEMPORARY
*
* This is being called by a Swing Timer, so this method is being run on the EDT.
* Painting is also done on the EDT. This is how we make sure that viewModelSnapshot does not
* change while a frame is being rendered.
*
* Also the EDT will coalesce paint events, so if the timer runs faster than the frame rate the
* EDT will take care of that.
*
* MKTODO Move drawing off the EDT.
* If we move drawing off the EDT then we need another solution for ensuring that viewModelSnapshot
* does not get re-assigned while a frame is being drawn.
*/
private void checkModelIsDirty() {
final boolean updateModel = viewModel.isDirty(true);
final boolean updateView = updateModel || contentChanged;
if(updateModel) {
updateModel();
}
if(updateView) {
updateView(UpdateType.ALL_FULL);
}
contentChanged = false;
}
private void updateModelAndView() {
updateModel();
updateView(UpdateType.ALL_FULL);
}
public void updateView(UpdateType updateType) {
renderComponent.updateView(updateType);
if(contentChanged) {
fireContentChanged();
}
setContentChanged(false);
// Fire this event on another thread (and debounce) so that it doesn't block the renderer
if(!eventFireTimer.isShutdown())
eventFireTimer.debounce(() -> eventHelper.fireEvent(new UpdateNetworkPresentationEvent(getViewModel())));
}
private void updateModel() {
// create a new snapshot, this should be very fast
viewModelSnapshot = viewModel.createSnapshot();
// Check for important changes between snapshots
Paint backgroundPaint = viewModelSnapshot.getVisualProperty(BasicVisualLexicon.NETWORK_BACKGROUND_PAINT);
renderComponent.setBackgroundPaint(backgroundPaint);
Collection<View<CyEdge>> animatedEdges = viewModelSnapshot.getTrackedEdges(DingNetworkViewFactory.ANIMATED_EDGES);
edgeDetails.updateAnimatedEdges(animatedEdges);
if(animatedEdges.isEmpty() && animationTimer != null) {
animationTimer.stop();
animationTimer = null;
} else if(!animatedEdges.isEmpty() && animationTimer == null) {
animationTimer = new Timer(200, e -> advanceAnimatedEdges());
animationTimer.setRepeats(true);
animationTimer.start();
}
// update LOD
boolean hd = viewModelSnapshot.getVisualProperty(DVisualLexicon.NETWORK_FORCE_HIGH_DETAIL);
renderComponent.setLOD(hd ? dingGraphLODAll : dingGraphLOD);
// update view (for example if "fit selected" was run)
double x = viewModelSnapshot.getVisualProperty(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION);
double y = viewModelSnapshot.getVisualProperty(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION);
renderComponent.setCenter(x, y);
double scaleFactor = viewModelSnapshot.getVisualProperty(BasicVisualLexicon.NETWORK_SCALE_FACTOR);
renderComponent.setScaleFactor(scaleFactor);
boolean annotationSelection = viewModelSnapshot.getVisualProperty(DVisualLexicon.NETWORK_ANNOTATION_SELECTION);
if(!annotationSelection)
cyAnnotator.getAnnotationSelection().clear();
setContentChanged(true);
}
public Color getBackgroundColor() {
return renderComponent.getBackgroundPaint();
}
private void advanceAnimatedEdges() {
edgeDetails.advanceAnimatedEdges();
RenderDetailFlags flags = renderComponent.getLastFastRenderFlags();
if(flags.renderEdges() != RenderEdges.NONE) {
updateView(UpdateType.JUST_EDGES);
}
}
public BendStore getBendStore() {
return bendStore;
}
public synchronized InputHandlerGlassPane getInputHandlerGlassPane() {
if(inputHandler == null) {
inputHandler = new InputHandlerGlassPane(serviceRegistrar, this);
}
return inputHandler;
}
/**
* Mainly for using as a parent when showing dialogs and menus.
*/
public JComponent getComponent() {
return getInputHandlerGlassPane();
}
public NodeDetails getNodeDetails() {
return nodeDetails;
}
public EdgeDetails getEdgeDetails() {
return edgeDetails;
}
public void setContentChanged() {
setContentChanged(true);
}
private void setContentChanged(boolean b) {
contentChanged = b;
}
private void fireContentChanged() {
for(var l : contentChangeListeners) {
l.contentChanged();
}
fireThumbnailChanged(null);
}
public void addContentChangeListener(ContentChangeListener l) {
contentChangeListeners.add(l);
}
public void removeContentChangeListener(ContentChangeListener l) {
contentChangeListeners.remove(l);
}
public void addTransformChangeListener(TransformChangeListener l) {
renderComponent.addTransformChangeListener(l);
}
public void removeTransformChangeListener(TransformChangeListener l) {
renderComponent.removeTransformChangeListener(l);
}
public void addThumbnailChangeListener(ThumbnailChangeListener l) {
thumbnailChangeListeners.add(l);
}
public void removeThumbnailChangeListener(ThumbnailChangeListener l) {
thumbnailChangeListeners.remove(l);
}
void fireThumbnailChanged(Image image) {
for(var l : thumbnailChangeListeners) {
l.thumbnailChanged(image);
}
}
/**
* Set the zoom level and redraw the view.
*/
public void setZoom(double zoom) {
synchronized (dingLock) {
renderComponent.setScaleFactor(checkZoom(zoom, renderComponent.getTransform().getScaleFactor()));
}
}
public double getZoom() {
return renderComponent.getTransform().getScaleFactor();
}
@Override
public void handleFitContent() {
eventHelper.flushPayloadEvents();
synchronized (dingLock) {
// make sure we use the latest snapshot, don't wait for timer to check dirty flag
CyNetworkViewSnapshot netViewSnapshot = getViewModel().createSnapshot();
if(netViewSnapshot.getNodeCount() == 0)
return;
if(!renderComponent.isInitialized())
return;
NetworkTransform transform = renderComponent.getTransform();
if(transform.getWidth() == 0 || transform.getHeight() == 0)
return;
double[] extents = new double[4];
netViewSnapshot.getSpacialIndex2D().getMBR(extents); // extents of the network
cyAnnotator.adjustBoundsToIncludeAnnotations(extents); // extents of the annotation canvases
netViewSnapshot.getMutableNetworkView().batch(netView -> {
if (!netView.isValueLocked(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION))
netView.setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION, (extents[0] + extents[2]) / 2.0d);
if (!netView.isValueLocked(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION))
netView.setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION, (extents[1] + extents[3]) / 2.0d);
if (!netView.isValueLocked(BasicVisualLexicon.NETWORK_SCALE_FACTOR)) {
// Apply a factor 0.98 to zoom, so that it leaves a small border around the network and any annotations.
final double zoom = Math.min(((double) transform.getWidth()) / (extents[2] - extents[0]),
((double) transform.getHeight()) / (extents[3] - extents[1])) * 0.98;
// Update view model. Zoom Level should be modified.
netView.setVisualProperty(BasicVisualLexicon.NETWORK_SCALE_FACTOR, zoom);
}
});
}
// MKTODO is this necessary, the timer will check the dirty flag
updateModelAndView();
}
@Override
public void handleUpdateView() {
updateModelAndView();
}
public void zoom(int ticks) {
if(getViewModelSnapshot().isValueLocked(BasicVisualLexicon.NETWORK_SCALE_FACTOR))
return;
double factor;
if (ticks < 0)
factor = 1.1; // scroll up, zoom in
else if (ticks > 0)
factor = 0.9; // scroll down, zoom out
else
return;
double scaleFactor = renderComponent.getTransform().getScaleFactor() * factor;
setZoom(scaleFactor);
getViewModel().batch(netView -> {
netView.setVisualProperty(BasicVisualLexicon.NETWORK_SCALE_FACTOR, scaleFactor);
}, false);
}
public void pan(double deltaX, double deltaY) {
synchronized (dingLock) {
NetworkTransform transform = renderComponent.getTransform();
double x = transform.getCenterX() + deltaX;
double y = transform.getCenterY() + deltaY;
setCenter(x, y);
}
}
public void setCenter(double x, double y) {
synchronized (dingLock) {
renderComponent.setCenter(x,y);
// Update view model
// TODO: don't do it from here?
getViewModel().batch(netView -> {
NetworkTransform transform = renderComponent.getTransform();
netView.setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION, transform.getCenterX());
netView.setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION, transform.getCenterY());
}, false); // don't set the dirty flag
}
}
@Override
public void handleFitSelected() {
eventHelper.flushPayloadEvents();
CyNetworkViewSnapshot netViewSnapshot = getViewModelSnapshot();
SpacialIndex2D<Long> spacial = netViewSnapshot.getSpacialIndex2D();
Collection<View<CyNode>> selectedElms = netViewSnapshot.getTrackedNodes(DingNetworkViewFactory.SELECTED_NODES);
if(selectedElms.isEmpty())
return;
float[] extentsBuff = new float[4];
float xMin = Float.POSITIVE_INFINITY;
float yMin = Float.POSITIVE_INFINITY;
float xMax = Float.NEGATIVE_INFINITY;
float yMax = Float.NEGATIVE_INFINITY;
View<CyNode> leftMost = null;
View<CyNode> rightMost = null;
for(View<CyNode> nodeView : selectedElms) {
spacial.get(nodeView.getSUID(), extentsBuff);
if (extentsBuff[0] < xMin) {
xMin = extentsBuff[0];
leftMost = nodeView;
}
if (extentsBuff[2] > xMax) {
xMax = extentsBuff[2];
rightMost = nodeView;
}
yMin = Math.min(yMin, extentsBuff[1]);
yMax = Math.max(yMax, extentsBuff[3]);
}
float xMinF = xMin - (getLabelWidth(leftMost) / 2);
float xMaxF = xMax + (getLabelWidth(rightMost) / 2);
float yMaxF = yMax;
float yMinF = yMin;
netViewSnapshot.getMutableNetworkView().batch(netView -> {
NetworkTransform transform = renderComponent.getTransform();
if (!netView.isValueLocked(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION)) {
double zoom = Math.min(((double) transform.getWidth()) / (((double) xMaxF) - ((double) xMinF)),
((double) transform.getHeight()) / (((double) yMaxF) - ((double) yMinF)));
zoom = checkZoom(zoom, transform.getScaleFactor());
// Update view model. Zoom Level should be modified.
netView.setVisualProperty(BasicVisualLexicon.NETWORK_SCALE_FACTOR, zoom);
}
if (!netView.isValueLocked(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION)) {
double xCenter = (((double) xMinF) + ((double) xMaxF)) / 2.0d;
netView.setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION, xCenter);
}
if (!netView.isValueLocked(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION)) {
double yCenter = (((double) yMinF) + ((double) yMaxF)) / 2.0d;
netView.setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION, yCenter);
}
});
updateModelAndView();
}
private int getLabelWidth(View<CyNode> nodeView) {
var fontMetrics = renderComponent.getFontMetrics();
if (nodeView == null || fontMetrics == null)
return 0;
String s = nodeDetails.getLabelText(nodeView);
if (s == null)
return 0;
char[] lab = s.toCharArray();
return fontMetrics.charsWidth(lab, 0, lab.length);
}
// File > Print
@Override
public int print(Graphics g, PageFormat pageFormat, int page) {
if(page != 0)
return NO_SUCH_PAGE;
((Graphics2D) g).translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// make sure the whole image on the screen will fit to the printable area of the paper
var transform = renderComponent.getTransform();
double image_scale = Math.min(pageFormat.getImageableWidth() / transform.getWidth(),
pageFormat.getImageableHeight() / transform.getHeight());
if (image_scale < 1.0d) {
((Graphics2D)g).scale(image_scale, image_scale);
}
// from InternalFrameComponent
g.clipRect(0, 0, renderComponent.getWidth(), renderComponent.getHeight());
PrintLOD printLOD = new PrintLOD();
CompositeGraphicsCanvas.paint((Graphics2D)g, this, getBackgroundColor(), printLOD, transform);
return PAGE_EXISTS;
}
// File > Export Network to Image... (JPEG, PNG, PDF, POSTSCRIPT, SVG)
@Override
public void printCanvas(Graphics g) {
final boolean contentChanged = this.contentChanged;
// Check properties related to printing:
boolean exportAsShape = "true".equalsIgnoreCase(props.getProperty("exportTextAsShape"));
boolean transparent = "true".equalsIgnoreCase(props.getProperty("exportTransparentBackground"));
boolean hideLabels = "true".equalsIgnoreCase(props.getProperty("exportHideLabels"));
PrintLOD printLOD = new PrintLOD();
printLOD.setPrintingTextAsShape(exportAsShape);
printLOD.setExportLabels(!hideLabels);
Color bg = transparent ? null : getBackgroundColor();
var transform = renderComponent.getTransform();
CompositeGraphicsCanvas.paint((Graphics2D)g, this, bg, printLOD, transform);
// Keep previous dirty flags, otherwise the actual view canvas may not be updated next time.
// (this method is usually only used to export the View as image, create thumbnails, etc,
// therefore it should not flag the Graph View as updated, because the actual view canvas
// may still have to be redrawn after this).
setContentChanged(contentChanged);
}
/**
* Method to return a reference to an Image object, which represents the current network view.
* @param width Width of desired image.
* @param height Height of desired image.
*/
@Override
public Image createImage(int width, int height) {
return createImage(width, height, false);
}
private Image createImage(int width, int height, boolean transparentBackground) {
if (width < 0 || height < 0)
throw new IllegalArgumentException("width and height arguments must be greater than zero");
// Run on the same thread as renderComponent to make sure the canvas is not in the middle of painting
// MKTODO could we reuse the birds-eye-view buffer instead of doing a full frame draw?
Future<Image> future = getSingleThreadExecutorService().submit(() -> {
// MKTODO copy-pasted from fitContent()
double[] extents = new double[4];
getViewModelSnapshot().getSpacialIndex2D().getMBR(extents); // extents of the network
cyAnnotator.adjustBoundsToIncludeAnnotations(extents); // extents of the annotation canvases
double xCenter = (extents[0] + extents[2]) / 2.0d;
double yCenter = (extents[1] + extents[3]) / 2.0d;
double zoom = Math.min(((double) width) / (extents[2] - extents[0]),
((double) height) / (extents[3] - extents[1])) * 0.98;
NetworkTransform transform = new NetworkTransform(width, height, xCenter, yCenter, zoom);
NetworkImageBuffer buffer = new NetworkImageBuffer(transform);
Color bgColor = transparentBackground ? null : getBackgroundColor();
CompositeGraphicsCanvas.paint(buffer.getGraphics(), this, bgColor, dingGraphLOD, transform);
return buffer.getImage();
});
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return null;
}
}
private double checkZoom(double zoom, double orig) {
if (zoom > 0)
return zoom;
logger.debug("invalid zoom: " + zoom + " using orig: " + orig);
return orig;
}
@Override
public Printable createPrintable() {
return this;
}
@Override
public Properties getProperties() {
return this.props;
}
@Override
public DVisualLexicon getVisualLexicon() {
return lexicon;
}
// For now the viewModelSnapshot should only be re-assigned on the EDT.
public CyNetworkViewSnapshot getViewModelSnapshot() {
return viewModelSnapshot;
}
@Override
public CyNetworkView getViewModel() {
return viewModel;
}
@Override
public <V> Icon createIcon(VisualProperty<V> vp, V value, int w, int h) {
return VisualPropertyIconFactory.createIcon(value, w, h);
}
/**
* Returns the current snapshot image of this view.
*
* <p>
* No unnecessary image object will be created if networks in the current
* session does not contain any nested network, i.e., should not have
* performance/memory issue.
*
* @return Image of this view. It is always up-to-date.
*/
protected TexturePaint getSnapshot(final double width, final double height) {
if(!latestSnapshot) {
// Need to update snapshot.
snapshotImage = (BufferedImage) createImage(DEF_SNAPSHOT_SIZE, DEF_SNAPSHOT_SIZE, true);
latestSnapshot = true;
}
// Handle non-square images
// Get the height and width of the image
int imageWidth = snapshotImage.getWidth();
int imageHeight = snapshotImage.getHeight();
double ratio = (double)imageHeight / (double) imageWidth;
int adjustedWidth = (int)((double)width/ratio)+1;
final Rectangle2D rect = new Rectangle2D.Double(-adjustedWidth / 2, -height / 2, adjustedWidth, height);
final TexturePaint texturePaint = new TexturePaint(snapshotImage, rect);
return texturePaint;
}
public CyAnnotator getCyAnnotator() {
return cyAnnotator;
}
public CyServiceRegistrar getServiceRegistrar() {
return serviceRegistrar;
}
@Override
public void handleDispose() {
dispose();
}
@Override
public void dispose() {
synchronized(this) {
if (inputHandler != null)
inputHandler.dispose();
checkDirtyTimer.stop();
eventFireTimer.shutdown();
cyAnnotator.dispose();
serviceRegistrar.unregisterAllServices(cyAnnotator);
renderComponent.dispose();
}
}
@Override
public String getRendererId() {
return DingRenderer.ID;
}
}
|
package com.documents4j.standalone;
public class CommandDescription {
public static final String ARGUMENT_LONG_BASE_FOLDER = "base-folder";
public static final String ARGUMENT_SHORT_BASE_FOLDER = "F";
public static final String DESCRIPTION_ARGUMENT_BASE_FOLDER = "A directory for saving temporary files and executable " +
"scripts. If not set, a temporary folder will be generated automatically.";
public static final String DESCRIPTION_CONTEXT_BASE_FOLDER = "The conversion software needs to save MS Office files to disc " +
"before they can be converted by a MS Office product. All such files will be safed in this directory and deleted when " +
"the conversion completed. Also, MS Office will be run by scripts. All theses scripts will be executed from this folder.";
public static final String ARGUMENT_LONG_CORE_POOL_SIZE = "core-size";
public static final String ARGUMENT_SHORT_CORE_POOL_SIZE = "S";
public static final String DESCRIPTION_ARGUMENT_CORE_POOL_SIZE = "The number of threads constantly " +
"ready to process conversions.";
public static final String DESCRIPTION_CONTEXT_CORE_POOL_SIZE = "These threads will be constantly held ready for picking " +
"up conversion jobs. This number should be adjusted to the share of regular conversions that are processed by this server on " +
"average. These threads are never killed. Idle threads do however imply a cost for maintenance. Together with the number of fallback " +
"thread, this parameter implicitly determines the number of maximum concurrent conversions. This number should not be set to high " +
"since the concurrent execution of too many shell processes can result in the operating system killing this application.";
public static final String ARGUMENT_LONG_MAXIMUM_POOL_SIZE = "fallback-size";
public static final String ARGUMENT_SHORT_MAXIMUM_POOL_SIZE = "B";
public static final String DESCRIPTION_ARGUMENT_MAXIMUM_POOL_SIZE = "The number of threads that " +
"are created dynamically when all core threads are busy.";
public static final String DESCRIPTION_CONTEXT_MAXIMUM_POOL_SIZE = "These threads will be created on demand if all core " +
"threads are busy. These threads can be used to overcome peaks. Their creation and maintenance does however imply a " +
"small overhead. Such threads will be destroyed after they were idle for a specified amount of milliseconds.";
public static final String ARGUMENT_LONG_KEEP_ALIVE_TIME = "lifetime";
public static final String ARGUMENT_SHORT_KEEP_ALIVE_TIME = "T";
public static final String DESCRIPTION_ARGUMENT_THREAD_POOL_FALLBACK_LIFE_TIME = "The number of milliseconds until " +
"an idle non-core thread is destroyed.";
public static final String DESCRIPTION_CONTEXT_KEEP_ALIVE_TIME = "Both the creation/destruction of a thread " +
"and its maintenance imply the use of system resources. A too high number will result in too many idle threads while " +
"a too low number will cause the constant creation and destruction of threads.";
public static final String ARGUMENT_LONG_PROCESS_TIME_OUT = "process-timeout";
public static final String ARGUMENT_SHORT_PROCESS_TIME_OUT = "P";
public static final String DESCRIPTION_ARGUMENT_PROCESS_TIME_OUT = "The number of milliseconds until a " +
"conversion process times out.";
public static final String DESCRIPTION_CONTEXT_PROCESS_TIME_OUT = "A conversion process is conducted by the execution " +
"of a shell script. Such executions might crash for reasons that cannot be observed by an application running on " +
"the Java Virtual Machine. Therefore, a timeout needs determine the maximum time for a shell process to terminate " +
"regularly. This time out is applied per file and counts only the time of actual conversion by an MS Office product.";
public static final String ARGUMENT_LONG_REQUEST_TIMEOUT = "request-timeout";
public static final String ARGUMENT_SHORT_REQUEST_TIMEOUT = "R";
public static final String DESCRIPTION_ARGUMENT_REQUEST_TIMEOUT = "The number of milliseconds until a web request times out.";
public static final String DESCRIPTION_CONTEXT_REQUEST_TIMEOUT = "If a web request cannot be answered in the specified amount of " +
"time, the request and the corresponding conversion will be cancelled. This timeout also applies, if the requesting entity " +
"fails to confirm an answer within this time frame. This value should be set considerably higher than the timeout " +
"of a conversion process. A too low value will result in requesting entities to be denied file conversion if the server " +
"is currently very busy.";
public static final String ARGUMENT_LONG_SSL = "ssl";
public static final String ARGUMENT_SHORT_SSL = "E";
public static final String DESCRIPTION_CONTEXT_SSL = "Registers the JVM's default SSL context for encryption of conversions.";
public static final String ARGUMENT_LONG_LOG_TO_FILE = "log";
public static final String ARGUMENT_SHORT_LOG_TO_FILE = "L";
public static final String DESCRIPTION_ARGUMENT_LOG_TO_FILE = "A file to which all log information will be written. If " +
"not set, all log information will be written to the console.";
public static final String DESCRIPTION_CONTEXT_LOG_TO_FILE = "This file will contain all log information instead of writing " +
"the log output to the console. Make sure that this file can be written to and that no other application holds locks to it.";
public static final String ARGUMENT_LONG_LOG_LEVEL = "level";
public static final String ARGUMENT_SHORT_LOG_LEVEL = "V";
public static final String DESCRIPTION_ARGUMENT_LOG_LEVEL = "The log level which determines the verbosity of the log messages. " +
"If this property is not set, only warnings and error messages are logged to the console.";
public static final String DESCRIPTION_CONTEXT_LOG_LEVEL = "The log level determines the verbosity of the logging that is enforced " +
"by the converter. Valid log levels are 'off', 'error', 'warn', 'info', 'debug' and 'trace'. Without explicit configuration, " +
"the 'warn' level is activated which is also the recommended level for production use of the converter.";
public static final String ARGUMENT_LONG_ENABLED_CONVERTER = "enable";
public static final String ARGUMENT_SHORT_ENABLED_CONVERTER = "E";
public static final String DESCRIPTION_ARGUMENT_ENABLED_CONVERTER = "The fully qualified Java class name of the document converter to enable.";
public static final String DESCRIPTION_CONTEXT_ENABLED_CONVERTER = "Without any explicit setup, the conversion server picks up any known " +
"document converter from the class path. By using this command, a custom conversion server can be installed, additionally to those " +
"that are discovered automatically.";
public static final String ARGUMENT_LONG_DISABLED_CONVERTER = "disable";
public static final String ARGUMENT_SHORT_DISABLED_CONVERTER = "D";
public static final String DESCRIPTION_ARGUMENT_DISABLED_CONVERTER = "The fully qualified Java class name of the document converter to disable.";
public static final String DESCRIPTION_CONTEXT_DISABLED_CONVERTER = "The conversion server picks up any known document converter from the class " +
"path. A converter can be disabled by either removing it from the class path or by specifying it by this command. If a converter is both " +
"specified to be enabled and disabled, it is considered to be enabled.";
public static final String ARGUMENT_LONG_HELP = "help";
public static final String ARGUMENT_SHORT_HELP = "?";
public static final String DESCRIPTION_CONTEXT_HELP = "Displays information about this application.";
public static final String DESCRIPTION_BASE_URI = "The base URI of the conversion server. (e.g. http://localhost:8080)";
private CommandDescription() {
throw new UnsupportedOperationException();
}
}
|
package com.mbppower;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.hardware.Camera;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.List;
public class CameraPreview extends CordovaPlugin implements CameraActivity.CameraPreviewListener {
private final String TAG = "CameraPreview";
private final String setOnPictureTakenHandlerAction = "setOnPictureTakenHandler";
private final String setColorEffectAction = "setColorEffect";
private final String startCameraAction = "startCamera";
private final String stopCameraAction = "stopCamera";
private final String switchCameraAction = "switchCamera";
private final String takePictureAction = "takePicture";
private final String showCameraAction = "showCamera";
private final String hideCameraAction = "hideCamera";
private final String getSupportedResolutionsAction = "getSupportedResolutions";
private CameraActivity fragment;
private CallbackContext takePictureCallbackContext;
private int containerViewId = 1;
public CameraPreview(){
super();
Log.d(TAG, "Constructing");
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (setOnPictureTakenHandlerAction.equals(action)){
return setOnPictureTakenHandler(args, callbackContext);
}
else if (startCameraAction.equals(action)){
return startCamera(args, callbackContext);
}
else if (takePictureAction.equals(action)){
return takePicture(args, callbackContext);
}
else if (setColorEffectAction.equals(action)){
return setColorEffect(args, callbackContext);
}
else if (stopCameraAction.equals(action)){
return stopCamera(args, callbackContext);
}
else if (hideCameraAction.equals(action)){
return hideCamera(args, callbackContext);
}
else if (showCameraAction.equals(action)){
return showCamera(args, callbackContext);
}
else if (switchCameraAction.equals(action)){
return switchCamera(args, callbackContext);
}
else if (getSupportedResolutionsAction.equals(action)) {
return getSupportedResolutions(args, callbackContext);
}
return false;
}
private boolean getSupportedResolutions(final JSONArray args, CallbackContext callbackContext) {
List<Camera.Size> supportedPhotoSizes;
Camera camera = fragment.getCamera();
if (camera != null) {
supportedPhotoSizes = camera.getParameters().getSupportedPictureSizes();
if (supportedPhotoSizes != null) {
JSONArray sizes = new JSONArray();
for (int i=0; i<supportedPhotoSizes.size(); i++) {
Camera.Size size = supportedPhotoSizes.get(i);
int h = size.height;
int w = size.width;
JSONObject jsonSize = new JSONObject();
jsonSize.put("height", new Integer(h)).put("width", new Integer(w));
sizes.put(jsonSize);
}
callbackContext.success(sizes);
return true;
}
callbackContext.error("Camera Parameters access error");
return false;
}
callbackContext.error("Camera needs to be started first");
return false;
}
private boolean startCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment != null){
return false;
}
fragment = new CameraActivity();
fragment.setEventListener(this);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
DisplayMetrics metrics = cordova.getActivity().getResources().getDisplayMetrics();
int x = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(0), metrics);
int y = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(1), metrics);
int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(2), metrics);
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, args.getInt(3), metrics);
String defaultCamera = invertCamera(args.getString(4));
Boolean tapToTakePicture = args.getBoolean(5);
Boolean dragEnabled = args.getBoolean(6);
Boolean toBack = args.getBoolean(7);
fragment.defaultCamera = defaultCamera;
fragment.tapToTakePicture = tapToTakePicture;
fragment.dragEnabled = dragEnabled;
fragment.setRect(x, y, width, height);
//create or update the layout params for the container view
FrameLayout containerView = (FrameLayout)cordova.getActivity().findViewById(containerViewId);
if(containerView == null){
containerView = new FrameLayout(cordova.getActivity().getApplicationContext());
containerView.setId(containerViewId);
FrameLayout.LayoutParams containerLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
cordova.getActivity().addContentView(containerView, containerLayoutParams);
}
//display camera bellow the webview
if(toBack){
webView.getView().setBackgroundColor(0x00000000);
((ViewGroup)webView.getView()).bringToFront();
}
else{
//set camera back to front
containerView.bringToFront();
}
//add the fragment to the container
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(containerView.getId(), fragment);
fragmentTransaction.commit();
fragment.switchCamera();
}
catch(Exception e){
e.printStackTrace();
}
}
});
return true;
}
private String invertCamera(String originalCamera) {
return originalCamera == "front" ? "back":"front";
}
private boolean takePicture(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
return false;
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
try {
double maxWidth = args.getDouble(0);
double maxHeight = args.getDouble(1);
fragment.takePicture(maxWidth, maxHeight);
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
public void onPictureTaken(String originalPicturePath){//, String previewPicturePath){
JSONArray data = new JSONArray();
data.put(originalPicturePath);//.put(previewPicturePath);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, data);
pluginResult.setKeepCallback(true);
takePictureCallbackContext.sendPluginResult(pluginResult);
}
private boolean setColorEffect(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
return false;
}
Camera camera = fragment.getCamera();
if (camera == null){
return true;
}
Camera.Parameters params = camera.getParameters();
try {
String effect = args.getString(0);
if (effect.equals("aqua")) {
params.setColorEffect(Camera.Parameters.EFFECT_AQUA);
} else if (effect.equals("blackboard")) {
params.setColorEffect(Camera.Parameters.EFFECT_BLACKBOARD);
} else if (effect.equals("mono")) {
params.setColorEffect(Camera.Parameters.EFFECT_MONO);
} else if (effect.equals("negative")) {
params.setColorEffect(Camera.Parameters.EFFECT_NEGATIVE);
} else if (effect.equals("none")) {
params.setColorEffect(Camera.Parameters.EFFECT_NONE);
} else if (effect.equals("posterize")) {
params.setColorEffect(Camera.Parameters.EFFECT_POSTERIZE);
} else if (effect.equals("sepia")) {
params.setColorEffect(Camera.Parameters.EFFECT_SEPIA);
} else if (effect.equals("solarize")) {
params.setColorEffect(Camera.Parameters.EFFECT_SOLARIZE);
} else if (effect.equals("whiteboard")) {
params.setColorEffect(Camera.Parameters.EFFECT_WHITEBOARD);
}
fragment.setCameraParameters(params);
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
private boolean stopCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
return false;
}
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
fragment = null;
return true;
}
private boolean showCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
return false;
}
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.show(fragment);
fragmentTransaction.commit();
return true;
}
private boolean hideCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null) {
return false;
}
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.hide(fragment);
fragmentTransaction.commit();
return true;
}
private boolean switchCamera(final JSONArray args, CallbackContext callbackContext) {
if(fragment == null){
return false;
}
fragment.switchCamera();
return true;
}
private boolean setOnPictureTakenHandler(JSONArray args, CallbackContext callbackContext) {
Log.d(TAG, "setOnPictureTakenHandler");
takePictureCallbackContext = callbackContext;
return true;
}
}
|
package be.ibridge.kettle.core.value;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.XMLInterface;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleEOFException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleFileException;
import be.ibridge.kettle.core.exception.KettleValueException;
import be.ibridge.kettle.repository.Repository;
/**
* This class is one of the core classes of the Kettle framework.
* It contains everything you need to manipulate atomic data (Values/Fields/...)
* and to describe it in the form of meta-data. (name, length, precision, etc.)
*
* @author Matt
* @since Beginning 2003
*/
public class Value implements Cloneable, XMLInterface, Serializable
{
private static final long serialVersionUID = -6310073485210258622L;
/**
* Value type indicating that the value has no type set.
*/
public static final int VALUE_TYPE_NONE = 0;
/**
* Value type indicating that the value contains a floating point double precision number.
*/
public static final int VALUE_TYPE_NUMBER = 1;
/**
* Value type indicating that the value contains a text String.
*/
public static final int VALUE_TYPE_STRING = 2;
/**
* Value type indicating that the value contains a Date.
*/
public static final int VALUE_TYPE_DATE = 3;
/**
* Value type indicating that the value contains a boolean.
*/
public static final int VALUE_TYPE_BOOLEAN = 4;
/**
* Value type indicating that the value contains a long integer.
*/
public static final int VALUE_TYPE_INTEGER = 5;
/**
* Value type indicating that the value contains a floating point precision number with arbitrary precision.
*/
public static final int VALUE_TYPE_BIGNUMBER = 6;
/**
* The descriptions of the value types.
*/
private static final String value_type_desc[]=
{
"-",
"Number", "String", "Date", "Boolean", "Integer", "BigNumber"
};
private ValueInterface value;
private String name;
private String origin;
private boolean NULL;
/**
* Constructs a new Value of type EMPTY
*
*/
public Value()
{
clearValue();
}
/**
* Constructs a new Value with a name.
*
* @param name Sets the name of the Value
*/
public Value(String name)
{
clearValue();
setName(name);
}
/**
* Constructs a new Value with a name and a type.
*
* @param name Sets the name of the Value
* @param val_type Sets the type of the Value (Value.VALUE_TYPE_*)
*/
public Value(String name, int val_type)
{
clearValue();
newValue(val_type);
setName(name);
}
/**
* This method allocates a new value of the appropriate type..
* @param val_type The new type of value
*/
private void newValue(int val_type)
{
switch(val_type)
{
case VALUE_TYPE_NUMBER : value = new ValueNumber(); break;
case VALUE_TYPE_STRING : value = new ValueString(); break;
case VALUE_TYPE_DATE : value = new ValueDate(); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(); break;
case VALUE_TYPE_INTEGER : value = new ValueInteger(); break;
case VALUE_TYPE_BIGNUMBER: value = new ValueBigNumber(); break;
default: value = null;
}
}
/**
* Convert the value to another type. This only works if a value has been set previously.
* That is the reason this method is private. Rather, use the public method setType(int type).
*
* @param val_type The type to convert to.
*/
private void convertTo(int val_type)
{
if (value!=null)
{
switch(val_type)
{
case VALUE_TYPE_NUMBER : value = new ValueNumber(value.getNumber()); break;
case VALUE_TYPE_STRING : value = new ValueString(value.getString()); break;
case VALUE_TYPE_DATE : value = new ValueDate(value.getDate()); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(value.getBoolean()); break;
case VALUE_TYPE_INTEGER : value = new ValueInteger(value.getInteger()); break;
case VALUE_TYPE_BIGNUMBER : value = new ValueBigNumber(value.getBigNumber()); break;
default: value = null;
}
}
}
/**
* Constructs a new Value with a name, a type, length and precision.
*
* @param name Sets the name of the Value
* @param val_type Sets the type of the Value (Value.VALUE_TYPE_*)
* @param length The length of the value
* @param precision The precision of the value
*/
public Value(String name, int val_type, int length, int precision)
{
this(name, val_type);
setLength(length, precision);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BIGNUMBER, with a name, containing a BigDecimal number
*
* @param name Sets the name of the Value
* @param bignum The number to store in this Value
*/
public Value(String name, BigDecimal bignum)
{
clearValue();
setValue(bignum);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_NUMBER, with a name, containing a number
*
* @param name Sets the name of the Value
* @param num The number to store in this Value
*/
public Value(String name, double num)
{
clearValue();
setValue(num);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, StringBuffer str)
{
this(name, str.toString());
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, String str)
{
clearValue();
setValue(str);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_DATE, with a name, containing a Date
*
* @param name Sets the name of the Value
* @param dat The date to store in this Value
*/
public Value(String name, Date dat)
{
clearValue();
setValue(dat);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BOOLEAN, with a name, containing a boolean value
*
* @param name Sets the name of the Value
* @param bool The boolean to store in this Value
*/
public Value(String name, boolean bool)
{
clearValue();
setValue(bool);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_INTEGER, with a name, containing an integer number
*
* @param name Sets the name of the Value
* @param l The integer to store in this Value
*/
public Value(String name, long l)
{
clearValue();
setValue(l);
setName(name);
}
/**
* Constructs a new Value as a copy of another value and renames it...
*
* @param name The new name of the copied Value
* @param v The value to be copied
*/
public Value(String name, Value v)
{
this(v);
setName(name);
}
/**
* Constructs a new Value as a copy of another value
*
* @param v The Value to be copied
*/
public Value(Value v)
{
if (v!=null)
{
setType( v.getType() );
value = v.getValueCopy();
if (v.getName()!=null) setName(new String(v.getName())); else name=null;
setLength(v.getLength(), v.getPrecision());
setNull(v.isNull());
if (v.origin!=null) setOrigin(new String(v.origin)); else origin=null;
}
else
{
clearValue();
}
}
public Object clone()
{
Value retval = null;
try
{
retval = (Value)super.clone();
}
catch(CloneNotSupportedException e)
{
retval=null;
}
return retval;
}
/**
* Build a copy of this Value
* @return a copy of another value
*
*/
public Value Clone()
{
Value v = new Value(this);
return v;
}
/**
* Clears the content and name of a Value
*
*/
public void clearValue()
{
value = null;
name = null;
NULL = false;
origin = null;
}
private ValueInterface getValueCopy()
{
if (value==null) return null;
return (ValueInterface)value.clone();
}
/**
* Sets the name of a Value
*
* @param name The new name of the value
*/
public void setName(String name)
{
this.name = name;
}
/**
* Obtain the name of a Value
*
* @return The name of the Value
*/
public String getName()
{
return name;
}
/**
* This method allows you to set the origin of the Value by means of the name of the originating step.
*
* @param step_of_origin The step of origin.
*/
public void setOrigin(String step_of_origin)
{
origin = step_of_origin;
}
/**
* Obtain the origin of the step.
*
* @return The name of the originating step
*/
public String getOrigin()
{
return origin;
}
/**
* Sets the value to a BigDecimal number value.
* @param num The number value to set the value to
*/
public void setValue(BigDecimal num)
{
if (value==null || value.getType()!=VALUE_TYPE_BIGNUMBER) value = new ValueBigNumber(num);
else value.setBigNumber(num);
setNull(false);
}
/**
* Sets the value to a double Number value.
* @param num The number value to set the value to
*/
public void setValue(double num)
{
if (value==null || value.getType()!=VALUE_TYPE_NUMBER) value = new ValueNumber(num);
else value.setNumber(num);
setNull(false);
}
/**
* Sets the Value to a String text
* @param str The StringBuffer to get the text from
*/
public void setValue(StringBuffer str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str.toString());
else value.setString(str.toString());
setNull(str==null);
}
/**
* Sets the Value to a String text
* @param str The String to get the text from
*/
public void setValue(String str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str);
else value.setString(str);
setNull(str==null);
}
/**
* Sets the Value to a Date
* @param dat The Date to set the Value to
*/
public void setValue(Date dat)
{
if (value==null || value.getType()!=VALUE_TYPE_DATE) value = new ValueDate(dat);
else value.setDate(dat);
setNull(dat==null);
}
/**
* Sets the Value to a boolean
* @param bool The boolean to set the Value to
*/
public void setValue(boolean bool)
{
if (value==null || value.getType()!=VALUE_TYPE_BOOLEAN) value = new ValueBoolean(bool);
else value.setBoolean(bool);
setNull(false);
}
/**
* Sets the Value to a long integer
* @param b The byte to convert to a long integer to which the Value is set.
*/
public void setValue(byte b)
{
setValue((long)b);
}
/**
* Sets the Value to a long integer
* @param i The integer to convert to a long integer to which the Value is set.
*/
public void setValue(int i)
{
setValue((long)i);
}
/**
* Sets the Value to a long integer
* @param l The long integer to which the Value is set.
*/
public void setValue(long l)
{
if (value==null || value.getType()!=VALUE_TYPE_INTEGER) value = new ValueInteger(l);
else value.setInteger(l);
setNull(false);
}
/**
* Copy the Value from another Value.
* It doesn't copy the name.
* @param v The Value to copy the settings and value from
*/
public void setValue(Value v)
{
if (v!=null)
{
value = v.getValueCopy();
setNull(v.isNull());
if (v.origin!=null) setOrigin(new String(v.origin)); else origin=null;
}
else
{
clearValue();
}
}
/**
* Get the BigDecimal number of this Value.
* If the value is not of type BIG_NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public BigDecimal getBigNumber()
{
if (value==null) return null;
return value.getBigNumber();
}
/**
* Get the double precision floating point number of this Value.
* If the value is not of type NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public double getNumber()
{
if (value==null) return 0.0;
return value.getNumber();
}
/**
* Get the String text representing this value.
* If the value is not of type STRING, a conversion if done first.
* @return the String text representing this value.
*/
public String getString()
{
if (value==null) return null;
return value.getString();
}
/**
* Get the length of the String representing this value.
* @return the length of the String representing this value.
*/
public int getStringLength()
{
String s = getString();
if (s==null) return 0;
return s.length();
}
/**
* Get the Date of this Value.
* If the Value is not of type DATE, a conversion is done first.
* @return the Date of this Value.
*/
public Date getDate()
{
if (value==null) return null;
return value.getDate();
}
public boolean getBoolean()
{
if (value==null) return false;
return value.getBoolean();
}
public long getInteger()
{
if (value==null) return 0L;
return value.getInteger();
}
/**
* Set the type of this Value
* @param val_type The type to which the Value will be set.
*/
public void setType(int val_type)
{
if (value==null) newValue(val_type);
else // Convert the value to the appropriate type...
{
convertTo(val_type);
}
}
/**
* Returns the type of this Value
* @return the type of this Value
*/
public int getType()
{
if (value==null) return VALUE_TYPE_NONE;
return value.getType();
}
/**
* Checks whether or not this Value is empty.
* A value is empty if it has the type VALUE_TYPE_EMPTY
* @return true if the value is empty.
*/
public boolean isEmpty()
{
if (value==null) return true;
return false;
}
/**
* Checks wheter or not the value is a String.
* @return true if the value is a String.
*/
public boolean isString()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_STRING;
}
/**
* Checks whether or not this value is a Date
* @return true if the value is a Date
*/
public boolean isDate()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_DATE;
}
/**
* Checks whether or not the value is a Big Number
* @return true is this value is a big number
*/
public boolean isBigNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BIGNUMBER;
}
/**
* Checks whether or not the value is a Number
* @return true is this value is a number
*/
public boolean isNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_NUMBER;
}
/**
* Checks whether or not this value is a boolean
* @return true if this value has type boolean.
*/
public boolean isBoolean()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BOOLEAN;
}
/**
* Checks whether or not this value is an Integer
* @return true if this value is an integer
*/
public boolean isInteger()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_INTEGER;
}
/**
* Checks whether or not this Value is Numeric
* A Value is numeric if it is either of type Number or Integer
* @return true if the value is either of type Number or Integer
*/
public boolean isNumeric()
{
return isInteger() || isNumber() || isBigNumber();
}
/**
* Checks whether or not the specified type is either Integer or Number
* @param t the type to check
* @return true if the type is Integer or Number
*/
public static final boolean isNumeric(int t)
{
return t==VALUE_TYPE_INTEGER || t==VALUE_TYPE_NUMBER || t==VALUE_TYPE_BIGNUMBER;
}
/**
* Returns a padded to length String text representation of this Value
* @return a padded to length String text representation of this Value
*/
public String toString()
{
return toString(true);
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @param pad true if you want to pad the resulting String
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toString(boolean pad)
{
String retval;
switch(getType())
{
case VALUE_TYPE_STRING : retval=toStringString(pad); break;
case VALUE_TYPE_NUMBER : retval=toStringNumber(pad); break;
case VALUE_TYPE_DATE : retval=toStringDate(); break;
case VALUE_TYPE_BOOLEAN: retval=toStringBoolean(); break;
case VALUE_TYPE_INTEGER: retval=toStringInteger(pad); break;
case VALUE_TYPE_BIGNUMBER: retval=toStringBigNumber(pad); break;
default: retval=""; break;
}
return retval;
}
/**
* Returns a String describing the meta-data (type & length description) of this Value.
* @return a String describing the meta-data (type & length description) of this Value.
*/
public String toStringMeta()
{
String retval=getTypeDesc();
switch(getType())
{
case VALUE_TYPE_STRING :
if (getLength()>0) retval+="("+getLength()+")";
break;
case VALUE_TYPE_NUMBER :
case VALUE_TYPE_BIGNUMBER :
if (getLength()>0)
{
retval+="("+getLength();
if (getPrecision()>0)
{
retval+=", "+getPrecision();
}
retval+=")";
}
break;
case VALUE_TYPE_INTEGER:
if (getLength()>0)
{
retval+="("+getLength()+")";
}
break;
default: break;
}
return retval;
}
/**
* Converts a String Value to String optionally padded to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringString(boolean pad)
{
String retval=null;
if (value==null) return null;
if (value.getLength()<=0) // No length specified!
{
if (isNull() || value.getString()==null)
retval = Const.NULL_STRING;
else
retval = value.getString();
}
else
{
StringBuffer ret;
if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING);
else ret=new StringBuffer(value.getString());
if (pad)
{
int length = value.getLength();
if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS.
Const.rightPad(ret, length);
}
retval=ret.toString();
}
return retval;
}
/**
* Converts a Number value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringNumber(boolean pad)
{
String retval;
if (value==null) return null;
if (pad)
{
if (value.getLength()<1)
{
if (isNull()) retval=Const.NULL_NUMBER;
else
{
DecimalFormat form= new DecimalFormat();
form.applyPattern( "
// System.out.println("local.pattern = ["+form.toLocalizedPattern()+"]");
retval=form. format(value.getNumber());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_NUMBER);
Const.rightPad(ret, value.getLength());
retval=ret.toString();
}
else
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getNumber()>=0) fmt.append(" "); // to compensate for minus sign.
if (value.getPrecision()<0) // Default: two decimals
{
if (value.getLength()<0) // format: 1234,56 (-1,-1)
{
fmt.append("0.00");
}
else // format 0000001234,00 --> (10,-1)
{
for (i=0;i<value.getLength();i++) fmt.append("0");
fmt.append(".00"); // for the .00
}
}
else
if (value.getLength()==0) // No decimals 0000001234 --> (10,0)
{
for (i=0;i<value.getLength();i++) fmt.append("0"); // all zeroes.
}
else // Floating point format 00001234,56 --> (12,2)
{
for (i=0;i<=value.getLength();i++) fmt.append("0"); // all zeroes.
int pos = value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0);
if (pos>=0 && pos <fmt.length())
{
fmt.setCharAt(value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0), '.'); // one 'comma'
}
}
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getNumber());
}
}
}
else
{
if (isNull()) retval=Const.NULL_NUMBER;
else retval=""+value.getNumber();
}
return retval;
}
/**
* Converts a Date value to a String.
* The date has format: <code>yyyy/MM/dd HH:mm:ss.SSS</code>
* @return a String representing the Date Value.
*/
private String toStringDate()
{
String retval;
if (value==null) return null;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
if (getLength()<=0)
{
if (isNull() || value.getDate()==null) retval=Const.NULL_DATE;
else
{
retval=df.format(value.getDate()).toString();
}
}
else
{
StringBuffer ret;
if (isNull() || value.getDate()==null)
ret=new StringBuffer(Const.NULL_DATE);
else ret=new StringBuffer(df.format(value.getDate()).toString());
Const.rightPad(ret, getLength()<=10?10:getLength());
retval=ret.toString();
}
return retval;
}
/**
* Returns a String representing the boolean value.
* If the length is 1: it will be "Y" & "N", otherwise "true" & "false"
* @return a String representing the boolean value.
*/
private String toStringBoolean()
{
String retval;
if (value==null) return null;
if (isNull())
{
retval=Const.NULL_BOOLEAN;
}
else
{
if (getLength()==1)
{
retval=value.getBoolean()?"Y":"N";
}
else
{
retval=value.getBoolean()?"true":"false";
}
}
if (getLength()>=0)
{
StringBuffer ret=new StringBuffer(retval);
Const.rightPad(ret, getLength());
retval=ret.toString();
}
return retval;
}
/**
* Converts an Integer value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringInteger(boolean pad)
{
String retval;
if (value==null) return null;
if (getLength()<1)
{
if (isNull()) retval=Const.NULL_INTEGER;
else
{
DecimalFormat form= new DecimalFormat("
retval=form.format(value.getInteger());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_INTEGER);
Const.rightPad(ret, getLength());
retval=ret.toString();
}
else
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getInteger()>=0) fmt.append(" "); // to compensate for minus sign.
if (getPrecision()<0) // Default: two decimals
{
if (getLength()<0) // format: 1234,56 (-1,-1)
{
fmt.append("0.00");
}
else // format 0000001234,00 --> (10,-1)
{
for (i=0;i<getLength();i++) fmt.append("0");
fmt.append(".00"); // for the .00
}
}
else
if (getPrecision()==0) // No decimals 0000001234 --> (10,0)
{
for (i=0;i<getLength();i++) fmt.append("0"); // all zeroes.
}
else // Floating point format 00001234,56 --> (12,2)
{
for (i=0;i<=getLength();i++) fmt.append("0"); // all zeroes.
fmt.setCharAt(getLength()-getPrecision()+1-(value.getInteger()<0?1:0), '.'); // one 'comma'
}
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getInteger());
}
}
return retval;
}
/**
* Converts a BigNumber value to a String, optionally padding the result to the specified length. // TODO: BigNumber padding
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringBigNumber(boolean pad)
{
if (value.getBigNumber()==null) return null;
String retval = value.getString();
// Localise . to ,
if (Const.DEFAULT_DECIMAL_SEPARATOR!='.')
{
retval = retval.replace('.', Const.DEFAULT_DECIMAL_SEPARATOR);
}
return retval;
}
/**
* Sets the length of the Number, Integer or String to the specified length
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
*/
public void setLength(int l)
{
if (value==null) return;
value.setLength(l);
}
/**
* Sets the length and the precision of the Number, Integer or String to the specified length & precision
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
* @param p the precision to which you want to set this Value
*/
public void setLength(int l, int p)
{
if (value==null) return;
value.setLength(l,p);
}
/**
* Get the length of this Value.
* @return the length of this Value.
*/
public int getLength()
{
if (value==null) return -1;
return value.getLength();
}
/**
* get the precision of this Value
* @return the precision of this Value.
*/
public int getPrecision()
{
if (value==null) return -1;
return value.getPrecision();
}
/**
* Sets the precision of this Value
* Note: no rounding or truncation takes place, this is meta-data only!
* @param p the precision to which you want to set this Value.
*/
public void setPrecision(int p)
{
if (value==null) return;
value.setPrecision(p);
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ...
* @return A String describing the type of value.
*/
public String getTypeDesc()
{
if (value==null) return "Unknown";
return value.getTypeDesc();
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... given a certain integer type
* @param t the type to convert to text.
* @return A String describing the type of a certain value.
*/
public static final String getTypeDesc(int t)
{
return value_type_desc[t];
}
/**
* Convert the String description of a type to an integer type.
* @param desc The description of the type to convert
* @return The integer type of the given String. (Value.TYPE_VALUE_...)
*/
public static final int getType(String desc)
{
int i;
for (i=1;i<value_type_desc.length;i++)
{
if (value_type_desc[i].equalsIgnoreCase(desc))
{
return i;
}
}
return VALUE_TYPE_NONE;
}
/**
* get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getTypes()
{
String retval[] = new String[value_type_desc.length-1];
for (int i=1;i<value_type_desc.length;i++)
{
retval[i-1]=value_type_desc[i];
}
return retval;
}
/**
* get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getAllTypes()
{
String retval[] = new String[value_type_desc.length];
for (int i=0;i<value_type_desc.length;i++)
{
retval[i]=value_type_desc[i];
}
return retval;
}
/**
* Sets the Value to null, no type is being changed.
*
*/
public void setNull()
{
setNull(true);
}
/**
* Sets or unsets a value to null, no type is being changed.
* @param n true if you want the value to be null, false if you don't want this to be the case.
*/
public void setNull(boolean n)
{
NULL=n;
}
/**
* Checks wheter or not a value is null.
* @return true if the Value is null.
*/
public boolean isNull()
{
return NULL;
}
/**
* Write the object to an ObjectOutputStream
* @param out
* @throws IOException
*/
private void writeObject(java.io.ObjectOutputStream out) throws IOException
{
writeObj(new DataOutputStream(out));
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
readObj(new DataInputStream(in));
}
public void writeObj(DataOutputStream dos) throws IOException
{
int type=getType();
// Handle type
dos.writeInt( getType() );
// Handle name-length
dos.writeInt( name.length() );
// Write name
dos.writeChars( name );
// length & precision
dos.writeInt( getLength() );
dos.writeInt( getPrecision() );
// NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(type)
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes().length);
dos.writeChars(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
/**
* Write the value, including the meta-data to a DataOutputStream
* @param outputStream the OutputStream to write to .
* @throws KettleFileException if something goes wrong.
*/
public void write(OutputStream outputStream) throws KettleFileException
{
try
{
writeObj(new DataOutputStream(outputStream));
}
catch(Exception e)
{
throw new KettleFileException("Unable to write value to output stream", e);
}
}
public void readObj(DataInputStream dis) throws IOException
{
// type
int theType = dis.readInt();
newValue(theType);
// name-length
int nameLength=dis.readInt();
// name
StringBuffer nameBuffer=new StringBuffer();
for (int i=0;i<nameLength;i++) nameBuffer.append( dis.readChar() );
setName(new String(nameBuffer));
// length & precision
setLength( dis.readInt(), dis.readInt() );
// Null?
setNull( dis.readBoolean() );
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
StringBuffer val_string=new StringBuffer();
for (int i=0;i<dataLength;i++) val_string.append(dis.readChar());
setValue( val_string.toString() );
}
if (theType==VALUE_TYPE_BIGNUMBER)
{
try
{
convertString(theType);
}
catch(KettleValueException e)
{
throw new IOException("Unable to convert String to BigNumber while reading from data input stream ["+getString()+"]");
}
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue( dis.readDouble() );
break;
case VALUE_TYPE_INTEGER:
setValue( dis.readLong() );
break;
case VALUE_TYPE_BOOLEAN:
setValue( dis.readBoolean() );
break;
}
}
}
public Value(InputStream is) throws KettleFileException
{
try
{
readObj(new DataInputStream(is));
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleFileException("Error reading from data input stream", e);
}
}
/**
* Write the data of this Value, without the meta-data to a DataOutputStream
* @param dos The DataOutputStream to write the data to
* @return true if all went well, false if something went wrong.
*/
public boolean writeData(DataOutputStream dos) throws KettleFileException
{
try
{
// Is the value NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes().length);
dos.writeChars(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
catch(IOException e)
{
throw new KettleFileException("Unable to write value data to output stream", e);
}
return true;
}
/**
* Read the data of a Value from a DataInputStream, the meta-data of the value has to be set before calling this method!
* @param dis the DataInputStream to read from
* @throws KettleFileException when the value couldn't be read from the DataInputStream
*/
public Value(Value metaData, DataInputStream dis) throws KettleFileException
{
setValue(metaData);
setName(metaData.getName());
try
{
// Is the value NULL?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
StringBuffer val_string=new StringBuffer();
for (int i=0;i<dataLength;i++) val_string.append(dis.readChar());
setValue( val_string.toString() );
}
if (metaData.isBigNumber()) convertString(metaData.getType());
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue( dis.readDouble() );
break;
case VALUE_TYPE_INTEGER:
setValue( dis.readLong() );
break;
case VALUE_TYPE_BOOLEAN:
setValue( dis.readBoolean() );
break;
}
}
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleEOFException("Error reading value data from stream", e);
}
}
/**
* Compare 2 values of the same or different type!
* The comparison of Strings is case insensitive
* @param v the value to compare with.
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v)
{
return compare(v, true);
}
/**
* Compare 2 values of the same or different type!
* @param v the value to compare with.
* @param caseInsensitive True if you want the comparison to be case insensitive
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v, boolean caseInsensitive)
{
boolean n1 = isNull() || ( isString() && ( getString()==null || getString().length()==0 )) || ( isDate() && getDate()==null);
boolean n2 = v.isNull() || (v.isString() && ( v.getString()==null || v.getString().length()==0 )) || (v.isDate() && v.getDate()==null);
// null is always smaller!
if ( n1 && !n2) return -1;
if (!n1 && n2) return 1;
if ( n1 && n2) return 0;
switch(getType())
{
case VALUE_TYPE_BOOLEAN:
if ( getBoolean() && v.getBoolean() ||
!getBoolean() && !v.getBoolean()) return 0; // true == true, false == false
if ( getBoolean() && !v.getBoolean()) return 1; // true > false
return -1; // false < true
case VALUE_TYPE_DATE :
return Double.compare(getNumber(), v.getNumber());
case VALUE_TYPE_NUMBER :
return Double.compare(getNumber(), v.getNumber());
case VALUE_TYPE_STRING:
String one = Const.rtrim(getString());
String two = Const.rtrim(v.getString());
if (caseInsensitive)
return one.compareToIgnoreCase(two);
else
return one.compareTo(two);
case VALUE_TYPE_INTEGER:
return Double.compare(getNumber(), v.getNumber());
case VALUE_TYPE_BIGNUMBER:
return getBigNumber().compareTo(v.getBigNumber());
}
// Still here? Not possible! But hey, give back 0, mkay?
return 0;
}
public boolean equals(Object v)
{
if (compare((Value)v)==0)
return true;
else
return false;
}
/**
* Check whether this value is equal to the String supplied.
* @param string The string to check for equality
* @return true if the String representation of the value is equal to string. (ignoring case)
*/
public boolean isEqualTo(String string)
{
return getString().equalsIgnoreCase(string);
}
/**
* Check whether this value is equal to the BigDecimal supplied.
* @param number The BigDecimal to check for equality
* @return true if the BigDecimal representation of the value is equal to number.
*/
public boolean isEqualTo(BigDecimal number)
{
return getBigNumber().equals(number);
}
/**
* Check whether this value is equal to the Number supplied.
* @param number The Number to check for equality
* @return true if the Number representation of the value is equal to number.
*/
public boolean isEqualTo(double number)
{
return getNumber() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(long number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(int number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(byte number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Date supplied.
* @param date The Date to check for equality
* @return true if the Date representation of the value is equal to date.
*/
public boolean isEqualTo(Date date)
{
return getDate() == date;
}
public int hashCode()
{
int hash=0; // name.hashCode(); -> Name shouldn't be part of hashCode()!
if (isNull())
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^= 1; break;
case VALUE_TYPE_DATE : hash^= 2; break;
case VALUE_TYPE_NUMBER : hash^= 4; break;
case VALUE_TYPE_STRING : hash^= 8; break;
case VALUE_TYPE_INTEGER : hash^=16; break;
case VALUE_TYPE_BIGNUMBER : hash^=32; break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
else
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^=Boolean.valueOf(getBoolean()).hashCode(); break;
case VALUE_TYPE_DATE : if (getDate()!=null) hash^=getDate().hashCode(); break;
case VALUE_TYPE_INTEGER :
case VALUE_TYPE_NUMBER : hash^=(new Double(getNumber())).hashCode(); break;
case VALUE_TYPE_STRING : if (getString()!=null) hash^=getString().hashCode(); break;
case VALUE_TYPE_BIGNUMBER : if (getBigNumber()!=null) hash^=getBigNumber().hashCode(); break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
return hash;
}
// OPERATORS & COMPARATORS
public Value and(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 & n2;
setValue(res);
return this;
}
public Value xor(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 ^ n2;
setValue(res);
return this;
}
public Value or(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 | n2;
setValue(res);
return this;
}
public Value bool_and(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 && b2;
setValue(res);
return this;
}
public Value bool_or(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 || b2;
setValue(res);
return this;
}
public Value bool_xor(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1&&b2 ? false : !b1&&!b2 ? false : true;
setValue(res);
return this;
}
public Value bool_not()
{
if (getBoolean()) value.setBoolean(!getBoolean());
return this;
}
public Value greater_equal(Value v)
{
if (compare(v)>=0) setValue(true); else setValue(false);
return this;
}
public Value smaller_equal(Value v)
{
if (compare(v)<=0) setValue(true); else setValue(false);
return this;
}
public Value different(Value v)
{
if (compare(v)!=0) setValue(true); else setValue(false);
return this;
}
public Value equal(Value v)
{
if (compare(v)==0) setValue(true); else setValue(false);
return this;
}
public Value like(Value v)
{
String cmp=v.getString();
// Is cmp part of look?
int idx=getString().indexOf(cmp);
if (idx<0) setValue(false); else setValue(true);
return this;
}
public Value greater(Value v)
{
if (compare(v)>0) setValue(true); else setValue(false);
return this;
}
public Value smaller(Value v)
{
if (compare(v)<0) setValue(true); else setValue(false);
return this;
}
public Value minus(BigDecimal v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(double v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(long v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(int v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(byte v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(Value v) throws KettleValueException
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : value.setBigNumber(getBigNumber().subtract(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : value.setNumber(getNumber()-v.getNumber()); break;
case VALUE_TYPE_INTEGER : value.setInteger(getInteger()-v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Subtraction can only be done with numbers!");
}
return this;
}
public Value plus(BigDecimal v) { return plus(new Value("tmp", v)); }
public Value plus(double v) { return plus(new Value("tmp", v)); }
public Value plus(long v) { return plus(new Value("tmp", v)); }
public Value plus(int v) { return plus(new Value("tmp", (long)v)); }
public Value plus(byte v) { return plus(new Value("tmp", (long)v)); }
public Value plus(Value v)
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().add(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()+v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()+v.getInteger()); break;
case VALUE_TYPE_BOOLEAN : setValue(getBoolean()|v.getBoolean()); break;
case VALUE_TYPE_STRING : setValue(getString()+v.getString()); break;
default: break;
}
return this;
}
public Value divide(BigDecimal v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(double v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(long v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(int v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(byte v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(Value v) throws KettleValueException
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().divide(v.getBigNumber(), BigDecimal.ROUND_UP)); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()/v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()/v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Division can only be done with numeric data!");
}
return this;
}
public Value multiply(BigDecimal v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(double v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(long v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(int v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(byte v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(Value v) throws KettleValueException
{
// a number and a string!
if ((v.isString() && isNumeric()) || (v.isNumeric() && isString()))
{
StringBuffer s;
String append="";
int n;
if (v.isString())
{
s=new StringBuffer(v.getString());
append=v.getString();
n=(int)getInteger();
}
else
{
s=new StringBuffer(getString());
append=getString();
n=(int)v.getInteger();
}
if (n==0) s.setLength(0);
else
for (int i=1;i<n;i++) s.append(append);
setValue(s);
}
else
// big numbers
if (isBigNumber() || v.isBigNumber())
{
setValue( getBigNumber().multiply(v.getBigNumber()) );
}
else
// numbers
if (isNumber() || v.isNumber())
{
setValue( getNumber()*v.getNumber() );
}
else
// integers
if (isInteger() || v.isInteger())
{
setValue( getInteger()*v.getInteger() );
}
else
{
throw new KettleValueException("Multiplication can only be done with numbers or a number and a string!");
}
return this;
}
// FUNCTIONS!!
// implement the ABS function, arguments in args[]
public Value abs() throws KettleValueException
{
if (isNull()) return this;
if (isBigNumber())
{
setValue(getBigNumber().abs());
}
else
if (isNumber())
{
setValue(Math.abs(getNumber()));
}
else
if (isInteger())
{
setValue(Math.abs(getInteger()));
}
else
{
throw new KettleValueException("Function ABS only works with a number");
}
return this;
}
// implement the ACOS function, arguments in args[]
public Value acos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.acos(getNumber()));
}
else
{
throw new KettleValueException("Function ACOS only works with numeric data");
}
return this;
}
// implement the ASIN function, arguments in args[]
public Value asin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.asin(getNumber()));
}
else
{
throw new KettleValueException("Function ASIN only works with numeric data");
}
return this;
}
// implement the ATAN function, arguments in args[]
public Value atan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.atan(getNumber()));
}
else
{
throw new KettleValueException("Function ATAN only works with numeric data");
}
return this;
}
// implement the ATAN2 function, arguments in args[]
public Value atan2(Value arg0) throws KettleValueException { return atan2(arg0.getNumber()); }
public Value atan2(double arg0) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.atan2(getNumber(), arg0));
}
else
{
throw new KettleValueException("Function ATAN2 only works with numbers");
}
return this;
}
// implement the CEIL function, arguments in args[]
public Value ceil() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.ceil(getNumber()));
}
else
{
throw new KettleValueException("Function CEIL only works with a number");
}
return this;
}
// implement the COS function, arguments in args[]
public Value cos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.cos(getNumber()));
}
else
{
throw new KettleValueException("Function COS only works with a number");
}
return this;
}
// implement the EXP function, arguments in args[]
public Value exp() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.exp(getNumber()));
}
else
{
throw new KettleValueException("Function EXP only works with a number");
}
return this;
}
// implement the FLOOR function, arguments in args[]
public Value floor() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.floor(getNumber()));
}
else
{
throw new KettleValueException("Function FLOOR only works with a number");
}
return this;
}
// implement the INITCAP function, arguments in args[]
public Value initcap() throws KettleValueException
{
if (isNull()) return this;
if (getType()==VALUE_TYPE_STRING)
{
if (getString()==null)
{
setNull();
}
else
{
StringBuffer change=new StringBuffer(getString());
boolean new_word;
int i;
char lower, upper, ch;
new_word=true;
for (i=0 ; i<getString().length() ; i++)
{
lower=change.substring(i,i+1).toLowerCase().charAt(0); // Lowercase is default.
upper=change.substring(i,i+1).toUpperCase().charAt(0); // Uppercase for new words.
ch=upper;
if (new_word)
{
change.setCharAt(i, upper);
}
else
{
change.setCharAt(i, lower);
}
new_word = false;
if ( !(ch>='A' && ch<='Z') &&
!(ch>='0' && ch<='9') &&
ch!='_'
) new_word = true;
}
setValue( change.toString() );
}
}
else
{
throw new KettleValueException("Function INITCAP only works with a string");
}
return this;
}
// implement the LENGTH function, arguments in args[]
public Value length() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
setValue(0L);
return this;
}
if (getType()==VALUE_TYPE_STRING)
{
setValue((double)getString().length());
}
else
{
throw new KettleValueException("Function LENGTH only works with a string");
}
return this;
}
// implement the LOG function, arguments in args[]
public Value log() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.log(getNumber()));
}
else
{
throw new KettleValueException("Function LOG only works with a number");
}
return this;
}
// implement the LOWER function, arguments in args[]
public Value lower()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
setValue( getString().toLowerCase() );
}
return this;
}
// implement the LPAD function: left pad strings or numbers...
public Value lpad(Value len) { return lpad((int)len.getNumber(), " "); }
public Value lpad(Value len, Value padstr) { return lpad((int)len.getNumber(), padstr.getString()); }
public Value lpad(int len) { return lpad(len, " "); }
public Value lpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also lpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.insert(0, padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(0);
i
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the LTRIM function
public Value ltrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getString()!=null)
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Left trim
while (s.length()>0 && s.charAt(0)==' ') s.deleteCharAt(0);
setValue(s);
}
else
{
setNull();
}
}
return this;
}
// implement the MOD function, arguments in args[]
public Value mod(Value arg) throws KettleValueException { return mod(arg.getNumber()); }
public Value mod(BigDecimal arg) throws KettleValueException { return mod(arg.doubleValue()); }
public Value mod(long arg) throws KettleValueException { return mod((double)arg); }
public Value mod(int arg) throws KettleValueException { return mod((double)arg); }
public Value mod(byte arg) throws KettleValueException { return mod((double)arg); }
public Value mod(double arg0) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
double n1=getNumber();
double n2=arg0;
setValue( n1 - (n2 * Math.floor(n1 /n2 )) );
}
else
{
throw new KettleValueException("Function MOD only works with numeric data");
}
return this;
}
// implement the NVL function, arguments in args[]
public Value nvl(Value alt)
{
if (isNull()) setValue(alt);
return this;
}
// implement the POWER function, arguments in args[]
public Value power(BigDecimal arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(double arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(Value v) throws KettleValueException
{
if (isNull()) return this;
else if (isNumeric())
{
setValue( Math.pow(getNumber(), v.getNumber()) );
}
else
{
throw new KettleValueException("Function POWER only works with numeric data");
}
return this;
}
// implement the REPLACE function, arguments in args[]
public Value replace(Value repl, Value with) { return replace(repl.getString(), with.getString()); }
public Value replace(String repl, String with)
{
if (isNull()) return this;
if (getString()==null)
{
setNull();
}
else
{
setValue( Const.replace(getString(), repl, with) );
}
return this;
}
/**
* Rounds of to the nearest integer.<p>
* See also: java.lang.Math.round()
*
* @return The rounded Number value.
*/
public Value round() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( (double)Math.round(getNumber()) );
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
/**
* Rounds the Number value to a certain number decimal places.
* @param decimalPlaces
* @return The rounded Number Value
* @throws KettleValueException in case it's not a number (or other problem).
*/
public Value round(int decimalPlaces) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
if (isBigNumber())
{
// Multiply by 10^decimalPlaces
// For example 123.458343938437, Decimalplaces = 2
BigDecimal bigDec = getBigNumber();
// System.out.println("ROUND decimalPlaces : "+decimalPlaces+", bigNumber = "+bigDec);
bigDec = bigDec.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
// System.out.println("ROUND finished result : "+bigDec);
setValue( bigDec );
}
else
{
setValue( (double)Const.round(getNumber(), decimalPlaces) );
}
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
// implement the RPAD function, arguments in args[]
public Value rpad(Value len) { return rpad((int)len.getNumber(), " "); }
public Value rpad(Value len, Value padstr) { return rpad((int)len.getNumber(), padstr.getString()); }
public Value rpad(int len) { return rpad(len, " "); }
public Value rpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also rpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.append(padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(i-1);
i
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the RTRIM function, arguments in args[]
public Value rtrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Rigth trim
while (s.length()>0 && s.charAt(s.length()-1)==' ') s.deleteCharAt(s.length()-1);
setValue(s);
}
return this;
}
// implement the SIGN function, arguments in args[]
public Value sign() throws KettleValueException
{
if (isNull()) return this;
if (isNumber())
{
int cmp = getBigNumber().compareTo(new BigDecimal(0L));
if (cmp>0) value.setBigNumber(new BigDecimal(1L));
else if (cmp<0) value.setBigNumber(new BigDecimal(-1L));
else value.setBigNumber(new BigDecimal(0L));
}
else
if (isNumber())
{
if (getNumber()>0) value.setNumber(1.0);
else if (getNumber()<0) value.setNumber(-1.0);
else value.setNumber(0.0);
}
else
if (isInteger())
{
if (getInteger()>0) value.setInteger(1);
else if (getInteger()<0) value.setInteger(-1);
else value.setInteger(0);
}
else
{
throw new KettleValueException("Function SIGN only works with a number");
}
return this;
}
// implement the SIN function, arguments in args[]
public Value sin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sin(getNumber()) );
}
else
{
throw new KettleValueException("Function SIN only works with a number");
}
return this;
}
// implement the SQRT function, arguments in args[]
public Value sqrt() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sqrt(getNumber()) );
}
else
{
throw new KettleValueException("Function SQRT only works with a number");
}
return this;
}
// implement the SUBSTR function, arguments in args[]
public Value substr(Value from, Value to) { return substr((int)from.getNumber(), (int)to.getNumber()); }
public Value substr(Value from) { return substr((int)from.getNumber(), -1); }
public Value substr(int from) { return substr(from, -1); }
public Value substr(int from, int to)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
if (getString()!=null)
{
if (to<0 && from>=0)
{
setValue( getString().substring(from) );
}
else if (to>=0 && from>=0)
{
setValue( getString().substring(from, to) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the RIGHTSTR function, arguments in args[]
public Value rightstr(Value len) { return rightstr((int)len.getNumber()); }
public Value rightstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f<0) f=0;
setValue( getString().substring(f) );
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the LEFTSTR function, arguments in args[]
public Value leftstr(Value len)
{
return leftstr((int)len.getNumber());
}
public Value leftstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f>0)
{
setValue( getString().substring(0,len) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
public Value startsWith(Value string)
{
return startsWith(string.getString());
}
public Value startsWith(String string)
{
if (isNull())
{
setType(VALUE_TYPE_BOOLEAN);
return this;
}
if (string==null)
{
setValue(false);
setNull();
return this;
}
setValue( getString().startsWith(string) );
return this;
}
// implement the SYSDATE function, arguments in args[]
public Value sysdate()
{
setValue( Calendar.getInstance().getTime() );
return this;
}
// implement the TAN function, arguments in args[]
public Value tan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.tan(getNumber()) );
}
else
{
throw new KettleValueException("Function TAN only works on a number");
}
return this;
}
// implement the TO_CHAR function, arguments in args[]
// number: NUM2STR( 123.456 ) : default format
// number: NUM2STR( 123.456, '###,##0.000') : format
// number: NUM2STR( 123.456, '###,##0.000', '.') : grouping
// number: NUM2STR( 123.456, '###,##0.000', '.', ',') : decimal
// number: NUM2STR( 123.456, '###,##0.000', '.', ',', '') : currency
public Value num2str() throws KettleValueException { return num2str(null, null, null, null); }
public Value num2str(String arg0) throws KettleValueException { return num2str(arg0, null, null, null); }
public Value num2str(String arg0, String arg1) throws KettleValueException { return num2str(arg0, arg1, null, null); }
public Value num2str(String arg0, String arg1, String arg2) throws KettleValueException { return num2str(arg0, arg1, arg2, null); }
public Value num2str(String arg0, String arg1, String arg2, String arg3) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
// Number to String conversion...
if (getType()==VALUE_TYPE_NUMBER || getType()==VALUE_TYPE_INTEGER)
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if (arg3!=null) dfs.setCurrencySymbol( arg3 );
if (arg2!=null) dfs.setGroupingSeparator( arg2.charAt(0) );
if (arg1!=null) dfs.setDecimalSeparator( arg1.charAt(0) );
df.setDecimalFormatSymbols(dfs); // in case of 4, 3 or 2
if (arg0!=null) df.applyPattern(arg0);
try
{
setValue( nf.format(getNumber()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("Couldn't convert Number to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function NUM2STR only works on Numbers and Integers");
}
}
return this;
}
public Value dat2str() throws KettleValueException { return dat2str(null, null); }
public Value dat2str(String arg0) throws KettleValueException { return dat2str(arg0, null); }
public Value dat2str(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_DATE)
{
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
setValue( df.format(getDate()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("TO_CHAR Couldn't convert Date to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function DAT2STR only works on a date");
}
}
return this;
}
// implement the TO_DATE function, arguments in args[]
public Value num2dat() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
if (isNumeric())
{
value = new ValueDate();
value.setInteger(getInteger());
setType(VALUE_TYPE_DATE);
setLength(-1,-1);
}
else
{
throw new KettleValueException("Function NUM2DAT only works on a number");
}
}
return this;
}
public Value str2dat(String arg0) throws KettleValueException { return str2dat(arg0, null); }
public Value str2dat(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
// System.out.println("Convert string ["+string+"] to date using pattern '"+arg0+"'");
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
value.setDate( df.parse(getString()) );
setType(VALUE_TYPE_DATE);
setLength(-1,-1);
}
catch(Exception e)
{
setType(VALUE_TYPE_DATE);
setNull();
throw new KettleValueException("TO_DATE Couldn't convert String to Date"+e.toString());
}
}
return this;
}
// implement the TO_NUMBER function, arguments in args[]
public Value str2num() throws KettleValueException { return str2num(null, null, null, null); }
public Value str2num(String pattern) throws KettleValueException { return str2num(pattern, null, null, null); }
public Value str2num(String pattern, String decimal) throws KettleValueException { return str2num(pattern, decimal, null, null); }
public Value str2num(String pattern, String decimal, String grouping) throws KettleValueException { return str2num(pattern, decimal, grouping, null); }
public Value str2num(String pattern, String decimal, String grouping, String currency) throws KettleValueException
{
// 0 : pattern
// 1 : Decimal separator
// 2 : Grouping separator
// 3 : Currency symbol
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_STRING)
{
if (getString()==null)
{
setNull();
setValue(0.0);
}
else
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if (currency!=null) dfs.setCurrencySymbol( currency );
if (grouping!=null) dfs.setGroupingSeparator( grouping.charAt(0) );
if (decimal!=null) dfs.setDecimalSeparator( decimal.charAt(0) );
if (pattern!=null) df.applyPattern(pattern);
try
{
setValue( nf.parse(getString()).doubleValue() );
}
catch(Exception e)
{
setType(VALUE_TYPE_NUMBER);
setNull();
throw new KettleValueException("Couldn't convert string to number "+e.toString());
}
}
}
else
{
throw new KettleValueException("Function STR2NUM works only on strings");
}
}
return this;
}
public Value dat2num() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
return this;
}
if (getType()==VALUE_TYPE_DATE)
{
if (getString()==null)
{
setNull();
setValue(0L);
}
else
{
setValue(getInteger());
}
}
else
{
throw new KettleValueException("Function DAT2NUM works only on dates");
}
return this;
}
/**
* Performs a right and left trim of spaces in the string.
* If the value is not a string a conversion to String is performed first.
*
* @return The trimmed string value.
*/
public Value trim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
String str = Const.trim(getString());
setValue(str);
return this;
}
// implement the UPPER function, arguments in args[]
public Value upper()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString().toUpperCase() );
return this;
}
// implement the E function, arguments in args[]
public Value e()
{
setValue(Math.E);
return this;
}
// implement the PI function, arguments in args[]
public Value pi()
{
setValue(Math.PI);
return this;
}
// implement the DECODE function, arguments in args[]
public Value v_decode(Value args[]) throws KettleValueException
{
int i;
boolean found;
// Decode takes as input the first argument...
// The next pair
// Limit to 3, 5, 7, 9, ... arguments
if (args.length>=3 && (args.length%2)==1)
{
i=0;
found=false;
while (i<args.length-1 && !found)
{
if (this.equals(args[i]))
{
setValue(args[i+1]);
found=true;
}
i+=2;
}
if (!found) setValue(args[args.length-1]);
}
else
{
// ERROR with nr of arguments
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the IF function, arguments in args[]
// IF( <condition>, <then value>, <else value>)
public Value v_if(Value args[]) throws KettleValueException
{
if (getType()==VALUE_TYPE_BOOLEAN)
{
if (args.length==1)
{
if (getBoolean()) setValue(args[0]); else setNull();
}
else
if (args.length==2)
{
if (getBoolean()) setValue(args[0]); else setValue(args[1]);
}
}
else
{
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the ADD_MONTHS function, one argument
public Value add_months(int months) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
month+=months;
int newyear = year+(int)Math.floor(month/12);
int newmonth = month%12;
cal.set(newyear, newmonth, 1);
int newday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (newday<day) cal.set(Calendar.DAY_OF_MONTH, newday);
else cal.set(Calendar.DAY_OF_MONTH, day);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_months only works on a date!");
}
return this;
}
/** Add a number of days to a Date value
*
* @param days The number of days to add to the current date value
* @return The resulting value
* @throws KettleValueException
*/
public Value add_days(long days) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
cal.add(Calendar.DAY_OF_YEAR, (int)days);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_days only works on a date!");
}
return this;
}
// implement the LAST_DAY function, arguments in args[]
public Value last_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
int last_day = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, last_day);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function last_day only works on a date");
}
return this;
}
public Value first_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.DAY_OF_MONTH, 1);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function first_day only works on a date");
}
return this;
}
// implement the TRUNC function, version without arguments
public Value trunc() throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(0, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
setValue( Math.floor(getNumber()) );
}
else
if (isInteger())
{
// Nothing
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function TRUNC only works on numbers and dates");
}
return this;
}
// implement the TRUNC function, arguments in args[]
public Value trunc(double level) throws KettleValueException { return trunc((int)level); }
public Value trunc(int level) throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(level, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
double pow=Math.pow(10, level);
setValue( Math.floor( getNumber() * pow ) / pow );
}
else
if (isInteger())
{
// Nothing!
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
switch((int)level)
{
// MONTHS
case 5: cal.set(Calendar.MONTH, 1);
// DAYS
case 4: cal.set(Calendar.DAY_OF_MONTH, 1);
// HOURS
case 3: cal.set(Calendar.HOUR_OF_DAY, 0);
// MINUTES
case 2: cal.set(Calendar.MINUTE, 0);
// SECONDS
case 1: cal.set(Calendar.SECOND, 0); break;
default:
throw new KettleValueException("Argument of TRUNC of date has to be between 1 and 5");
}
}
else
{
throw new KettleValueException("Function TRUNC only works with numbers and dates");
}
return this;
}
/* Some javascript extensions...
*
*/
public static final Value getInstance() { return new Value(); }
public String getClassName() { return "Value"; }
public void jsConstructor()
{
}
public void jsConstructor(String name)
{
setName(name);
}
public void jsConstructor(String name, String value)
{
setName(name);
setValue(value);
}
/**
* Produce the XML representation of this value.
* @return a String containing the XML to represent this Value.
*/
public String getXML()
{
String retval="";
retval+=XMLHandler.addTagValue("name", getName(), false);
retval+=XMLHandler.addTagValue("type", getTypeDesc(), false);
retval+=XMLHandler.addTagValue("text", toString(false), false);
retval+=XMLHandler.addTagValue("length", getLength(), false);
retval+=XMLHandler.addTagValue("precision", getPrecision(), false);
retval+=XMLHandler.addTagValue("isnull", isNull(), false);
return retval;
}
/**
* Construct a new Value and read the data from XML
* @param valnode The XML Node to read from.
*/
public Value(Node valnode)
{
this();
loadXML(valnode);
}
/**
* Read the data for this Value from an XML Node
* @param valnode The XML Node to read from
* @return true if all went well, false if something went wrong.
*/
public boolean loadXML(Node valnode)
{
try
{
String valname = XMLHandler.getTagValue(valnode, "name");
int valtype = getType( XMLHandler.getTagValue(valnode, "type") );
String text = XMLHandler.getTagValue(valnode, "text");
boolean isnull = "Y".equalsIgnoreCase(XMLHandler.getTagValue(valnode, "isnull"));
int len = Const.toInt(XMLHandler.getTagValue(valnode, "length"), -1);
int prec = Const.toInt(XMLHandler.getTagValue(valnode, "precision"), -1);
setName(valname);
setValue(text);
setLength(len, prec);
if (valtype!=VALUE_TYPE_STRING)
{
trim();
convertString(valtype);
}
if (isnull) setNull();
}
catch(Exception e)
{
setNull();
return false;
}
return true;
}
/**
* Convert this Value from type String to another type
* @param newtype The Value type to convert to.
*/
public void convertString(int newtype) throws KettleValueException
{
switch(newtype)
{
case VALUE_TYPE_STRING : break;
case VALUE_TYPE_NUMBER : setValue( getNumber() ); break;
case VALUE_TYPE_DATE : setValue( getDate() ); break;
case VALUE_TYPE_BOOLEAN : setValue( getBoolean() ); break;
case VALUE_TYPE_INTEGER : setValue( getInteger() ); break;
case VALUE_TYPE_BIGNUMBER : setValue( getBigNumber() ); break;
default:
throw new KettleValueException("Please specify the type to convert to from String type.");
}
}
public Value(Repository rep, long id_value)
throws KettleException
{
try
{
Row r = rep.getValue(id_value);
if (r!=null)
{
name = r.getString("NAME", null);
String valstr = r.getString("VALUE_STR", null);
setValue( valstr );
int valtype = getType( r.getString("VALUE_TYPE", null) );
setType(valtype);
setNull( r.getBoolean("IS_NULL", false) );
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load Value from repository with id_value="+id_value, dbe);
}
}
}
|
package beast.math.distributions;
import beast.core.Description;
import beast.core.Distribution;
import beast.core.Input;
import beast.core.Input.Validate;
import beast.core.State;
import beast.evolution.alignment.TaxonSet;
import beast.evolution.tree.Node;
import beast.evolution.tree.Tree;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@Description("Prior over set of taxa, useful for defining monophyletic constraints and "
+ "distributions over MRCA times or (sets of) tips of trees")
public class MRCAPrior extends Distribution {
public Input<Tree> m_treeInput = new Input<Tree>("tree", "the tree containing the taxon set", Validate.REQUIRED);
public Input<TaxonSet> m_taxonset = new Input<TaxonSet>("taxonset",
"set of taxa for which prior information is available");
public Input<Boolean> m_bIsMonophyleticInput = new Input<Boolean>("monophyletic",
"whether the taxon set is monophyletic (forms a clade without other taxa) or nor. Default is false.", false);
public Input<ParametricDistribution> m_distInput = new Input<ParametricDistribution>("distr",
"distribution used to calculate prior over MRCA time, "
+ "e.g. normal, beta, gamma. If not specified, monophyletic must be true");
public Input<Boolean> m_bOnlyUseTipsInput = new Input<Boolean>("tipsonly",
"flag to indicate tip dates are to be used instead of the MRCA node. " +
"If set to true, the prior is applied to the height of all tips in the taxonset " +
"and the monophyletic flag is ignored. Default is false.", false);
/** shadow members **/
ParametricDistribution m_dist;
Tree m_tree;
// number of taxa in taxon set
int m_nNrOfTaxa = -1;
// array of flags to indicate which taxa are in the set
boolean[] m_bTaxaSet;
// array of indices of taxa
int [] m_iTaxa;
// stores time to be calculated
double m_fMRCATime = -1;
double m_fStoredMRCATime = -1;
// flag indicating taxon set is monophyletic
boolean m_bIsMonophyletic = false;
boolean m_bOnlyUseTips = false;
@Override
public void initAndValidate() throws Exception {
m_dist = m_distInput.get();
m_tree = m_treeInput.get();
List<String> sTaxaNames = new ArrayList<String>();
for (String sTaxon : m_tree.getTaxaNames()) {
sTaxaNames.add(sTaxon);
}
// determine nr of taxa in taxon set
List<String> set = null;
if (m_taxonset.get() != null) {
set = m_taxonset.get().asStringList();
m_nNrOfTaxa = set.size();
} else {
// assume all taxa
m_nNrOfTaxa = sTaxaNames.size();
}
m_bOnlyUseTips = m_bOnlyUseTipsInput.get();
if (m_nNrOfTaxa == 1) {
// ignore test for Monophyletic when it only involves a tree tip
m_bOnlyUseTips = true;
}
if (!m_bOnlyUseTips && m_nNrOfTaxa < 2) {
throw new Exception("At least two taxa are required in a taxon set");
}
if (!m_bOnlyUseTips && m_taxonset.get() == null) {
throw new Exception("Taxonset must be specified OR tipsonly be set to true");
}
// determine which taxa are in the set
m_iTaxa = new int[m_nNrOfTaxa];
if (m_taxonset.get() != null) {
m_bTaxaSet = new boolean[sTaxaNames.size()];
int k = 0;
for (String sTaxon : set) {
int iTaxon = sTaxaNames.indexOf(sTaxon);
if (iTaxon < 0) {
throw new Exception("Cannot find taxon " + sTaxon + " in data");
}
if (m_bTaxaSet[iTaxon]) {
throw new Exception("Taxon " + sTaxon + " is defined multiple times, while they should be unique");
}
m_bTaxaSet[iTaxon] = true;
m_iTaxa[k++] = iTaxon;
}
} else {
for (int i = 0; i < m_nNrOfTaxa; i++) {
m_iTaxa[i] = i;
}
}
}
@Override
public double calculateLogP() throws Exception {
logP = 0;
if (m_bOnlyUseTips) {
// tip date
for (int i : m_iTaxa) {
m_fMRCATime = m_tree.getNode(i).getHeight();
logP += m_dist.logDensity(m_fMRCATime);
}
return logP;
} else {
// internal node
calcMRCAtime(m_tree.getRoot(), new int[1]);
}
if (m_bIsMonophyleticInput.get() && !m_bIsMonophyletic) {
return Double.NEGATIVE_INFINITY;
}
if (m_dist != null) {
logP = m_dist.logDensity(m_fMRCATime);
}
return logP;
}
/**
* Recursively visit all leaf nodes, and collect number of taxa in the taxon
* set. When all taxa in the set are visited, record the time.
* **/
int calcMRCAtime(Node node, int[] nTaxonCount) {
if (node.isLeaf()) {
nTaxonCount[0]++;
if (m_bTaxaSet[node.getNr()]) {
return 1;
} else {
return 0;
}
} else {
int iTaxons = calcMRCAtime(node.m_left, nTaxonCount);
int nLeftTaxa = nTaxonCount[0];
nTaxonCount[0] = 0;
if (node.m_right != null) {
iTaxons += calcMRCAtime(node.m_right, nTaxonCount);
int nRightTaxa = nTaxonCount[0];
nTaxonCount[0] = nLeftTaxa + nRightTaxa;
if (iTaxons == m_nNrOfTaxa) {
// we are at the MRCA, so record the height
m_fMRCATime = node.getHeight();
m_bIsMonophyletic = (nTaxonCount[0] == m_nNrOfTaxa);
return iTaxons + 1;
}
}
return iTaxons;
}
}
@Override
public void store() {
m_fStoredMRCATime = m_fMRCATime;
// don't need to store m_bIsMonophyletic since it is never reported
// explicitly, only logP and MRCA time are (re)stored
super.store();
}
@Override
public void restore() {
m_fMRCATime = m_fStoredMRCATime;
super.restore();
}
@Override
protected boolean requiresRecalculation() {
return super.requiresRecalculation();
}
/** Loggable interface implementation follows **/
@Override
public void init(PrintStream out) throws Exception {
if (m_bOnlyUseTips) {
if (m_dist != null) {
out.print("logP(mrca("+getID()+"))\t");
}
for (int i : m_iTaxa) {
out.print("height(" + m_tree.getTaxaNames()[i] + ")\t");
}
} else {
if (m_dist != null || m_bIsMonophyleticInput.get()) {
out.print("logP(mrca("+m_taxonset.get().getID()+"))\t");
}
out.print("mrcatime(" + m_taxonset.get().getID() + ")\t");
}
}
@Override
public void log(int nSample, PrintStream out) {
if (m_bOnlyUseTips) {
if (m_dist != null) {
out.print(getCurrentLogP() + "\t");
}
for (int i : m_iTaxa) {
out.print(m_tree.getNode(i).getHeight() + "\t");
}
} else {
if (m_dist != null || m_bIsMonophyleticInput.get()) {
out.print(getCurrentLogP() + "\t");
} else {
calcMRCAtime(m_tree.getRoot(), new int[1]);
}
out.print(m_fMRCATime + "\t");
}
}
@Override
public void close(PrintStream out) {
// nothing to do
}
/** Valuable interface implementation follows, first dimension is log likelihood, second the time **/
@Override
public int getDimension() {return 2;}
@Override
public double getArrayValue() {
return logP;
}
@Override
public double getArrayValue(int iDim) {
switch (iDim) {
case 0: return logP;
case 1: return m_fMRCATime;
default: return 0;
}
}
@Override
public void sample(State state, Random random) {
}
@Override
public List<String> getArguments() {
return null;
}
@Override
public List<String> getConditions() {
return null;
}
}
|
package plugin.google.maps;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.util.Base64;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.LatLngBounds.Builder;
public class PluginUtil {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static JSONObject location2Json(Location location) throws JSONException {
JSONObject latLng = new JSONObject();
latLng.put("lat", location.getLatitude());
latLng.put("lng", location.getLongitude());
JSONObject params = new JSONObject();
params.put("latLng", latLng);
if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.put("elapsedRealtimeNanos", location.getElapsedRealtimeNanos());
} else {
params.put("elapsedRealtimeNanos", 0);
}
params.put("time", location.getTime());
/*
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date(location.getTime());
params.put("timeFormatted", format.format(date));
*/
if (location.hasAccuracy()) {
params.put("accuracy", location.getAccuracy());
}
if (location.hasBearing()) {
params.put("bearing", location.getBearing());
}
if (location.hasAltitude()) {
params.put("altitude", location.getAltitude());
}
if (location.hasSpeed()) {
params.put("speed", location.getSpeed());
}
params.put("provider", location.getProvider());
params.put("hashCode", location.hashCode());
return params;
}
/**
* return color integer value
* @param arrayRGBA
* @throws JSONException
*/
public static int parsePluginColor(JSONArray arrayRGBA) throws JSONException {
return Color.argb(arrayRGBA.getInt(3), arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2));
}
public static List<LatLng> JSONArray2LatLngList(JSONArray points) throws JSONException {
List<LatLng> path = new ArrayList<LatLng>();
JSONObject pointJSON;
int i = 0;
for (i = 0; i < points.length(); i++) {
pointJSON = points.getJSONObject(i);
path.add(new LatLng(pointJSON.getDouble("lat"), pointJSON.getDouble("lng")));
}
return path;
}
/*
public static Set<LatLng> JSONArray2LatLngHash(JSONArray points) throws JSONException {
Set<LatLng> path = new HashSet<LatLng>();
JSONObject pointJSON;
int i = 0;
for (i = 0; i < points.length(); i++) {
pointJSON = points.getJSONObject(i);
path.add(new LatLng(pointJSON.getDouble("lat"), pointJSON.getDouble("lng")));
}
return path;
}
*/
public static LatLngBounds JSONArray2LatLngBounds(JSONArray points) throws JSONException {
List<LatLng> path = JSONArray2LatLngList(points);
Builder builder = LatLngBounds.builder();
int i = 0;
for (i = 0; i < path.size(); i++) {
builder.include(path.get(i));
}
return builder.build();
}
public static Bundle Json2Bundle(JSONObject json) {
Bundle mBundle = new Bundle();
@SuppressWarnings("unchecked")
Iterator<String> iter = json.keys();
Object value;
while (iter.hasNext()) {
String key = iter.next();
try {
value = json.get(key);
if (Boolean.class.isInstance(value)) {
mBundle.putBoolean(key, (Boolean)value);
} else if (Double.class.isInstance(value)) {
mBundle.putDouble(key, (Double)value);
} else if (Integer.class.isInstance(value)) {
mBundle.putInt(key, (Integer)value);
} else if (Long.class.isInstance(value)) {
mBundle.putLong(key, (Long)value);
} else if (JSONObject.class.isInstance(value)) {
mBundle.putBundle(key, Json2Bundle((JSONObject)value));
} else {
mBundle.putString(key, json.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mBundle;
}
public static Bitmap resizeBitmap(Bitmap bitmap, int width, int height) {
if (bitmap == null) {
return null;
}
Bitmap resizeBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
return resizeBitmap;
}
public static Bitmap scaleBitmapForDevice(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
float density = Resources.getSystem().getDisplayMetrics().density;
int width = (int)(bitmap.getWidth() * density);
int height = (int)(bitmap.getHeight() * density);
Bitmap resizeBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
return resizeBitmap;
}
public static Bitmap getBitmapFromBase64encodedImage(String base64EncodedImage) {
byte[] byteArray= Base64.decode(base64EncodedImage, Base64.DEFAULT);
Bitmap image= null;
try {
image = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
public static JSONObject Bundle2Json(Bundle bundle) {
JSONObject json = new JSONObject();
Set<String> keys = bundle.keySet();
Iterator<String> iter = keys.iterator();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = bundle.get(key);
if (Bundle.class.isInstance(value)) {
value = Bundle2Json((Bundle)value);
}
if (value.getClass().isArray()) {
JSONArray values = new JSONArray();
Object[] objects = (Object[])value;
int i = 0;
for (i = 0; i < objects.length; i++) {
if (Bundle.class.isInstance(objects[i])) {
objects[i] = Bundle2Json((Bundle)objects[i]);
}
values.put(objects[i]);
}
json.put(key, values);
} else if (value.getClass() == ArrayList.class) {
JSONArray values = new JSONArray();
Iterator<?> listIterator = ((ArrayList<?>)value).iterator();
while(listIterator.hasNext()) {
value = listIterator.next();
if (Bundle.class.isInstance(value)) {
value = Bundle2Json((Bundle)value);
}
values.put(value);
}
json.put(key, values);
} else {
json.put(key, value);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return json;
}
}
|
package br.ufrj.cos.redes.fileAccess;
import java.io.Serializable;
public class Chunk implements Comparable<Chunk>, Serializable {
private static final long serialVersionUID = 1L;
private long seqNum;
private byte[] bytes;
private int actualChunkLength;
private boolean available;
public Chunk(int chunkLength) {
bytes = new byte[chunkLength];
}
public Chunk(int chunkLength, boolean available) {
bytes = new byte[chunkLength];
this.available = available;
}
public long getSeqNum() {
return seqNum;
}
public void setSeqNum(long seqNum) {
this.seqNum = seqNum;
}
public byte[] getBytes() {
return bytes;
}
public int getActualChunkLength() {
return actualChunkLength;
}
public void setActualChunkLength(int actualChunkLength) {
this.actualChunkLength = actualChunkLength;
}
@Override
public int compareTo(Chunk otherChunk) {
if (this.seqNum < otherChunk.getSeqNum()) {
return -1;
} else if (this.seqNum > otherChunk.getSeqNum()) {
return 1;
} else {
return 0;
}
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
|
package codeu.chat.client.simplegui2;
import codeu.chat.client.BroadCastReceiver;
import codeu.chat.client.ClientContext;
import codeu.chat.common.ConversationSummary;
import codeu.chat.common.Message;
import codeu.chat.util.Time;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.swing.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
public class ChatMenu {
private BorderPane mainWindow;
private Scene scene;
private Stage stage;
private ListView<String> conversationPanel;
private final ClientContext clientContext;
private final DefaultListModel<String> messageListModel = new DefaultListModel<>();
private final BroadCastReceiver receiver;
//ChatMenu constructor
public ChatMenu(ClientContext clientContext, BroadCastReceiver receiver) {
this.clientContext = clientContext;
this.receiver = receiver;
//initializes the different panels within the grid layout
mainWindow = new BorderPane();
mainWindow.setMinHeight(700);
mainWindow.setMinWidth(700);
//create listView to be added to panel
conversationPanel = new ListView<>();
conversationPanel.setPadding(new Insets(3));
conversationPanel.setMinWidth(200);
//border for conversation Panel
conversationPanel.setStyle("-fx-padding: 10;" +
"-fx-border-style: solid inside;" +
"-fx-border-width: 4;" +
"-fx-border-insets: 0;" +
"-fx-border-radius: 5;" +
"-fx-border-color: #336699;");
//add action listener to selected item
conversationPanel.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observableValue, String s, String t1) {
//I believe t1 is the String of the newly selected item (index?, name?)
int index=conversationPanel.getSelectionModel().getSelectedIndex();
//if t1 is the conversation title
int localIndex=0;
for (final ConversationSummary cs : clientContext.conversation.getConversationSummaries()) {
if (localIndex >= index && cs.title.equals(t1)) {
clientContext.conversation.setCurrent(cs);
//update message panel
receiver.joinConversation(cs);
break;
}
localIndex++;
}
}
});
conversationPanel.setOnMouseEntered(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
updateConversationPanel(conversationPanel);
}
});
//organize main Pane
mainWindow.setTop(topMenuBar());
mainWindow.setLeft(conversationPanel);
mainWindow.setBottom(textBar());
mainWindow.setCenter(centralTextBox());
stage = new Stage();
scene = new Scene(mainWindow);
stage.setScene(scene);
getAllMessages(clientContext.conversation.getCurrent());
receiver.start();
}
//Public method to call in order to display the main chat stage
public void display() {
stage.show();
}
private HBox topMenuBar() {
//create menu at top
HBox topbar = new HBox(10);
topbar.setMaxHeight(100);
topbar.setPadding(new Insets(15, 12, 15, 12));
topbar.setStyle("-fx-background-color: #336699;");
//add buttons for different options
final Button signOut = new Button("Sign Out");
signOut.setPrefSize(100, 20);
final Button addUser = new Button("Add User");
addUser.setPrefSize(100, 20);
final Button newConvo = new Button("New Conversation");
newConvo.setPrefSize(100, 20);
signOut.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
if (clientContext.user.hasCurrent()) {
boolean successfulSignOut = clientContext.user.signOutUser();
} else {
AlertBox alertNoUser = new AlertBox("You are not signed in.",
"You cannot sign out without being logged in.");
alertNoUser.display();
}
}
});
addUser.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
if (clientContext.user.hasCurrent()) {
AlertBox alertNoUser = new AlertBox("A user is signed in.", "Please sign out first.");
alertNoUser.display();
} else {
NewUser addNewUser = new NewUser(clientContext);
final String s = addNewUser.getInput();
if (s != null && s.length() > 0) {
clientContext.user.addUser(s);
clientContext.user.signInUser(s);
}
}
}
});
newConvo.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
if (clientContext.user.hasCurrent()) {
NewConversation addConversationBox = new NewConversation(clientContext,
"Add Conversation", "Enter new conversation name:");
addConversationBox.enterNewConversation();
String s = addConversationBox.conversationInput();
if (s != null && s.length() > 0) {
clientContext.conversation.startConversation(s, clientContext.user.getCurrent().id);
for (ConversationSummary cs: clientContext.conversation.getConversationSummaries()) {
addNewConversation(cs.title);
}
}
} else {
AlertBox alertNoUser = new AlertBox("You are not signed in.",
"Please sign in before joining a conversation.");
alertNoUser.display();
}
}
});
//add buttons to menu
topbar.getChildren().addAll(signOut, addUser, newConvo);
return topbar;
}
private HBox textBar() {
//create menu at bottom
HBox bottombar = new HBox(10);
bottombar.setMinHeight(200);
TextArea textBox = new TextArea();
textBox.setWrapText(true);
//border for box
bottombar.setStyle("-fx-padding: 10;" +
"-fx-border-style: solid inside;" +
"-fx-border-width: 4;" +
"-fx-border-radius: 5;" +
"-fx-border-color: #336699;");
//Button to send messages.
Button send = new Button("Send");
send.setPrefSize(100, 20);
send.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
//if no user or current conversation, alert box
if (!clientContext.user.hasCurrent()) {
AlertBox alertNoInput = new AlertBox("Cannot send message", "You are not signed in");
alertNoInput.display();
} else if (!clientContext.conversation.hasCurrent()) {
AlertBox alertNoInput = new AlertBox("Cannot send message", "No current conversations");
alertNoInput.display();
} else if (containsBadLanguage(textBox.getText())) {
AlertBox alertNoInput = new AlertBox("Cannot send message",
"Cannot send an omitted word");
alertNoInput.display();
} else {
final String messageText = textBox.getText();
if (messageText != null && messageText.length() > 0) {
clientContext.message.addMessage(
clientContext.user.getCurrent().id,
clientContext.conversation.getCurrentId(),
messageText);
ChatMenu.this.getAllMessages(clientContext.conversation.getCurrent());
}
}
}
});
//will be place to input text
bottombar.getChildren().addAll(textBox, send);
return bottombar;
}
private VBox centralTextBox() {
VBox centralBox = new VBox();
TextArea messages = new TextArea();
messages.setPrefSize(500, 500);
messages.setEditable(false);
messages.setWrapText(true);
centralBox.getChildren().addAll(messages);
this.receiver.onBroadCast((Message message) -> {
final String authorName = clientContext.user.getName(message.author);
final String displayString = String.format("%s: [%s]: %s",
((authorName == null) ? message.author : authorName), message.creation, message.content);
messages.appendText("\n" + displayString);
});
return centralBox;
}
private void getAllMessages(ConversationSummary conversation) {
messageListModel.clear();
for (final Message m : clientContext.message.getConversationContents(conversation)) {
// Display author name if available. Otherwise display the author UUID.
final String authorName = clientContext.user.getName(m.author);
Time time= m.creation;
String cutSecondsOffTime= time.toString();
cutSecondsOffTime=cutSecondsOffTime.substring(0, cutSecondsOffTime.length()- 7);
final String displayString = String.format("%s: [%s]: %s",
((authorName == null) ? m.author : authorName), cutSecondsOffTime, m.content);
messageListModel.addElement(displayString);
}
}
//pulls each word out of line and checks against list of omitted words
private boolean containsBadLanguage(String userLine) {
boolean containsBadWord = false;
int size = userLine.length();
int position = 0;
ArrayList<String> separators = new ArrayList<>();
commonSeparators(separators);
String[] omittedWords = {"fuck", "bitch", "ass", "shit", "damnit", "dammit", "hoe", "faggot"};
while (position < size && !containsBadWord) {
String singleWord = nextWordOrSeparator(userLine, position, separators);
singleWord = singleWord.toLowerCase();
for (String omitted : omittedWords) {
if (singleWord.contains(omitted)) {
containsBadWord = true;
}
}
position += singleWord.length();
}
return containsBadWord;
}
//returns a single word or a group of separators from starting position
private static String nextWordOrSeparator(String text, int position,
ArrayList<String> separators) {
assert text != null : "Violation of: text is not null";
assert separators != null : "Violation of: separators is not null";
assert 0 <= position : "Violation of: 0 <= position";
assert position < text.length() : "Violation of: position < |text|";
boolean wordOrSep = separators
.contains(text.substring(position, position + 1));
int length = 0;
//while characters match type of first found, increment length
while (position + length < text.length()
&& separators.contains(text.substring(position + length,
position + length + 1)) == wordOrSep) {
length++;
}
//return the substring of given word or sep
return text.substring(position, position + length);
}
private static void commonSeparators(ArrayList<String> sep) {
sep.clear();
sep.add("\t");
sep.add("\n");
sep.add("\r");
sep.add(".");
sep.add(",");
sep.add(" ");
sep.add("?");
sep.add("\'");
sep.add("\"");
sep.add("-");
sep.add("!");
sep.add(";");
sep.add(":");
sep.add("/");
sep.add("\\");
sep.add("(");
sep.add(")");
sep.add("[");
sep.add("]");
sep.add("{");
sep.add("}");
sep.add("*");
sep.add("`");
}
private void addNewConversation(String conversationName){
conversationPanel.getItems().add(conversationName);
}
private void updateConversationPanel(ListView<String> conversationPanel) {
System.out.println("Updating Conversations");
clientContext.conversation.updateAllConversations(false);
conversationPanel.getItems().clear();
for (ConversationSummary cs: clientContext.conversation.getConversationSummaries()) {
conversationPanel.getItems().add(cs.title);
}
}
}
|
package com.linkedin.thirdeye.impl;
import com.linkedin.thirdeye.api.StarTreeConfig;
import com.linkedin.thirdeye.api.StarTreeConstants;
import com.linkedin.thirdeye.api.StarTreeNode;
import com.linkedin.thirdeye.api.StarTreeRecord;
import com.linkedin.thirdeye.api.StarTreeRecordStore;
import com.linkedin.thirdeye.api.StarTreeRecordStoreFactory;
import com.linkedin.thirdeye.api.StarTreeRecordThresholdFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class StarTreeNodeImpl implements StarTreeNode
{
private static final long serialVersionUID = -403250971215465050L;
private static final Logger LOG = LoggerFactory.getLogger(StarTreeNodeImpl.class);
private transient StarTreeRecordThresholdFunction thresholdFunction;
private transient StarTreeRecordStoreFactory recordStoreFactory;
private transient StarTreeConfig config;
private transient StarTreeRecordStore recordStore;
private final ReadWriteLock lock = new ReentrantReadWriteLock(true);
private final UUID nodeId;
private final String dimensionName;
private final String dimensionValue;
private final Map<String, StarTreeNode> children;
private final List<String> ancestorDimensionNames;
private final AtomicBoolean isSplit;
private StarTreeNode otherNode;
private StarTreeNode starNode;
private String childDimensionName;
public StarTreeNodeImpl(UUID nodeId,
StarTreeRecordThresholdFunction thresholdFunction,
StarTreeRecordStoreFactory recordStoreFactory,
String dimensionName,
String dimensionValue,
List<String> ancestorDimensionNames,
Map<String, StarTreeNode> children,
StarTreeNode otherNode,
StarTreeNode starNode)
{
this.nodeId = nodeId;
this.thresholdFunction = thresholdFunction;
this.recordStoreFactory = recordStoreFactory;
this.dimensionName = dimensionName;
this.dimensionValue = dimensionValue;
this.ancestorDimensionNames = ancestorDimensionNames;
this.children = children;
this.otherNode = otherNode;
this.starNode = starNode;
this.isSplit = new AtomicBoolean(false);
}
@Override
public UUID getId()
{
return nodeId;
}
@Override
public void init(StarTreeConfig config)
{
lock.writeLock().lock();
try
{
this.config = config;
this.thresholdFunction = config.getThresholdFunction();
if (this.children.isEmpty()) // only init record stores for leaves
{
try
{
this.recordStoreFactory = config.getRecordStoreFactory();
this.recordStore = recordStoreFactory.createRecordStore(nodeId);
this.recordStore.open();
}
catch (Exception e)
{
throw new IllegalStateException(e);
}
}
}
finally
{
lock.writeLock().unlock();
}
}
@Override
public boolean isLeaf()
{
lock.readLock().lock();
try
{
return children.isEmpty();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public Collection<StarTreeNode> getChildren()
{
lock.readLock().lock();
try
{
return children.values();
}
finally
{
lock.readLock().unlock();
}
}
@Override
public StarTreeNode getChild(String dimensionValue)
{
lock.readLock().lock();
try
{
if (children.isEmpty())
{
throw new UnsupportedOperationException("Cannot get child of leaf node");
}
return children.get(dimensionValue);
}
finally
{
lock.readLock().unlock();
}
}
@Override
public StarTreeNode getOtherNode()
{
lock.readLock().lock();
try
{
return otherNode;
}
finally
{
lock.readLock().unlock();
}
}
@Override
public StarTreeNode getStarNode()
{
lock.readLock().lock();
try
{
return starNode;
}
finally
{
lock.readLock().unlock();
}
}
@Override
public StarTreeRecordStore getRecordStore()
{
lock.readLock().lock();
try
{
return recordStore;
}
finally
{
lock.readLock().unlock();
}
}
@Override
public String getDimensionName()
{
return dimensionName; // immutable
}
@Override
public String getChildDimensionName()
{
lock.readLock().lock();
try
{
return childDimensionName;
}
finally
{
lock.readLock().unlock();
}
}
@Override
public List<String> getAncestorDimensionNames()
{
lock.readLock().lock();
try
{
return ancestorDimensionNames;
}
finally
{
lock.readLock().unlock();
}
}
@Override
public String getDimensionValue()
{
return dimensionValue; // immutable
}
@Override
public void split(String splitDimensionName)
{
lock.writeLock().lock();
try
{
if (!isSplit.getAndSet(true))
{
// Check
if (!children.isEmpty())
{
return;
}
else if (recordStore == null)
{
throw new IllegalStateException("Splitting a node with null record store on dimension " + splitDimensionName);
}
// Split info
StringBuilder nodeName = new StringBuilder();
if (!ancestorDimensionNames.isEmpty())
{
nodeName.append(StarTreeConstants.STAR).append(".");
}
for (String ancestorName : ancestorDimensionNames)
{
nodeName.append(ancestorName).append(".");
}
nodeName.append(dimensionName);
LOG.info("Splitting node " + nodeName.toString() + ":" + dimensionValue
+ " on dimension " + splitDimensionName + " (records=" + recordStore.size() + ")");
// Ancestor dimension names now contain the current node's dimension name
List<String> nextAncestorDimensionNames = new ArrayList<String>();
if (!StarTreeConstants.STAR.equals(dimensionName))
{
nextAncestorDimensionNames.addAll(ancestorDimensionNames);
nextAncestorDimensionNames.add(dimensionName);
}
// Group all records by the dimension value on which we're splitting
Map<String, List<StarTreeRecord>> groupedRecords = new HashMap<String, List<StarTreeRecord>>();
for (StarTreeRecord record : recordStore)
{
String dimensionValue = record.getDimensionValues().get(splitDimensionName);
List<StarTreeRecord> records = groupedRecords.get(dimensionValue);
if (records == null)
{
records = new ArrayList<StarTreeRecord>();
groupedRecords.put(dimensionValue, records);
}
records.add(record);
}
// Apply function to see which records pass threshold and which don't
Set<String> passingValues;
if (thresholdFunction == null)
{
passingValues = new HashSet<String>(groupedRecords.keySet());
}
else
{
passingValues = thresholdFunction.apply(groupedRecords);
}
LOG.info("Passing dimension values for split on {}", splitDimensionName);
for (String passingValue : passingValues)
{
LOG.info("\t{}", passingValue);
}
// Add star node
starNode = new StarTreeNodeImpl(
UUID.randomUUID(),
thresholdFunction,
recordStoreFactory,
splitDimensionName,
StarTreeConstants.STAR,
nextAncestorDimensionNames,
new HashMap<String, StarTreeNode>(),
null,
null);
starNode.init(config);
// Add other node
otherNode = new StarTreeNodeImpl(
UUID.randomUUID(),
thresholdFunction,
recordStoreFactory,
splitDimensionName,
StarTreeConstants.OTHER,
nextAncestorDimensionNames,
new HashMap<String, StarTreeNode>(),
null,
null);
otherNode.init(config);
// Add children nodes who passed
for (String dimensionValue : passingValues)
{
StarTreeNode child = new StarTreeNodeImpl(
UUID.randomUUID(),
thresholdFunction,
recordStoreFactory,
splitDimensionName,
dimensionValue,
nextAncestorDimensionNames,
new HashMap<String, StarTreeNode>(),
null,
null);
child.init(config);
children.put(dimensionValue, child);
}
// Now, add all records from the leaf node's store
for (Map.Entry<String, List<StarTreeRecord>> entry : groupedRecords.entrySet())
{
String dimensionValue = entry.getKey();
List<StarTreeRecord> records = entry.getValue();
// To the appropriate specific or "other" node
StarTreeNode child = children.get(dimensionValue);
if (child == null) // other
{
child = otherNode;
}
// Add records and compute aggregate
for (StarTreeRecord record : records)
{
StarTreeRecord recordForUpdate = record;
if (child == otherNode)
{
recordForUpdate = record.aliasOther(splitDimensionName);
}
child.getRecordStore().update(recordForUpdate);
starNode.getRecordStore().update(recordForUpdate.relax(splitDimensionName));
}
}
// Clear this node's record store
recordStore.clear();
// Set the children dimension name
childDimensionName = splitDimensionName;
}
}
finally
{
lock.writeLock().unlock();
}
}
}
|
/*
* generated by Xtext
*/
package cl.uchile.pleiad;
import cl.uchile.pleiad.types.ITypeSystem;
import cl.uchile.pleiad.types.TypeSystem;
/**
* Use this class to register components to be used at runtime / without the Equinox extension registry.
*/
public class TextRAMRuntimeModule extends cl.uchile.pleiad.AbstractTextRAMRuntimeModule {
public Class<? extends ITypeSystem> bindITypeSystem() {
return TypeSystem.class;
}
}
|
package org.westmalle.wayland.protocol;
import org.freedesktop.wayland.server.Client;
import org.freedesktop.wayland.server.WlSeatResource;
import org.freedesktop.wayland.server.WlShellSurfaceResource;
import org.freedesktop.wayland.server.WlSurfaceResource;
import org.freedesktop.wayland.server.jna.WaylandServerLibrary;
import org.freedesktop.wayland.server.jna.WaylandServerLibraryMapping;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.westmalle.wayland.output.wlshell.ShellSurface;
import java.util.Optional;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest(WaylandServerLibrary.class)
public class WlShellSurfaceTest {
@Mock
private ShellSurface shellSurface;
@Mock
private WaylandServerLibraryMapping waylandServerLibraryMapping;
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(WaylandServerLibrary.class);
when(WaylandServerLibrary.INSTANCE()).thenReturn(this.waylandServerLibraryMapping);
}
@Test
public void testMove() throws Exception {
//given
final WlSurfaceResource wlSurfaceResource = mock(WlSurfaceResource.class);
final WlShellSurface wlShellSurface = new WlShellSurface(this.shellSurface,
wlSurfaceResource);
final WlSeatResource wlSeatResource = mock(WlSeatResource.class);
final WlSeat wlSeat = mock(WlSeat.class);
when(wlSeatResource.getImplementation()).thenReturn(wlSeat);
final WlPointer wlPointer = mock(WlPointer.class);
when(wlSeat.getOptionalWlPointer()).thenReturn(Optional.of(wlPointer));
final WlShellSurfaceResource wlShellSurfaceResource = mock(WlShellSurfaceResource.class);
final int serial = 454;
//when
wlShellSurface.move(wlShellSurfaceResource,
wlSeatResource,
serial);
//then
verify(this.shellSurface).move(wlSurfaceResource,
wlPointer,
serial);
}
@Test
public void testCreate() throws Exception {
//given
final Client client = mock(Client.class);
final int version = 1;
final int id = 1;
final WlSurfaceResource wlSurfaceResource = mock(WlSurfaceResource.class);
final WlShellSurface wlShellSurface = new WlShellSurface(this.shellSurface,
wlSurfaceResource);
//when
final WlShellSurfaceResource wlShellSurfaceResource = wlShellSurface.create(client,
version,
id);
//then
assertThat(wlShellSurfaceResource).isNotNull();
}
@Test
public void testResize() throws Exception {
//given
final WlSurfaceResource wlSurfaceResource = mock(WlSurfaceResource.class);
final WlShellSurface wlShellSurface = new WlShellSurface(this.shellSurface,
wlSurfaceResource);
final WlSeatResource wlSeatResource = mock(WlSeatResource.class);
final WlSeat wlSeat = mock(WlSeat.class);
when(wlSeatResource.getImplementation()).thenReturn(wlSeat);
final WlPointer wlPointer = mock(WlPointer.class);
when(wlSeat.getOptionalWlPointer()).thenReturn(Optional.of(wlPointer));
final WlShellSurfaceResource wlShellSurfaceResource = mock(WlShellSurfaceResource.class);
final int serial = 454;
final int edges = 8;
//when
wlShellSurface.resize(wlShellSurfaceResource,
wlSeatResource,
serial,
edges);
//then
verify(this.shellSurface).resize(wlShellSurfaceResource,
wlSurfaceResource,
wlPointer,
serial,
edges);
}
@Test
public void testPong() {
//given
final WlSurfaceResource wlSurfaceResource = mock(WlSurfaceResource.class);
final WlShellSurface wlShellSurface = new WlShellSurface(this.shellSurface,
wlSurfaceResource);
final WlShellSurfaceResource wlShellSurfaceResource = mock(WlShellSurfaceResource.class);
final int serial = 7654;
//when
wlShellSurface.pong(wlShellSurfaceResource,
serial);
//then
verify(this.shellSurface).pong(wlShellSurfaceResource,
serial);
}
@Test
public void testSetTitle() {
//given
final WlSurfaceResource wlSurfaceResource = mock(WlSurfaceResource.class);
final WlShellSurface wlShellSurface = new WlShellSurface(this.shellSurface,
wlSurfaceResource);
final WlShellSurfaceResource wlShellSurfaceResource = mock(WlShellSurfaceResource.class);
final String title = "appTitle";
//when
wlShellSurface.setTitle(wlShellSurfaceResource,
title);
//then
verify(this.shellSurface).setTitle(Optional.of(title));
}
@Test
public void testSetClass() {
//given
final WlSurfaceResource wlSurfaceResource = mock(WlSurfaceResource.class);
final WlShellSurface wlShellSurface = new WlShellSurface(this.shellSurface,
wlSurfaceResource);
final WlShellSurfaceResource wlShellSurfaceResource = mock(WlShellSurfaceResource.class);
final String clazz = "appClass";
//when
wlShellSurface.setClass(wlShellSurfaceResource,
clazz);
//then
verify(this.shellSurface).setClazz(Optional.of(clazz));
}
@Test
public void testSetToplevel() throws Exception {
//given
final WlSurfaceResource wlSurfaceResource = mock(WlSurfaceResource.class);
final WlShellSurface wlShellSurface = new WlShellSurface(this.shellSurface,
wlSurfaceResource);
final WlShellSurfaceResource wlShellSurfaceResource = mock(WlShellSurfaceResource.class);
//when
wlShellSurface.setToplevel(wlShellSurfaceResource);
//then
verify(this.shellSurface).toFront(wlSurfaceResource);
}
@Test
public void testSetTransient() throws Exception {
//given
final WlSurfaceResource wlSurfaceResource = mock(WlSurfaceResource.class);
final WlShellSurface wlShellSurface = new WlShellSurface(this.shellSurface,
wlSurfaceResource);
final WlShellSurfaceResource wlShellSurfaceResource = mock(WlShellSurfaceResource.class);
final WlSurfaceResource parentWlSurfaceResource = mock(WlSurfaceResource.class);
final int x = 1235;
final int y = 9876;
final int flags = 0;
//when
wlShellSurface.setTransient(wlShellSurfaceResource,
parentWlSurfaceResource,
x,
y,
flags);
//then
verify(this.shellSurface).setTransient(wlSurfaceResource,
parentWlSurfaceResource,
x,
y,
flags);
}
}
|
package com.aha.businesslogic.model;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author HB
*/
public class Passenger extends User {
private List<Booking> booking;
public Passenger() {
this.booking = new ArrayList<>();
}
public List<Booking> getBooking() {
return booking;
}
public void setBooking(List<Booking> booking) {
this.booking = booking;
}
}
|
package edu.umd.cs.findbugs.flybush;
import com.google.common.base.Supplier;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.googlecode.charts4j.AxisLabels;
import com.googlecode.charts4j.AxisLabelsFactory;
import com.googlecode.charts4j.AxisStyle;
import com.googlecode.charts4j.AxisTextAlignment;
import com.googlecode.charts4j.BarChart;
import com.googlecode.charts4j.Color;
import com.googlecode.charts4j.Data;
import com.googlecode.charts4j.DataEncoding;
import com.googlecode.charts4j.GCharts;
import com.googlecode.charts4j.Line;
import com.googlecode.charts4j.LineChart;
import com.googlecode.charts4j.Plots;
import org.apache.commons.lang.StringEscapeUtils;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.logging.Level;
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
public class ReportServlet extends AbstractFlybushServlet {
private static final DateFormat DATE_FORMAT = DateFormat.getDateInstance(DateFormat.SHORT);
private static final DateFormat DATE_TIME_FORMAT = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String uri = req.getRequestURI();
PersistenceManager pm = getPersistenceManager();
try {
if (uri.equals("/stats")) {
showStats(req, resp, pm);
} else {
show404(resp);
}
} finally {
pm.close();
}
}
private void showStats(HttpServletRequest req, HttpServletResponse resp, PersistenceManager pm)
throws IOException {
if (req.getParameter("user") != null) {
showUserStats(req, resp, pm, req.getParameter("user"));
} else if (req.getParameter("package") != null) {
showPackageStats(req, resp, pm, req.getParameter("package"));
} else {
showSummaryStats(req, resp, pm);
}
}
@SuppressWarnings({"unchecked"})
private void showPackageStats(HttpServletRequest req, HttpServletResponse resp,
PersistenceManager pm, String desiredPackage) throws IOException {
if (desiredPackage.equals("*"))
desiredPackage = "";
Query query = pm.newQuery("select from " + persistenceHelper.getDbEvaluationClass().getName() + " order by when");
List<DbEvaluation> evals = (List<DbEvaluation>) query.execute();
Map<Long,Integer> evalsPerWeek = Maps.newHashMap();
Map<Long,Integer> newIssuesPerWeek = Maps.newHashMap();
Multimap<String,String> issuesByPkg = HashMultimap.create();
Set<String> seenIssues = Sets.newHashSet();
Map<String, Integer> evalsByPkg = Maps.newHashMap();
List<String> lines = Lists.newArrayList();
for (DbEvaluation eval : evals) {
String epkg = getPackageName(eval.getIssue().getPrimaryClass());
if (epkg == null)
continue;
if (!isPackageOrSubPackage(desiredPackage, epkg)) {
continue;
}
issuesByPkg.put(epkg, eval.getIssue().getHash());
increment(evalsByPkg, epkg);
long beginningOfWeek = getBeginningOfWeekInMillis(eval.getWhen());
increment(evalsPerWeek, beginningOfWeek);
if (seenIssues.add(eval.getIssue().getHash()))
increment(newIssuesPerWeek, beginningOfWeek);
lines.add(createEvalsTableEntry(req, eval));
}
LineChart timelineChart = null;
BarChart subpkgChart = null;
if (evalsPerWeek.size() != 0) {
timelineChart = buildEvaluationTimeline("Evaluations & Issues - " + desiredPackage + " (recursive)",
evalsPerWeek, newIssuesPerWeek);
if (evalsByPkg.size() > 1)
subpkgChart = buildByPkgChart(issuesByPkg, evalsByPkg);
}
resp.setStatus(200);
ServletOutputStream page = resp.getOutputStream();
page.println(
"<html>\n" +
"<head><title>" + escapeHtml(desiredPackage) + " - FindBugs Cloud Stats</title></head>\n" +
"<body>\n" +
backButton(req));
printPackageForm(req, resp, desiredPackage);
printPackageTree(req, resp, desiredPackage, evalsByPkg);
page.println("<br><br>");
if (timelineChart == null)
page.print("No evaluations for classes in " + escapeHtml(desiredPackage));
else
showChartImg(resp, timelineChart.toURLString());
if (subpkgChart != null)
showChartImg(resp, subpkgChart.toURLString());
printEvalsTable(resp, lines);
}
private String backButton(HttpServletRequest req) {
return "<a href=\"" + req.getRequestURI() + "\"><< Back</a>";
}
private void printPackageForm(HttpServletRequest req, HttpServletResponse resp, String desiredPackage)
throws IOException {
resp.getOutputStream().println("<form action=\"" + req.getRequestURI() + "\" method=get>\n" +
"Package stats: <input type=text name=package size=30 value=\""
+ escapeHtml(desiredPackage) + "\">\n" +
"<input type=submit value=Go>\n" +
"</form>");
}
private void printPackageTree(HttpServletRequest req, HttpServletResponse resp,
String desiredPackage, Map<String, Integer> evalsByPkg) throws IOException {
ServletOutputStream page = resp.getOutputStream();
boolean isDefaultPackage = desiredPackage.equals("");
page.println("<ul>");
if (desiredPackage.contains("."))
page.println("<li> " + linkToPkg(req, desiredPackage.substring(0, desiredPackage.lastIndexOf('.'))));
else if (isDefaultPackage)
page.println("<li>");
else
page.println("<li> <a href=\"" + req.getRequestURI() + "?package=*\"><default package></a>");
page.println("<ul>");
page.println("<li> " + (isDefaultPackage ? "<default package>" : escapeHtml(desiredPackage)));
page.println("<ul>");
Set<String> alreadyPrinted = Sets.newHashSet();
for (String pkg : Sets.newTreeSet(evalsByPkg.keySet())) {
if (pkg.equals(desiredPackage))
continue;
String remainder = isDefaultPackage ? pkg : pkg.substring(desiredPackage.length() + 1);
int dot = remainder.indexOf('.');
String subpkg;
if (dot != -1) {
subpkg = remainder.substring(0, dot);
} else {
subpkg = remainder;
}
String pkgToPrint = isDefaultPackage ? subpkg : desiredPackage + "." + subpkg;
if (!alreadyPrinted.add(pkgToPrint))
continue;
page.println("<li> " + linkToPkg(req, pkgToPrint)
+ " (" + getEvalCountForTree(evalsByPkg, pkgToPrint) + ")</li>");
}
page.println("</li>");
page.println("</li>");
page.println("</ul>");
}
private String linkToPkg(HttpServletRequest req, String pkg) {
String escaped = escapeHtml(pkg);
try {
return "<a href=\"" + req.getRequestURI() + "?package=" + URLEncoder.encode(escaped, "UTF-8") + "\">"
+ escaped + "</a>";
} catch (UnsupportedEncodingException e) {
LOGGER.log(Level.SEVERE, pkg, e);
return "(ERROR)";
}
}
private int getEvalCountForTree(Map<String, Integer> evalsByPkg, String rootPackage) {
int x = 0;
for (Entry<String, Integer> entry : evalsByPkg.entrySet()) {
if (isPackageOrSubPackage(rootPackage, entry.getKey()))
x += entry.getValue();
}
return x;
}
@SuppressWarnings({"SimplifiableIfStatement"})
private static boolean isPackageOrSubPackage(String possibleParent, String possibleChild) {
if (possibleParent.equals(""))
return true;
return possibleChild.equals(possibleParent) || possibleChild.startsWith(possibleParent + ".");
}
@SuppressWarnings({"unchecked"})
private void showUserStats(HttpServletRequest req, HttpServletResponse resp,
PersistenceManager pm, String email) throws IOException {
Query query = pm.newQuery("select from " + persistenceHelper.getDbEvaluationClass().getName()
+ " where email == :email order by when");
List<DbEvaluation> evals = (List<DbEvaluation>) query.execute(email);
if (evals.isEmpty()) {
setResponse(resp, 404, "No such user");
}
Map<Long, Integer> evalsPerWeek = Maps.newHashMap();
Set<String> seenIssues = Sets.newHashSet();
Map<Long, Integer> newIssuesByWeek = Maps.newHashMap();
List<String> table = Lists.newArrayList();
for (DbEvaluation eval : evals) {
long beginningOfWeek = getBeginningOfWeekInMillis(eval.getWhen());
increment(evalsPerWeek, beginningOfWeek);
if (seenIssues.add(eval.getIssue().getHash()))
increment(newIssuesByWeek, beginningOfWeek);
table.add(createEvalsTableEntry(req, eval));
}
query.closeAll();
LineChart chart = null;
if (!evalsPerWeek.isEmpty())
chart = buildEvaluationTimeline("Evaluations over Time - " + email, evalsPerWeek, newIssuesByWeek);
resp.setStatus(200);
ServletOutputStream page = resp.getOutputStream();
page.println(
"<html>\n" +
"<head><title>" + escapeHtml(email) + " - FindBugs Cloud Stats</title></head>\n" +
"<body>\n" +
backButton(req));
Set<String> users = getAllUserEmails(pm);
printUserStatsSelector(req, resp, users, email);
if (chart == null) {
page.println("Oops! No evaluations uploaded by " + escapeHtml(email));
return;
}
showChartImg(resp, chart.toURLString());
printEvalsTable(resp, table);
}
/**
* @param table should be sorted in ascending order
*/
private static void printEvalsTable(HttpServletResponse resp, List<String> table) throws IOException {
ServletOutputStream page = resp.getOutputStream();
page.println("<br><br>Evaluation history:");
page.println("<div style='overflow:auto;height:400px;border:2px solid black'>\n" +
"<table cellspacing=0 border=1 cellpadding=6>\n" +
"<tr><th>Date (UTC)</th><th>User</th><th>Pattern&Class</th><th>Designation</th><th>Comment</th></tr>");
Collections.reverse(table);
int odd = 0;
for (String line : table) {
page.println("<tr style=background-color:" + ((++odd%2==0) ?"#ffddee":"white") + ";vertical-align:top>" + line + "</tr>");
}
page.println("</table>\n" +
"</div>");
}
private static String createEvalsTableEntry(HttpServletRequest req, DbEvaluation eval) {
return String.format("<td>%s</td>" +
"<td><a href='%s'>%s</a></td>" +
"<td>%s<br>%s</td>" +
"<td>%s</td>" +
"<td>%s</td>",
DATE_TIME_FORMAT.format(new Date(eval.getWhen())).replaceAll(" UTC", ""),
req.getRequestURI() + "?user=" + escapeHtml(eval.getEmail()),
escapeHtml(eval.getEmail()),
eval.getIssue().getBugPattern(),
printPackageLinks(req, eval.getIssue().getPrimaryClass()),
escapeHtml(eval.getDesignation()),
escapeHtml(eval.getComment()));
}
@SuppressWarnings({"StringConcatenationInsideStringBufferAppend"})
private static String printPackageLinks(HttpServletRequest req, String cls) {
StringBuilder str = new StringBuilder();
int lastdot;
int dot = -1;
while (true) {
lastdot = dot;
dot = cls.indexOf('.', dot + 1);
if (dot == -1)
break;
String sofar = cls.substring(0,dot);
if (lastdot != -1)
str.append(".");
str.append("<a href=\"" + req.getRequestURI() + "?package=" + StringEscapeUtils.escapeHtml(sofar) + "\">");
str.append(cls.substring(lastdot+1,dot));
str.append("</a>");
}
return str.toString();
}
@SuppressWarnings({"unchecked"})
private Set<String> getAllUserEmails(PersistenceManager pm) {
Query userQuery = pm.newQuery("select from " + persistenceHelper.getDbUserClass().getName());
List<DbUser> userObjs = (List<DbUser>) userQuery.execute();
Set<String> users = Sets.newHashSet();
for (DbUser userObj : userObjs) {
users.add(userObj.getEmail());
}
userQuery.closeAll();
return users;
}
private LineChart buildEvaluationTimeline(String title,
Map<Long, Integer> evalsPerWeek, Map<Long, Integer> newIssuesByWeek) {
int maxEvalsPerWeek = Collections.max(evalsPerWeek.values());
List<Double> evalsData = Lists.newArrayList();
List<String> labels = Lists.newArrayList();
List<Double> newIssuesData = Lists.newArrayList();
for (Calendar cal : iterateByWeek(evalsPerWeek.keySet())) {
Integer evalsThisWeek = evalsPerWeek.get(cal.getTimeInMillis());
if (evalsThisWeek == null)
evalsThisWeek = 0;
Integer newIssuesThisWeek = newIssuesByWeek.get(cal.getTimeInMillis());
if (newIssuesThisWeek == null)
newIssuesThisWeek = 0;
evalsData.add(evalsThisWeek * 100.0 / maxEvalsPerWeek);
newIssuesData.add(newIssuesThisWeek * 100.0 / maxEvalsPerWeek);
labels.add(DATE_FORMAT.format(new Date(cal.getTimeInMillis())));
}
Line evalsLine = Plots.newLine(Data.newData(evalsData), Color.LIGHTPINK, "Updated evaluations");
evalsLine.setFillAreaColor(Color.LIGHTPINK);
Line issuesLine = Plots.newLine(Data.newData(newIssuesData), Color.ORCHID, "Initial evaluations");
issuesLine.setFillAreaColor(Color.ORCHID);
LineChart chart = GCharts.newLineChart(evalsLine, issuesLine);
chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels(labels));
chart.addYAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(0, maxEvalsPerWeek));
chart.setTitle(title);
chart.setDataEncoding(DataEncoding.TEXT);
chart.setSize(800, 350);
return chart;
}
@SuppressWarnings({"unchecked"})
private void showSummaryStats(HttpServletRequest req, HttpServletResponse resp, PersistenceManager pm)
throws IOException {
Query query = pm.newQuery("select from "
+ persistenceHelper.getDbEvaluationClass().getName()
+ " order by when");
List<DbEvaluation> evals = (List<DbEvaluation>) query.execute();
Map<String,Integer> totalCountByUser = Maps.newHashMap();
Map<String,Integer> issueCountByUser = Maps.newHashMap();
Multimap<String, String> issuesByUser = Multimaps.newSetMultimap(Maps.<String, Collection<String>>newHashMap(),
new Supplier<Set<String>>() {
public Set<String> get() {
return Sets.newHashSet();
}
});
Map<Long, Integer> evalsByWeek = Maps.newHashMap();
Map<Long, Integer> issueCountByWeek = Maps.newHashMap();
Map<Long, Integer> userCountByWeek = Maps.newHashMap();
Map<String,Integer> evalCountByPkg = Maps.newHashMap();
Multimap<String, String> issuesByPkg = HashMultimap.create();
Set<String> seenIssues = Sets.newHashSet();
Set<String> seenUsers = Sets.newHashSet();
for (DbEvaluation eval : evals) {
String email = eval.getEmail();
if (email == null)
continue;
DbIssue issue = eval.getIssue();
String issueHash = issue.getHash();
issuesByUser.put(email, issueHash);
increment(totalCountByUser, email);
issueCountByUser.put(email, issuesByUser.get(email).size());
String pkg = getPackageName(issue.getPrimaryClass());
if (pkg != null) {
increment(evalCountByPkg, pkg);
issuesByPkg.put(pkg, issueHash);
}
long beginningOfWeek = getBeginningOfWeekInMillis(eval.getWhen());
increment(evalsByWeek, beginningOfWeek);
seenIssues.add(issueHash);
issueCountByWeek.put(beginningOfWeek, seenIssues.size());
seenUsers.add(email);
userCountByWeek.put(beginningOfWeek, seenUsers.size());
}
query.closeAll();
// build charts
BarChart histogram = buildEvaluatorsHistogram(issuesByUser);
BarChart evalsByUserChart = buildByUserChart(totalCountByUser, issueCountByUser);
BarChart evalsByPkgChart = buildByPkgChart(issuesByPkg, evalCountByPkg);
LineChart evalsOverTimeChart = createTimelineChart(evalsByWeek, issueCountByWeek, userCountByWeek);
LineChart cumulativeTimeline = createCumulativeTimelineChart(evalsByWeek, issueCountByWeek, userCountByWeek);
// print results
resp.setStatus(200);
ServletOutputStream page = resp.getOutputStream();
page.println("<html>" +
"<head><title>FindBugs Cloud Stats</title></head>" +
"<body>");
showChartImg(resp, evalsOverTimeChart.toURLString());
page.println("<br><br>");
showChartImg(resp, cumulativeTimeline.toURLString());
page.println("<br><br>");
printUserStatsSelector(req, resp, seenUsers, null);
printPackageForm(req, resp, "");
showChartImg(resp, evalsByPkgChart.toURLString());
page.println("<br><br>");
showChartImg(resp, evalsByUserChart.toURLString());
page.println("<br><br>");
showChartImg(resp, histogram.toURLString());
}
private String getPackageName(String className) {
if (className == null) {
return null;
}
int lastDot = className.lastIndexOf('.');
if (lastDot == -1) {
return null;
}
return className.substring(0, lastDot);
}
private void printUserStatsSelector(HttpServletRequest req, HttpServletResponse resp,
Collection<String> seenUsers, String selectedEmail) throws IOException {
ServletOutputStream page = resp.getOutputStream();
page.println("User stats:" +
"<form action=\"" + req.getRequestURI() + "\" method=get>\n" +
"<select name=user>\n" +
"<option value=\"\"></option>");
List<String> seenUsersList = Lists.newArrayList(seenUsers);
Collections.sort(seenUsersList);
for (String email : seenUsersList) {
String escaped = escapeHtml(email);
page.println(String.format("<option value=\"%s\"%s>%s</option>",
escaped, email.equals(selectedEmail) ? " selected" : "", escaped));
}
page.println("</select>\n" +
"<input type=submit value=Go>\n" +
"</form>");
}
private BarChart buildEvaluatorsHistogram(Multimap<String, String> issuesByUser) {
Map<String, Integer> usersPerIssue = Maps.newHashMap();
for (String email : issuesByUser.keySet()) {
for (String hash : issuesByUser.get(email)) {
increment(usersPerIssue, hash);
}
}
// map from # of evaluators -> # of issues with that many evaluators
Map<Integer, Integer> issuesPerEvaluatorCount = Maps.newHashMap();
for (String issue : usersPerIssue.keySet()) {
increment(issuesPerEvaluatorCount, usersPerIssue.get(issue));
}
List<Double> histogramData = Lists.newArrayList();
int maxEvaluators = Collections.max(issuesPerEvaluatorCount.keySet());
int maxIssues = Collections.max(issuesPerEvaluatorCount.values());
List<String> barLabels = Lists.newArrayList();
for (int evaluators = 1; evaluators <= maxEvaluators; evaluators++) {
Integer issuesWithThisManyEvaluators = issuesPerEvaluatorCount.get(evaluators);
if (issuesWithThisManyEvaluators == null)
issuesWithThisManyEvaluators = 0;
histogramData.add(issuesWithThisManyEvaluators * 100.0 / maxIssues);
barLabels.add(Integer.toString(evaluators));
}
BarChart histogram = GCharts.newBarChart(Plots.newBarChartPlot(Data.newData(histogramData)));
histogram.setSize(400, 500);
histogram.setBarWidth(BarChart.AUTO_RESIZE);
histogram.setTitle("Histogram: Evaluators Per Issue");
histogram.setDataEncoding(DataEncoding.TEXT);
histogram.addXAxisLabels(AxisLabelsFactory.newAxisLabels(barLabels));
histogram.addYAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(0, maxIssues));
AxisLabels bigLabel = AxisLabelsFactory.newAxisLabels("No. of evaluators", 50);
bigLabel.setAxisStyle(AxisStyle.newAxisStyle(Color.BLACK, 12, AxisTextAlignment.CENTER));
histogram.addXAxisLabels(bigLabel);
return histogram;
}
private <E> void increment(Map<E, Integer> map, E key) {
Integer oldCount = map.get(key);
if (oldCount == null) oldCount = 0;
map.put(key, oldCount + 1);
}
private LineChart createTimelineChart(Map<Long, Integer> evalsByWeek, Map<Long, Integer> issueCountByWeek,
Map<Long, Integer> userCountByWeek) {
int maxEvalsPerWeek = Collections.max(evalsByWeek.values());
List<Double> evalsData = new ArrayList<Double>();
List<Double> userCountData = new ArrayList<Double>();
List<Double> newIssuesData = Lists.newArrayList();
List<String> timelineLabels = Lists.newArrayList();
int issuesCount = 0;
int userCount = 0;
for (Calendar cal : iterateByWeek(evalsByWeek.keySet())) {
Integer evalsThisWeek = evalsByWeek.get(cal.getTimeInMillis());
Integer issuesThisWeek = issueCountByWeek.get(cal.getTimeInMillis());
int newIssuesThisWeek;
if (issuesThisWeek != null) {
newIssuesThisWeek = (issuesThisWeek - issuesCount);
issuesCount = issuesThisWeek;
} else {
newIssuesThisWeek = 0;
}
Integer usersThisWeek = userCountByWeek.get(cal.getTimeInMillis());
int newUsersThisWeek;
if (usersThisWeek != null) {
newUsersThisWeek = (usersThisWeek - userCount);
userCount = usersThisWeek;
} else {
newUsersThisWeek = 0;
}
evalsThisWeek = evalsThisWeek == null ? 0 : evalsThisWeek;
evalsData.add(evalsThisWeek * 100.0 / maxEvalsPerWeek);
userCountData.add(newUsersThisWeek * 100.0 / maxEvalsPerWeek);
newIssuesData.add(newIssuesThisWeek * 100.0 / maxEvalsPerWeek);
timelineLabels.add(DATE_FORMAT.format(new Date(cal.getTimeInMillis())));
}
Line evalsLine = Plots.newLine(Data.newData(evalsData), Color.LIGHTPINK, "New evals for existing issues");
evalsLine.setFillAreaColor(Color.LIGHTPINK);
Line issuesLine = Plots.newLine(Data.newData(newIssuesData), Color.ORCHID, "New issues evaluated");
issuesLine.setFillAreaColor(Color.ORCHID);
Line usersLine = Plots.newLine(Data.newData(userCountData), Color.LIGHTSTEELBLUE, "New users");
LineChart chart = GCharts.newLineChart(evalsLine, issuesLine, usersLine);
chart.setTitle("New Evaluations, Issues, & Users Over Time");
chart.setDataEncoding(DataEncoding.TEXT);
chart.setSize(850, 350);
chart.setGrid(100, 10 / (maxEvalsPerWeek / 100.0), 4, 1);
chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels(timelineLabels));
chart.addYAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(0, maxEvalsPerWeek));
return chart;
}
private LineChart createCumulativeTimelineChart(Map<Long, Integer> evalsByWeek, Map<Long, Integer> issueCountByWeek,
Map<Long, Integer> userCountByWeek) {
int totalEvals = 0;
for (Integer val : evalsByWeek.values()) {
totalEvals += val;
}
int totalUsers = Collections.max(userCountByWeek.values());
List<Double> issuesData = Lists.newArrayList();
List<Double> evalsData = Lists.newArrayList();
List<Double> usersData = Lists.newArrayList();
List<String> labels = Lists.newArrayList();
int issuesCount = 0;
int userCount = 0;
int evalCount = 0;
for (Calendar cal : iterateByWeek(evalsByWeek.keySet())) {
long time = cal.getTimeInMillis();
Integer issuesThisWeek = issueCountByWeek.get(time);
if (issuesThisWeek != null)
issuesCount = issuesThisWeek;
Integer usersThisWeek = userCountByWeek.get(time);
if (usersThisWeek != null)
userCount = usersThisWeek;
Integer evalsThisWeek = evalsByWeek.get(time);
if (evalsThisWeek != null)
evalCount += evalsThisWeek;
labels.add(DATE_FORMAT.format(new Date(time)));
issuesData.add(issuesCount * 100.0 / totalEvals);
usersData.add(userCount * 100.0 / totalUsers);
evalsData.add(evalCount * 100.0 / totalEvals);
}
Line evalsLine = Plots.newLine(Data.newData(evalsData), Color.LIGHTPINK, "Total Evaluations");
evalsLine.setFillAreaColor(Color.LIGHTPINK);
Line issuesLine = Plots.newLine(Data.newData(issuesData), Color.ORCHID, "Total Issues Evaluated");
issuesLine.setFillAreaColor(Color.ORCHID);
Line usersLine = Plots.newLine(Data.newData(usersData), Color.LIGHTSTEELBLUE, "Total Users");
LineChart chart = GCharts.newLineChart(evalsLine, issuesLine, usersLine);
chart.setTitle("Growth Over Time");
chart.setDataEncoding(DataEncoding.TEXT);
chart.setSize(800, 350);
chart.setGrid(100, 100 / (totalEvals / 100.0), 8, 2);
chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels(labels));
AxisLabels leftLabels = AxisLabelsFactory.newNumericRangeAxisLabels(0, totalEvals);
leftLabels.setAxisStyle(AxisStyle.newAxisStyle(Color.DARKORCHID, 10, AxisTextAlignment.RIGHT));
chart.addYAxisLabels(leftLabels);
AxisLabels rightLabels = AxisLabelsFactory.newNumericRangeAxisLabels(0, totalUsers);
rightLabels.setAxisStyle(AxisStyle.newAxisStyle(Color.STEELBLUE, 10, AxisTextAlignment.LEFT));
chart.addRightAxisLabels(rightLabels);
return chart;
}
private Iterable<Calendar> iterateByWeek(Set<Long> unixtimes) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Collections.min(unixtimes));
cal.add(Calendar.DAY_OF_MONTH, -7); // one week prior
final long first = cal.getTimeInMillis();
final long last = Collections.max(unixtimes);
return new Iterable<Calendar>() {
public Iterator<Calendar> iterator() {
return new Iterator<Calendar>() {
private Calendar cal = Calendar.getInstance();
{
cal.setTimeInMillis(first);
}
public boolean hasNext() {
return cal.getTimeInMillis() <= last;
}
public Calendar next() {
if (!hasNext())
throw new NoSuchElementException();
Calendar toReturn = (Calendar) cal.clone();
cal.add(Calendar.DAY_OF_MONTH, 7);
return toReturn;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
private void resetToMidnight(Calendar cal) {
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
}
private long getBeginningOfWeekInMillis(long when) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(when);
Calendar weekCal = Calendar.getInstance();
weekCal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR));
weekCal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
resetToMidnight(weekCal);
weekCal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return weekCal.getTimeInMillis();
}
private BarChart buildByPkgChart(Multimap<String,String> issuesByPkg,
Map<String, Integer> evalCountByPkg) {
List<String> labels = Lists.newArrayList();
List<Double> evalsData = Lists.newArrayList();
List<Double> issuesData = Lists.newArrayList();
int maxPerPkg = Collections.max(evalCountByPkg.values());
int count = 0;
List<Entry<String, Integer>> entries = sortEntriesByValue(evalCountByPkg.entrySet());
Collections.reverse(entries);
for (Entry<String, Integer> entry : entries) {
labels.add(entry.getKey());
evalsData.add(entry.getValue() * 100.0 / maxPerPkg);
issuesData.add((double) issuesByPkg.get(entry.getKey()).size());
if (count++ >= 19)
break;
}
Collections.reverse(labels);
BarChart chart = GCharts.newBarChart(Plots.newBarChartPlot(Data.newData(issuesData), Color.DARKORCHID, "Issues"),
Plots.newBarChartPlot(Data.newData(evalsData), Color.ORCHID, "Evaluations"));
chart.setTitle("Evaluations Per Package");
chart.setGrid(10.0 / (maxPerPkg / 100.0), 100, 4, 1);
chart.setDataStacked(true);
chart.addYAxisLabels(AxisLabelsFactory.newAxisLabels(labels));
chart.addXAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(0, maxPerPkg, 10));
chart.setBarWidth(BarChart.AUTO_RESIZE);
chart.setSize(600, 500);
chart.setHorizontal(true);
chart.setDataEncoding(DataEncoding.TEXT);
return chart;
}
private BarChart buildByUserChart(Map<String, Integer> totalCountByUser,
Map<String, Integer> issueCountByUser) {
List<String> labels = Lists.newArrayList();
List<Double> totals = Lists.newArrayList();
List<Double> issues = Lists.newArrayList();
int max = Collections.max(totalCountByUser.values());
for (Entry<String, Integer> entry : sortEntriesByValue(totalCountByUser.entrySet())) {
String email = entry.getKey();
int issueCount = issueCountByUser.get(email);
int evalCount = entry.getValue();
labels.add(email);
totals.add((evalCount - issueCount) * 100.0 / max);
issues.add(issueCount * 100.0 / max);
}
Collections.reverse(totals);
Collections.reverse(issues);
BarChart chart = GCharts.newBarChart(Plots.newBarChartPlot(Data.newData(issues), Color.DARKORCHID, "Initial evaluation"),
Plots.newBarChartPlot(Data.newData(totals), Color.ORCHID, "Updated evaluation"));
chart.setTitle("Evaluations Per Human");
chart.setDataStacked(true);
chart.setGrid(20.0 / (max / 100.0), 100, 4, 1);
chart.addYAxisLabels(AxisLabelsFactory.newAxisLabels(labels));
chart.addXAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(0, max));
chart.setBarWidth(BarChart.AUTO_RESIZE);
chart.setSize(600, 500);
chart.setHorizontal(true);
chart.setDataEncoding(DataEncoding.TEXT);
return chart;
}
private List<Entry<String, Integer>> sortEntriesByValue(Collection<Entry<String, Integer>> entries) {
List<Entry<String, Integer>> result = new ArrayList<Entry<String, Integer>>(entries);
Collections.sort(result, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
int numbers = o1.getValue().compareTo(o2.getValue());
if (numbers != 0)
return numbers;
// fallback to alpha order by email
return o1.getKey().compareTo(o2.getKey());
}
});
return result;
}
/** protected for testing */
protected void showChartImg(HttpServletResponse resp, String url) throws IOException {
resp.getOutputStream().print("<img src='" + url + "'>");
}
@Override
protected void handlePost(PersistenceManager pm, HttpServletRequest req, HttpServletResponse resp, String uri)
throws IOException {
}
}
|
package com.ecyrd.jspwiki.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader;
import java.util.ArrayList;
import com.ecyrd.jspwiki.StringTransmutator;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.WikiEngine;
/**
* Provides an abstract interface towards the parser instances.
*
* @author jalkanen
*
*/
public abstract class MarkupParser
{
/** Allow this many characters to be pushed back in the stream. In effect,
this limits the size of a single heading line. */
private static final int PUSHBACK_BUFFER_SIZE = 10*1024;
protected PushbackReader m_in;
protected WikiEngine m_engine;
protected WikiContext m_context;
/** Optionally stores internal wikilinks */
protected ArrayList m_localLinkMutatorChain = new ArrayList();
protected ArrayList m_externalLinkMutatorChain = new ArrayList();
protected ArrayList m_attachmentLinkMutatorChain = new ArrayList();
protected ArrayList m_headingListenerChain = new ArrayList();
protected ArrayList m_linkMutators = new ArrayList();
protected boolean m_inlineImages = true;
protected MarkupParser( WikiContext context, Reader in )
{
m_engine = context.getEngine();
m_context = context;
setInputReader( in );
}
/**
* Replaces the current input character stream with a new one.
* @param in New source for input. If null, this method does nothing.
* @return the old stream
*/
public Reader setInputReader( Reader in )
{
Reader old = m_in;
if( in != null )
{
m_in = new PushbackReader( new BufferedReader( in ),
PUSHBACK_BUFFER_SIZE );
}
return old;
}
/**
* Adds a hook for processing link texts. This hook is called
* when the link text is written into the output stream, and
* you may use it to modify the text. It does not affect the
* actual link, only the user-visible text.
*
* @param mutator The hook to call. Null is safe.
*/
public void addLinkTransmutator( StringTransmutator mutator )
{
if( mutator != null )
{
m_linkMutators.add( mutator );
}
}
/**
* Adds a hook for processing local links. The engine
* transforms both non-existing and existing page links.
*
* @param mutator The hook to call. Null is safe.
*/
public void addLocalLinkHook( StringTransmutator mutator )
{
if( mutator != null )
{
m_localLinkMutatorChain.add( mutator );
}
}
public void addExternalLinkHook( StringTransmutator mutator )
{
if( mutator != null )
{
m_externalLinkMutatorChain.add( mutator );
}
}
/**
* Adds a hook for processing attachment links.
*
* @param mutator The hook to call. Null is safe.
*/
public void addAttachmentLinkHook( StringTransmutator mutator )
{
if( mutator != null )
{
m_attachmentLinkMutatorChain.add( mutator );
}
}
public void addHeadingListener( HeadingListener listener )
{
if( listener != null )
{
m_headingListenerChain.add( listener );
}
}
protected boolean m_parseAccessRules = true;
public void disableAccessRules()
{
m_parseAccessRules = false;
}
/**
* Use this to turn on or off image inlining.
* @param toggle If true, images are inlined (as per set in jspwiki.properties)
* If false, then images won't be inlined; instead, they will be
* treated as standard hyperlinks.
* @since 2.2.9
*/
public void enableImageInlining( boolean toggle )
{
m_inlineImages = toggle;
}
/**
* Parses the document.
* @return
* @throws IOException
*/
public abstract WikiDocument parse()
throws IOException;
}
|
package com.gh4a.activities.home;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBar;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.gh4a.BasePagerActivity;
import com.gh4a.Gh4Application;
import com.gh4a.R;
import com.gh4a.activities.BookmarkListActivity;
import com.gh4a.activities.SearchActivity;
import com.gh4a.activities.SettingsActivity;
import com.gh4a.adapter.DrawerAdapter;
import com.gh4a.fragment.RepositoryListContainerFragment;
import com.gh4a.loader.LoaderCallbacks;
import com.gh4a.loader.LoaderResult;
import com.gh4a.loader.UserLoader;
import com.gh4a.utils.AvatarHandler;
import com.gh4a.utils.IntentUtils;
import org.eclipse.egit.github.core.User;
import java.util.Arrays;
import java.util.List;
public class HomeActivity extends BasePagerActivity implements
View.OnClickListener, RepositoryListContainerFragment.Callback {
private static final int REQUEST_SETTINGS = 10000;
private FragmentFactory mFactory;
private SparseArray<Fragment> mFragments;
private DrawerAdapter mDrawerAdapter;
private ImageView mAvatarView;
private String mUserLogin;
private int mSelectedFactoryId;
private boolean mStarted;
private static final String STATE_KEY_FACTORY_ITEM = "factoryItem";
private static final int ITEM_NEWS_FEED = 1;
private static final int ITEM_REPOSITORIES = 2;
private static final int ITEM_ISSUES = 3;
private static final int ITEM_PULLREQUESTS = 4;
private static final int ITEM_GISTS = 5;
private static final int ITEM_TIMELINE = 6;
private static final int ITEM_TRENDING = 7;
private static final int ITEM_BLOG = 8;
private static final int ITEM_SEARCH = 9;
private static final int ITEM_BOOKMARKS = 10;
private static final int ITEM_SETTINGS = 11;
private static final List<DrawerAdapter.Item> DRAWER_ITEMS = Arrays.asList(
new DrawerAdapter.EntryItem(R.string.user_news_feed, 0, ITEM_NEWS_FEED),
new DrawerAdapter.EntryItem(R.string.my_repositories, 0, ITEM_REPOSITORIES),
new DrawerAdapter.EntryItem(R.string.my_issues, 0, ITEM_ISSUES),
new DrawerAdapter.EntryItem(R.string.my_pull_requests, 0, ITEM_PULLREQUESTS),
new DrawerAdapter.EntryItem(R.string.my_gists, 0, ITEM_GISTS),
new DrawerAdapter.DividerItem(),
new DrawerAdapter.EntryItem(R.string.pub_timeline, 0, ITEM_TIMELINE),
new DrawerAdapter.EntryItem(R.string.trend, 0, ITEM_TRENDING),
new DrawerAdapter.EntryItem(R.string.blog, 0, ITEM_BLOG),
new DrawerAdapter.DividerItem(),
new DrawerAdapter.EntryItem(R.string.search, 0, ITEM_SEARCH),
new DrawerAdapter.EntryItem(R.string.bookmarks, 0, ITEM_BOOKMARKS),
new DrawerAdapter.EntryItem(R.string.settings, 0, ITEM_SETTINGS)
);
private LoaderCallbacks<User> mUserCallback = new LoaderCallbacks<User>() {
@Override
public Loader<LoaderResult<User>> onCreateLoader(int id, Bundle args) {
return new UserLoader(HomeActivity.this, mUserLogin);
}
@Override
public void onResultReady(LoaderResult<User> result) {
User user = result.getData();
mAvatarView.setTag(user);
AvatarHandler.assignAvatar(mAvatarView, user);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
mUserLogin = Gh4Application.get().getAuthLogin();
if (savedInstanceState != null) {
mSelectedFactoryId = savedInstanceState.getInt(STATE_KEY_FACTORY_ITEM);
} else {
mSelectedFactoryId = ITEM_NEWS_FEED;
}
mFactory = getFactoryForItem(mSelectedFactoryId, savedInstanceState);
mFragments = new SparseArray<>();
super.onCreate(savedInstanceState);
if (hasErrorView()) {
return;
}
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(mFactory.getTitleResId());
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_KEY_FACTORY_ITEM, mSelectedFactoryId);
mFactory.onSaveInstanceState(outState);
}
@Override
public void onClick(View view) {
User user = (User) view.getTag();
Intent intent = IntentUtils.getUserActivityIntent(this, user);
if (intent != null) {
closeDrawers();
startActivity(intent);
}
}
@Override
protected ListAdapter getLeftNavigationDrawerAdapter() {
mDrawerAdapter = new DrawerAdapter(this, DRAWER_ITEMS);
return mDrawerAdapter;
}
@Override
protected ListAdapter getRightNavigationDrawerAdapter() {
return mFactory.getToolDrawerAdapter();
}
@Override
protected View getLeftDrawerTitle(ViewGroup container) {
View view = getLayoutInflater().inflate(R.layout.drawer_title_home, container, false);
mAvatarView = (ImageView) view.findViewById(R.id.avatar);
mAvatarView.setOnClickListener(this);
getSupportLoaderManager().initLoader(0, null, mUserCallback);
TextView nameView = (TextView) view.findViewById(R.id.user_name);
nameView.setText(mUserLogin);
return view;
}
@Override
protected boolean onDrawerItemSelected(boolean left, int position) {
if (!left) {
return mFactory.onDrawerItemSelected(position);
}
int id = DRAWER_ITEMS.get(position).getId();
FragmentFactory factory = getFactoryForItem(id, null);
if (factory != null) {
switchTo(id, factory);
return true;
}
switch (id) {
case ITEM_SEARCH:
startActivity(new Intent(this, SearchActivity.class));
return true;
case ITEM_BOOKMARKS:
startActivity(new Intent(this, BookmarkListActivity.class));
return true;
case ITEM_SETTINGS:
startActivityForResult(new Intent(this, SettingsActivity.class), REQUEST_SETTINGS);
return true;
}
return super.onDrawerItemSelected(left, position);
}
private FragmentFactory getFactoryForItem(int id, Bundle savedInstanceState) {
switch (id) {
case ITEM_NEWS_FEED:
return new NewsFeedFactory(this, mUserLogin);
case ITEM_REPOSITORIES:
return new RepositoryFactory(this, mUserLogin, savedInstanceState);
case ITEM_ISSUES:
return new IssueListFactory(this, mUserLogin, false);
case ITEM_PULLREQUESTS:
return new IssueListFactory(this, mUserLogin, true);
case ITEM_GISTS:
return new GistFactory(this, mUserLogin);
case ITEM_TIMELINE:
return new TimelineFactory(this);
case ITEM_BLOG:
return new BlogFactory(this);
case ITEM_TRENDING:
return new TrendingFactory(this);
}
return null;
}
@Override
protected int[] getTabTitleResIds() {
return mFactory.getTabTitleResIds();
}
@Override
protected Fragment getFragment(int position) {
Fragment fragment = mFactory.getFragment(position);
mFragments.put(position, fragment);
return fragment;
}
@Override
protected void onStart() {
super.onStart();
if (mDrawerAdapter != null) {
updateDrawerSelectionState();
}
mStarted = true;
mFactory.onStart();
}
@Override
protected void onStop() {
super.onStop();
mStarted = false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (mFactory.onCreateOptionsMenu(menu)) {
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mFactory.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SETTINGS) {
if (data.getBooleanExtra(SettingsActivity.RESULT_EXTRA_THEME_CHANGED, false)
|| data.getBooleanExtra(SettingsActivity.RESULT_EXTRA_AUTH_CHANGED, false)) {
goToToplevelActivity(false);
finish();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
protected Intent navigateUp() {
return getToplevelActivityIntent();
}
@Override
protected boolean canSwipeToRefresh() {
return true;
}
@Override
public void onRefresh() {
for (int i = 0; i < mFragments.size(); i++) {
int position = mFragments.keyAt(i);
mFactory.onRefreshFragment(mFragments.get(position));
}
refreshDone();
}
@Override
public void supportInvalidateOptionsMenu() {
if (mFactory instanceof RepositoryFactory) {
// happens when load is done; we ignore it as we don't want to close the IME in that case
} else {
super.supportInvalidateOptionsMenu();
}
}
@Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else if (!closeDrawers()) {
super.onBackPressed();
}
}
@Override
public void initiateFilter() {
toggleRightSideDrawer();
}
@Override
protected boolean fragmentNeedsRefresh(Fragment object) {
return true;
}
public void doInvalidateOptionsMenu() {
super.supportInvalidateOptionsMenu();
}
public void invalidateFragments() {
super.invalidateFragments();
mFragments.clear();
}
public void toggleToolDrawer() {
toggleRightSideDrawer();
}
public void invalidateTitle() {
getSupportActionBar().setTitle(mFactory.getTitleResId());
}
private void switchTo(int itemId, FragmentFactory factory) {
mFactory = factory;
mSelectedFactoryId = itemId;
updateRightNavigationDrawer();
updateDrawerSelectionState();
super.supportInvalidateOptionsMenu();
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
invalidateTitle();
invalidateTabs();
if (mStarted) {
mFactory.onStart();
}
}
private void updateDrawerSelectionState() {
for (int i = 0; i < mDrawerAdapter.getCount(); i++) {
Object item = mDrawerAdapter.getItem(i);
if (item instanceof DrawerAdapter.EntryItem) {
DrawerAdapter.EntryItem dei = (DrawerAdapter.EntryItem) item;
dei.setSelected(dei.getId() == mSelectedFactoryId);
}
}
mDrawerAdapter.notifyDataSetChanged();
}
}
|
package com.irccloud.android;
import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Log;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
@SuppressLint("UseSparseArrays")
public class EventsDataSource {
public class Event {
int cid;
int bid;
long eid;
String timestamp;
String type;
String msg;
String hostmask;
String from;
String from_mode;
String nick;
String old_nick;
String server;
String diff;
String html;
boolean highlight;
boolean self;
boolean to_chan;
int color;
int bg_color;
JsonObject ops;
long group_eid;
int row_type;
String group_msg;
boolean linkify;
String target_mode;
int reqid;
boolean pending;
}
public class comparator implements Comparator<Event> {
public int compare(Event e1, Event e2) {
long l1 = e1.eid, l2 = e2.eid;
if(l1 == l2)
return 0;
else if(l1 > l2)
return 1;
else return -1;
}
}
private HashMap<Integer,TreeMap<Long, Event>> events;
private static EventsDataSource instance = null;
public long highest_eid = -1;
public static EventsDataSource getInstance() {
if(instance == null)
instance = new EventsDataSource();
return instance;
}
public EventsDataSource() {
events = new HashMap<Integer,TreeMap<Long, Event>>();
}
public void clear() {
synchronized(events) {
events.clear();
highest_eid = -1;
}
}
public void addEvent(Event event) {
synchronized(events) {
if(!events.containsKey(event.bid))
events.put(event.bid, new TreeMap<Long,Event>());
events.get(event.bid).put(event.eid, event);
}
}
public Event addEvent(IRCCloudJSONObject event) {
synchronized(events) {
if(!events.containsKey(event.bid()))
events.put(event.bid(), new TreeMap<Long,Event>());
Event e = getEvent(event.eid(), event.bid());
if(e == null) {
e = new Event();
events.get(event.bid()).put(event.eid(), e);
}
e.cid = event.cid();
e.bid = event.bid();
e.eid = event.eid();
e.type = event.type();
e.msg = event.getString("msg");
e.hostmask = event.getString("hostmask");
e.from = event.getString("from");
e.from_mode = event.getString("from_mode");
if(event.has("newnick"))
e.nick = event.getString("newnick");
else if(event.has("nick"))
e.nick = event.getString("nick");
else
e.nick = null;
e.old_nick = event.getString("oldnick");
e.server = event.getString("server");
e.diff = event.getString("diff");
e.highlight = event.getBoolean("highlight");
e.self = event.getBoolean("self");
e.to_chan = event.getBoolean("to_chan");
e.ops = event.getJsonObject("ops");
e.color = R.color.row_message_label;
e.bg_color = R.color.message_bg;
e.row_type = 0;
e.html = null;
e.group_msg = null;
e.linkify = true;
e.target_mode = null;
e.pending = false;
if(event.has("reqid"))
e.reqid = event.getInt("reqid");
else
e.reqid = -1;
if(e.from != null)
e.from = TextUtils.htmlEncode(e.from);
if(e.msg != null)
e.msg = TextUtils.htmlEncode(e.msg);
if(e.type.equalsIgnoreCase("socket_closed")) {
e.from = "";
e.row_type = MessageViewFragment.ROW_SOCKETCLOSED;
e.color = R.color.timestamp;
if(event.has("pool_lost"))
e.msg = "Connection pool lost";
else if(event.has("server_ping_timeout"))
e.msg = "Server PING timed out";
else if(event.has("reason") && event.getString("reason").length() > 0)
e.msg = "Connection lost: " + event.getString("reason");
else if(event.has("abnormal"))
e.msg = "Connection closed unexpectedly";
else
e.msg = "";
} else if(e.type.equalsIgnoreCase("user_channel_mode")) {
e.target_mode = event.getString("newmode");
} else if(e.type.equalsIgnoreCase("buffer_me_msg")) {
e.nick = e.from;
e.from = "";
} else if(e.type.equalsIgnoreCase("too_fast")) {
e.from = "";
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("no_bots")) {
e.from = "";
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("nickname_in_use")) {
e.from = event.getString("nick");
e.msg = "is already in use";
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("unhandled_line") || e.type.equalsIgnoreCase("unparsed_line")) {
e.from = "";
e.msg = "";
if(event.has("command"))
e.msg = event.getString("command") + " ";
if(event.has("raw"))
e.msg += event.getString("raw");
else
e.msg += event.getString("msg");
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("connecting_cancelled")) {
e.from = "";
e.msg = "Cancelled";
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("msg_services")) {
e.from = "";
e.bg_color = R.color.error;
} else if(e.type.equalsIgnoreCase("connecting_failed")) {
e.row_type = MessageViewFragment.ROW_SOCKETCLOSED;
e.color = R.color.timestamp;
e.from = "";
e.msg = "Failed to connect: " + event.getString("reason");
} else if(e.type.equalsIgnoreCase("quit_server")) {
e.from = "";
e.msg = "⇐ You disconnected";
e.color = R.color.timestamp;
} else if(e.type.equalsIgnoreCase("self_details")) {
e.from = "";
e.msg = "Your hostmask: <b>" + event.getString("usermask") + "</b>";
e.bg_color = R.color.status_bg;
e.linkify = false;
} else if(e.type.equalsIgnoreCase("myinfo")) {
e.from = "";
e.msg = "Host: " + event.getString("server") + "\n";
e.msg += "IRCd: " + event.getString("version") + "\n";
e.msg += "User modes: " + event.getString("user_modes") + "\n";
e.msg += "Channel modes: " + event.getString("channel_modes") + "\n";
e.msg = TextUtils.htmlEncode(e.msg);
e.bg_color = R.color.status_bg;
e.linkify = false;
} else if(e.type.equalsIgnoreCase("wait")) {
e.from = "";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("user_mode")) {
e.from = "";
e.msg = "Your user mode is: <b>+" + event.getString("newmode") + "</b>";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("your_unique_id")) {
e.from = "";
e.msg = "Your unique ID is: <b>" + event.getString("unique_id") + "</b>";
e.bg_color = R.color.status_bg;
} else if(e.type.startsWith("stats")) {
e.from = "";
if(event.has("parts") && event.getString("parts").length() > 0)
e.msg = event.getString("parts") + ": " + e.msg;
e.bg_color = R.color.status_bg;
e.linkify = false;
} else if(e.type.equalsIgnoreCase("endofstats")) {
e.from = "";
e.msg = event.getString("parts") + ": " + e.msg;
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("kill")) {
e.from = "";
e.msg = "You were killed";
if(event.has("from"))
e.msg += " by " + event.getString("from");
if(event.has("killer_hostmask"))
e.msg += " (" + event.getString("killer_hostmask") + ")";
if(event.has("reason"))
e.msg += ": " + TextUtils.htmlEncode(event.getString("reason"));
e.bg_color = R.color.status_bg;
e.linkify = false;
} else if(e.type.equalsIgnoreCase("banned")) {
e.from = "";
e.msg = "You were banned";
if(event.has("server"))
e.msg += " from " + event.getString("server");
if(event.has("reason"))
e.msg += ": " + TextUtils.htmlEncode(event.getString("reason"));
e.bg_color = R.color.status_bg;
e.linkify = false;
} else if(e.type.equalsIgnoreCase("channel_topic")) {
e.from = event.getString("author");
e.msg = "set the topic: " + TextUtils.htmlEncode(event.getString("topic"));
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("channel_mode")) {
e.nick = e.from;
e.from = "";
e.msg = "Channel mode set to: <b>" + event.getString("diff") + "</b>";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("channel_mode_is")) {
e.from = "";
if(event.getString("diff") != null && event.getString("diff").length() > 0)
e.msg = "Channel mode is: <b>" + event.getString("diff") + "</b>";
else
e.msg = "No channel mode";
e.bg_color = R.color.status_bg;
} else if(e.type.equalsIgnoreCase("kicked_channel") || e.type.equalsIgnoreCase("you_kicked_channel")) {
e.from = "";
e.from_mode = null;
e.old_nick = event.getString("nick");
e.nick = event.getString("kicker");
e.hostmask = event.getString("kicker_hostmask");
e.color = R.color.timestamp;
e.linkify = false;
} else if(e.type.equalsIgnoreCase("channel_mode_list_change")) {
boolean unknown = true;
JsonObject ops = event.getJsonObject("ops");
if(ops != null) {
JsonArray add = ops.getAsJsonArray("add");
if(add != null && add.size() > 0) {
JsonObject op = add.get(0).getAsJsonObject();
if(op.get("mode").getAsString().equalsIgnoreCase("b")) {
e.nick = e.from;
e.from = "";
e.msg = "Channel ban set for <b>" + op.get("param").getAsString() + "</b> (+b) by ";
unknown = false;
}
}
JsonArray remove = ops.getAsJsonArray("remove");
if(remove != null && remove.size() > 0) {
JsonObject op = remove.get(0).getAsJsonObject();
if(op.get("mode").getAsString().equalsIgnoreCase("b")) {
e.nick = e.from;
e.from = "";
e.msg = "Channel ban removed for <b>" + op.get("param").getAsString() + "</b> (-b) by ";
unknown = false;
}
}
}
if(unknown) {
e.nick = e.from;
e.from = "";
e.msg = "Channel mode set to: <b>" + event.getString("diff") + "</b> by ";
}
e.bg_color = R.color.status_bg;
e.linkify = false;
} else if(e.type.equalsIgnoreCase("motd_response") || e.type.equalsIgnoreCase("server_motd")) {
JsonArray lines = event.getJsonArray("lines");
e.from = "";
if(lines != null) {
StringBuilder builder = new StringBuilder("<pre>");
if(event.has("start"))
builder.append(event.getString("start") + "<br/>");
for(int i = 0; i < lines.size(); i++) {
builder.append(TextUtils.htmlEncode(lines.get(i).getAsString()).replace(" ", " ") + "<br/>");
}
builder.append("</pre>");
e.msg = builder.toString();
}
e.bg_color = R.color.self;
} else if(e.type.equalsIgnoreCase("notice")) {
e.msg = "<pre>" + e.msg.replace(" ", " ") + "</pre>";
e.bg_color = R.color.notice;
} else if(e.type.toLowerCase().startsWith("hidden_host_set")) {
e.bg_color = R.color.status_bg;
e.linkify = false;
e.from = "";
e.msg = "<b>" + event.getString("hidden_host") + "</b> " + e.msg;
} else if(e.type.toLowerCase().startsWith("server_")) {
e.bg_color = R.color.status_bg;
e.linkify = false;
} else if(e.type.equalsIgnoreCase("inviting_to_channel")) {
e.from = "";
e.msg = "You invited " + event.getString("recipient") + " to join " + event.getString("channel");
e.bg_color = R.color.notice;
} else if(e.type.equalsIgnoreCase("channel_invite")) {
e.msg = "<pre>Invite to join " + event.getString("channel") + "</pre>";
e.old_nick = event.getString("channel");
e.highlight = true;
} else if(e.type.equalsIgnoreCase("callerid")) {
e.from = e.nick;
e.msg = "<pre>" + e.msg + "</pre>";
e.highlight = true;
e.linkify = false;
e.hostmask = event.getString("usermask");
} else if(e.type.equalsIgnoreCase("link_channel")) {
e.from = "";
e.msg = "<pre>You tried to join " + event.getString("invalid_chan") + " but were forwarded to " + event.getString("valid_chan") + "</pre>";
e.bg_color = R.color.error;
}
if(event.has("value")) {
e.msg = event.getString("value") + " " + e.msg;
}
if(e.highlight)
e.bg_color = R.color.highlight;
if(e.self)
e.bg_color = R.color.self;
if(highest_eid < event.eid())
highest_eid = event.eid();
return e;
}
}
public Event getEvent(long eid, int bid) {
synchronized(events) {
if(events.containsKey(bid))
return events.get(bid).get(eid);
}
return null;
}
public void deleteEvent(long eid, int bid) {
synchronized(events) {
if(events.containsKey(bid) && events.get(bid).containsKey(eid))
events.get(bid).remove(eid);
}
}
public void deleteEventsForBuffer(int bid) {
synchronized(events) {
if(events.containsKey(bid))
events.remove(bid);
}
}
public TreeMap<Long,Event> getEventsForBuffer(int bid) {
synchronized(events) {
if(events.containsKey(bid)) {
return events.get(bid);
}
}
return null;
}
public int getUnreadCountForBuffer(int bid, long last_seen_eid, String buffer_type) {
int count = 0;
synchronized(events) {
if(events.containsKey(bid)) {
Iterator<Event> i = events.get(bid).values().iterator();
while(i.hasNext()) {
Event e = i.next();
try {
if(e.eid > last_seen_eid && isImportant(e, buffer_type))
count++;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
return count;
}
public boolean isImportant(Event e, String buffer_type) {
if(e == null) {
Log.w("IRCCloud", "isImportant: NULL event");
return false;
}
if(e.self)
return false;
String type = e.type;
if(type == null) {
Log.w("IRCCloud", "isImportant: NULL type");
return false;
}
if (type.equals("notice") && buffer_type != null && buffer_type.equals("console")) {
if (e.server != null || e.to_chan == true) {
return false;
}
}
return (type.equals("buffer_msg") ||
type.equals("buffer_me_msg") ||
type.equals("notice") ||
type.equals("channel_invite") ||
type.equals("callerid") ||
type.equals("wallops"));
}
public synchronized int getHighlightCountForBuffer(int bid, long last_seen_eid, String buffer_type) {
int count = 0;
synchronized(events) {
if(events.containsKey(bid)) {
Iterator<Event> i = events.get(bid).values().iterator();
while(i.hasNext()) {
Event e = i.next();
try {
if(e.eid > last_seen_eid && isImportant(e, buffer_type) && (e.highlight || buffer_type.equalsIgnoreCase("conversation")))
count++;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
return count;
}
}
|
package com.jetbrains.ther.xdebugger;
import com.intellij.icons.AllIcons;
import com.intellij.xdebugger.frame.*;
import com.intellij.xdebugger.frame.presentation.XStringValuePresentation;
import com.intellij.xdebugger.frame.presentation.XValuePresentation;
import com.jetbrains.ther.debugger.data.TheRDebugConstants;
import com.jetbrains.ther.debugger.data.TheRVar;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
// TODO [xdbg][test]
class TheRXVar extends XNamedValue {
@NotNull
private final TheRVar myVar;
public TheRXVar(@NotNull final TheRVar var) {
super(var.getName());
myVar = var;
}
@Override
public void computePresentation(@NotNull final XValueNode node, @NotNull final XValuePlace place) {
if (isFunction()) {
node.setPresentation(
AllIcons.Debugger.Value,
new FunctionXValuePresentation(),
true
);
}
else {
node.setPresentation(
AllIcons.Debugger.Value,
myVar.getType(),
myVar.getValue(),
false
);
}
}
@Override
public void computeChildren(@NotNull final XCompositeNode node) {
if (isFunction()) {
node.addChildren(
XValueChildrenList.singleton(new FunctionXNamedValue(myVar)),
true
);
}
}
private boolean isFunction() {
return myVar.getType().equals(TheRDebugConstants.FUNCTION_TYPE);
}
private static class FunctionXValuePresentation extends XValuePresentation {
@Nullable
@Override
public String getType() {
return TheRDebugConstants.FUNCTION_TYPE;
}
@Override
public void renderValue(@NotNull final XValueTextRenderer renderer) {
}
}
private static class FunctionXNamedValue extends XNamedValue {
@NotNull
private final TheRVar myVar;
public FunctionXNamedValue(@NotNull final TheRVar var) {
super(var.getName());
myVar = var;
}
@Override
public void computePresentation(@NotNull final XValueNode node, @NotNull final XValuePlace place) {
node.setPresentation(
AllIcons.Debugger.Value,
new XStringValuePresentation(myVar.getValue()),
false
);
}
}
}
|
package com.jme3.monkeyzone;
import com.jme3.app.Application;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.bullet.control.CharacterControl;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.monkeyzone.messages.ActionMessage;
import com.jme3.monkeyzone.messages.StartGameMessage;
import com.jme3.network.physicssync.PhysicsSyncManager;
import com.jme3.scene.Spatial;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Manages the actual gameplay on the server side
* @author normenhansen
*/
public class ServerGameManager extends AbstractAppState {
PhysicsSyncManager server;
WorldManager worldManager;
private boolean running;
String mapName;
String[] modelNames;
@Override
public void initialize(AppStateManager stateManager, Application app) {
super.initialize(stateManager, app);
this.worldManager = app.getStateManager().getState(WorldManager.class);
this.server = worldManager.getSyncManager();
}
/**
* starts the game
*/
public synchronized boolean startGame(String map) {
if (running) {
return false;
}
running = true;
mapName = map;
//TODO: parse client side string, create preload model list automatically
modelNames = new String[]{"Models/HoverTank/HoverTank.j3o", "Models/Sinbad/Sinbad.j3o", "Models/Ferrari/Car.j3o"};//, "Models/Buggy/Buggy.j3o"
server.getServer().broadcast(new StartGameMessage(mapName, modelNames));
worldManager.loadLevel(mapName);
worldManager.createNavMesh();
worldManager.preloadModels(modelNames);
worldManager.attachLevel();
//create character entities for all players, then enter the entites
int i = 0;
for (Iterator<PlayerData> it = PlayerData.getPlayers().iterator(); it.hasNext();) {
PlayerData playerData = it.next();
long entityId = worldManager.addNewEntity("Models/Sinbad/Sinbad.j3o", new Vector3f(i * 3, 3, 0), new Quaternion());
playerData.setData("character_entity_id", entityId);
worldManager.enterEntity(playerData.getId(), entityId);
//create new ai player for user
long playearId = worldManager.addNewPlayer(PlayerData.getIntData(playerData.getId(), "group_id"), "AI", 0);
long entitayId = worldManager.addNewEntity("Models/Sinbad/Sinbad.j3o", new Vector3f(i * 3, 3, 3), new Quaternion());
PlayerData.setData(playearId, "character_entity_id", entitayId);
worldManager.enterEntity(playearId, entitayId);
//create a vehicle
worldManager.addNewEntity("Models/Ferrari/Car.j3o", new Vector3f(i * 3, 3, -3), new Quaternion());
i++;
}
return true;
}
/**
* stops the game
*/
public synchronized boolean stopGame() {
if (!running) {
return false;
}
mapName = "null";
modelNames = new String[]{};
server.getServer().broadcast(new StartGameMessage(mapName, modelNames));
worldManager.closeLevel();
running = false;
return true;
}
/**
* checks if the game is running
* @return
*/
public synchronized boolean isRunning() {
return running;
}
/**
* called when an entity (human or AI) performs an action
* @param entityId
* @param action
* @param pressed
*/
public void performAction(long entityId, int action, boolean pressed) {
Spatial myEntity = worldManager.getEntity(entityId);
if (myEntity == null) {
Logger.getLogger(ServerGameManager.class.getName()).log(Level.WARNING, "Cannot find entity performing action!");
return;
}
long player_id = (Long) myEntity.getUserData("player_id");
if (player_id == -1) {
Logger.getLogger(ServerGameManager.class.getName()).log(Level.WARNING, "Cannot find player id for entity performing action!");
return;
}
//enter entity
if (action == ActionMessage.ENTER_ACTION && pressed) {
performEnterEntity(player_id, myEntity);
} else if (action == ActionMessage.SHOOT_ACTION && pressed) {
performShoot(myEntity);
}
}
/**
* handle player performing "enter entity" action
* @param player_id
* @param myEntity
*/
private void performEnterEntity(long player_id, Spatial myEntity) {
long characterId = PlayerData.getLongData(player_id, "character_entity_id");
long curEntityId = (Long) myEntity.getUserData("entity_id");
Spatial entity = worldManager.doRayTest(myEntity, 4, null);
if (entity != null && (Long) entity.getUserData("player_id") == -1l) {
if (curEntityId == characterId) {
worldManager.disableEntity(characterId);
worldManager.enterEntity(player_id, (Long) entity.getUserData("entity_id"));
} else {
worldManager.enterEntity(player_id, characterId);
worldManager.enableEntity(characterId, myEntity.getWorldTranslation().add(Vector3f.UNIT_Y), myEntity.getWorldRotation());
}
} else {
if (curEntityId != characterId) {
worldManager.enterEntity(player_id, characterId);
worldManager.enableEntity(characterId, myEntity.getWorldTranslation().add(Vector3f.UNIT_Y), myEntity.getWorldRotation());
}
}
}
/**
* handle entity shooting
* @param myEntity
*/
private void performShoot(Spatial myEntity) {
CharacterControl control = myEntity.getControl(CharacterControl.class);
if (control == null) {
Logger.getLogger(ServerGameManager.class.getName()).log(Level.WARNING, "Cannot shoot when not character!");
return;
}
worldManager.playWorldEffect("Effects/GunShotA.j3o", myEntity.getWorldTranslation(), 0.1f);
Vector3f hitLocation = new Vector3f();
Spatial hitEntity = worldManager.doRayTest(myEntity, 10, hitLocation);
if (hitEntity != null) {
long targetId = (Long) hitEntity.getUserData("entity_id");
Float hp = (Float) hitEntity.getUserData("HitPoints");
if (hp != null) {
hp -= 10;
worldManager.playWorldEffect("Effects/ExplosionA.j3o", hitLocation, 2.0f);
worldManager.setEntityUserData(targetId, "HitPoints", hp);
if (hp <= 0) {
worldManager.removeEntity(targetId);
worldManager.playWorldEffect("Effects/ExplosionB.j3o", hitEntity.getWorldTranslation(), 2.0f);
}
}
}
}
}
|
package com.rwoar.pfacalculator;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.rwoar.pfacalculator.widget.NumberPicker;
public class PFACalculator extends ListActivity {
private final int RUN_DIALOG_ID = 0;
private final int GENDER_DIALOG_ID = 1;
private final int SITUP_DIALOG_ID = 2;
private final int PUSHUP_DIALOG_ID = 3;
private final int AGE_DIALOG_ID = 4;
private final int WAIST_DIALOG_ID = 5;
private final int OVERALL_SCORE_DIALOG_ID = 6;
private final int MINIMUM_DIALOG_ID = 7;
private final int MAXIMUM_DIALOG_ID = 8;
private final int DEFAULT_AGE = 20;
private final int DEFAULT_PUSHUP = 45;
private final int DEFAULT_SITUP = 50;
private final int DEFAULT_WAIST_INCHES = 34;
private final int DEFAULT_WAIST_CENTIMETERS = 0;
private final int FOR_MAIN_LIST = 0;
private final int FOR_MINIMUM = 1;
private final int FOR_MAXIMUM = 2;
private CalculatorVO calculatorVO = null;
static ArrayList<HashMap<String,String>> optionsList;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pfa_list_view);
if (calculatorVO == null){
if (savedInstanceState != null && savedInstanceState.containsKey("calculatorVO"))
calculatorVO = (CalculatorVO) savedInstanceState.getSerializable("calculatorVO");
else
calculatorVO = new CalculatorVO();
}
ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
ViewGroup footer = (ViewGroup)inflater.inflate(R.layout.pfa_footer, lv, false);
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.pfa_header_ads, lv, false);
lv.addFooterView(footer, null, false);
lv.addHeaderView(header, null, false);
updateList();
}
protected void onSaveInstanceState(Bundle outState){
outState.putSerializable("calculatorVO", calculatorVO);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case RUN_DIALOG_ID:
return runDialog("Enter Run Time");
case GENDER_DIALOG_ID:
return genderDialog();
case SITUP_DIALOG_ID:
return numberDialog("Amount of Sit-ups", SITUP_DIALOG_ID);
case PUSHUP_DIALOG_ID:
return numberDialog("Amount of Push-ups", PUSHUP_DIALOG_ID);
case WAIST_DIALOG_ID:
return waistDialog("Waist Measurement");
case AGE_DIALOG_ID:
return ageGroupDialog(FOR_MAIN_LIST);
case OVERALL_SCORE_DIALOG_ID:
return overallScoreDialog();
case MINIMUM_DIALOG_ID:
return ageGroupDialog(FOR_MINIMUM);
case MAXIMUM_DIALOG_ID:
return ageGroupDialog(FOR_MAXIMUM);
}
return null;
}
protected void onPrepareDialog(int id, Dialog dialog){
switch (id){
case OVERALL_SCORE_DIALOG_ID:
ScoreCalculator sc = new ScoreCalculator(this, calculatorVO);
TextView situps = (TextView) dialog.findViewById(R.id.situp_performance_value);
boolean bool_situp = sc.passedSitups();
if (bool_situp == true){
situps.setText("Passed");
situps.setTextColor(Color.GREEN);
}
else {
situps.setText("Failed");
situps.setTextColor(Color.RED);
}
TextView pushup = (TextView) dialog.findViewById(R.id.pushup_performance_value);
boolean bool_pushup = sc.passedPushups();
if (bool_pushup == true){
pushup.setText("Passed");
pushup.setTextColor(Color.GREEN);
}
else {
pushup.setText("Failed");
pushup.setTextColor(Color.RED);
}
TextView run = (TextView) dialog.findViewById(R.id.run_performance_value);
boolean bool_run = sc.passedRun();
if (bool_run == true){
run.setText("Passed");
run.setTextColor(Color.GREEN);
}
else {
run.setText("Failed");
run.setTextColor(Color.RED);
}
TextView waist = (TextView) dialog.findViewById(R.id.waist_performance_value);
boolean bool_waist = sc.passedWaist();
if (bool_waist == true){
waist.setText("Passed");
waist.setTextColor(Color.GREEN);
}
else {
waist.setText("Failed");
waist.setTextColor(Color.RED);
}
TextView performance = (TextView) dialog.findViewById(R.id.overall_performance_value);
boolean bool_perform = sc.passedOverallTest();
if (bool_perform == true){
performance.setText("Passed");
performance.setTextColor(Color.GREEN);
}
else {
performance.setText("Failed");
performance.setTextColor(Color.RED);
}
TextView total_score_value = (TextView) dialog.findViewById(R.id.total_score_value);
Double total = sc.getTotalScore();
total_score_value.setText(Double.toString(total));
break;
}
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// This is 'position-1' because of the header
HashMap<?, ?> choice = (HashMap<?, ?>) this.getListAdapter().getItem(position-1);
if (choice.get("option").equals("Run Time"))
showDialog(RUN_DIALOG_ID);
else if (choice.get("option").equals("Gender"))
showDialog(GENDER_DIALOG_ID);
else if (choice.get("option").equals("Sit-Ups"))
showDialog(SITUP_DIALOG_ID);
else if (choice.get("option").equals("Age Group"))
showDialog(AGE_DIALOG_ID);
else if (choice.get("option").equals("Push-Ups"))
showDialog(PUSHUP_DIALOG_ID);
else if (choice.get("option").equals("Waist Measurement"))
showDialog(WAIST_DIALOG_ID);
}
public void buttonClickHandler(View v)
{
switch(v.getId()){
case R.id.calculateButton:
if (calculatorVO.isComplete() == false){
Toast.makeText(getApplicationContext(), R.string.incompleteCalculatorVO, Toast.LENGTH_SHORT).show();
break;
}
else
showDialog(OVERALL_SCORE_DIALOG_ID);
break;
case R.id.clearButton:
calculatorVO.clear();
updateList();
break;
default:
// Do nothing!
return;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.pfa_calculator, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.minimumsMenuButton:
showDialog(MINIMUM_DIALOG_ID);
return true;
case R.id.maximumsMenuButton:
// Do maximums stuff
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void updateList() {
optionsList = new ArrayList<HashMap<String,String>>();
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("option","Gender");
temp.put("selection", calculatorVO.getGenderString());
temp.put("description", "Male or Female");
optionsList.add(temp);
HashMap<String,String> temp1 = new HashMap<String,String>();
temp1.put("option","Push-Ups");
temp1.put("selection", calculatorVO.getPushupsString());
temp1.put("description", "Amount Per Minute");
optionsList.add(temp1);
HashMap<String,String> temp2 = new HashMap<String,String>();
temp2.put("option","Sit-Ups");
temp2.put("selection", calculatorVO.getSitupsString());
temp2.put("description", "Amount Per Minute");
optionsList.add(temp2);
HashMap<String,String> temp3 = new HashMap<String,String>();
temp3.put("option","Run Time");
temp3.put("selection", calculatorVO.getRunString());
temp3.put("description", "1.5 Mile Run");
optionsList.add(temp3);
HashMap<String,String> temp4 = new HashMap<String,String>();
temp4.put("option","Age Group");
temp4.put("selection", calculatorVO.getAgeGroupString());
temp4.put("description", "Age Category");
optionsList.add(1, temp4);
HashMap<String,String> temp5 = new HashMap<String,String>();
temp5.put("option","Waist Measurement");
temp5.put("selection", calculatorVO.getWaistString());
temp5.put("description", "Abdominal Circumference");
optionsList.add(2, temp5);
SimpleAdapter adapter = new SimpleAdapter(
this,
optionsList,
R.layout.pfa_row_view,
new String[] {"option","selection", "description"},
new int[] {R.id.pfa_rowtext1,R.id.pfa_rowtext2,R.id.pfa_rowtext3}
);
setListAdapter(adapter);
}
private AlertDialog genderDialog(){
final CharSequence[] items = {"Male", "Female"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose your gender");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item+1 == CalculatorVO.MALE)
calculatorVO.setGender(CalculatorVO.MALE);
else if (item+1 == CalculatorVO.FEMALE)
calculatorVO.setGender(CalculatorVO.FEMALE);
updateList();
}
});
AlertDialog alert = builder.create();
return alert;
}
private AlertDialog ageGroupDialog(int option){
String[] array = (String[])calculatorVO.ageStringsMap.values().toArray(new String[calculatorVO.ageStringsMap.values().size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Age Group");
if (option == FOR_MAIN_LIST){
builder.setItems(array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
calculatorVO.setAgeGroup(item);
updateList();
}
});
} else {
builder.setItems(array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
minimumsMaximumsDialog(item).show();
}
});
}
AlertDialog alert = builder.create();
return alert;
}
private AlertDialog numberDialog(String title, final int dialogID){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.number_dialog,
(ViewGroup) findViewById(R.id.number_dialog_layout_root));
alert.setTitle(title);
final NumberPicker np = (NumberPicker) layout.findViewById(R.id.number_dialog_numpicker);
// Set default values
switch(dialogID){
case SITUP_DIALOG_ID:
np.setCurrent(DEFAULT_SITUP);
break;
case PUSHUP_DIALOG_ID:
np.setCurrent(DEFAULT_PUSHUP);
break;
case AGE_DIALOG_ID:
np.setCurrent(DEFAULT_AGE);
break;
}
alert.setView(layout);
alert.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
int newNumber = np.getCurrent();
switch(dialogID){
case SITUP_DIALOG_ID:
calculatorVO.setSitups(newNumber);
break;
case PUSHUP_DIALOG_ID:
calculatorVO.setPushups(newNumber);
break;
case WAIST_DIALOG_ID:
calculatorVO.setWaist(newNumber);
break;
}
PFACalculator.this.updateList();
return;
}
});
alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
AlertDialog ad = alert.create();
return ad;
}
private AlertDialog waistDialog(String title){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.waist_dialog,
(ViewGroup) findViewById(R.id.waist_dialog_layout_root));
alert.setTitle(title);
final NumberPicker inches = (NumberPicker) layout.findViewById(R.id.waist_dialog_inches);
inches.setCurrent(DEFAULT_WAIST_INCHES);
final NumberPicker centimeters = (NumberPicker) layout.findViewById(R.id.waist_dialog_centimeters);
centimeters.setCurrent(DEFAULT_WAIST_CENTIMETERS);
String[] vals = {"0","5"};
centimeters.setRange(0, 1, vals);
alert.setView(layout);
alert.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
int inchesNum = inches.getCurrent();
int centimetersNum = centimeters.getCurrent();
calculatorVO.setWaist(Double.parseDouble(inchesNum+"."+ ((centimetersNum == 0) ? 0 : 5)));
PFACalculator.this.updateList();
return;
}
});
alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
AlertDialog ad = alert.create();
return ad;
}
private AlertDialog runDialog(String title){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.run_dialog,
(ViewGroup) findViewById(R.id.run_dialog_layout_root));
alert.setTitle(title);
final NumberPicker minutes = (NumberPicker) layout.findViewById(R.id.run_dialog_minute);
minutes.setCurrent(DEFAULT_WAIST_INCHES);
minutes.setRange(0, 59);
minutes.setCurrent(10);
final NumberPicker seconds = (NumberPicker) layout.findViewById(R.id.run_dialog_second);
seconds.setCurrent(DEFAULT_WAIST_CENTIMETERS);
ArrayList<String> vals = new ArrayList<String>();
for (int i = 0; i<=59;i++){
vals.add(String.format("%02d", i));
}
seconds.setRange(0, 59, vals.toArray(new String[60]));
seconds.setCurrent(30);
alert.setView(layout);
alert.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
int minutesNum = minutes.getCurrent();
int secondsNum = seconds.getCurrent();
calculatorVO.setRun(minutesNum, secondsNum);
PFACalculator.this.updateList();
return;
}
});
alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
AlertDialog ad = alert.create();
return ad;
}
private AlertDialog overallScoreDialog(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.overall_score_dialog,
(ViewGroup) findViewById(R.id.overall_score_dialog_layout_root));
alert.setTitle("PFA Results");
alert.setView(layout);
alert.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
return;
}
});
AlertDialog ad = alert.create();
return ad;
}
private AlertDialog minimumsMaximumsDialog(int option){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.minimum_maximum_dialog,
(ViewGroup) findViewById(R.id.minimum_maximum_dialog_layout_roots));
alert.setTitle(option == FOR_MAXIMUM ? "Maximums" : "Minimums");
alert.setView(layout);
alert.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
return;
}
});
AlertDialog ad = alert.create();
return ad;
}
}
|
package com.startingblocktech.tcases;
import com.startingblocktech.tcases.util.ToString;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeSet;
/**
* Represents a test case for a system function, defining a set of input variable bindings.
*
* @version $Revision$, $Date$
*/
public class TestCase implements Comparable<TestCase>
{
/**
* Defines the type of a {@link TestCase}
*
* @version $Revision$, $Date$
*/
public enum Type
{
/**
* Valid input, expected to produce a valid response.
*/
SUCCESS,
/**
* Invalid input, expected to produce an error response.
*/
FAILURE;
}
/**
* Creates a new TestCase object.
*/
public TestCase( int id)
{
setId( id);
}
/**
* Changes the test case id.
*/
protected void setId( int id)
{
id_ = id;
}
/**
* Returns the test case id.
*/
public int getId()
{
return id_;
}
/**
* Returns the type of this test case.
*/
public Type getType()
{
return
getInvalidValue() != null
? Type.FAILURE
: Type.SUCCESS;
}
/**
* Adds a new variable binding.
*/
public TestCase addVarBinding( VarBinding varBinding)
{
assert varBinding != null;
assert varBinding.getVar() != null;
String varName = varBinding.getVar();
if( varBindings_.containsKey( varName))
{
throw new IllegalStateException( "Binding for " + varName + " already defined for testCase=" + getId());
}
varBindings_.put( varName, varBinding);
return this;
}
/**
* Removes the binding for the given variable.
*/
public TestCase removeVarBinding( String name)
{
varBindings_.remove( name);
return this;
}
/**
* Returns the binding for the given variable.
*/
public VarBinding getVarBinding( String name)
{
return varBindings_.get( name);
}
/**
* Returns the variable that is bound to an invalid value.
*/
public VarBinding getInvalidValue()
{
VarBinding invalidBinding;
Iterator<VarBinding> bindings;
for( invalidBinding = null,
bindings = varBindings_.values().iterator();
bindings.hasNext()
&& (invalidBinding = bindings.next()).isValueValid();
invalidBinding = null);
return invalidBinding;
}
/**
* Returns the variable bindings for this function.
*/
public Iterator<VarBinding> getVarBindings()
{
return varBindings_.values().iterator();
}
/**
* Returns the set of {@link IVarDef#getType variable type} identifiers for this test case.
*/
public String[] getVarTypes()
{
TreeSet<String> typeSet = new TreeSet<String>();
for( Iterator<VarBinding> vars = getVarBindings(); vars.hasNext(); )
{
typeSet.add( vars.next().getType());
}
String[] types = new String[ typeSet.size()];
typeSet.toArray( types);
return types;
}
public String toString()
{
return
ToString.getBuilder( this)
.append( getId())
.append( getType())
.toString();
}
public int compareTo( TestCase other)
{
return getId() - other.getId();
}
public int hashCode()
{
return id_ ^ varBindings_.hashCode();
}
public boolean equals( Object object)
{
TestCase other =
object != null && object.getClass().equals( getClass())
? (TestCase) object
: null;
return
other != null
&& id_ == other.id_
&& varBindings_.equals( other.varBindings_);
}
private int id_;
private Map<String,VarBinding> varBindings_ = new HashMap<String,VarBinding>();
}
|
package mil.nga.giat.mage;
import java.util.Locale;
import mil.nga.giat.mage.preferences.PublicPreferencesActivity;
import mil.nga.giat.mage.sdk.location.LocationService;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* FIXME: Currently a mock of what a landing page might look like. Could be
* replaced entirely if need be. Menu options do exist.
*
* @author wiedemannse
*
*/
public class LandingActivity extends FragmentActivity implements ActionBar.TabListener {
private static final int RESULT_PUBLIC_PREFERENCES = 1;
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
protected LocationService locationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
////////////// FIXME: TESTING //////////////
// Start the location services!
// if (locationService == null) {
// locationService = new LocationService(getApplicationContext());
// // TODO : is app configured to report location?!?
// if (!locationService.isPolling()) {
// locationService.start();
// UserDatabase userDatabase = new UserDatabase(getApplicationContext());
// userDatabase.addUser("CoolBeans");
//ObservationDatabase obsDatabase = new ObservationDatabase(getApplicationContext());
//obsDatabase.onUpgrade(obsDatabase.getWritableDatabase(),1,1);
//obsDatabase.onCreate(obsDatabase.getWritableDatabase());
try {
/*
DBHelper helper = new DBHelper(getApplicationContext());
Dao<Observation, ?> observationDao = helper.getObservationDao();
Dao<State, ?> stateDao = helper.getStateDao();
Dao<Geometry, ?> geometryDao = helper.getGeometryDao();
Dao<GeometryType, ?> geometryTypeDao = helper.getGeometryTypeDao();
Dao<Property, ?> propertyDao = helper.getPropertyDao();
Dao<Attachment, ?> attachmentDao = helper.getAttachmentDao();
State state = new State("active");
stateDao.create(state);
GeometryType geometryType = new GeometryType("POINT");
geometryTypeDao.create(geometryType);
Geometry geometry = new Geometry("[33.33,44.44]", geometryType);
geometryDao.create(geometry);
Property prop1 = new Property("HOTDOG_DATE",String.valueOf(new Date().getTime()));
Property prop2 = new Property("HAMBUR_DATE",String.valueOf(new Date().getTime()));
Collection<Property> properties = new ArrayList<Property>();
properties.add(prop1);
properties.add(prop2);
Attachment attachment1 = new Attachment("png", 12345L, "test.png", "/a/b/c", "d/e/f");
Attachment attachment2 = new Attachment("jpg", 12345L, "fame.png", "/g/h/i", "j/k/l");
Collection<Attachment> attachments = new ArrayList<Attachment>();
attachments.add(attachment1);
attachments.add(attachment2);
Observation obs = new Observation("123LMNOP",state,geometry,properties,attachments);
Observation o = observationDao.createIfNotExists(obs);
prop1.setObservation(o);
prop2.setObservation(o);
propertyDao.create(prop1);
propertyDao.create(prop2);
attachment1.setObservation(o);
attachment2.setObservation(o);
attachmentDao.create(attachment1);
attachmentDao.create(attachment2);
List<Observation> observations = observationDao.queryForAll();
for(Observation observation : observations) {
stateDao.refresh(observation.getState());
geometryDao.refresh(observation.getGeometry());
geometryTypeDao.refresh(observation.getGeometry().getGeometryType());
System.out.println("Observation: " + observation.getPk_id() + " " + observation.getRemote_id());
System.out.println(" State: " + observation.getState().getState());
System.out.println(" Geometry: " + observation.getGeometry().getCoordinates());
System.out.println(" GeometryType: " + observation.getGeometry().getGeometryType().getType());
System.out.println(" Properties: " + observation.getProperties().toArray().length);
for(Property p : observation.getProperties()) {
System.out.println(" " + p.getKey() + "," + p.getValue());
}
System.out.println(" Attachments: " + observation.getAttachments().toArray().length);
for(Attachment a : observation.getAttachments()) {
System.out.println(" " + a.getName() + "," + a.getSize() + "," + a.getContent_type() + "," +
a.getLocal_path() + "," + a.getRemote_path());
}
}
*/
}
catch(Exception e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
locationService.stop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.landing, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(this, PublicPreferencesActivity.class);
startActivityForResult(i, RESULT_PUBLIC_PREFERENCES);
break;
case R.id.menu_logout:
// TODO : wipe user certs
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_PUBLIC_PREFERENCES:
System.out.println(RESULT_PUBLIC_PREFERENCES);
break;
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_map).toUpperCase(l);
case 1:
return getString(R.string.title_newsfeed).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
// LocationService locationService = new
// LocationService(container.getContext());
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText("Viewing " + Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
|
package navigators.smart.tom;
//import br.ufsc.das.communication.SimpleCommunicationSystem;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.concurrent.Semaphore;
import navigators.smart.reconfiguration.ReconfigurationManager;
import navigators.smart.reconfiguration.ReconfigureReply;
import navigators.smart.reconfiguration.View;
import navigators.smart.tom.core.messages.TOMMessage;
import navigators.smart.tom.util.Extractor;
import navigators.smart.tom.util.Logger;
import navigators.smart.tom.util.TOMUtil;
/**
* This class implements a TOMSender and represents a proxy to be used on the
* client side of the replicated system.
* It sends a request to the replicas, receives the reply, and delivers it to
* the application.
*/
public class ServiceProxy extends TOMSender {
//
// Semaphores used to render this object thread-safe
// TODO: o mutex nao poderia ser antes um reentrantlock, em vez de um semaforo?
private Semaphore mutex = new Semaphore(1);
private Semaphore mutexToSend = new Semaphore(1);
//
private Semaphore sm = new Semaphore(0);
private int reqId = -1; // request id
private int replyQuorum = 0; // size of the reply quorum
private TOMMessage replies[] = null; // Replies from replicas are stored here
private int receivedReplies = 0; // Number of received replies
private TOMMessage response = null; // Reply delivered to the application
private LinkedList<TOMMessage> aheadOfTimeReplies = new LinkedList<TOMMessage>();
private Comparator comparator;
private Extractor extractor;
/**
* Constructor
*
* @see bellow
*/
public ServiceProxy(int processId) {
this(processId, null, null, null);
}
/**
* Constructor
*
* @see bellow
*/
public ServiceProxy(int processId, String configHome) {
this(processId, configHome, null, null);
}
/**
* Constructor
*
* @param id Process id for this client (should be different from replicas)
* @param configHome Configuration directory for BFT-SMART
* @param replyComparator used for comparing replies from different servers
* to extract one returned by f+1
* @param replyExtractor used for extracting the response from the matching
* quorum of replies
*/
public ServiceProxy(int processId, String configHome,
Comparator replyComparator, Extractor replyExtractor) {
if (configHome == null) {
init(processId);
} else {
init(processId, configHome);
}
replies = new TOMMessage[getViewManager().getCurrentViewN()];
comparator = (replyComparator != null)? replyComparator : new Comparator<byte[]>() {
@Override
public int compare(byte[] o1, byte[] o2) {
return Arrays.equals(o1, o2) ? 0 : -1;
}
};
extractor = (replyExtractor != null)? replyExtractor : new Extractor() {
@Override
public TOMMessage extractResponse(TOMMessage[] replies, int sameContent, int lastReceived) {
return replies[lastReceived];
}
};
}
/**
* This method sends a request to the replicas, and returns the related reply. This method is
* thread-safe.
*
* @param request Request to be sent
* @return The reply from the replicas related to request
*/
public byte[] invoke(byte[] request) {
return invoke(request, ReconfigurationManager.TOM_NORMAL_REQUEST, false);
}
public byte[] invoke(byte[] request, boolean readOnly) {
return invoke(request, ReconfigurationManager.TOM_NORMAL_REQUEST, readOnly);
}
/**
* This method sends a request to the replicas, and returns the related reply.
* This method is thread-safe.
*
* @param request Request to be sent
* @param reqType TOM_NORMAL_REQUESTS for service requests, and other for
* reconfig requests.
* @param readOnly it is a read only request (will not be ordered)
* @return The reply from the replicas related to request
*/
public byte[] invoke(byte[] request, int reqType, boolean readOnly) {
// Ahead lies a critical section.
// This ensures the thread-safety by means of a semaphore
try {
this.mutexToSend.acquire();
} catch (Exception e) {}
// Clean all statefull data to prepare for receiving next replies
Arrays.fill(replies, null);
receivedReplies = 0;
response = null;
//if n=3f+1, read-only requests wait for 2f+1 matching replies while normal
//requests wait for only f+1
replyQuorum = readOnly?
((int) Math.ceil((getViewManager().getCurrentViewN() + getViewManager().getCurrentViewF()) / 2) + 1):
(getViewManager().getCurrentViewF() + 1);
Logger.println("Sending request (readOnly = "+readOnly+")");
Logger.println("Expected number of matching replies: "+replyQuorum);
// Send the request to the replicas, and get its ID
doTOMulticast(request, reqType, readOnly);
reqId = getLastSequenceNumber();
// This instruction blocks the thread, until a response is obtained.
// The thread will be unblocked when the method replyReceived is invoked
// by the client side communication system
try {
this.sm.acquire();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
Logger.println("Response extracted = "+response);
if (response == null) {
//the response can be null if n-f replies are received but there isn't
//a replyQuorum of matching replies
Logger.println("Received n-f replies and no response could be extracted.");
mutexToSend.release();
if(readOnly) {
//invoke the operation again, whitout the read-only flag
Logger.println("
Logger.println("
Logger.println("
return invoke(request, reqType, false);
} else {
throw new RuntimeException("Received n-f replies without f+1 of them matching.");
}
} else {
//normal operation
//
byte[] ret = null;
if (reqType == ReconfigurationManager.TOM_NORMAL_REQUEST) {
//Reply to a normal request!
if (response.getViewID() == getViewManager().getCurrentViewId()) {
ret = response.getContent(); // return the response
mutexToSend.release();
return ret;
} else {//if(response.getViewID() > getViewManager().getCurrentViewId())
//updated view received
reconfigureTo((View) TOMUtil.getObject(response.getContent()));
mutexToSend.release();
return invoke(request, reqType, readOnly);
}
} else {
//Reply to a reconfigure request!
Logger.println("Reconfiguration request' reply received!");
if (response.getViewID() > getViewManager().getCurrentViewId()) {
Object r = TOMUtil.getObject(response.getContent());
if (r instanceof View) {
reconfigureTo((View) r);
mutexToSend.release();
return invoke(request, reqType, readOnly);
} else {
reconfigureTo(((ReconfigureReply) r).getView());
ret = response.getContent(); // return the response
mutexToSend.release();
return ret;
}
} else {
ret = response.getContent(); // return the response
mutexToSend.release();
return ret;
}
}
}
//
}
//
private void reconfigureTo(View v) {
Logger.println("Installing a most up-to-date view");
getViewManager().reconfigureTo(v);
replies = new TOMMessage[getViewManager().getCurrentViewN()];
getCommunicationSystem().updateConnections();
}
//
/**
* This is the method invoked by the client side comunication system.
*
* @param reply The reply delivered by the client side comunication system
*/
@Override
public void replyReceived(TOMMessage reply) {
Logger.println("reply received: sender="+reply.getSender()+" reqId="+reply.getSequence());
// Ahead lies a critical section.
// This ensures the thread-safety by means of a semaphore
try {
this.mutex.acquire();
} catch (Exception e) {
e.printStackTrace();
}
//
int pos = getViewManager().getCurrentViewPos(reply.getSender());
if (pos < 0) { //ignore messages that don't come from replicas
this.mutex.release();
return;
}
//
if (reply.getSequence() > reqId) { // Is this a reply for the last request sent?
Logger.println("Storing reply from "+reply.getSender()+" with reqId:"+reply.getSequence());
aheadOfTimeReplies.add(reply);
} else if(reply.getSequence() == reqId) {
Logger.println("Receiving reply from "+reply.getSender()+" with reqId:"+reply.getSequence()+". Putting on pos="+pos);
if(receivedReplies == 0) {
//If this is the first reply received for reqId, lets look at ahead
//of time messages to process possible messages for this reqId that
//were already received
for(ListIterator<TOMMessage> li = aheadOfTimeReplies.listIterator(); li.hasNext(); ) {
TOMMessage rr = li.next();
if(rr.getSequence() == reqId) {
Logger.println("Adding old message.");
int rpos = getViewManager().getCurrentViewPos(rr.getSender());
receivedReplies++;
replies[rpos] = rr;
li.remove();
}
}
}
receivedReplies++;
replies[pos] = reply;
// Compare the reply just received, to the others
int sameContent = 1;
for (int i = 0; i < replies.length; i++) {
Logger.println(i+" ("+reqId+"): "+sameContent+"/"+receivedReplies+"/"+replyQuorum);
if (i != pos && replies[i] != null && (comparator.compare(replies[i].getContent(), reply.getContent()) == 0)) {
sameContent++;
if (sameContent >= replyQuorum) {
response = extractor.extractResponse(replies, sameContent, pos);
reqId = -1;
this.sm.release(); // resumes the thread that is executing the "invoke" method
break;
}
}
}
if (response == null && receivedReplies >=
getViewManager().getCurrentViewN() - getViewManager().getCurrentViewF()) {
//it's not safe to wait for more replies (n-f replies received),
//but there is no response available...
reqId = -1;
Logger.println("releasing sm without response");
this.sm.release(); // resumes the thread that is executing the "invoke" method
}
} else {
Logger.println("Discarding reply from "+reply.getSender()+" with reqId:"+reply.getSequence()+". Putting on pos="+pos);
}
// Critical section ends here. The semaphore can be released
this.mutex.release();
}
}
|
package nl.mpi.arbil.data;
import java.net.URI;
import java.util.Vector;
import nl.mpi.arbil.ImdiTableModel;
import nl.mpi.arbil.LinorgFavourites;
import nl.mpi.arbil.LinorgSessionStorage;
import nl.mpi.arbil.LinorgWindowManager;
import nl.mpi.arbil.TreeHelper;
import nl.mpi.arbil.clarin.CmdiComponentBuilder;
public class MetadataBuilder {
public void requestRootAddNode(String nodeType, String nodeTypeDisplayName) {
ImdiTreeObject imdiTreeObject;
imdiTreeObject = new ImdiTreeObject(LinorgSessionStorage.getSingleInstance().getNewImdiFileName(LinorgSessionStorage.getSingleInstance().getSaveLocation(""), nodeType));
requestAddNode(imdiTreeObject, nodeType, nodeTypeDisplayName);
}
public void requestAddNode(final ImdiTreeObject destinationNode, final String nodeTypeDisplayNameLocal, final ImdiTreeObject addableNode) {
new Thread() {
@Override
public void run() {
synchronized (destinationNode.domLockObject) {
String nodeTypeDisplayName = nodeTypeDisplayNameLocal;
// todo: update this when functional
if (destinationNode.isCmdiMetaDataNode()) {
CmdiComponentBuilder componentBuilder = new CmdiComponentBuilder();
// todo handle this outside the gui thread
URI addedNodePath = componentBuilder.insertResourceProxy(destinationNode, addableNode);
destinationNode.reloadNode();
}
ImdiTreeObject[] sourceImdiNodeArray;
if (addableNode.isEmptyMetaNode()) {
sourceImdiNodeArray = addableNode.getChildArray();
} else {
sourceImdiNodeArray = new ImdiTreeObject[]{addableNode};
}
for (ImdiTreeObject currentImdiNode : sourceImdiNodeArray) {
String nodeType;
String favouriteUrlString = null;
URI resourceUrl = null;
String mimeType = null;
if (currentImdiNode.isArchivableFile() && !currentImdiNode.isMetaDataNode()) {
nodeType = ImdiSchema.getSingleInstance().getNodeTypeFromMimeType(currentImdiNode.mpiMimeType);
resourceUrl = currentImdiNode.getURI();
mimeType = currentImdiNode.mpiMimeType;
nodeTypeDisplayName = "Resource";
} else {
nodeType = LinorgFavourites.getSingleInstance().getNodeType(currentImdiNode, destinationNode);
favouriteUrlString = currentImdiNode.getUrlString();
}
if (nodeType != null) {
String targetXmlPath = destinationNode.getURI().getFragment();
if (nodeType == null) { // targetXmlPath hass been added at this point to preserve the sub node (N) which otherwise had been lost for the (x) and this is required to add to a sub node correctly
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Cannot add this type of node", null);
} else {
// if (this.isImdiChild()) {
// System.out.println("requestAddNodeChild: " + this.getUrlString());
// this.domParentImdi.requestAddNode(nodeType, this.nodeUrl.getRef(), nodeTypeDisplayName, favouriteUrlString, resourceUrl, mimeType);
// } else {
System.out.println("requestAddNode: " + nodeType + " : " + nodeTypeDisplayName + " : " + favouriteUrlString + " : " + resourceUrl);
processAddNodes(destinationNode, nodeType, targetXmlPath, nodeTypeDisplayName, favouriteUrlString, mimeType, resourceUrl);
ImdiLoader.getSingleInstance().requestReload(destinationNode);
}
}
}
}
}
}.start();
}
public void requestAddNode(final ImdiTreeObject destinationNode, final String nodeType, final String nodeTypeDisplayName) {
new Thread() {
@Override
public void run() {
synchronized (destinationNode.domLockObject) {
System.out.println("requestAddNode: " + nodeType + " : " + nodeTypeDisplayName);
processAddNodes(destinationNode, nodeType, destinationNode.getURI().getFragment(), nodeTypeDisplayName, null, null, null);
ImdiLoader.getSingleInstance().requestReload(destinationNode);
}
}
}.start();
}
private void processAddNodes(ImdiTreeObject currentImdiObject, String nodeType, String targetXmlPath, String nodeTypeDisplayName, String favouriteUrlString, String mimeType, URI resourceUri) {
// if (currentImdiObject.addQueue.size() > 0) { // add any child nodes requested
// URI resourceUri = null;
// String[] addRequestArrayString = currentImdiObject.addQueue.remove(0);
// nodeType = addRequestArrayString[0];
// targetXmlPath = addRequestArrayString[1];
// nodeTypeDisplayName = addRequestArrayString[2];
// favouriteUrlString = addRequestArrayString[3];
// if (addRequestArrayString[4] != null) {
// try {
// resourceUri = new URI(addRequestArrayString[4]);
// } catch (URISyntaxException urise) {
// GuiHelper.linorgBugCatcher.logError(urise);
// mimeType = addRequestArrayString[5];
// Vector<ImdiTreeObject> allChildren = new Vector();
// allChildren.add(favouriteImdiNode);
// favouriteImdiNode.getAllChildren(allChildren);
// sub node loop
// for (ImdiTreeObject currentFavChild : allChildren.toArray(new ImdiTreeObject[]{}))
String newTableTitleString = "new " + nodeTypeDisplayName;
if (currentImdiObject.isMetaDataNode() && !currentImdiObject.fileNotFound) {
newTableTitleString = newTableTitleString + " in " + currentImdiObject.toString();
}
System.out.println("addQueue:-\nnodeType: " + nodeType + "\ntargetXmlPath: " + targetXmlPath + "\nnodeTypeDisplayName: " + nodeTypeDisplayName + "\nfavouriteUrlString: " + favouriteUrlString + "\nresourceUrl: " + resourceUri + "\nmimeType: " + mimeType);
// ImdiTreeObject addedImdiObject = TreeHelper.getSingleInstance().addImdiChildNode(currentImdiObject, nodeType, nodeTypeDisplayName, resourceUrl, mimeType);
URI addedNodeUri = currentImdiObject.addChildNode(nodeType, targetXmlPath, resourceUri, mimeType);
ImdiTreeObject addedImdiObject = ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(addedNodeUri);
// if (addedImdiObject == null) {
// LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Could not add node of type: " + nodeType, "Error inserting node");
// } else {
if (addedImdiObject != null) {
Vector<ImdiTreeObject> allAddedNodes = new Vector<ImdiTreeObject>();
// imdiTableModel.addImdiObjects(new ImdiTreeObject[]{addedImdiObject});
//ImdiTableModel imdiTableModel = LinorgWindowManager.getSingleInstance().openAllChildNodesInFloatingTableOnce(new ImdiTreeObject[]{addedImdiObject}, newTableTitleString);
allAddedNodes.add(addedImdiObject);
addedImdiObject.loadImdiDom();
if (favouriteUrlString != null) {
mergeWithFavourite(addedImdiObject, favouriteUrlString, allAddedNodes, progressMonitor);
}
// addedImdiObject.loadChildNodes();
addedImdiObject.clearIcon();
addedImdiObject.clearChildIcons();
addedImdiObject.scrollToRequested = true;
TreeHelper.getSingleInstance().updateTreeNodeChildren(currentImdiObject.getParentDomNode());
if (currentImdiObject.getParentDomNode() != addedImdiObject.getParentDomNode()) {
TreeHelper.getSingleInstance().updateTreeNodeChildren(addedImdiObject.getParentDomNode());
}
//ImdiTableModel imdiTableModel = LinorgWindowManager.getSingleInstance().openFloatingTableOnce(allAddedNodes.toArray(new ImdiTreeObject[]{}), newTableTitleString);
}
ImdiTableModel imdiTableModel = LinorgWindowManager.getSingleInstance().openFloatingTableOnce(new URI[]{addedNodeUri}, newTableTitleString);
// } else {
//// if (currentImdiObject.autoLoadChildNodes) {
//// currentImdiObject.loadChildNodes();
// TreeHelper.getSingleInstance().updateTreeNodeChildren(currentImdiObject);
}
}
|
package cz.bakaj.solvers.impl;
import cz.bakaj.model.Item;
import cz.bakaj.model.Knapsack;
import cz.bakaj.solvers.Solver;
import java.util.Comparator;
import java.util.List;
public class HeuristicSolver implements Solver {
@Override
public Knapsack solve(Knapsack knapsack) {
List<Item> temp = knapsack.getItems();
temp.sort(Comparator.comparing(Item::getRatio));
int max = 0;
for (int i = temp.size()-1; i>= 0; i
int t = i;
int cur = 0;
int capacity = knapsack.getCapacity();
while (t>=0) {
if (capacity - temp.get(t).getWeight() >= 0) {
capacity -= temp.get(t).getWeight();
cur += temp.get(t).getCost();
}
t
}
if (cur > max) {
max = cur;
}
}
knapsack.setResult(max);
return knapsack;
}
}
|
package ch.ntb.inf.deep.ui.view;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
import ch.ntb.inf.deep.loader.Downloader;
import ch.ntb.inf.deep.loader.DownloaderException;
import ch.ntb.inf.deep.loader.UsbMpc555Loader;
import ch.ntb.inf.deep.ui.model.MemorySegment;
public class MemoryView extends ViewPart implements Listener {
public static final String ID = "ch.ntb.inf.deep.view.MemoryView";
private TableViewer viewer;
private Text addr;
private Text count;
private Button button;
private Downloader bdi;
class ViewLabelProvider extends LabelProvider implements
ITableLabelProvider {
public String getColumnText(Object obj, int index) {
switch (index) {
case 0:
if (((MemorySegment) obj).addr == -1) {
return "";
}
return "0x" + Integer.toHexString(((MemorySegment) obj).addr);
case 1:
if (((MemorySegment) obj).addr == -1) {
return "";
}
return "0x" + Integer.toHexString(((MemorySegment) obj).value);
default:
throw new RuntimeException("Should not happen");
}
}
public Image getColumnImage(Object obj, int index) {
return null;
}
}
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(5, false);
parent.setLayout(layout);
Label label = new Label(parent, SWT.NONE);
label.setText("start address: ");
addr = new Text(parent, SWT.BORDER);
addr.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String string = addr.getText() + e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
if (chars[0] == '0' && chars.length > 1) {// hex value
if ((chars[1] == 'x' || chars[1] == 'X')) {
if (chars.length > 2) {
for (int i = 2; i < chars.length; i++) {
if (!(('0' <= chars[i] && chars[i] <= '9')
|| ('A' <= chars[i] && chars[i] <= 'F') || ('a' <= chars[i] && chars[i] <= 'f'))) {
e.doit = false;
return;
}
}
}
} else {
e.doit = false;
return;
}
} else {
for (int i = 0; i < chars.length; i++) {
if (!('0' <= chars[i] && chars[i] <= '9')) {
e.doit = false;
return;
}
}
}
}
});
Label label2 = new Label(parent, SWT.NONE);
label2.setText("nofWords: ");
count = new Text(parent, SWT.BORDER);
count.addListener(SWT.Verify, new Listener() {
public void handleEvent(Event e) {
String string = addr.getText() + e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
if (chars[0] == '0' && chars.length > 1) {// hex value
if ((chars[1] == 'x' || chars[1] == 'X')) {
if (chars.length > 2) {
for (int i = 2; i < chars.length; i++) {
if (!(('0' <= chars[i] && chars[i] <= '9')
|| ('A' <= chars[i] && chars[i] <= 'F') || ('a' <= chars[i] && chars[i] <= 'f'))) {
e.doit = false;
return;
}
}
}
} else {
e.doit = false;
return;
}
} else {
for (int i = 0; i < chars.length; i++) {
if (!('0' <= chars[i] && chars[i] <= '9')) {
e.doit = false;
return;
}
}
}
}
});
button = new Button(parent, SWT.PUSH);
button.setText("read");
button.addListener(SWT.Selection, this);
createViewer(parent);
}
private void createViewer(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
String[] titels = { "Address", "Value" };
int[] bounds = { 60, 230 };
for (int i = 0; i < titels.length; i++) {
TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(titels[i]);
column.getColumn().setWidth(bounds[i]);
column.getColumn().setResizable(false);
column.getColumn().setMoveable(false);
}
final Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
viewer.setContentProvider(new ArrayContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
// Get the content for the viewer, setInput will call getElements in the
// contentProvider
viewer.setInput(new MemorySegment[] { new MemorySegment(),
new MemorySegment(), new MemorySegment() });// TODO fill Array
// into
// Layout the viewer
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 5;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
}
@Override
public void setFocus() {
viewer.getControl().setFocus();
}
@Override
public void handleEvent(Event event) {
if (event.widget.equals(button)) {
int startAddr = 0;
int size = 0;
String addrStr = addr.getText();
String countStr = count.getText();
//work around for problem when in hex-int-number the most significant bit is set;
//once for the start addres
if(addrStr.charAt(0) == '0' && addrStr.length() > 9 && addrStr.charAt(2) > '7'){
String most = addrStr.substring(2, 3);
addrStr = "0x0" + addrStr.substring(3);
startAddr = (Integer.parseInt(most,16) << 28) |Integer.decode(addrStr);
}else{
startAddr = Integer.decode(addr.getText());
}
//once for the size
if(countStr.charAt(0) == '0' && countStr.length() > 9 && countStr.charAt(2) > '7'){
String most = countStr.substring(2, 3);
countStr = "0x0" + countStr.substring(3);
size = (Integer.parseInt(most,16) << 28) |Integer.decode(countStr);
}else{
size = Integer.decode(count.getText());
}
if (bdi == null) {
bdi = UsbMpc555Loader.getInstance();
}
if(bdi.isConnected()){//reopen
bdi.closeConnection();
try {
bdi.openConnection();
} catch (DownloaderException e) {
e.printStackTrace();
}
}
if (size > 0) {
MemorySegment[] segs = new MemorySegment[size];
try {
boolean wasFreezeAsserted = bdi.isFreezeAsserted();
if (!wasFreezeAsserted) {
bdi.stopTarget();
}
for (int i = 0; i < size; i++) {
segs[i] = new MemorySegment(startAddr + i * 4, bdi
.getMem(startAddr + i * 4, 4));
}
if (!wasFreezeAsserted) {
bdi.startTarget();
}
} catch (DownloaderException e1) {
e1.printStackTrace();
}
viewer.setInput(segs);
viewer.refresh();
}
}
}
}
|
package org.apache.fop.fo;
import org.apache.fop.layout.FontState;
import org.apache.fop.layout.FontInfo;
import org.apache.fop.layout.BorderAndPadding;
import org.apache.fop.fo.properties.BreakBefore;
import org.apache.fop.fo.properties.Constants;
import org.apache.fop.layout.HyphenationProps;
import org.apache.fop.apps.FOPException;
import java.text.MessageFormat;
import java.text.FieldPosition;
public class PropertyManager {
private PropertyList properties;
private FontState fontState=null;
private BorderAndPadding borderAndPadding = null;
private HyphenationProps hyphProps = null;
private String[] saLeft ;
private String[] saRight;
private String[] saTop ;
private String[] saBottom ;
private static MessageFormat msgColorFmt = new MessageFormat("border-{0}-color");
private static MessageFormat msgStyleFmt = new MessageFormat("border-{0}-style");
private static MessageFormat msgWidthFmt = new MessageFormat("border-{0}-width");
private static MessageFormat msgPaddingFmt = new MessageFormat("padding-{0}");
public PropertyManager(PropertyList pList) {
this.properties = pList;
}
private void initDirections() {
saLeft = new String[1];
saRight = new String[1];
saTop = new String[1];
saBottom = new String[1];
saTop[0] = properties.wmAbsToRel(PropertyList.TOP);
saBottom[0] = properties.wmAbsToRel(PropertyList.BOTTOM);
saLeft[0] = properties.wmAbsToRel(PropertyList.LEFT);
saRight[0] = properties.wmAbsToRel(PropertyList.RIGHT);
}
public FontState getFontState(FontInfo fontInfo) throws FOPException {
if (fontState == null) {
String fontFamily = properties.get("font-family").getString();
String fontStyle =properties.get("font-style").getString();
String fontWeight =properties.get("font-weight").getString();
// NOTE: this is incomplete. font-size may be specified with
// various kinds of keywords too
int fontSize =properties.get("font-size").getLength().mvalue();
int fontVariant =properties.get("font-variant").getEnum();
// fontInfo is same for the whole FOP run but set in all FontState
fontState = new FontState(fontInfo, fontFamily,
fontStyle, fontWeight, fontSize, fontVariant);
}
return fontState ;
}
public BorderAndPadding getBorderAndPadding() {
if (borderAndPadding == null) {
this.borderAndPadding = new BorderAndPadding();
initDirections();
initBorderInfo(BorderAndPadding.TOP, saTop);
initBorderInfo(BorderAndPadding.BOTTOM, saBottom);
initBorderInfo(BorderAndPadding.LEFT, saLeft);
initBorderInfo(BorderAndPadding.RIGHT, saRight);
}
return borderAndPadding;
}
private void initBorderInfo(int whichSide, String[] saSide) {
borderAndPadding.setPadding(whichSide,
properties.get(msgPaddingFmt.format(saSide)).getCondLength());
// If style = none, force width to 0, don't get Color
int style = properties.get(msgStyleFmt.format(saSide)).getEnum();
if (style != Constants.NONE) {
borderAndPadding.setBorder(whichSide, style,
properties.get(msgWidthFmt.format(saSide)).getCondLength(),
properties.get(msgColorFmt.format(saSide)).getColorType());
}
}
public HyphenationProps getHyphenationProps() {
if (hyphProps == null) {
this.hyphProps = new HyphenationProps();
hyphProps.hyphenate = this.properties.get("hyphenate").getEnum();
hyphProps.hyphenationChar = this.properties.get("hyphenation-character").getCharacter();
hyphProps.hyphenationPushCharacterCount = this.properties.get( "hyphenation-push-character-count").getNumber().intValue();
hyphProps.hyphenationRemainCharacterCount = this.properties.get( "hyphenation-remain-character-count").getNumber().intValue();
hyphProps.language = this.properties.get("language").getString();
hyphProps.country = this.properties.get("country").getString();
}
return hyphProps;
}
public int checkBreakBefore() {
switch(properties.get("break-before").getEnum()) {
case BreakBefore.PAGE:
return Status.FORCE_PAGE_BREAK;
case BreakBefore.ODD_PAGE:
return Status.FORCE_PAGE_BREAK_ODD;
case BreakBefore.EVEN_PAGE:
return Status.FORCE_PAGE_BREAK_EVEN;
case BreakBefore.COLUMN:
return Status.FORCE_COLUMN_BREAK;
default:
return Status.OK;
}
}
}
|
package org.appwork.utils.zip;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.appwork.utils.Hash;
/**
* @author daniel
*
*/
public class ZipIOWriter {
private ZipOutputStream zipStream = null;
private OutputStream fileStream = null;
private File zipFile = null;
private final byte[] buf = new byte[8192];
public ZipIOWriter(final ByteArrayOutputStream stream) throws FileNotFoundException, ZipIOException {
this.fileStream = stream;
this.zipStream = new ZipOutputStream(this.fileStream);
}
/**
* constructor for ZipIOWriter
*
* @param zipFile
* zipFile we want create (does not overwrite existing files!)
* @throws FileNotFoundException
* @throws ZipIOException
*/
public ZipIOWriter(final File zipFile) throws FileNotFoundException, ZipIOException {
this.zipFile = zipFile;
this.openZip(false);
}
/**
* constructor for ZipIOWriter
*
* @param zipFile
* zipFile we want create
* @param overwrite
* overwrite existing ziFiles?
* @throws FileNotFoundException
* @throws ZipIOException
*/
public ZipIOWriter(final File zipFile, final boolean overwrite) throws FileNotFoundException, ZipIOException {
this.zipFile = zipFile;
this.openZip(overwrite);
}
/**
* add given File (File or Directory) to this ZipFile
*
* @param add
* File to add
* @param compress
* compress or store
* @param path
* customized path
* @throws ZipIOException
* @throws IOException
*/
public synchronized void add(final File add, final boolean compress, final String path) throws ZipIOException, IOException {
if (add == null || !add.exists()) { throw new ZipIOException("add " + add.getAbsolutePath() + " invalid"); }
if (add.isFile()) {
this.addFileInternal(add, compress, path);
} else if (add.isDirectory()) {
this.addDirectoryInternal(add, compress, path);
} else {
throw new ZipIOException("add " + add.getAbsolutePath() + " invalid");
}
}
public synchronized void addByteArry(final byte[] data, final boolean compress, final String path, final String name) throws IOException, ZipIOException {
boolean zipEntryAdded = false;
try {
if (data == null) { throw new ZipIOException("data array is invalid"); }
final ZipEntry zipAdd = new ZipEntry((path != null && path.trim().length() > 0 ? path + "/" : "") + name);
zipAdd.setSize(data.length);
if (compress) {
zipAdd.setMethod(ZipEntry.DEFLATED);
} else {
zipAdd.setMethod(ZipEntry.STORED);
zipAdd.setCompressedSize(data.length);
/* STORED must have a CRC32! */
zipAdd.setCrc(Hash.getCRC32(data));
}
this.zipStream.putNextEntry(zipAdd);
zipEntryAdded = true;
this.zipStream.write(data, 0, data.length);
} finally {
if (zipEntryAdded) {
this.zipStream.closeEntry();
}
}
}
/**
* add given Directory to this ZipFile
*
* @param addDirectory
* Directory to add
* @param compress
* compress or store
* @param path
* customized path
* @throws ZipIOException
* @throws IOException
*/
public synchronized void addDirectory(final File addDirectory, final boolean compress, final String path) throws ZipIOException, IOException {
this.addDirectoryInternal(addDirectory, compress, path);
}
private void addDirectoryInternal(final File addDirectory, final boolean compress, final String path) throws ZipIOException, IOException {
if (addDirectory == null || !addDirectory.isDirectory() || !addDirectory.exists()) { throw new ZipIOException("addDirectory " + addDirectory.getAbsolutePath() + " invalid"); }
final File[] list = addDirectory.listFiles();
if (list == null) { return; }
for (final File add : list) {
if (add.isFile()) {
this.addFileInternal(add, compress, (path != null && path.trim().length() > 0 ? path + "/" : "") + addDirectory.getName());
} else if (add.isDirectory()) {
this.addDirectoryInternal(add, compress, (path != null && path.trim().length() > 0 ? path + "/" : "") + addDirectory.getName());
} else {
throw new ZipIOException("addDirectory " + addDirectory.getAbsolutePath() + " invalid");
}
}
}
/**
* add given File to this ZipFile
*
* @param addFile
* File to add
* @param compress
* compress or store
* @param path
* customized path
* @throws ZipIOException
* @throws IOException
*/
public synchronized void addFile(final File addFile, final boolean compress, final String path) throws ZipIOException, IOException {
this.addFileInternal(addFile, compress, path);
}
private void addFileInternal(final File addFile, final boolean compress, final String path) throws ZipIOException, IOException {
FileInputStream fin = null;
boolean zipEntryAdded = false;
try {
if (addFile == null || !addFile.isFile() || !addFile.exists()) { throw new ZipIOException("addFile " + addFile.getAbsolutePath() + " invalid"); }
final ZipEntry zipAdd = new ZipEntry((path != null && path.trim().length() > 0 ? path + "/" : "") + addFile.getName());
zipAdd.setSize(addFile.length());
if (compress) {
zipAdd.setMethod(ZipEntry.DEFLATED);
} else {
zipAdd.setMethod(ZipEntry.STORED);
zipAdd.setCompressedSize(addFile.length());
/* STORED must have a CRC32! */
zipAdd.setCrc(Hash.getCRC32(addFile));
}
fin = new FileInputStream(addFile);
this.zipStream.putNextEntry(zipAdd);
zipEntryAdded = true;
int len;
while ((len = fin.read(this.buf)) > 0) {
this.zipStream.write(this.buf, 0, len);
}
} finally {
if (zipEntryAdded) {
this.zipStream.closeEntry();
}
if (fin != null) {
fin.close();
}
}
}
/**
* closes the ZipFile
*
* @throws Throwable
*/
public synchronized void close() throws IOException {
Throwable e = null;
try {
try {
this.zipStream.flush();
} catch (final Throwable e2) {
if (e == null) {
e = e2;
}
}
try {
this.fileStream.flush();
} catch (final Throwable e2) {
if (e == null) {
e = e2;
}
}
try {
this.zipStream.close();
} catch (final Throwable e2) {
if (e == null) {
e = e2;
}
}
try {
this.fileStream.close();
} catch (final Throwable e2) {
if (e == null) {
e = e2;
}
}
} finally {
this.zipStream = null;
this.fileStream = null;
}
if (e != null) { throw new IOException(e); }
}
/**
* opens the zipFile for further use
*
* @param overwrite
* overwrite existing zipFiles?
* @throws ZipIOException
* @throws FileNotFoundException
*/
private void openZip(final boolean overwrite) throws ZipIOException, FileNotFoundException {
if (this.fileStream != null && this.zipStream != null) { return; }
if (this.zipFile == null || this.zipFile.isDirectory()) { throw new ZipIOException("invalid zipFile"); }
if (this.zipFile.exists() && !overwrite) { throw new ZipIOException("zipFile already exists"); }
this.fileStream = new FileOutputStream(this.zipFile);
this.zipStream = new ZipOutputStream(this.fileStream);
}
}
|
package org.beanmaker;
import java.util.List;
import java.util.Set;
import org.jcodegen.java.AnonymousClassCreation;
import org.jcodegen.java.Assignment;
import org.jcodegen.java.Comparison;
import org.jcodegen.java.Condition;
import org.jcodegen.java.ConstructorDeclaration;
import org.jcodegen.java.ElseBlock;
import org.jcodegen.java.ElseIfBlock;
import org.jcodegen.java.ExceptionThrow;
import org.jcodegen.java.ForLoop;
import org.jcodegen.java.FunctionArgument;
import org.jcodegen.java.FunctionCall;
import org.jcodegen.java.FunctionDeclaration;
import org.jcodegen.java.GenericType;
import org.jcodegen.java.IfBlock;
import org.jcodegen.java.JavaClass;
import org.jcodegen.java.JavaCodeBlock;
import org.jcodegen.java.LineOfCode;
import org.jcodegen.java.ObjectCreation;
import org.jcodegen.java.OperatorExpression;
import org.jcodegen.java.ReturnStatement;
import org.jcodegen.java.VarDeclaration;
import org.jcodegen.java.Visibility;
import org.jcodegen.java.WhileBlock;
import org.dbbeans.util.Strings;
import static org.beanmaker.SourceFiles.chopId;
import static org.dbbeans.util.Strings.*;
public class BaseClassSourceFile extends BeanCodeWithDBInfo {
private final Set<String> types;
private final String internalsVar;
private final String parametersVar;
public BaseClassSourceFile(final String beanName, final String packageName, final Columns columns, final String tableName) {
super(beanName, packageName, "Base", columns, tableName);
internalsVar = beanVarName + "Internals";
parametersVar = Strings.uncamelize(beanName).toUpperCase() + "_PARAMETERS";
types = columns.getJavaTypes();
createSourceCode();
}
private void addImports() {
importsManager.addImport("java.sql.PreparedStatement");
importsManager.addImport("java.sql.ResultSet");
importsManager.addImport("java.sql.SQLException");
importsManager.addImport("java.util.ArrayList");
importsManager.addImport("java.util.List");
importsManager.addImport("java.util.Locale");
importsManager.addImport("org.beanmaker.util.BeanInternals");
importsManager.addImport("org.beanmaker.util.DbBeanInterface");
importsManager.addImport("org.beanmaker.util.DBQueries");
importsManager.addImport("org.beanmaker.util.ErrorMessage");
importsManager.addImport("org.beanmaker.util.IdNamePair");
importsManager.addImport("org.dbbeans.sql.DBQueryRetrieveData");
importsManager.addImport("org.dbbeans.sql.DBQuerySetup");
importsManager.addImport("org.dbbeans.sql.DBQuerySetupProcess");
importsManager.addImport("org.dbbeans.sql.DBTransaction");
importsManager.addImport("org.dbbeans.util.Strings");
if (columns.containNumericalData())
importsManager.addImport("org.beanmaker.util.FormatCheckHelper");
if (types.contains("Date")) {
importsManager.addImport("java.sql.Date");
importsManager.addImport("java.text.DateFormat");
importsManager.addImport("org.dbbeans.util.Dates");
importsManager.addImport("org.dbbeans.util.SimpleInputDateFormat");
}
if (types.contains("Time")) {
importsManager.addImport("java.sql.Time");
importsManager.addImport("java.text.DateFormat");
importsManager.addImport("org.dbbeans.util.Dates");
importsManager.addImport("org.dbbeans.util.SimpleInputTimeFormat");
}
if (types.contains("Timestamp")) {
importsManager.addImport("java.sql.Timestamp");
importsManager.addImport("java.text.DateFormat");
importsManager.addImport("org.dbbeans.util.Dates");
importsManager.addImport("org.dbbeans.util.SimpleInputDateFormat");
importsManager.addImport("org.dbbeans.util.SimpleInputTimestampFormat");
}
if (types.contains("Money")) {
importsManager.addImport("org.dbbeans.util.Money");
importsManager.addImport("org.dbbeans.util.MoneyFormat");
}
if (columns.hasLastUpdate())
importsManager.addImport("org.dbbeans.util.Dates");
}
private void addClassModifiers() {
javaClass.markAsAbstract().extendsClass("DbBean").implementsInterface("DbBeanInterface");
}
private void addProperties() {
for (Column column: columns.getList()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
final VarDeclaration declaration;
if (type.equals("String"))
declaration = new VarDeclaration("String", field, EMPTY_STRING);
else if (type.equals("Money"))
declaration = new VarDeclaration("Money", field, new ObjectCreation("Money").addArgument("0").addArgument(new FunctionCall("getDefaultMoneyFormat")));
else
declaration = new VarDeclaration(type, field);
addProperty(declaration);
if (type.equals("Money"))
addProperty(new VarDeclaration("String", field + "Str", new FunctionCall("toString", field)));
if (JAVA_TEMPORAL_TYPES.contains(type) || ((type.equals("int") || type.equals("long")) && !field.startsWith("id") && !field.equals("itemOrder")))
addProperty(new VarDeclaration("String", field + "Str", EMPTY_STRING));
}
if (columns.hasLastUpdate())
addProperty("boolean", "updateOK");
if (columns.hasOneToManyRelationships()) {
boolean first = true;
for (OneToManyRelationship relationship: columns.getOneToManyRelationships())
if (!relationship.isListOnly()) {
if (first) {
newLine();
first = false;
}
addProperty(VarDeclaration.createListDeclaration(relationship.getBeanClass(), relationship.getJavaName()));
}
}
newLine();
javaClass.addContent(
new VarDeclaration("BeanInternals", internalsVar,
new ObjectCreation("BeanInternals").addArgument(quickQuote(bundleName))).markAsFinal().visibility(Visibility.PROTECTED)
);
final String parametersClass = beanName + "Parameters";
javaClass.addContent(
new VarDeclaration(parametersClass, parametersVar,
new ObjectCreation(parametersClass)).markAsFinal().markAsStatic().visibility(Visibility.PROTECTED)
);
newLine();
}
private void addConstructors() {
javaClass.addContent(getBaseConstructor()).addContent(EMPTY_LINE);
javaClass.addContent(getIdArgumentConstructor()).addContent(EMPTY_LINE);
javaClass.addContent(getCopyConstructor()).addContent(EMPTY_LINE);
javaClass.addContent(getFieldConstructor()).addContent(EMPTY_LINE);
}
private ConstructorDeclaration getBaseConstructor() {
return javaClass.createConstructor();
}
private ConstructorDeclaration getIdArgumentConstructor() {
return getBaseConstructor().addArgument(new FunctionArgument("long", "id")).addContent("setId(id);");
}
private ConstructorDeclaration getCopyConstructor() {
final ConstructorDeclaration copyConstructor = getBaseConstructor();
copyConstructor.addArgument(new FunctionArgument(beanName + "Base", "model")).addContent(new Assignment("id", "0"));
for (Column column: columns.getList()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if (!field.equals("id")) {
if (field.equals("itemOrder"))
copyConstructor.addContent(new Assignment("itemOrder", "0"));
else if (field.startsWith("id") || type.equals("boolean") || type.equals("String"))
copyConstructor.addContent(new Assignment(field, "model." + field));
else
copyConstructor.addContent(new FunctionCall("set" + capitalize(field)).addArgument("model." + field).byItself());
}
}
for (OneToManyRelationship relationship: columns.getOneToManyRelationships())
if (!relationship.isListOnly()) {
final String beanClass = relationship.getBeanClass();
final String beanObject = uncapitalize(beanClass);
final String javaName = relationship.getJavaName();
copyConstructor.addContent(EMPTY_LINE).addContent(
new ForLoop(beanClass + " " + beanObject + ": model." + javaName).addContent(
new FunctionCall("add", javaName).byItself().addArgument(
new ObjectCreation(beanClass).addArgument(new FunctionCall("getId", beanObject))
)
)
);
}
return copyConstructor;
}
private ConstructorDeclaration getFieldConstructor() {
final ConstructorDeclaration fieldConstructor = getBaseConstructor().visibility(Visibility.PROTECTED);
for (Column column: columns.getList())
fieldConstructor.addArgument(new FunctionArgument(column.getJavaType(), column.getJavaName()));
for (Column column: columns.getList()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if (field.startsWith("id") || field.equals("itemOrder") || type.equals("boolean") || type.equals("String"))
fieldConstructor.addContent(new Assignment("this." + field, field));
else
fieldConstructor.addContent(new FunctionCall("set" + capitalize(field)).addArgument(field).byItself());
}
// For now, to be replaced when getAll has been updated with database friendly code
for (OneToManyRelationship relationship: columns.getOneToManyRelationships())
if (!relationship.isListOnly()) {
final String beanClass = relationship.getBeanClass();
final String beanObject = uncapitalize(beanClass);
final String javaName = relationship.getJavaName();
fieldConstructor.addArgument(new FunctionArgument(new GenericType("List", beanClass).toString(), javaName));
fieldConstructor.addContent(EMPTY_LINE).addContent(
new ForLoop(beanClass + " " + beanObject + ": " + javaName).addContent(
new FunctionCall("add", "this." + javaName).byItself().addArgument(beanObject)
)
);
}
return fieldConstructor;
}
private void addSetIdFunction() {
final List<OneToManyRelationship> relationships = columns.getOneToManyRelationships();
final FunctionDeclaration function = new FunctionDeclaration("setId")
.addArgument(new FunctionArgument("long", "id"));
// function inner class for database row retrieval
final JavaClass databaseInnerClass = new JavaClass("DataFromDBQuery").visibility(Visibility.NONE)
.implementsInterface("DBQuerySetupProcess");
for (Column column: columns.getList()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if (!field.equals("id")) {
if (type.equals("int") || type.equals("long"))
databaseInnerClass.addContent(new VarDeclaration(type, field, "0"));
else if (type.equals("String") || JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money"))
databaseInnerClass.addContent(new VarDeclaration(type, field, "null"));
else if (type.equals("boolean"))
databaseInnerClass.addContent(new VarDeclaration(type, field, "false"));
else
throw new IllegalStateException("Java type not allowed: " + type);
}
}
databaseInnerClass.addContent(new VarDeclaration("boolean", "idOK", "false"))
.addContent(EMPTY_LINE)
.addContent(getInnerClassSetupPSWithIdFunction())
.addContent(EMPTY_LINE);
final FunctionDeclaration processRS = getInnerClassProcessRSFunctionStart();
final IfBlock ifRsNext = new IfBlock(new Condition("rs.next()"));
int index = 0;
for (Column column: columns.getList()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if (!field.equals("id")) {
++index;
if (type.equals("Money"))
ifRsNext.addContent(new Assignment(field, new ObjectCreation("Money")
.addArgument(new FunctionCall("getLong")
.addArgument(Integer.toString(index))
.addArgument(new FunctionCall("getDefaultMoneyFormat")))));
else {
final String getterName = "get" + capitalize(type);
ifRsNext.addContent(new Assignment(field, new FunctionCall(getterName, "rs").addArgument(Integer.toString(index))));
}
}
}
ifRsNext.addContent(new Assignment("idOK", "true"));
processRS.addContent(ifRsNext);
databaseInnerClass.addContent(processRS);
function.addContent(databaseInnerClass).addContent(EMPTY_LINE);
// for objects containing one or more list of other kind of objects
for (OneToManyRelationship relationship: relationships) {
if (!relationship.isListOnly()) {
final JavaClass extraDBInnerClass = new JavaClass("DataFromDBQuery" + capitalize(relationship.getJavaName()))
.visibility(Visibility.NONE).implementsInterface("DBQuerySetupProcess")
.addContent(VarDeclaration.createListDeclaration(relationship.getBeanClass(), relationship.getJavaName()).markAsFinal())
.addContent(EMPTY_LINE)
.addContent(getInnerClassSetupPSWithIdFunction())
.addContent(EMPTY_LINE);
final FunctionDeclaration processRSExtra = getInnerClassProcessRSFunctionStart()
.addContent(new WhileBlock(new Condition("rs.next()"))
.addContent(new FunctionCall("add", relationship.getJavaName())
.byItself()
.addArgument(new ObjectCreation(relationship.getBeanClass())
.addArgument("rs.getLong(1)"))));
extraDBInnerClass.addContent(processRSExtra);
function.addContent(extraDBInnerClass).addContent(EMPTY_LINE);
}
}
// check for bad ID
function.addContent(new IfBlock(new Condition("id <= 0")).addContent("throw new IllegalArgumentException(\"id = \" + id + \" <= 0\");"))
.addContent(EMPTY_LINE);
// instantiate DBQuery inner class & use it to retrieve data
function.addContent(
new VarDeclaration("DataFromDBQuery", "dataFromDBQuery", new ObjectCreation("DataFromDBQuery")).markAsFinal()
).addContent(
new FunctionCall("processQuery", "dbAccess")
.byItself()
.addArgument(quickQuote(getReadSQLQuery()))
.addArgument("dataFromDBQuery")
).addContent(EMPTY_LINE);
// check if data was returned
function.addContent(
new IfBlock(new Condition("!dataFromDBQuery.idOK")).addContent(
new ExceptionThrow("IllegalArgumentException").addArgument("\"id = \" + id + \" does not exist\"")
)
).addContent(EMPTY_LINE);
// for objects containing one or more list of other kind of objects
for (OneToManyRelationship relationship: relationships) {
if (!relationship.isListOnly()) {
final String cappedJavaName = capitalize(relationship.getJavaName());
function.addContent(
new VarDeclaration("DataFromDBQuery" + cappedJavaName, "dataFromDBQuery" + cappedJavaName, new ObjectCreation("DataFromDBQuery" + cappedJavaName)).markAsFinal()
).addContent(
new FunctionCall("processQuery", "dbAccess")
.byItself()
.addArgument(quickQuote(getReadSQLQueryOneToManyRelationship(relationship.getTable(), relationship.getIdSqlName())))
.addArgument("dataFromDBQuery" + cappedJavaName)
).addContent(EMPTY_LINE);
}
}
// extra DB actions
function.addContent("initExtraDbActions(id);").addContent(EMPTY_LINE);
// fields assignment
function.addContent(new Assignment("this.id", "id"));
for (Column column: columns.getList()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if (!field.equals("id")) {
function.addContent(new Assignment("this." + field, "dataFromDBQuery." + field));
if (JAVA_TEMPORAL_TYPES.contains(type))
function.addContent(
new Assignment(field +"Str",
new FunctionCall("convert" + type + "ToString").addArgument(field))
);
if ((type.equals("int") || type.equals("long")) && !field.equals("itemOrder") && !field.startsWith("id"))
function.addContent(
new Assignment(field +"Str",
new FunctionCall("valueOf", "String").addArgument(field))
);
if (type.equals("Money"))
function.addContent(
new Assignment(field +"Str",
new FunctionCall("toString", field))
);
}
}
for (OneToManyRelationship relationship: relationships)
if (!relationship.isListOnly())
function.addContent(
new Assignment("this." + relationship.getJavaName(), "dataFromDBQuery" + capitalize(relationship.getJavaName()) + "." + relationship.getJavaName())
);
function.addContent(EMPTY_LINE).addContent("postInitActions();");
javaClass.addContent(function).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("initExtraDbActions")
.visibility(Visibility.PROTECTED)
.addArgument(new FunctionArgument("long", "id"))
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("postInitActions")
.visibility(Visibility.PROTECTED)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("resetId")
.addContent("id = 0;")
).addContent(EMPTY_LINE);
}
private FunctionDeclaration getInnerClassSetupPSWithIdFunction() {
return new FunctionDeclaration("setupPreparedStatement")
.addException("SQLException")
.annotate("@Override")
.addArgument(new FunctionArgument("PreparedStatement", "stat"))
.addContent("stat.setLong(1, id);");
}
private FunctionDeclaration getInnerClassProcessRSFunctionStart() {
return new FunctionDeclaration("processResultSet")
.addException("SQLException")
.annotate("@Override")
.addArgument(new FunctionArgument("ResultSet", "rs"));
}
private void addEquals() {
javaClass.addContent(
new FunctionDeclaration("equals", "boolean").addArgument(new FunctionArgument("Object", "object")).annotate("@Override").addContent(
new IfBlock(new Condition(new Comparison("id", "0"))).addContent(
new ReturnStatement("false")
)
).addContent(EMPTY_LINE).addContent(
new IfBlock(new Condition("object instanceof " + beanName)).addContent(
new ReturnStatement("((" + beanName + ") object).getId() == id")
)
).addContent(EMPTY_LINE).addContent(
new ReturnStatement("false")
)
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("hashCode", "int").annotate("@Override").addContent(
new IfBlock(new Condition(new Comparison("id", "0"))).addContent(
new ReturnStatement("-1")
)
).addContent(EMPTY_LINE).addContent(
new ReturnStatement("31 * ((int) (id ^ (id >>> 32))) + 17")
)
).addContent(EMPTY_LINE);
}
private void addToString() {
final String returnExpression = "\"[" + beanName + " - " + tableName + "
javaClass.addContent(
new FunctionDeclaration("toString", "String").annotate("@Override").addContent(
new ReturnStatement(returnExpression)
)
).addContent(EMPTY_LINE);
}
private void addSetters() {
for (Column column: columns.getList()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if (!field.equals("id") && !field.equals("lastUpdate") && !field.equals("modifiedBy") && !field.equals("itemOrder")) {
final FunctionDeclaration setter = new FunctionDeclaration("set" + capitalize(field))
.addArgument(new FunctionArgument(type, field));
if (JAVA_TEMPORAL_TYPES.contains(type))
setter.addContent(
new Assignment("this." + field,
new ObjectCreation(type)
.addArgument(new FunctionCall("getTime", field)))
);
else
setter.addContent(
new Assignment("this." + field, field)
);
if (type.equals("int") && !field.startsWith("id"))
setter.addContent(
new Assignment(field + "Str", new FunctionCall("toString", "Integer").addArgument(field))
);
if (type.equals("long") && !field.startsWith("id"))
setter.addContent(
new Assignment(field + "Str", new FunctionCall("toString", "Long").addArgument(field))
);
if (JAVA_TEMPORAL_TYPES.contains(type))
setter.addContent(
new Assignment(field + "Str", new FunctionCall("convert" + capitalize(type) + "ToString").addArgument(field))
);
if (type.equals("Money"))
setter.addContent(
new Assignment(field + "Str", new FunctionCall("toString", field))
);
javaClass.addContent(setter).addContent(EMPTY_LINE);
if (column.couldHaveAssociatedBean() && column.hasAssociatedBean()) {
final String associatedBeanClass = column.getAssociatedBeanClass();
final String associatedBeanObject = uncapitalize(chopId(field));
final FunctionDeclaration fromObjectSetter = new FunctionDeclaration("set" + capitalize(associatedBeanObject))
.addArgument(new FunctionArgument(associatedBeanClass, associatedBeanObject))
.addContent(new IfBlock(new Condition(new Comparison(new FunctionCall("getId", associatedBeanObject), "0")))
.addContent(new ExceptionThrow("IllegalArgumentException")
.addArgument(quickQuote("Cannot accept uninitialized " + associatedBeanClass + " bean (id = 0) as argument."))))
.addContent(EMPTY_LINE)
.addContent(new Assignment(field, new FunctionCall("getId", associatedBeanObject)));
javaClass.addContent(fromObjectSetter).addContent(EMPTY_LINE);
}
if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("long")) && !field.startsWith("id"))) {
final FunctionDeclaration strSetter = new FunctionDeclaration("set" + capitalize(field) + "Str")
.addArgument(new FunctionArgument("String", field + "Str"))
.addContent(new Assignment("this." + field + "Str", field + "Str"));
javaClass.addContent(strSetter).addContent(EMPTY_LINE);
}
}
}
}
private void addGetters() {
for (Column column: columns.getList()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
final String prefix;
if (type.equals("boolean"))
prefix = "is";
else
prefix = "get";
final FunctionDeclaration getter = new FunctionDeclaration(prefix + capitalize(field), type);
if (JAVA_TEMPORAL_TYPES.contains(type))
getter.addContent(
new IfBlock(new Condition(new Comparison(field, "null"))).addContent(new ReturnStatement("null"))
).addContent(
EMPTY_LINE
).addContent(
new ReturnStatement(new ObjectCreation(type).addArgument(new FunctionCall("getTime", field)))
);
else
getter.addContent(
new ReturnStatement(field)
);
javaClass.addContent(getter).addContent(EMPTY_LINE);
if (column.hasAssociatedBean()) {
final String associatedBeanClass = column.getAssociatedBeanClass();
final FunctionDeclaration associatedBeanGetter = new FunctionDeclaration("get" + chopId(field), associatedBeanClass)
.addContent(new ReturnStatement(new ObjectCreation(associatedBeanClass).addArgument(field)));
javaClass.addContent(associatedBeanGetter).addContent(EMPTY_LINE);
}
if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("long")) && !field.startsWith("id") && !field.equals("itemOrder"))) {
final FunctionDeclaration strGetter = new FunctionDeclaration("get" + capitalize(field) + "Str", "String")
.addContent(new ReturnStatement(field + "Str"));
javaClass.addContent(strGetter).addContent(EMPTY_LINE);
}
if (JAVA_TEMPORAL_TYPES.contains(type)) {
final String capField = capitalize(field);
final FunctionDeclaration formattedGetter = new FunctionDeclaration("get" + capField + "Formatted", "String")
.addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "Empty")))
.addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "Required")))
.addContent(getCannotDisplayBadDataException()))
.addContent(new ReturnStatement(EMPTY_STRING)))
.addContent(EMPTY_LINE)
.addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "OK"), true)).addContent(getCannotDisplayBadDataException()))
.addContent(EMPTY_LINE)
.addContent(new ReturnStatement(new FunctionCall("format" + type).addArgument(new FunctionCall("convertStringTo" + type).addArgument(field + "Str"))));
javaClass.addContent(formattedGetter).addContent(EMPTY_LINE);
}
if (type.equals("boolean")) {
final FunctionDeclaration booleanValGetter = new FunctionDeclaration("get" + capitalize(field) + "Val", "String")
.addContent(new IfBlock(new Condition(field))
.addContent(new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote("true_value")))))
.addContent(EMPTY_LINE)
.addContent(new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote("false_value"))));
javaClass.addContent(booleanValGetter).addContent(EMPTY_LINE);
}
}
}
private void addLabelGetters() {
for (Column column: columns.getList()) {
final String field = column.getJavaName();
if (!column.isSpecial())
javaClass.addContent(
new FunctionDeclaration("get" + capitalize(field) + "Label", "String").addContent(
new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote(field)))
)
).addContent(EMPTY_LINE);
}
}
private ExceptionThrow getCannotDisplayBadDataException() {
return new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot display bad data"));
}
private void addRequiredIndicators() {
for (Column column: columns.getList())
addIndicator(column.getJavaName(), "Required", column.isRequired(), true);
}
private void addUniqueIndicators() {
for (Column column: columns.getList())
addIndicator(column.getJavaName(), "ToBeUnique", column.isUnique(), true);
}
private void addOneToManyRelationshipManagement() {
for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) {
final String beanClass = relationship.getBeanClass();
final String itemName = uncapitalize(beanClass);
final String listName = relationship.getJavaName();
if (relationship.isListOnly()) {
importsManager.addImport("org.dbbeans.sql.DBQuerySetupRetrieveData");
final FunctionDeclaration preparedStatementSetup = new FunctionDeclaration("setupPreparedStatement")
.annotate("@Override")
.addException("SQLException")
.addArgument(new FunctionArgument("PreparedStatement", "stat"))
.addContent(new FunctionCall("setLong", "stat")
.addArgument("1")
.addArgument("id")
.byItself());
final FunctionCall dbAccessFunction = new FunctionCall("processQuery", "dbAccess").byItself();
final FunctionDeclaration listGetter =
new FunctionDeclaration("get" + capitalize(listName), new GenericType("List", beanClass))
.addContent(VarDeclaration.createListDeclaration(beanClass, listName).markAsFinal())
.addContent(EMPTY_LINE)
.addContent(dbAccessFunction
.addArgument(new OperatorExpression(quickQuote("SELECT id FROM " + relationship.getTable() + " WHERE " + relationship.getIdSqlName() + "=? ORDER BY "),
new FunctionCall("getOrderByFields", beanClass + "." + Strings.uncamelize(beanClass).toUpperCase() + "_PARAMETERS"),
OperatorExpression.Operator.ADD))
.addArgument(new AnonymousClassCreation("DBQuerySetupProcess").setContext(dbAccessFunction)
.addContent(preparedStatementSetup)
.addContent(EMPTY_LINE)
.addContent(new FunctionDeclaration("processResultSet")
.annotate("@Override")
.addException("SQLException")
.addArgument(new FunctionArgument("ResultSet", "rs"))
.addContent(new WhileBlock(new Condition("rs.next()"))
.addContent(new FunctionCall("add", listName).byItself()
.addArgument(new ObjectCreation(beanClass)
.addArgument(new FunctionCall("getLong", "rs")
.addArgument("1"))))))))
.addContent(EMPTY_LINE)
.addContent(new ReturnStatement(listName));
javaClass.addContent(listGetter).addContent(EMPTY_LINE);
final FunctionCall dbAccessForCountFunction = new FunctionCall("processQuery", "dbAccess");
final FunctionDeclaration countGetter =
new FunctionDeclaration("getCountFor" + capitalize(listName), "long")
.addContent(new ReturnStatement(
dbAccessForCountFunction
.addArgument(quickQuote("SELECT COUNT(id) FROM " + relationship.getTable() + " WHERE " + relationship.getIdSqlName() + "=?"))
.addArgument(new AnonymousClassCreation("DBQuerySetupRetrieveData<Long>").setContext(dbAccessFunction)
.addContent(preparedStatementSetup)
.addContent(new FunctionDeclaration("processResultSet", "Long")
.annotate("@Override")
.addException("SQLException")
.addArgument(new FunctionArgument("ResultSet", "rs"))
.addContent(new FunctionCall("next", "rs").byItself())
.addContent(new ReturnStatement(new FunctionCall("getLong", "rs").addArgument("1")))))
));
javaClass.addContent(countGetter).addContent(EMPTY_LINE);
} else {
importsManager.addImport("java.util.Collections");
javaClass.addContent(
new FunctionDeclaration("add" + beanClass)
.addArgument(new FunctionArgument(beanClass, itemName))
.addContent(new FunctionCall("add", listName).byItself()
.addArgument(itemName))
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("get" + beanClass, beanClass)
.addArgument(new FunctionArgument("int", "index"))
.addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName))
.addContent(EMPTY_LINE)
.addContent(new ReturnStatement(new FunctionCall("get", listName).addArgument("index")))
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("insert" + beanClass)
.addArgument(new FunctionArgument("int", "index"))
.addArgument(new FunctionArgument(beanClass, itemName))
.addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName))
.addContent(EMPTY_LINE)
.addContent(new FunctionCall("add", listName).addArgument("index").addArgument(itemName).byItself())
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("delete" + beanClass)
.addArgument(new FunctionArgument("int", "index"))
.addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName))
.addContent(EMPTY_LINE)
.addContent(new FunctionCall("remove", listName).addArgument("index").byItself())
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("clear" + capitalize(listName))
.addContent(new FunctionCall("clear", listName).byItself())
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("get" + capitalize(listName), new GenericType("List", beanClass))
.addContent(new ReturnStatement(new FunctionCall("unmodifiableList", "Collections").addArgument(listName)))
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("getCountFor" + capitalize(listName), "long")
.addContent(new ReturnStatement(new FunctionCall("size", listName)))
).addContent(EMPTY_LINE);
}
}
}
private IfBlock getOneToManyRelationshipIndexOutOfBoundTest(final String listName) {
return new IfBlock(new Condition(new Comparison("index", "0", Comparison.Comparator.LESS_THAN))
.orCondition(new Condition(new Comparison("index", new FunctionCall("size", listName), Comparison.Comparator.GT_EQUAL))))
.addContent(new ExceptionThrow("IndexOutOfBoundsException")
.addArgument(getOneToManyRelationshipIndexOutOfBoundExceptionText(listName)));
}
private String getOneToManyRelationshipIndexOutOfBoundExceptionText(final String listName) {
return "\"Bounds : 0-\" + " + listName + ".size() + \", index : \" + index";
}
private void addItemOrderManagement() {
if (!columns.hasItemOrder())
return;
final Column itemOrderField = columns.getItemOrderField();
javaClass.addContent(
new FunctionDeclaration("isFirstItemOrder", "boolean").addContent(
checkForItemOrderOperationOnUninitializedBean()
).addContent(EMPTY_LINE).addContent(
new ReturnStatement("itemOrder == 1")
)
).addContent(EMPTY_LINE);
final FunctionDeclaration isLastItemOrderFunction = new FunctionDeclaration("isLastItemOrder", "boolean").addContent(
checkForItemOrderOperationOnUninitializedBean()
).addContent(EMPTY_LINE);
if (!itemOrderField.isUnique())
isLastItemOrderFunction.addContent(
new IfBlock(new Condition(new Comparison(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())), "0"))).addContent(
new ReturnStatement(new Comparison("itemOrder", getMaxItemOrderFunctionCall(itemOrderField, false, true)))
).addContent(EMPTY_LINE)
);
isLastItemOrderFunction.addContent(
new ReturnStatement(new Comparison("itemOrder", getMaxItemOrderFunctionCall(itemOrderField, false, false)))
);
javaClass.addContent(isLastItemOrderFunction).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("itemOrderMoveUp").addContent(
checkForItemOrderOperationOnUninitializedBean()
).addContent(EMPTY_LINE).addContent(
new IfBlock(new Condition(new FunctionCall("isFirstItemOrder"))).addContent(
new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot move Item Order above position 1 which it currently occupies"))
)
).addContent(EMPTY_LINE).addContent(
getItemOrderFunctionCalls("itemOrderMoveUp", itemOrderField)
).addContent(EMPTY_LINE).addContent(
new LineOfCode("itemOrder
)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("itemOrderMoveDown").addContent(
checkForItemOrderOperationOnUninitializedBean()
).addContent(EMPTY_LINE).addContent(
new IfBlock(new Condition(new FunctionCall("isLastItemOrder"))).addContent(
new ExceptionThrow("IllegalArgumentException").addArgument("\"Cannot move Item Order below max position: \" + itemOrder")
)
).addContent(EMPTY_LINE).addContent(
getItemOrderFunctionCalls("itemOrderMoveDown", itemOrderField)
).addContent(EMPTY_LINE).addContent(
new LineOfCode("itemOrder++;")
)
).addContent(EMPTY_LINE);
if (itemOrderField.isUnique()) {
javaClass.addContent(
new FunctionDeclaration("itemOrderMoveAfter")
.addArgument(new FunctionArgument(beanName, beanVarName))
.addContent(
new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD))
.addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar))
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument("itemOrder")
).elseClause(new ElseBlock().addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar))
.addArgument("itemOrder")
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD))
))
)
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("itemOrderMoveBefore")
.addArgument(new FunctionArgument(beanName, beanVarName))
.addContent(
new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar))
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT))
.addArgument("itemOrder")
).elseClause(new ElseBlock().addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT))
.addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar))
.addArgument("itemOrder")
.addArgument(new FunctionCall("getItemOrder", beanVarName))
))
)
).addContent(EMPTY_LINE).addContent(
getBaseItemOrderMoveFunction().addContent(
new FunctionCall("updateItemOrdersInBetween", "DBQueries").addArguments("query", "transaction", "lowerBound", "upperBound").byItself()
).addContent(
getItemOrderCompleteTransactionFunctionCall()
)
).addContent(EMPTY_LINE);
} else {
final String associatedFieldJavaName = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField()));
final String associatedFieldJavaFunction = "get" + camelize(itemOrderField.getItemOrderAssociatedField());
javaClass.addContent(
new FunctionDeclaration("itemOrderMoveAfter").addArgument(new FunctionArgument(beanName, beanVarName)).addContent(
new IfBlock(new Condition(new Comparison(associatedFieldJavaName, new FunctionCall(associatedFieldJavaFunction, beanVarName)))).addContent(
new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent(
new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD))
.addArgument(new FunctionCall("getIncreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar))
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument("itemOrder")
).elseClause(new ElseBlock().addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD))
.addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar))
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument("itemOrder")
.addArgument(associatedFieldJavaName)
))
).elseClause(new ElseBlock().addContent(
new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument(new FunctionCall("getDecreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar))
.addArgument("itemOrder")
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD))
).elseClause(new ElseBlock().addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar))
.addArgument("itemOrder")
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD))
.addArgument(associatedFieldJavaName)
))
))
).elseClause(new ElseBlock().addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD))
.addArgument(beanVarName)
))
)
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("itemOrderMoveBefore").addArgument(new FunctionArgument(beanName, beanVarName)).addContent(
new IfBlock(new Condition(new Comparison(associatedFieldJavaName, new FunctionCall(associatedFieldJavaFunction, beanVarName)))).addContent(
new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent(
new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument(new FunctionCall("getIncreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar))
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT))
.addArgument("itemOrder")
).elseClause(new ElseBlock().addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar))
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT))
.addArgument("itemOrder")
.addArgument(associatedFieldJavaName)
))
).elseClause(new ElseBlock().addContent(
new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT))
.addArgument(new FunctionCall("getDecreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar))
.addArgument("itemOrder")
.addArgument(new FunctionCall("getItemOrder", beanVarName))
).elseClause(new ElseBlock().addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT))
.addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar))
.addArgument("itemOrder")
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument(associatedFieldJavaName)
))
))
).elseClause(new ElseBlock().addContent(
new FunctionCall("itemOrderMove").byItself()
.addArgument(new FunctionCall("getItemOrder", beanVarName))
.addArgument(beanVarName)
))
)
).addContent(EMPTY_LINE).addContent(
getBaseItemOrderMoveFunction().addArgument(new FunctionArgument("long...", "parameters")).addContent(
new FunctionCall("updateItemOrdersInBetween", "DBQueries").addArguments("query", "transaction", "lowerBound", "upperBound", "parameters").byItself()
).addContent(
getItemOrderCompleteTransactionFunctionCall()
)
).addContent(EMPTY_LINE).addContent(
getItemOrderMoveDeclarationStart()
.addArgument(new FunctionArgument("long", "newItemOrder"))
.addArgument(new FunctionArgument(beanName, beanVarName))
.addContent(
new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent(
getItemOrderMoveCall()
.addArgument(new FunctionCall("getPushItemOrdersUpQueryWithNullSecondaryField", parametersVar))
.addArgument("newItemOrder - 1")
.addArgument(new FunctionCall("getPushItemOrdersDownQuery", parametersVar))
.addArgument(beanVarName)
).addElseIfClause(new ElseIfBlock(new Condition(new Comparison(new FunctionCall(associatedFieldJavaFunction, beanVarName), "0"))).addContent(
getItemOrderMoveCall()
.addArgument(new FunctionCall("getPushItemOrdersUpQuery", parametersVar))
.addArgument("newItemOrder - 1")
.addArgument(new FunctionCall("getPushItemOrdersDownQueryWithNullSecondaryField", parametersVar))
.addArgument(beanVarName)
)).elseClause(new ElseBlock().addContent(
getItemOrderMoveCall()
.addArgument(new FunctionCall("getPushItemOrdersUpQuery", parametersVar))
.addArgument("newItemOrder - 1")
.addArgument(new FunctionCall("getPushItemOrdersDownQuery", parametersVar))
.addArgument(beanVarName)
))
)
).addContent(EMPTY_LINE).addContent(
getItemOrderMoveDeclarationStart()
.addArgument(new FunctionArgument("long", "newItemOrder"))
.addArgument(new FunctionArgument("String", "queryDest"))
.addArgument(new FunctionArgument("long", "destLowerBound"))
.addArgument(new FunctionArgument("String", "queryOrig"))
.addArgument(new FunctionArgument(beanName, beanVarName))
.addContent(
new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()
).addContent(
new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent(
getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryDest", "transaction", "destLowerBound")
).elseClause(new ElseBlock().addContent(
getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryDest", "transaction", "destLowerBound", associatedFieldJavaName)
))
).addContent(
new IfBlock(new Condition(new Comparison(new FunctionCall(associatedFieldJavaFunction, beanVarName), "0"))).addContent(
getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryOrig", "transaction", "itemOrder")
).elseClause(new ElseBlock().addContent(
getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryOrig", "transaction", "itemOrder", associatedFieldJavaName)
))
).addContent(
getItemOrderCompleteTransactionFunctionCall()
)
).addContent(EMPTY_LINE).addContent(
new FunctionDeclaration("itemOrderReassociateWith").addArgument(new FunctionArgument("long", associatedFieldJavaName)).addContent(
new IfBlock(new Condition(new Comparison("id", "0"))).addContent(
ExceptionThrow.getThrowExpression("IllegalArgumentException", "Bean must be saved in DB before reassociation.")
)
).addContent(
new IfBlock(new Condition(new Comparison("this." + associatedFieldJavaName, associatedFieldJavaName))).addContent(
ExceptionThrow.getThrowExpression("IllegalArgumentException", "Association already exists.")
)
).addContent(EMPTY_LINE).addContent(
new FunctionCall("itemOrderMove").addArgument(associatedFieldJavaName).byItself()
)
).addContent(EMPTY_LINE).addContent(
getItemOrderMoveDeclarationStart().addArgument(new FunctionArgument("long", associatedFieldJavaName)).addContent(
new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()
).addContent(
new VarDeclaration("long", "newItemOrder")
).addContent(
new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent(
new Assignment("newItemOrder", new OperatorExpression(
new FunctionCall("getMaxItemOrder", "DBQueries")
.addArgument("transaction")
.addArgument(new FunctionCall("getItemOrderMaxQueryWithNullSecondaryField", parametersVar)),
"1",
OperatorExpression.Operator.ADD))
).elseClause(new ElseBlock().addContent(
new Assignment("newItemOrder", new OperatorExpression(
new FunctionCall("getMaxItemOrder", "DBQueries")
.addArgument("transaction")
.addArgument(new FunctionCall("getItemOrderMaxQuery", parametersVar))
.addArgument(associatedFieldJavaName),
"1",
OperatorExpression.Operator.ADD))
))
).addContent(
new IfBlock(new Condition(new Comparison("this." + associatedFieldJavaName, "0"))).addContent(
new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself()
.addArgument(new FunctionCall("getUpdateItemOrdersAboveQueryWithNullSecondaryField", parametersVar))
.addArgument("transaction").addArgument("itemOrder")
).elseClause(new ElseBlock().addContent(
new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself()
.addArgument(new FunctionCall("getUpdateItemOrdersAboveQuery", parametersVar))
.addArgument("transaction").addArgument("itemOrder")
.addArgument("this." + associatedFieldJavaName)
))
).addContent(
new Assignment("this." + associatedFieldJavaName, associatedFieldJavaName)
).addContent(
getItemOrderCompleteTransactionFunctionCall()
)
).addContent(EMPTY_LINE);
}
javaClass.addContent(
new FunctionDeclaration("itemOrderMoveCompleteTransaction").visibility(Visibility.PROTECTED)
.addArgument(new FunctionArgument("long", "newItemOrder"))
.addArgument(new FunctionArgument("DBTransaction", "transaction"))
.addContent(new Assignment("itemOrder", "newItemOrder"))
.addContent(new FunctionCall("updateRecord").addArgument("transaction").byItself())
.addContent(new FunctionCall("commit", "transaction").byItself())
).addContent(EMPTY_LINE);
}
private FunctionDeclaration getItemOrderMoveDeclarationStart() {
return new FunctionDeclaration("itemOrderMove").visibility(Visibility.PROTECTED);
}
private FunctionDeclaration getBaseItemOrderMoveFunction() {
return getItemOrderMoveDeclarationStart()
.addArgument(new FunctionArgument("long", "newItemOrder"))
.addArgument(new FunctionArgument("String", "query"))
.addArgument(new FunctionArgument("long", "lowerBound"))
.addArgument(new FunctionArgument("long", "upperBound"))
.addContent(new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal());
}
private FunctionCall getItemOrderMoveCall() {
return new FunctionCall("itemOrderMove").byItself().addArgument("newItemOrder");
}
private FunctionCall getDBQueriesUpdateItemOrdersAboveCall() {
return new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself();
}
private FunctionCall getItemOrderCompleteTransactionFunctionCall() {
return new FunctionCall("itemOrderMoveCompleteTransaction").addArguments("newItemOrder", "transaction").byItself();
}
private FunctionCall getMaxItemOrderFunctionCall(final Column itemOrderField, final boolean withTransaction, final boolean nullSecondaryVariant) {
final FunctionCall functionCall = new FunctionCall("getMaxItemOrder", "DBQueries");
if (withTransaction)
functionCall.addArgument("transaction");
else
functionCall.addArgument("db");
if (nullSecondaryVariant)
functionCall.addArgument(new FunctionCall("getItemOrderMaxQueryWithNullSecondaryField", parametersVar));
else {
functionCall.addArgument(new FunctionCall("getItemOrderMaxQuery", parametersVar));
if (!itemOrderField.isUnique())
functionCall.addArgument(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())));
}
return functionCall;
}
private JavaCodeBlock getItemOrderFunctionCalls(final String functionName, final Column itemOrderField) {
final FunctionCall itemOrderFunctionCall = getItemOrderFunctionCall(functionName, "getIdFromItemOrderQuery");
if (itemOrderField.isUnique())
return itemOrderFunctionCall;
final String itemOrderAssociatedFieldJavaName = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField()));
itemOrderFunctionCall.addArgument(itemOrderAssociatedFieldJavaName);
final FunctionCall itemOrderFunctionCallNullCase = getItemOrderFunctionCall(functionName, "getIdFromItemOrderQueryWithNullSecondaryField");
return new IfBlock(new Condition(new Comparison(itemOrderAssociatedFieldJavaName, "0", Comparison.Comparator.GREATER_THAN)))
.addContent(itemOrderFunctionCall)
.elseClause(new ElseBlock().addContent(itemOrderFunctionCallNullCase));
}
private FunctionCall getItemOrderFunctionCall(final String functionName, final String parameterFunctionName) {
return new FunctionCall(functionName, "DBQueries")
.addArgument("db")
.addArgument(new FunctionCall(parameterFunctionName, parametersVar))
.addArgument(quickQuote(tableName))
.addArgument("id")
.addArgument("itemOrder")
.byItself();
}
private IfBlock checkForItemOrderOperationOnUninitializedBean() {
return new IfBlock(new Condition("id == 0")).addContent(
new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Item Order operations not allowed on beans that have not been saved to the database"))
);
}
private static FunctionCall getPreUpdateConversionCall() {
return new FunctionCall("preUpdateConversions").byItself();
}
private void addUpdateDB() {
if (columns.hasLastUpdate())
javaClass.addContent(
new FunctionDeclaration("isUpdateOK", "boolean").addContent(
new ReturnStatement("updateOK")
)
).addContent(EMPTY_LINE);
final FunctionDeclaration updateDBFunction = new FunctionDeclaration("updateDB");
if (columns.hasModifiedBy())
updateDBFunction.addArgument(new FunctionArgument("String", "username"));
updateDBFunction.addContent(
getPreUpdateConversionCall()
).addContent(EMPTY_LINE);
final FunctionCall createRecordCall = new FunctionCall("createRecord").byItself();
if (columns.hasModifiedBy())
createRecordCall.addArgument("username");
updateDBFunction.addContent(
new IfBlock(new Condition("id == 0")).addContent(createRecordCall).addContent(new ReturnStatement())
).addContent(EMPTY_LINE);
final FunctionCall updateRecordCall = new FunctionCall("updateRecord").byItself();
if (columns.hasModifiedBy())
updateRecordCall.addArgument("username");
updateDBFunction.addContent(
new IfBlock(new Condition("id > 0")).addContent(updateRecordCall).addContent(new ReturnStatement())
).addContent(EMPTY_LINE);
updateDBFunction.addContent(
new LineOfCode("assert (false) : \"id < 0 ?!?\";")
);
javaClass.addContent(updateDBFunction).addContent(EMPTY_LINE);
final FunctionDeclaration updateDBFunctionWithTransaction = new FunctionDeclaration("updateDB", "long").addArgument(new FunctionArgument("DBTransaction", "transaction"));
if (columns.hasModifiedBy())
updateDBFunctionWithTransaction.addArgument(new FunctionArgument("String", "username"));
updateDBFunctionWithTransaction.addContent(
getPreUpdateConversionCall()
).addContent(EMPTY_LINE);
final FunctionCall createRecordCallWithTransaction = new FunctionCall("createRecord").addArgument("transaction");
if (columns.hasModifiedBy())
createRecordCallWithTransaction.addArgument("username");
updateDBFunctionWithTransaction.addContent(
new IfBlock(new Condition("id == 0")).addContent(new Assignment("id", createRecordCallWithTransaction)).addContent(new ReturnStatement("id"))
).addContent(EMPTY_LINE);
final FunctionCall updateRecordCallWithTransaction = new FunctionCall("updateRecord").addArgument("transaction").byItself();
if (columns.hasModifiedBy())
updateRecordCallWithTransaction.addArgument("username");
updateDBFunctionWithTransaction.addContent(
new IfBlock(new Condition("id > 0")).addContent(updateRecordCallWithTransaction).addContent(new ReturnStatement("id"))
).addContent(EMPTY_LINE);
updateDBFunctionWithTransaction.addContent(
new LineOfCode("assert (false) : \"id < 0 ?!?\";")
).addContent(
new ReturnStatement("-1")
);
javaClass.addContent(updateDBFunctionWithTransaction).addContent(EMPTY_LINE);
final FunctionDeclaration preUpdateConversionsFunction = new FunctionDeclaration("preUpdateConversions");
preUpdateConversionsFunction.addContent(
ifNotDataOK().addContent(
ExceptionThrow.getThrowExpression("IllegalArgumentException", "BAD DATA")
)
).addContent(EMPTY_LINE);
for (Column column: columns.getList()) {
if (!column.isSpecial()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if ((type.equals("int") || type.equals("long")) && !field.startsWith("id"))
preUpdateConversionsFunction.addContent(
new Assignment(field,
new FunctionCall("Strings.get" + capitalize(type) + "Val").addArgument(field + "Str"))
);
if (JAVA_TEMPORAL_TYPES.contains(type))
preUpdateConversionsFunction.addContent(
new IfBlock(new Condition(new FunctionCall("isEmpty", "Strings").addArgument(field + "Str"), true)).addContent(
new Assignment(field, new FunctionCall("convertStringTo" + type).addArgument(field + "Str"))
).elseClause(new ElseBlock().addContent(
new Assignment(field, "null")
))
);
if (type.equals("Money"))
preUpdateConversionsFunction.addContent(
new Assignment(field, new ObjectCreation("Money").addArgument(field + "Str").addArgument(new FunctionCall("getDefaultMoneyFormat")))
);
}
}
javaClass.addContent(preUpdateConversionsFunction).addContent(EMPTY_LINE);
}
private void addDataOK() {
final FunctionDeclaration dataOKFunction = new FunctionDeclaration("isDataOK", "boolean").addContent(
new FunctionCall("clearErrorMessages", internalsVar).byItself()
).addContent(
new VarDeclaration("boolean", "ok", "true")
).addContent(EMPTY_LINE);
for (Column column: columns.getList()) {
if (!column.isSpecial() && !column.getJavaType().equals("boolean")) {
final String field = column.getJavaName();
final String fieldCap = capitalize(field);
final IfBlock checkRequired = new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Required"))).addContent(
new FunctionCall("addErrorMessage", internalsVar).byItself()
.addArgument("id")
.addArgument(quickQuote(field))
.addArgument(new FunctionCall("get" + fieldCap + "Label"))
.addArgument(new FunctionCall("get" + fieldCap + "EmptyErrorMessage"))
).addContent(new Assignment("ok", "false"));
final IfBlock checkOKAndUnique = new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "OK"), true)).addContent(
new FunctionCall("addErrorMessage", internalsVar).byItself()
.addArgument("id")
.addArgument(quickQuote(field))
.addArgument(new FunctionCall("get" + fieldCap + "Label"))
.addArgument(new FunctionCall("get" + fieldCap + "BadFormatErrorMessage"))
).addContent(new Assignment("ok", "false"));
if (column.isUnique())
checkOKAndUnique.elseClause(new ElseBlock().addContent(
new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Unique"), true)).addContent(
new FunctionCall("addErrorMessage", internalsVar).byItself()
.addArgument("id")
.addArgument(quickQuote(field))
.addArgument(new FunctionCall("get" + fieldCap + "Label"))
.addArgument(new FunctionCall("get" + fieldCap + "NotUniqueErrorMessage"))
).addContent(new Assignment("ok", "false"))
));
dataOKFunction.addContent(
new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Empty"))).addContent(checkRequired)
.elseClause(new ElseBlock().addContent(checkOKAndUnique))
).addContent(EMPTY_LINE);
}
}
dataOKFunction.addContent(
new ReturnStatement("ok")
);
javaClass.addContent(dataOKFunction).addContent(EMPTY_LINE);
for (Column column: columns.getList()) {
if (!column.isSpecial() && !column.getJavaType().equals("boolean")) {
final String type = column.getJavaType();
final String field = column.getJavaName();
final String fieldCap = capitalize(field);
final ReturnStatement returnStatement;
if ((type.equals("int") || type.equals("long")) && field.startsWith("id"))
returnStatement = new ReturnStatement(new Comparison(field, "0", Comparison.Comparator.EQUAL));
else {
final String arg;
if (type.equals("String"))
arg = field;
else
arg = field + "Str";
returnStatement = new ReturnStatement(new FunctionCall("isEmpty", "Strings").addArgument(arg));
}
javaClass.addContent(
new FunctionDeclaration("is" + fieldCap + "Empty", "boolean").addContent(returnStatement)
).addContent(EMPTY_LINE);
}
}
for (Column column: columns.getList()) {
if (!column.isSpecial() && !column.getJavaType().equals("boolean")) {
final String field = column.getJavaName();
final String fieldCap = capitalize(field);
javaClass.addContent(
new FunctionDeclaration("get" + fieldCap + "EmptyErrorMessage", "String").addContent(
new ReturnStatement(new FunctionCall("getRequiredErrorMessage", internalsVar).addArgument(quickQuote(field)))
)
).addContent(EMPTY_LINE);
}
}
for (Column column: columns.getList()) {
if (!column.isSpecial() && !column.getJavaType().equals("boolean")) {
final String type = column.getJavaType();
final String field = column.getJavaName();
final String fieldCap = capitalize(field);
final FunctionDeclaration isOKFunction = new FunctionDeclaration("is" + fieldCap + "OK", "boolean");
if ((type.equals("int") || type.equals("long"))) {
if (field.startsWith("id"))
isOKFunction.addContent(new ReturnStatement(new FunctionCall("isIdOK", column.getAssociatedBeanClass()).addArgument(field)));
else {
importsManager.addImport("org.beanmaker.util.FormatCheckHelper");
isOKFunction.addContent(new ReturnStatement(new FunctionCall("isNumber", "FormatCheckHelper").addArgument(field + "Str")));
}
}
else if (JAVA_TEMPORAL_TYPES.contains(type)) {
isOKFunction.addContent(new ReturnStatement(new FunctionCall("validate" + type + "Format").addArgument(field + "Str")));
}
else if (type.equals("String")) {
if (field.equalsIgnoreCase("email") || field.equalsIgnoreCase("e-mail")) {
importsManager.addImport("org.beanmaker.util.FormatCheckHelper");
isOKFunction.addContent(new ReturnStatement(new FunctionCall("isEmailValid", "FormatCheckHelper").addArgument(field)));
} else
isOKFunction.addContent(new ReturnStatement("true"));
}
else if (type.equals("Money")) {
isOKFunction.addContent(new ReturnStatement(new FunctionCall("isValOK", "getDefaultMoneyFormat()").addArgument(field + "Str")));
}
else
throw new IllegalStateException("Apparently unsupported type " + type + " encountered.");
javaClass.addContent(isOKFunction).addContent(EMPTY_LINE);
}
}
for (Column column: columns.getList()) {
if (!column.isSpecial() && !column.getJavaType().equals("boolean")) {
final String field = column.getJavaName();
final String fieldCap = capitalize(field);
javaClass.addContent(
new FunctionDeclaration("get" + fieldCap + "BadFormatErrorMessage", "String").addContent(
new ReturnStatement(new FunctionCall("getBadFormatErrorMessage", internalsVar).addArgument(quickQuote(field)))
)
).addContent(EMPTY_LINE);
}
}
for (Column column: columns.getList()) {
if (!column.isSpecial() && column.isUnique()) {
importsManager.addImport("org.dbbeans.sql.queries.BooleanCheckQuery");
final FunctionCall dbAccessFunctionCall = new FunctionCall("processQuery", "!dbAccess");
javaClass.addContent(
new FunctionDeclaration("is" + capitalize(column.getJavaName() + "Unique"), "boolean").addContent( // TODO: IMPLEMENT!!!
new ReturnStatement(
dbAccessFunctionCall
.addArgument(Strings.quickQuote(getNotUniqueQuery(column)))
.addArgument(new AnonymousClassCreation("BooleanCheckQuery").setContext(dbAccessFunctionCall, 1).addContent(
new FunctionDeclaration("setupPreparedStatement")
.addArgument(new FunctionArgument("PreparedStatement", "stat"))
.annotate("@Override").addException("SQLException").addContent(
new FunctionCall("set" + capitalize(column.getJavaType()), "stat")
.addArgument("1").addArgument(column.getJavaName()).byItself()
).addContent(
new FunctionCall("setLong", "stat")
.addArguments("2", "id").byItself()
)
))
)
)
).addContent(EMPTY_LINE);
}
}
for (Column column: columns.getList()) {
if (!column.isSpecial() && column.isUnique()) {
final String field = column.getJavaName();
final String fieldCap = capitalize(field);
javaClass.addContent(
new FunctionDeclaration("get" + fieldCap + "NotUniqueErrorMessage", "String").addContent(
new ReturnStatement(new FunctionCall("getNotUniqueErrorMessage", internalsVar).addArgument(quickQuote(field)))
)
).addContent(EMPTY_LINE);
}
}
javaClass.addContent(
new FunctionDeclaration("getErrorMessages", "List<ErrorMessage>").addContent(
new ReturnStatement(new FunctionCall("getErrorMessages", internalsVar))
)
).addContent(EMPTY_LINE);
}
private String getNotUniqueQuery(final Column column) {
return "SELECT id FROM " + tableName + " WHERE " + column.getSqlName() + "=? AND id <> ?";
}
private void addReset() {
final FunctionDeclaration resetFunction = new FunctionDeclaration("reset");
for (Column column: columns.getList()) {
if (!column.isSpecial()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if (type.equals("boolean"))
resetFunction.addContent(new Assignment(field, "false"));
else if (type.equals("int") || type.equals("long"))
resetFunction.addContent(new Assignment(field, "0"));
else if (type.equals("String"))
resetFunction.addContent(new Assignment(field, EMPTY_STRING));
else if (type.equals("Money"))
resetFunction.addContent(new Assignment(field, new ObjectCreation("Money").addArgument("0").addArgument(new FunctionCall("getDefaultMoneyFormat"))));
else
resetFunction.addContent(new Assignment(field, "null"));
if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("int")) && !field.startsWith("id")))
resetFunction.addContent(new Assignment(field + "Str", EMPTY_STRING));
}
}
for (OneToManyRelationship relationship: columns.getOneToManyRelationships())
if (!relationship.isListOnly())
resetFunction.addContent(new FunctionCall("clear", relationship.getJavaName()).byItself());
resetFunction.addContent(new FunctionCall("clearErrorMessages", internalsVar).byItself());
javaClass.addContent(resetFunction).addContent(EMPTY_LINE);
final FunctionDeclaration fullResetFunction = new FunctionDeclaration("fullReset").addContent(
new FunctionCall("reset").byItself()
).addContent(
new Assignment("id", "0")
);
for (Column column: columns.getList()) {
if (column.isLastUpdate())
fullResetFunction.addContent(new Assignment("lastUpdate", "0"));
if (column.isModifiedBy())
fullResetFunction.addContent(new Assignment("modifiedBy", "null"));
if (column.isItemOrder())
fullResetFunction.addContent(new Assignment("itemOrder", "0"));
}
javaClass.addContent(fullResetFunction).addContent(EMPTY_LINE);
}
private void addDelete() {
final FunctionDeclaration deleteFunction = new FunctionDeclaration("delete");
final FunctionCall accessDB = new FunctionCall("addUpdate", "transaction").byItself();
deleteFunction.addContent(
new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()
);
if (columns.hasItemOrder())
deleteFunction.addContent(
new VarDeclaration("long", "curItemOrder").markAsFinal()
).addContent(
new IfBlock(new Condition(new FunctionCall("isLastItemOrder"))).addContent(
new Assignment("curItemOrder", "0")
).elseClause(new ElseBlock().addContent(
new Assignment("curItemOrder", "itemOrder")
))
);
deleteFunction.addContent(
accessDB.addArgument(quickQuote(getDeleteSQLQuery()))
.addArgument(new AnonymousClassCreation("DBQuerySetup").setContext(accessDB).addContent(
new FunctionDeclaration("setupPreparedStatement").annotate("@Override").addException("SQLException")
.addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent(
new FunctionCall("setLong", "stat").addArguments("1", "id").byItself()
)
))
);
if (columns.hasItemOrder()) {
final IfBlock checkItemOrderNotMax = new IfBlock(new Condition(new Comparison("curItemOrder", "0", Comparison.Comparator.GREATER_THAN)));
final Column itemOrderField = columns.getItemOrderField();
if (itemOrderField.isUnique())
checkItemOrderNotMax.addContent(
getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQuery", null)
);
else {
final String itemOrderAssociatedField = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField()));
checkItemOrderNotMax.addContent(
new IfBlock(new Condition(new Comparison(itemOrderAssociatedField, "0"))).addContent(
getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQueryWithNullSecondaryField", null)
).elseClause(new ElseBlock().addContent(
getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQuery", itemOrderAssociatedField)
)));
}
deleteFunction.addContent(checkItemOrderNotMax);
}
deleteFunction.addContent(
new FunctionCall("deleteExtraDbActions").byItself().addArgument("transaction")
).addContent(
new FunctionCall("commit", "transaction").byItself()
).addContent(
EMPTY_LINE
).addContent(
new FunctionCall("postDeleteActions").byItself()
).addContent(
new FunctionCall("fullReset").byItself()
);
javaClass.addContent(deleteFunction).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("deleteExtraDbActions").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("DBTransaction", "transaction"))
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("postDeleteActions").visibility(Visibility.PROTECTED)
).addContent(EMPTY_LINE);
}
private FunctionCall getUpdateItemOrderAboveFunctionCall(final String queryRetrievalFunction, final String itemOrderAssociatedField) {
final FunctionCall functionCall = new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself()
.addArgument(new FunctionCall(queryRetrievalFunction, parametersVar))
.addArgument("transaction")
.addArgument("curItemOrder");
if (itemOrderAssociatedField != null)
functionCall.addArgument(itemOrderAssociatedField);
return functionCall;
}
private FunctionCall getStatSetFunction(final String type, final String field, final int index) {
return new FunctionCall("set" + capitalize(type), "stat").byItself().addArguments(Integer.toString(index), field);
}
private JavaCodeBlock getFieldCreationOrUpdate(final Column column, final int index) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if (column.isRequired())
return getStatSetFunction(type, field, index);
if (column.hasAssociatedBean())
return new IfBlock(new Condition(new Comparison(field, "0"))).addContent(
new FunctionCall("setNull", "stat").byItself().addArguments(Integer.toString(index), "java.sql.Types.INTEGER")
).elseClause(new ElseBlock().addContent(
getStatSetFunction(type, field, index)
));
if (JAVA_TEMPORAL_TYPES.contains(type))
return new IfBlock(new Condition(new Comparison(field, "null"))).addContent(
new FunctionCall("setNull", "stat").byItself().addArguments(Integer.toString(index), "java.sql.Types." + type.toUpperCase())
).elseClause(new ElseBlock().addContent(
getStatSetFunction(type, field, index)
));
return getStatSetFunction(type, field, index);
}
private void addCreate() {
int index = 0;
final JavaClass recordCreationSetupClass = new JavaClass("RecordCreationSetup").implementsInterface("DBQuerySetup").visibility(Visibility.PRIVATE);
final FunctionDeclaration setupStatFunction = new FunctionDeclaration("setupPreparedStatement").annotate("@Override")
.addException("SQLException").addArgument(new FunctionArgument("PreparedStatement", "stat"));
for (Column column: columns.getList()) {
final String type = column.getJavaType();
final String field = column.getJavaName();
if (!column.isId()) {
if (type.equals("Money")) {
final String suggestedType = Column.getSuggestedType(column.getSqlTypeName(), column.getPrecision());
if (suggestedType.equals("int"))
setupStatFunction.addContent(
new FunctionCall("setInt", "stat").byItself().addArgument(Integer.toString(++index)).addArgument(new FunctionCall("getIntVal", field))
);
else if (suggestedType.equals("long"))
setupStatFunction.addContent(
new FunctionCall("setLong", "stat").byItself().addArgument(Integer.toString(++index)).addArgument(new FunctionCall("getVal", field))
);
else
throw new IllegalStateException("Money cannot be used with non INTEGER SQL field: " + column.getSqlName());
} else {
setupStatFunction.addContent(
getFieldCreationOrUpdate(column, ++index)
);
}
}
}
javaClass.addContent(recordCreationSetupClass.addContent(setupStatFunction)).addContent(EMPTY_LINE);
javaClass.addContent(
new JavaClass("RecordUpdateSetup").extendsClass("RecordCreationSetup").visibility(Visibility.PRIVATE).addContent(
new FunctionDeclaration("setupPreparedStatement").annotate("@Override")
.addException("SQLException").addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent(
new FunctionCall("setupPreparedStatement", "super").byItself().addArgument("stat")
).addContent(
new FunctionCall("setLong", "stat").byItself().addArguments(Integer.toString(++index), "id")
)
)
).addContent(EMPTY_LINE);
final FunctionDeclaration createRecordFunction = new FunctionDeclaration("createRecord").visibility(Visibility.PRIVATE).addContent(
new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()).addContent(
new VarDeclaration("long", "id", new FunctionCall("createRecord").addArgument("transaction")).markAsFinal());
addOneToManyRelationshipDBUpdateFunctionCalls(createRecordFunction);
createRecordFunction.addContent(
new FunctionCall("createExtraDbActions").byItself().addArguments("transaction", "id")
).addContent(
new FunctionCall("commit", "transaction").byItself()
).addContent(EMPTY_LINE).addContent(
new Assignment("this.id", "id")
).addContent(
new FunctionCall("postCreateActions").byItself()
);
javaClass.addContent(createRecordFunction).addContent(EMPTY_LINE);
final FunctionDeclaration createRecordFunctionWithTransaction =
new FunctionDeclaration("createRecord", "long").addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PRIVATE);
if (columns.hasItemOrder()) {
final Column itemOrderField = columns.getItemOrderField();
final IfBlock uninitializedItemOrderCase = new IfBlock(new Condition(new Comparison("itemOrder", "0")));
if (itemOrderField.isUnique())
uninitializedItemOrderCase.addContent(
new Assignment("itemOrder",
new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, false), "1", OperatorExpression.Operator.ADD))
);
else {
uninitializedItemOrderCase.addContent(
new IfBlock(new Condition(new Comparison(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())), "0"))).addContent(
new Assignment("itemOrder",
new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, true), "1", OperatorExpression.Operator.ADD))
).elseClause(new ElseBlock().addContent(
new Assignment("itemOrder",
new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, false), "1", OperatorExpression.Operator.ADD))
))
);
}
createRecordFunctionWithTransaction.addContent(uninitializedItemOrderCase).addContent(EMPTY_LINE);
}
createRecordFunctionWithTransaction.addContent(
new ReturnStatement(new FunctionCall("addRecordCreation", "transaction")
.addArgument(quickQuote(getInsertSQLQuery()))
.addArgument(new ObjectCreation("RecordCreationSetup")))
);
javaClass.addContent(createRecordFunctionWithTransaction).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("createExtraDbActions")
.addArgument(new FunctionArgument("DBTransaction", "transaction"))
.addArgument(new FunctionArgument("long", "id")).visibility(Visibility.PROTECTED)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("postCreateActions").visibility(Visibility.PROTECTED)
).addContent(EMPTY_LINE);
}
private void addOneToManyRelationshipDBUpdateFunctionCalls(final FunctionDeclaration function) {
for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) {
if (!relationship.isListOnly())
function.addContent(
new FunctionCall("update" + capitalize(relationship.getJavaName()) + "InDB").byItself().addArguments("transaction", "id")
);
}
}
private void addUpdate() {
final FunctionDeclaration updateRecordFunction = new FunctionDeclaration("updateRecord").visibility(Visibility.PRIVATE).addContent(
new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()
).addContent(
new FunctionCall("updateRecord").byItself().addArgument("transaction")
);
addOneToManyRelationshipDBUpdateFunctionCalls(updateRecordFunction);
updateRecordFunction.addContent(
new FunctionCall("updateExtraDbActions").byItself().addArgument("transaction")
).addContent(
new FunctionCall("commit", "transaction").byItself()
).addContent(
new FunctionCall("postUpdateActions").byItself()
);
javaClass.addContent(updateRecordFunction).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("updateRecord").addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PRIVATE).addContent(
new FunctionCall("addUpdate", "transaction").byItself()
.addArgument(quickQuote(getUpdateSQLQuery()))
.addArgument(new ObjectCreation("RecordUpdateSetup"))
)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("updateExtraDbActions").visibility(Visibility.PROTECTED)
.addArgument(new FunctionArgument("DBTransaction", "transaction"))
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("postUpdateActions").visibility(Visibility.PROTECTED)
).addContent(EMPTY_LINE);
}
private void addOneToManyRelationshipInDB() {
for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) {
if (!relationship.isListOnly()) {
final FunctionDeclaration updateRelationshipFunction = new FunctionDeclaration("update" + capitalize(relationship.getJavaName()) + "InDB")
.addArgument(new FunctionArgument("DBTransaction", "transaction"))
.addArgument(new FunctionArgument("long", "id"))
.visibility(Visibility.PRIVATE);
final FunctionCall dbAccessFunction = new FunctionCall("addUpdate", "transaction").byItself();
updateRelationshipFunction.addContent(
dbAccessFunction
.addArgument(quickQuote(getDeleteOneToManyRelationshipQuery(relationship.getTable(), relationship.getIdSqlName())))
.addArgument(new AnonymousClassCreation("DBQuerySetup").setContext(dbAccessFunction).addContent(
new FunctionDeclaration("setupPreparedStatement").annotate("@Override").addException("SQLException")
.addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent(
new FunctionCall("setLong", "stat").byItself().addArguments("1", "id")
)
))
).addContent(EMPTY_LINE);
final String var = uncapitalize(relationship.getBeanClass());
updateRelationshipFunction.addContent(
new ForLoop(relationship.getBeanClass() + " " + var + ": " + relationship.getJavaName()).addContent(
new FunctionCall("resetId", var).byItself()
).addContent(
new FunctionCall("setId" + beanName, var).addArgument("id").byItself()
).addContent(
new FunctionCall("updateDB", var).addArgument("transaction").byItself()
)
);
javaClass.addContent(updateRelationshipFunction).addContent(EMPTY_LINE);
}
}
}
private void addTemporalFunctions() {
if (types.contains("Date")) {
javaClass.addContent(
new FunctionDeclaration("formatDate", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Date", "date")).addContent(
new ReturnStatement(
new FunctionCall(
"format",
new FunctionCall(
"getDateInstance",
"DateFormat").addArgument("DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar))
).addArgument("date")
)
)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("convertStringToDate", "Date").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent(
new ReturnStatement(
new FunctionCall("getDateFromYYMD", "Dates").addArguments("str", quickQuote("-"))
)
)
).addContent(EMPTY_LINE);
javaClass.addContent(getTemporalConvertToStringFunction("Date", "date")).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("validateDateFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent(
new VarDeclaration(
"SimpleInputDateFormat", "simpleInputDateFormat",
new ObjectCreation("SimpleInputDateFormat")
.addArguments("SimpleInputDateFormat.ElementOrder.YYMD", quickQuote("-"))
).markAsFinal()
).addContent(
new ReturnStatement(
new FunctionCall(
"validate",
"simpleInputDateFormat"
).addArgument("str")
)
)
).addContent(EMPTY_LINE);
}
if (types.contains("Time")) {
javaClass.addContent(
new FunctionDeclaration("formatTime", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Time", "time")).addContent(
new ReturnStatement(
new FunctionCall(
"format",
new FunctionCall(
"getTimeInstance",
"DateFormat").addArgument("DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar))
).addArgument("time")
)
)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("convertStringToTime", "Time").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent(
new ReturnStatement(
new FunctionCall("getTimeFromString", "Dates").addArguments("str", quickQuote(":"))
)
)
).addContent(EMPTY_LINE);
javaClass.addContent(getTemporalConvertToStringFunction("Time", "time")).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("validateTimeFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent(
new VarDeclaration(
"SimpleInputTimeFormat", "simpleInputTimeFormat",
new ObjectCreation("SimpleInputTimeFormat").addArgument(quickQuote(":"))
).markAsFinal()
).addContent(
new ReturnStatement(
new FunctionCall(
"validate",
"simpleInputTimeFormat"
).addArgument("str")
)
)
).addContent(EMPTY_LINE);
}
if (types.contains("Timestamp")) {
javaClass.addContent(
new FunctionDeclaration("formatTimestamp", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Timestamp", "timestamp")).addContent(
new ReturnStatement(
new FunctionCall(
"format",
new FunctionCall(
"getDateTimeInstance",
"DateFormat").addArguments("DateFormat.LONG", "DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar))
).addArgument("timestamp")
)
)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("convertStringToTimestamp", "Timestamp").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent(
new ReturnStatement(
new FunctionCall("getTimestampFromYYMD", "Dates").addArguments("str", quickQuote("-"), quickQuote(":"))
)
)
).addContent(EMPTY_LINE);
javaClass.addContent(getTemporalConvertToStringFunction("Timestamp", "timestamp")).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("validateTimestampFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent(
new VarDeclaration(
"SimpleInputTimestampFormat", "simpleInputTimestampFormat",
new ObjectCreation("SimpleInputTimestampFormat")
.addArguments("SimpleInputDateFormat.ElementOrder.YYMD", quickQuote("-"), quickQuote(":"))
).markAsFinal()
).addContent(
new ReturnStatement(
new FunctionCall(
"validate",
"simpleInputTimestampFormat"
).addArgument("str")
)
)
).addContent(EMPTY_LINE);
}
}
private void addGetAll() {
javaClass.addContent(
new FunctionDeclaration("getAll", "List<" + beanName + ">").markAsStatic().addContent(
new ReturnStatement(new FunctionCall("getAll").addArgument(new FunctionCall("getOrderByFields", parametersVar)))
)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("getAll", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED)
.addArgument(new FunctionArgument("String", "orderBy")).addContent(
new ReturnStatement(new FunctionCall("getSelection").addArguments("null", "orderBy", "null"))
)
).addContent(EMPTY_LINE);
final ObjectCreation newBeanFromFields = new ObjectCreation(beanName);
int index = 0;
for (Column column: columns.getList()) {
final String javaType = column.getJavaType();
if (javaType.equals("Money"))
throw new UnsupportedOperationException("Money not supported for now."); // for now...
++index;
newBeanFromFields.addArgument(new FunctionCall("get" + capitalize(javaType), "rs").addArguments(Integer.toString(index)));
}
for (OneToManyRelationship relationship: columns.getOneToManyRelationships())
if (!relationship.isListOnly())
newBeanFromFields.addArgument(new FunctionCall("getSelection", relationship.getBeanClass())
.addArgument(new OperatorExpression("\"id_" + uncamelize(beanVarName) + "=\"", new FunctionCall("getLong", "rs").addArgument("1"), OperatorExpression.Operator.ADD)));
javaClass.addContent(
new JavaClass("GetSelectionQueryProcess").implementsInterface("DBQueryRetrieveData<List<" + beanName + ">>").visibility(Visibility.PRIVATE).markAsStatic().addContent(
new FunctionDeclaration("processResultSet", "List<" + beanName + ">").annotate("@Override").addException("SQLException")
.addArgument(new FunctionArgument("ResultSet", "rs")).addContent(
VarDeclaration.createListDeclaration(beanName, "list").markAsFinal()
).addContent(EMPTY_LINE).addContent(
new WhileBlock(new Condition(new FunctionCall("next", "rs"))).addContent(
new FunctionCall("add", "list").byItself().addArgument(newBeanFromFields)
)
).addContent(EMPTY_LINE).addContent(
new ReturnStatement("list")
)
)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED)
.addArgument(new FunctionArgument("String", "whereClause")).addContent(
new ReturnStatement(new FunctionCall("getSelection").addArguments("whereClause", "null"))
)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED)
.addArgument(new FunctionArgument("String", "whereClause"))
.addArgument(new FunctionArgument("DBQuerySetup", "setup")).addContent(
new ReturnStatement(new FunctionCall("getSelection")
.addArgument("whereClause")
.addArguments(new FunctionCall("getOrderByFields", parametersVar))
.addArgument("setup"))
)
).addContent(EMPTY_LINE);
javaClass.addContent(
new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED)
.addArgument(new FunctionArgument("String", "whereClause"))
.addArgument(new FunctionArgument("String", "orderBy"))
.addArgument(new FunctionArgument("DBQuerySetup", "setup")).addContent(
new IfBlock(new Condition(new Comparison("whereClause", "null"))
.andCondition(new Condition(new Comparison("setup", "null", Comparison.Comparator.NEQ)))).addContent(
new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot accept setup code without a WHERE clause."))
)
).addContent(EMPTY_LINE).addContent(
new VarDeclaration("StringBuilder", "query", new ObjectCreation("StringBuilder")).markAsFinal()
).addContent(
new FunctionCall("append", "query").addArgument(quickQuote(getAllFieldsQuery())).byItself()
).addContent(
new IfBlock(new Condition(new Comparison("whereClause", "null", Comparison.Comparator.NEQ))).addContent(
new FunctionCall("append", new FunctionCall("append", "query").addArgument(quickQuote(" WHERE "))).addArgument("whereClause").byItself()
)
).addContent(
new IfBlock(new Condition(new Comparison("orderBy", "null", Comparison.Comparator.NEQ))).addContent(
new FunctionCall("append", new FunctionCall("append", "query").addArgument(quickQuote(" ORDER BY "))).addArgument("orderBy").byItself()
)
).addContent(EMPTY_LINE).addContent(
new IfBlock(new Condition(new Comparison("whereClause", "null"))
.orCondition(new Condition(new Comparison("setup", "null")))).addContent(
new ReturnStatement(new FunctionCall("processQuery", "dbAccess")
.addArgument(new FunctionCall("toString", "query"))
.addArgument(new ObjectCreation("GetSelectionQueryProcess")))
)
).addContent(EMPTY_LINE).addContent(
new ReturnStatement(new FunctionCall("processQuery", "dbAccess")
.addArgument(new FunctionCall("toString", "query"))
.addArgument("setup")
.addArgument(new ObjectCreation("GetSelectionQueryProcess")))
)
).addContent(EMPTY_LINE);
}
private void addGetIdNamePairs() {
javaClass.addContent(
new FunctionDeclaration("getIdNamePairs", "List<IdNamePair>").visibility(Visibility.PROTECTED).markAsStatic().addArguments(
new FunctionArgument("String", "whereClause"),
new FunctionArgument("List<String>", "dataFields"),
new FunctionArgument("List<String>", "orderingFields")
).addContent(
new ReturnStatement(
new FunctionCall("getIdNamePairs", "DBQueries").addArguments("db", quickQuote(tableName), "whereClause", "dataFields", "orderingFields")
)
)
).addContent(EMPTY_LINE);
}
private void addGetCount() {
javaClass.addContent(
new FunctionDeclaration("getCount", "long").markAsStatic().addContent(
new ReturnStatement(new FunctionCall("getLongCount", "DBQueries").addArguments("db", quickQuote(tableName)))
)
).addContent(EMPTY_LINE);
}
private void addIdOK() {
javaClass.addContent(
new FunctionDeclaration("isIdOK", "boolean").markAsStatic().addArgument(new FunctionArgument("long", "id")).addContent(
new ReturnStatement(new FunctionCall("isIdOK", "DBQueries").addArguments("db", quickQuote(tableName), "id"))
)
).addContent(EMPTY_LINE);
}
private void addHumanReadableTitle() {
javaClass.addContent(
new FunctionDeclaration("getHumanReadableTitle", "String").markAsStatic().addArgument(new FunctionArgument("long", "id")).addContent(
new ReturnStatement(new FunctionCall("getHumanReadableTitle", "DBQueries")
.addArguments("db", quickQuote(tableName), "id")
.addArgument(new FunctionCall("getNamingFields", parametersVar)))
)
).addContent(EMPTY_LINE);
}
private void addSetLocale() {
javaClass.addContent(
new FunctionDeclaration("setLocale").addArgument(new FunctionArgument("Locale", "locale")).addContent(
new FunctionCall("setLocale", internalsVar).addArgument("locale").byItself()
)
).addContent(EMPTY_LINE);
}
private void createSourceCode() {
sourceFile.setStartComment(SourceFiles.getCommentAndVersion());
addImports();
addClassModifiers();
addProperties();
addConstructors();
addSetIdFunction();
addEquals();
addToString();
addSetters();
addGetters();
addLabelGetters();
addRequiredIndicators();
addUniqueIndicators();
addOneToManyRelationshipManagement();
addItemOrderManagement();
addUpdateDB();
addDataOK();
addReset();
addDelete();
addCreate();
addUpdate();
addOneToManyRelationshipInDB();
addTemporalFunctions();
addGetAll();
addGetIdNamePairs();
addGetCount();
addIdOK();
addHumanReadableTitle();
addSetLocale();
}
private String getReadSQLQuery() {
StringBuilder buf = new StringBuilder();
buf.append("SELECT ");
for (Column column: columns.getList()) {
final String name = column.getSqlName();
if (!name.equals("id")) {
buf.append(name);
buf.append(", ");
}
}
buf.delete(buf.length() - 2, buf.length());
buf.append(" FROM ");
buf.append(tableName);
buf.append(" WHERE id=?");
return buf.toString();
}
private String getAllFieldsQuery() {
StringBuilder buf = new StringBuilder();
buf.append("SELECT ");
for (Column column: columns.getList()) {
final String name = column.getSqlName();
buf.append(name);
buf.append(", ");
}
buf.delete(buf.length() - 2, buf.length());
buf.append(" FROM ");
buf.append(tableName);
return buf.toString();
}
private String getReadSQLQueryOneToManyRelationship(final String tableName, final String indexField) {
return "SELECT id FROM " + tableName + " WHERE " + indexField + "=?";
}
private String getDeleteSQLQuery() {
return "DELETE FROM " + tableName + " WHERE id=?";
}
private String getInsertSQLQuery() {
StringBuilder buf = new StringBuilder();
buf.append("INSERT INTO ");
buf.append(tableName);
buf.append(" (");
int count = 0;
for (Column column: columns.getList()) {
final String name = column.getSqlName();
if (!name.equals("id")) {
count++;
buf.append(name);
buf.append(", ");
}
}
buf.delete(buf.length() - 2, buf.length());
buf.append(") VALUES (");
for (int i = 0; i < count; i++)
buf.append("?, ");
buf.delete(buf.length() - 2, buf.length());
buf.append(")");
return buf.toString();
}
private String getUpdateSQLQuery() {
StringBuilder buf = new StringBuilder();
buf.append("UPDATE ");
buf.append(tableName);
buf.append(" SET ");
for (Column column: columns.getList()) {
final String name = column.getSqlName();
if (!name.equals("id")) {
buf.append(name);
buf.append("=?, ");
}
}
buf.delete(buf.length() - 2, buf.length());
buf.append(" WHERE id=?");
if (columns.hasLastUpdate())
buf.append(" AND last_update=?");
return buf.toString();
}
private String getDeleteOneToManyRelationshipQuery(final String tableName, final String indexField) {
return "DELETE FROM " + tableName + " WHERE " + indexField + "=?";
}
private FunctionDeclaration getTemporalConvertToStringFunction(final String className, final String varName) {
return new FunctionDeclaration("convert" + className + "ToString", "String").addArgument(new FunctionArgument(className, varName)).addContent(
new IfBlock(new Condition(new Comparison(varName, "null"))).addContent(
new ReturnStatement(EMPTY_STRING)
)
).addContent(EMPTY_LINE).addContent(
new ReturnStatement(new FunctionCall("toString", varName))
).visibility(Visibility.PROTECTED);
}
private void addIndicator(final String javaName, final String indicatorName, final boolean value, final boolean isFinal) {
final FunctionDeclaration indicator = new FunctionDeclaration("is" + capitalize(javaName) + indicatorName, "boolean");
if (isFinal)
indicator.markAsFinal();
if (value)
indicator.addContent(new ReturnStatement("true"));
else
indicator.addContent(new ReturnStatement("false"));
javaClass.addContent(indicator).addContent(EMPTY_LINE);
}
}
|
package org.broad.igv.ui.panel;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.PreferenceManager;
import org.broad.igv.dev.affective.AffectiveUtils;
import org.broad.igv.feature.Chromosome;
import org.broad.igv.feature.genome.ChromosomeCoordinate;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeImpl;
import org.broad.igv.ui.FontManager;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.UIConstants;
import org.broad.igv.ui.WaitCursorManager;
import org.broad.igv.util.LongRunningTask;
import org.broad.igv.util.NamedRunnable;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
* @author jrobinso
*/
public class RulerPanel extends JPanel {
private static Logger log = Logger.getLogger(RulerPanel.class);
private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat();
// TODO -- get from preferences
boolean affective = false;
boolean drawSpan = true;
boolean drawEllipsis = false;
private Font tickFont = FontManager.getFont(Font.BOLD, 9);
private Font spanFont = FontManager.getFont(Font.BOLD, 12);
private List<ClickLink> chromosomeRects = new ArrayList();
private static Color dragColor = new Color(.5f, .5f, 1f, .3f);
private static Color zoomBoundColor = new Color(0.5f, 0.5f, 0.5f);
boolean dragging = false;
int dragStart;
int dragEnd;
public static final String WHOLE_GENOME_TOOLTIP = "<html>Click on a chromosome number to jump to that chromosome," +
"<br>or click and drag to zoom in.";
public static final String CHROM_TOOLTIP = "Click and drag to zoom in.";
ReferenceFrame frame;
public RulerPanel(ReferenceFrame frame) {
this.frame = frame;
affective = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.AFFECTIVE_ENABLE);
drawSpan = !affective;
init();
}
private boolean isWholeGenomeView() {
return frame.getChrName().equals(Globals.CHR_ALL);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
render(g);
if (dragging) {
g.setColor(dragColor);
int start = Math.min(dragStart, dragEnd);
int w = Math.abs(dragEnd - dragStart);
final int height = getHeight();
g.fillRect(start, 0, w, height);
g.setColor(zoomBoundColor);
g.drawLine(dragStart, 0, dragStart, height);
g.drawLine(dragEnd, 0, dragEnd, height);
}
}
private void render(Graphics g) {
g.setColor(Color.black);
if (isWholeGenomeView()) {
drawChromosomeTicks(g);
} else {
// Clear panel
if (affective) {
drawTimeTicks(g);
} else {
drawTicks(g);
}
if (drawSpan) {
drawSpan(g);
}
if (drawEllipsis) {
drawEllipsis(g);
}
}
}
private void drawSpan(Graphics g) {
//TODO -- hack
int w = getWidth();
g.setFont(spanFont);
// Positions are 1/2 open, subtract 1 to compensate
int range = (int) (frame.getScale() * w) + 1;
// TODO -- hack, assumes location unit for whole genome is kilo-base
boolean scaleInKB = frame.getChrName().equals(Globals.CHR_ALL);
TickSpacing ts = findSpacing(range, scaleInKB);
String rangeString = formatNumber((double) range / ts.getUnitMultiplier()) + " " + ts.getMajorUnit();
int strWidth = g.getFontMetrics().stringWidth(rangeString);
int strHeight = g.getFontMetrics().getAscent();
int strPosition = (w - strWidth) / 2;
int lineY = getHeight() - 35 - strHeight / 2;
g.drawLine(0, lineY, (w - strWidth) / 2 - 10, lineY);
int[] arrowX = {0, 10, 10};
int[] arrowY = {lineY, lineY + 3, lineY - 3};
g.fillPolygon(arrowX, arrowY, arrowX.length);
g.drawLine((w + strWidth) / 2 + 10, lineY, w, lineY);
arrowX = new int[]{w, w - 10, w - 10};
g.fillPolygon(arrowX, arrowY, arrowX.length);
g.drawString(rangeString, strPosition, getHeight() - 35);
}
private void drawEllipsis(Graphics g) {
double cytobandScale = ((double) frame.getChromosomeLength()) / getWidth();
double maxPixel = frame.getMaxPixel();
//visibleFraction = maxPixel < 0 ? 0 : ((double) getViewContext().getDataPanelWidth()) / maxPixel;
int start = (int) ((frame.getOrigin()) / cytobandScale);
int span = (int) ((getWidth() * frame.getScale()) / cytobandScale);
int end = start + span;
g.drawLine(start, 0, 0, getHeight());
g.drawLine(end, 0, getWidth(), getHeight());
}
private void drawTicks(Graphics g) {
int w = getWidth();
if (w < 200) {
return;
}
g.setFont(tickFont);
// TODO -- hack, assumes location unit for whole genome is kilo-base
boolean scaleInKB = frame.getChrName().equals(Globals.CHR_ALL);
int range = (int) (w * frame.getScale());
TickSpacing ts = findSpacing(range, scaleInKB);
double spacing = ts.getMajorTick();
// Find starting point closest to the current origin
int nTick = (int) (frame.getOrigin() / spacing) - 1;
int l = (int) (nTick * spacing);
int x = frame.getScreenPosition(l - 1); // 0 vs 1 based coordinates
//int strEnd = Integer.MIN_VALUE;
while (x < getWidth()) {
l = (int) (nTick * spacing);
x = frame.getScreenPosition(l - 1);
String chrPosition = formatNumber((double) l / ts.getUnitMultiplier()) +
" " + ts.getMajorUnit();
int strWidth = g.getFontMetrics().stringWidth(chrPosition);
int strPosition = x - strWidth / 2;
//if (strPosition > strEnd) {
final int height = getHeight();
if (nTick % 2 == 0) {
g.drawString(chrPosition, strPosition, height - 15);
}
g.drawLine(x, height - 10, x, height - 2);
nTick++;
}
}
private void drawChromosomeTicks(Graphics g) {
Font chrFont = FontManager.getFont(10);
//this.removeAll();
this.setLayout(null);
// TODO -- remove hardcoded value
int locationUnit = 1000;
g.setFont(chrFont);
Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome();
if (genome == null) {
log.info("No genome found with id: " + genome.getId());
PreferenceManager.getInstance().remove(PreferenceManager.DEFAULT_GENOME_KEY);
}
boolean even = true;
long offset = 0;
chromosomeRects.clear();
List<String> chrNames = genome.getChromosomeNames();
if (chrNames == null) {
log.info("No chromosomes found for genome: " + genome.getId());
PreferenceManager.getInstance().remove(PreferenceManager.DEFAULT_GENOME_KEY);
}
if (chrNames.size() > 500) {
return;
}
final FontMetrics fontMetrics = g.getFontMetrics();
for (String chrName : chrNames) {
Chromosome c = genome.getChromosome(chrName);
int chrLength = c.getLength();
int x = (int) (offset / (locationUnit * frame.getScale()));
int dw = (int) (chrLength / (locationUnit * frame.getScale()));
// Dont draw very small chromosome & contigs in whole genome view
if (dw > 1) {
g.drawLine(x, getHeight() - 10, x, getHeight() - 2);
// Don't label chromosome if its width is < 5 pixels
if (dw > 5) {
int center = x + dw / 2;
String displayName = null;
if (chrName.startsWith("gi|")) {
displayName = GenomeImpl.getNCBIName(chrName);
} else {
displayName = chrName.replace("chr", "");
}
int strWidth = fontMetrics.stringWidth(displayName);
int strPosition = center - strWidth / 2;
int y = (even ? getHeight() - 35 : getHeight() - 25);
g.drawString(displayName, strPosition, y);
int sw = (int) fontMetrics.getStringBounds(displayName, g).getWidth();
Rectangle clickRect = new Rectangle(strPosition, y - 15, sw, 15);
String tooltipText = "Jump to chromosome: " + chrName;
chromosomeRects.add(new ClickLink(clickRect, chrName, tooltipText));
even = !even;
}
}
offset += chrLength;
}
}
public static String formatNumber(double position) {
//NumberFormatter f = new NumberFormatter();
return DECIMAL_FORMAT.format((int) position);
//return f.valueToString(position);
}
public static TickSpacing findSpacing(long maxValue, boolean scaleInKB) {
if (maxValue < 10) {
return new TickSpacing(1, "bp", 1);
}
// Now man zeroes?
int nZeroes = (int) Math.log10(maxValue);
String majorUnit = scaleInKB ? "kb" : "bp";
int unitMultiplier = 1;
if (nZeroes > 9) {
majorUnit = scaleInKB ? "tb" : "gb";
unitMultiplier = 1000000000;
}
if (nZeroes > 6) {
majorUnit = scaleInKB ? "gb" : "mb";
unitMultiplier = 1000000;
} else if (nZeroes > 3) {
majorUnit = scaleInKB ? "mb" : "kb";
unitMultiplier = 1000;
}
double nMajorTicks = maxValue / Math.pow(10, nZeroes - 1);
if (nMajorTicks < 25) {
return new TickSpacing(Math.pow(10, nZeroes - 1), majorUnit, unitMultiplier);
} else {
return new TickSpacing(Math.pow(10, nZeroes) / 2, majorUnit, unitMultiplier);
}
}
private void init() {
setBorder(BorderFactory.createLineBorder(UIConstants.TRACK_BORDER_GRAY));
setCursor(Cursor.getDefaultCursor());
if (isWholeGenomeView()) {
this.setToolTipText(WHOLE_GENOME_TOOLTIP);
} else {
this.setToolTipText("Click and drag to zoom");
}
MouseInputAdapter mouseAdapter = new MouseInputAdapter() {
int lastMousePressX;
@Override
public void mouseClicked(MouseEvent evt) {
final MouseEvent e = evt;
setCursor(Cursor.getDefaultCursor());
WaitCursorManager.CursorToken token = WaitCursorManager.showWaitCursor();
try {
if (!isWholeGenomeView()) {
double newLocation = frame.getChromosomePosition(e.getX());
frame.centerOnLocation(newLocation);
} else {
for (final ClickLink link : chromosomeRects) {
if (link.region.contains(e.getPoint())) {
NamedRunnable runnable = new NamedRunnable() {
final String chrName = link.value;
public void run() {
frame.setChrName(chrName);
frame.recordHistory();
// TODO -- get rid of this ugly reference to IGV.theInstance
IGV.getInstance().chromosomeChangeEvent(chrName);
}
public String getName() {
return "Select chromosome: " + chrName;
}
};
LongRunningTask.submit(runnable);
return;
}
}
}
} finally {
WaitCursorManager.removeWaitCursor(token);
}
}
@Override
public void mouseMoved(MouseEvent e) {
if (isWholeGenomeView()) {
for (ClickLink link : chromosomeRects) {
if (link.region.contains(e.getPoint())) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setToolTipText(link.tooltipText);
return;
}
}
setCursor(Cursor.getDefaultCursor());
setToolTipText(WHOLE_GENOME_TOOLTIP);
}
}
@Override
public void mouseEntered(MouseEvent e) {
setCursor(Cursor.getDefaultCursor());
if (isWholeGenomeView()) {
setToolTipText(WHOLE_GENOME_TOOLTIP);
} else {
setToolTipText(CHROM_TOOLTIP);
}
}
@Override
public void mouseDragged(MouseEvent e) {
if (Math.abs(e.getPoint().getX() - dragStart) > 1) {
dragEnd = e.getX();
dragging = true;
repaint();
}
}
@Override
public void mousePressed(MouseEvent e) {
dragStart = e.getX();
}
@Override
public void mouseReleased(MouseEvent e) {
if (dragging) {
dragEnd = e.getX();
dragging = false;
zoom();
}
}
//@Override
//public void mouseExited(MouseEvent e) {
//dragging = false;
};
addMouseMotionListener(mouseAdapter);
addMouseListener(mouseAdapter);
}
private void zoom() {
NamedRunnable runnable = new NamedRunnable() {
public void run() {
double s = frame.getChromosomePosition(dragStart);
double e = frame.getChromosomePosition(dragEnd);
if (e < s) {
double tmp = s;
s = e;
e = tmp;
}
if (e - s < 40) {
double c = (s + e) / 2;
s = c - 20;
e = c + 20;
}
s = Math.max(0.0, s);
String chr = null;
if (isWholeGenomeView()) {
Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome();
ChromosomeCoordinate start = genome.getChromosomeCoordinate((int) s);
ChromosomeCoordinate end = genome.getChromosomeCoordinate((int) e);
chr = start.getChr();
s = start.getCoordinate();
e = end.getCoordinate();
if (end.getChr() != start.getChr()) {
e = genome.getChromosome(start.getChr()).getLength();
}
} else {
chr = frame.getChrName();
}
frame.jumpTo(chr, (int) Math.min(s, e), (int) Math.max(s, e));
frame.recordHistory();
}
public String getName() {
return "Rule panel zoom";
}
};
LongRunningTask.submit(runnable);
}
public static class TickSpacing {
private double majorTick;
private double minorTick;
private String majorUnit = "";
private int unitMultiplier = 1;
TickSpacing(double majorTick, String majorUnit, int unitMultiplier) {
this.majorTick = majorTick;
this.minorTick = majorTick / 10.0;
this.majorUnit = majorUnit;
this.unitMultiplier = unitMultiplier;
}
public double getMajorTick() {
return majorTick;
}
public double getMinorTick() {
return minorTick;
}
public String getMajorUnit() {
return majorUnit;
}
public void setMajorUnit(String majorUnit) {
this.majorUnit = majorUnit;
}
public int getUnitMultiplier() {
return unitMultiplier;
}
public void setUnitMultiplier(int unitMultiplier) {
this.unitMultiplier = unitMultiplier;
}
}
// TODO -- possibly generalize?
class ClickLink {
Rectangle region;
String value;
String tooltipText;
ClickLink(Rectangle region, String value, String tooltipText) {
this.region = region;
this.value = value;
this.tooltipText = tooltipText;
}
}
/**
* Special renderer for "Affective Computing" timescale, chromosome => day, units are hours, minutes, seconds.
*
* @param g
*/
private void drawTimeTicks(Graphics g) {
double timeStep = 1.0 / AffectiveUtils.POINTS_PER_SECOND;
int w = getWidth();
double start = frame.getOrigin();
double end = frame.getEnd();
double seconds = (start - end) * timeStep;
// Determine step sizes
double secsPerPixel = frame.getScale() * timeStep;
double minsPerPixel = secsPerPixel / 60;
double hoursPerPixel = minsPerPixel / 60;
g.setFont(tickFont);
FontMetrics fm = g.getFontMetrics();
int startHour = (int) ((start * timeStep) / 3600);
int endHour = (int) ((end * timeStep) / 3600) + 1;
double originHour = (start * timeStep) / 3600;
// Rectangle rect = getBounds();
int height = getHeight();
for (double h = startHour; h < endHour; h++) {
double pixel = (int) ((h - originHour) / hoursPerPixel);
if (pixel > w) {
break;
}
if (pixel > 0) {
g.drawLine((int) pixel, height, (int) pixel, height - 15);
// Label
int absoluteHour = AffectiveUtils.START_TIME_HR + (int) h;
String label = absoluteHour + ":00";
int labelWidth = fm.stringWidth(label);
int labelX = (int) pixel - labelWidth / 2;
if (labelX > 0) {
g.drawString(label, labelX, height - 20);
}
}
// If room for 1/4 hours
if (15 / minsPerPixel > 2) {
pixel = (int) ((h - originHour) / hoursPerPixel);
for (int mm = 0; mm < 60; mm += 15) {
double dx = mm / minsPerPixel;
int mPixel = (int) (pixel + dx);
if (mPixel > w) {
break;
}
if (mPixel > 0) {
g.drawLine(mPixel, height, mPixel, height - 10);
}
}
}
// If room for minutes do minutes
pixel = (int) ((h - originHour) / hoursPerPixel);
if (1 / minsPerPixel > 4) {
for (int m = 1; m < 60; m++) {
double dx = m / minsPerPixel;
int mPixel = (int) (pixel + dx);
if (mPixel > w) {
break;
}
if (mPixel > 0) {
g.drawLine(mPixel, height, mPixel, height - 5);
}
}
// Seconds
if (1 / secsPerPixel > 4) {
for (int s = 1; s < 60; s++) {
double dx = s / secsPerPixel;
int sPixel = (int) (pixel + dx);
if (sPixel > w) {
break;
}
if (sPixel > 0) {
g.drawLine(sPixel, height, sPixel, height - 5);
}
}
}
}
}
}
}
|
package org.hcjf.io.net.http;
import org.hcjf.io.net.NetStreamingSource;
import org.hcjf.properties.SystemProperties;
/**
* This class represents a http response package.
* @author javaito
* @email javaito@gmail.com
*/
public class HttpResponse extends HttpPackage {
private static final int VERSION_INDEX = 0;
private static final int RESPONSE_CODE_INDEX = 1;
private static final int REASON_PHRASE_INDEX = 2;
private Integer responseCode;
private String reasonPhrase;
private NetStreamingSource netStreamingSource;
public HttpResponse() {
}
protected HttpResponse(HttpResponse httpResponse) {
super(httpResponse);
this.responseCode = httpResponse.responseCode;
this.reasonPhrase = httpResponse.reasonPhrase;
}
/**
* Return the numeric code that represents the status of the http request.
* @return Response code.
*/
public Integer getResponseCode() {
return responseCode;
}
/**
* Set the numeric code that represents the status of the http request.
* @param responseCode Response code.
*/
public void setResponseCode(Integer responseCode) {
this.responseCode = responseCode;
}
/**
* Return a phrase that represents why the server response with this package.
* @return Reason phrase.
*/
public String getReasonPhrase() {
return reasonPhrase;
}
/**
* Set a phrase that represents why the server response with this package.
* @param reasonPhrase Reason phrase.
*/
public void setReasonPhrase(String reasonPhrase) {
this.reasonPhrase = reasonPhrase;
}
/**
* This kind of http package never process his body.
* @param body Package body.
*/
@Override
protected void processBody(byte[] body) {}
/**
* Set the values of the first line of the package.
* @param firstLine String representation of the firs line.
*/
@Override
protected void processFirstLine(String firstLine) {
String[] parts = firstLine.split(LINE_FIELD_SEPARATOR);
if(parts.length == 2) {
setResponseCode(Integer.parseInt(parts[RESPONSE_CODE_INDEX]));
setHttpVersion(parts[VERSION_INDEX]);
} if(parts.length == 3) {
setResponseCode(Integer.parseInt(parts[RESPONSE_CODE_INDEX]));
setReasonPhrase(parts[REASON_PHRASE_INDEX]);
setHttpVersion(parts[VERSION_INDEX]);
}
}
public NetStreamingSource getNetStreamingSource() {
return netStreamingSource;
}
public void setNetStreamingSource(NetStreamingSource netStreamingSource) {
this.netStreamingSource = netStreamingSource;
}
/**
* Return the string representation of the package header.
* @return String representation of the package header.
*/
private String toStringProtocolHeader() {
StringBuilder builder = new StringBuilder();
builder.append(getHttpVersion()).append(LINE_FIELD_SEPARATOR);
builder.append(getResponseCode()).append(LINE_FIELD_SEPARATOR);
builder.append(getReasonPhrase() == null ? "" : getReasonPhrase()).append(STRING_LINE_SEPARATOR);
for(HttpHeader header : getHeaders()) {
builder.append(header).append(STRING_LINE_SEPARATOR);
}
builder.append(STRING_LINE_SEPARATOR);
return builder.toString();
}
/**
* Return the byte array that represents the http package header.
* @return Byte array.
*/
@Override
public byte[] getProtocolHeader() {
return toStringProtocolHeader().getBytes();
}
/**
* Create the standard representation of the http response package.
* @return String representation of the package
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(toStringProtocolHeader());
if(getBody() != null) {
int maxLength = SystemProperties.getInteger(SystemProperties.Net.Http.OUTPUT_LOG_BODY_MAX_LENGTH);
if(maxLength > 0) {
if (getBody().length > maxLength) {
builder.append(new String(getBody(), 0, maxLength));
builder.append(" ... [").append(getBody().length - maxLength).append(" more]");
} else {
String s = new String(getBody());
builder.append(new String(getBody()));
}
}
}
return builder.toString();
}
}
|
package org.jmist.framework;
import org.jmist.toolkit.Ray3;
import org.jmist.toolkit.Tuple;
/**
* @author bkimmel
*
*/
public class ScatterResult {
private ScatterResult(Ray3 scatteredRay, Tuple wavelengths, double[] weights, boolean diffuse) {
assert(scatteredRay != null);
assert(wavelengths.size() == weights.length);
this.scatteredRay = scatteredRay;
this.wavelengths = wavelengths;
this.weights = weights;
this.diffuse = diffuse;
}
private ScatterResult(Ray3 scatteredRay, double wavelength, double weight, boolean diffuse) {
assert(scatteredRay != null);
this.scatteredRay = scatteredRay;
this.wavelengths = new Tuple(wavelength);
this.weights = new double[]{ weight };
this.diffuse = diffuse;
}
public static ScatterResult diffuse(Ray3 transmittedRay, Tuple wavelengths, double[] weights) {
return new ScatterResult(transmittedRay, wavelengths, weights, true);
}
public static ScatterResult specular(Ray3 transmittedRay, Tuple wavelengths, double[] weights) {
return new ScatterResult(transmittedRay, wavelengths, weights, false);
}
public static ScatterResult diffuse(Ray3 transmittedRay, double wavelength, double weight) {
return new ScatterResult(transmittedRay, wavelength, weight, true);
}
public static ScatterResult specular(Ray3 transmittedRay, double wavelength, double weight) {
return new ScatterResult(transmittedRay, wavelength, weight, false);
}
public Ray3 scatteredRay() {
return this.scatteredRay;
}
public Tuple wavelengths() {
return this.wavelengths;
}
public double weightAt(int index) {
return this.weights[index];
}
public boolean diffuse() {
return this.diffuse;
}
private final Ray3 scatteredRay;
private final Tuple wavelengths;
private final double[] weights;
private final boolean diffuse;
}
|
/*
* $Id: BasePlugin.java,v 1.49 2007-08-12 06:29:51 tlipkis Exp $
*/
package org.lockss.plugin.base;
import java.util.*;
import org.lockss.util.*;
import org.lockss.util.urlconn.*;
import org.lockss.app.*;
import org.lockss.config.ConfigManager;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.plugin.*;
import org.lockss.plugin.wrapper.*;
import org.lockss.extractor.*;
/**
* Abstract base class for Plugins. Plugins are encouraged to extend this
* class to get some common Plugin functionality.
*/
public abstract class BasePlugin
implements Plugin {
static Logger log = Logger.getLogger("BasePlugin");
static final String PARAM_TITLE_DB = ConfigManager.PARAM_TITLE_DB;
// Below org.lockss.title.xxx.
static final String TITLE_PARAM_TITLE = "title";
static final String TITLE_PARAM_JOURNAL = "journalTitle";
public static final String TITLE_PARAM_PLUGIN = "plugin";
static final String TITLE_PARAM_PLUGIN_VERSION = "pluginVersion";
static final String TITLE_PARAM_EST_SIZE = "estSize";
static final String TITLE_PARAM_ATTRIBUTES = "attributes";
static final String TITLE_PARAM_PARAM = "param";
// Below org.lockss.title.xxx.param.n.
static final String TITLE_PARAM_PARAM_KEY = "key";
static final String TITLE_PARAM_PARAM_VALUE = "value";
static final String TITLE_PARAM_PARAM_EDITABLE = "editable";
protected LockssDaemon theDaemon;
protected PluginManager pluginMgr;
protected Collection aus = new ArrayList();
protected Map titleConfigMap;
// XXX need to generalize this
protected CacheResultMap resultMap;
protected MimeTypeMap mimeMap;
protected HashMap filterMap = new HashMap(4);
// ClassLoader used to load plugin. null if not loadable plugin
protected ClassLoader classLoader;
Configuration.Callback configCb = new Configuration.Callback() {
public void configurationChanged(Configuration newConfig,
Configuration prevConfig,
Configuration.Differences changedKeys) {
setConfig(newConfig, prevConfig, changedKeys);
}
public String toString() {
return getPluginId();
}
};
/**
* Must invoke this constructor in plugin subclass.
*/
protected BasePlugin() {
}
public void initPlugin(LockssDaemon daemon) {
theDaemon = daemon;
pluginMgr = theDaemon.getPluginManager();
mimeMap = new MimeTypeMap(MimeTypeMap.DEFAULT);
theDaemon.getConfigManager().registerConfigurationCallback(configCb);
initResultMap();
}
public void stopPlugin() {
theDaemon.getConfigManager().unregisterConfigurationCallback(configCb);
}
public void stopAu(ArchivalUnit au) {
// Is there any reason to notify the AU itself?
aus.remove(au);
}
/** Subclasses should override this if they want to require a minimum
* daemon version in order to run
*/
public String getRequiredDaemonVersion() {
return "0.0.0";
}
/** Subclasses should override this if they want to supply a publishing
* platform name
*/
public String getPublishingPlatform() {
return null;
}
/**
* Default implementation collects keys from titleConfigMap.
* @return a List
*/
public List getSupportedTitles() {
if (titleConfigMap == null) {
return Collections.EMPTY_LIST;
}
return new ArrayList(titleConfigMap.keySet());
}
/**
* Default implementation looks in titleConfigMap.
*/
public TitleConfig getTitleConfig(String title) {
if (titleConfigMap == null) {
return null;
}
return (TitleConfig)titleConfigMap.get(title);
}
/** Set up our titleConfigMap from the title definitions in the
* Configuration. Each title config looks like:<pre>
* org.lockss.title.uid.title=Sample Title
* org.lockss.title.uid.plugin=org.lockss.plugin.sample.SamplePlugin
* org.lockss.title.uid.param.1.key=base_url
* org.lockss.title.uid.param.1.value=http\://sample.org/
* org.lockss.title.uid.param.2.key=year
* org.lockss.title.uid.param.2.value=2003
* org.lockss.title.uid.param.2.editable=true</pre> where
* <code>uid</code> is an identifier that is unique for each title.
* Parameters for which <code>editable</code> is true (<i>eg</i>,
* <code>year</code>) may be edited by the user to select a related AU.
* <br>See TitleParams (and test/scripts/title-params) for an easy way to
* create these property files.
*/
protected void setConfig(Configuration newConfig,
Configuration prevConfig,
Configuration.Differences changedKeys) {
if (changedKeys.contains(PARAM_TITLE_DB)) {
setTitleConfig(newConfig);
}
}
private void setTitleConfig(Configuration config) {
String myName = getPluginId();
Map titleMap = new HashMap();
Collection myTitles = config.getTitleConfigs(myName);
if (myTitles != null) {
for (Iterator iter = myTitles.iterator(); iter.hasNext(); ) {
Configuration titleConfig = (Configuration)iter.next();
String pluginName = titleConfig.get(TITLE_PARAM_PLUGIN);
if (myName.equals(pluginName)) {
if (log.isDebug2()) {
log.debug2("my titleConfig: " + titleConfig);
}
String title = titleConfig.get(TITLE_PARAM_TITLE);
TitleConfig tc = initOneTitle(titleConfig);
titleMap.put(title, tc);
} else {
if (log.isDebug3()) {
log.debug3("titleConfig: " + titleConfig);
}
}
}
}
//TODO: decide on how to support plug-ins which do not use the title registry
if (!titleMap.isEmpty()) {
setTitleConfigMap(titleMap);
notifyAusTitleDbChanged();
}
}
TitleConfig initOneTitle(Configuration titleConfig) {
String title = titleConfig.get(TITLE_PARAM_TITLE);
TitleConfig tc = new TitleConfig(title, this);
tc.setPluginVersion(titleConfig.get(TITLE_PARAM_PLUGIN_VERSION));
tc.setJournalTitle(titleConfig.get(TITLE_PARAM_JOURNAL));
if (titleConfig.containsKey(TITLE_PARAM_EST_SIZE)) {
tc.setEstimatedSize(titleConfig.getSize(TITLE_PARAM_EST_SIZE, 0));
}
Configuration attrs = titleConfig.getConfigTree(TITLE_PARAM_ATTRIBUTES);
if (!attrs.isEmpty()) {
Map attrMap = new HashMap();
for (Iterator iter = attrs.nodeIterator(); iter.hasNext(); ) {
String attr = (String)iter.next();
String val = attrs.get(attr);
attrMap.put(attr, val);
}
tc.setAttributes(attrMap);
}
ArrayList params = new ArrayList();
Configuration allParams = titleConfig.getConfigTree(TITLE_PARAM_PARAM);
for (Iterator iter = allParams.nodeIterator(); iter.hasNext(); ) {
Configuration oneParam = allParams.getConfigTree((String)iter.next());
String key = oneParam.get(TITLE_PARAM_PARAM_KEY);
String val = oneParam.get(TITLE_PARAM_PARAM_VALUE);
ConfigParamDescr descr = findParamDescr(key);
if (descr != null) {
ConfigParamAssignment cpa = new ConfigParamAssignment(descr, val);
if (oneParam.containsKey(TITLE_PARAM_PARAM_EDITABLE)) {
cpa.setEditable(oneParam.getBoolean(TITLE_PARAM_PARAM_EDITABLE,
cpa.isEditable()));
}
params.add(cpa);
} else {
log.warning("Unknown parameter key: " + key + " in title: " + title);
log.debug(" title config: " + titleConfig);
}
}
// This list is kept permanently, so trim array to size
params.trimToSize();
tc.setParams(params);
return tc;
}
protected void setTitleConfigMap(Map titleConfigMap) {
this.titleConfigMap = titleConfigMap;
pluginMgr.resetTitles();
}
protected void notifyAusTitleDbChanged() {
for (Iterator iter = getAllAus().iterator(); iter.hasNext(); ) {
// They should all be BaseArchivalUnits, but just in case...
try {
BaseArchivalUnit au = (BaseArchivalUnit)iter.next();
au.titleDbChanged();
} catch (Exception e) {
log.warning("notifyAusTitleDbChanged: " + this, e);
}
}
}
public List getAuConfigDescrs() {
List res = new ArrayList(getLocalAuConfigDescrs());
if (res.isEmpty()) {
// Don't add internal params if plugin has no params. (testing)
return res;
}
res.add(ConfigParamDescr.AU_CLOSED);
res.add(ConfigParamDescr.PUB_DOWN);
res.add(ConfigParamDescr.PUB_NEVER);
res.add(ConfigParamDescr.PROTOCOL_VERSION);
return res;
}
abstract protected List getLocalAuConfigDescrs();
/**
* Find the ConfigParamDescr that this plugin uses for the specified key.
* @return the element of {@link #getAuConfigDescrs()} whose key
* matches <code>key</code>, or null if none.
*/
protected ConfigParamDescr findParamDescr(String key) {
List descrs = getAuConfigDescrs();
for (Iterator iter = descrs.iterator(); iter.hasNext(); ) {
ConfigParamDescr descr = (ConfigParamDescr)iter.next();
if (descr.getKey().equals(key)) {
return descr;
}
}
return null;
}
// for now use the plugin's class name
// tk - this will have to change to account for versioning
public String getPluginId() {
return this.getClass().getName();
}
public Collection getAllAus() {
if (log.isDebug2()) log.debug2("getAllAus: aus: " + aus);
return aus;
}
public ArchivalUnit configureAu(Configuration config, ArchivalUnit au) throws
ArchivalUnit.ConfigurationException {
if(config == null) {
throw new ArchivalUnit.ConfigurationException("Null Configuration");
}
if (au != null) {
au.setConfiguration(config);
}
else {
au = createAu(config);
}
return au;
}
/** Create an AU and add it to our list. Subclasses should implement
* {@link #createAu0(Configuration)} to create the actual AU */
public final ArchivalUnit createAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
ArchivalUnit au = createAu0(auConfig);
aus.add(au);
return au;
}
/** Create an AU. Subclasses should implement this */
protected abstract ArchivalUnit createAu0(Configuration auConfig)
throws ArchivalUnit.ConfigurationException;
/**
* Return the LockssDaemon instance
* @return the LockssDaemon instance
*/
public LockssDaemon getDaemon() {
return theDaemon;
}
/**
* return the CacheResultMap to use with this plugin
* @return CacheResultMap
*/
public CacheResultMap getCacheResultMap() {
return resultMap;
}
protected void initResultMap() {
resultMap = new HttpResultMap();
}
String siteNormalizeUrl(String url, ArchivalUnit au) {
try {
return getUrlNormalizer().normalizeUrl(url, au);
} catch (PluginException e) {
throw new RuntimeException(e);
}
}
/**
* Return a {@link LinkExtractor} that knows how to extract URLs from
* content of the given MIME type
* @param contentType content type to get a content parser for
* @return A LinkExtractor or null
*/
public LinkExtractor getLinkExtractor(String contentType)
throws PluginException.InvalidDefinition {
MimeTypeInfo mti = getMimeTypeInfo(contentType);
LinkExtractorFactory fact = mti.getLinkExtractorFactory();
if (fact != null) {
try {
return fact.createLinkExtractor(contentType);
} catch (PluginException e) {
throw new RuntimeException(e);
}
}
return null;
}
protected MimeTypeInfo getMimeTypeInfo(String contentType) {
if (contentType == null) {
log.debug3("getMimeTypeInfo: null content type");
return MimeTypeInfo.NULL_INFO;
}
MimeTypeInfo mti = mimeMap.getMimeTypeInfo(contentType);
if (mti == null) {
return MimeTypeInfo.NULL_INFO;
}
return mti;
}
protected UrlNormalizer getUrlNormalizer() {
return NullUrlNormalizer.INSTANCE;
}
protected UrlNormalizer urlNorm;
public static class NullUrlNormalizer implements UrlNormalizer {
public static final UrlNormalizer INSTANCE = new NullUrlNormalizer();
public String normalizeUrl (String url, ArchivalUnit au) {
return url;
}
}
/**
* Returns a filter rule from the cache if found, otherwise calls
* 'constructFilterRule()' and caches the result if non-null. Content-type
* is converted to lowercase. If contenttype is null, returns null.
* @param contentType the content type
* @return the FilterRule
*/
public FilterRule getFilterRule(String contentType) {
if (contentType != null) {
Object obj = filterMap.get(contentType);
FilterRule rule = null;
if (obj==null) {
rule = constructFilterRule(contentType);
if (rule != null) {
if (log.isDebug3()) log.debug3(contentType + " filter: " + rule);
filterMap.put(contentType, rule);
} else {
if (log.isDebug3()) log.debug3("No filter for "+contentType);
}
} else if (obj instanceof FilterRule) {
rule = (FilterRule)obj;
}
return rule;
}
log.debug3("getFilterRule: null content type");
return null;
}
/**
* Override to provide proper filter rules.
* @param contentType content type
* @return null, since we don't filter by default
*/
protected FilterRule constructFilterRule(String contentType) {
log.debug3("constructFilterRule default: null");
return null;
}
/**
* Returns the filter factory for the mime type, if any
* @param contentType the content type
* @return the FilterFactory
*/
public FilterFactory getFilterFactory(String contentType) {
MimeTypeInfo mti = getMimeTypeInfo(contentType);
if (mti == null) {
return null;
}
if (log.isDebug3())
log.debug3(contentType + " filter: " + mti.getFilterFactory());
return mti.getFilterFactory();
}
/**
* Returns the fetch rate limiter for the mime type, if any
* @param contentType the content type
* @return the RateLimiter or null
*/
public RateLimiter getFetchRateLimiter(String contentType) {
MimeTypeInfo mti = getMimeTypeInfo(contentType);
if (mti == null) {
return null;
}
if (log.isDebug3())
log.debug3(contentType + " rate limiter: " + mti.getFetchRateLimiter());
return mti.getFetchRateLimiter();
}
// CLASS LOADING SUPPORT ROUTINES
/** Retuen the ClassLoader that was used to load the plugin, or null if
* not a loadable plugin or loaded from system classpath */
ClassLoader getClassLoader() {
return classLoader;
}
PluginException.InvalidDefinition auxErr(String msg, Throwable t) {
log.error(msg, t);
return new PluginException.InvalidDefinition(msg, t);
}
/** Create and return a new instance of a plugin auxilliary class.
* @param className the name of the auxilliary class
* @param expectedType Type (class or interface) of expected rexult
*/
public Object newAuxClass(String className, Class expectedType) {
Object obj = null;
try {
if (classLoader != null) {
obj = Class.forName(className, true, classLoader).newInstance();
} else {
obj = Class.forName(className).newInstance();
}
} catch (ExceptionInInitializerError e) {
throw auxErr("Initializer error in dynamically loaded class "
+ className,
e);
} catch (LinkageError e) {
throw auxErr("Linkage error in dynamically loaded class " + className,
e);
} catch (ClassNotFoundException e) {
throw auxErr("Dynamically loadable class not found " + className,
e);
} catch (IllegalAccessException e) {
throw auxErr("Class " + className
+ " (or its no-argument constructor) is not public",
e);
} catch (InstantiationException e) {
throw auxErr("Error instantiating dynamically loaded class " + className,
e);
} catch (ClassCastException e) {
// can't happen
throw auxErr("Class " + className + " is not of type "
+ expectedType.getName(),
e);
} catch (Exception e) {
throw auxErr("Error loading class " + className, e);
}
if (!expectedType.isInstance(obj)) {
throw auxErr(className + " is not a " + expectedType.getName(), null);
}
return WrapperUtil.wrap(obj, expectedType);
}
}
|
package org.objectweb.proactive;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.UnknownHostException;
import java.rmi.AlreadyBoundException;
import java.util.Collection;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.factory.GenericFactory;
import org.objectweb.fractal.api.factory.InstantiationException;
import org.objectweb.fractal.util.Fractal;
import org.objectweb.proactive.core.Constants;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.body.AbstractBody;
import org.objectweb.proactive.core.body.BodyAdapter;
import org.objectweb.proactive.core.body.LocalBodyStore;
import org.objectweb.proactive.core.body.MetaObjectFactory;
import org.objectweb.proactive.core.body.ProActiveMetaObjectFactory;
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.body.future.Future;
import org.objectweb.proactive.core.body.future.FuturePool;
import org.objectweb.proactive.core.body.http.HttpBodyAdapter;
import org.objectweb.proactive.core.body.ibis.IbisBodyAdapter;
import org.objectweb.proactive.core.body.migration.Migratable;
import org.objectweb.proactive.core.body.migration.MigrationException;
import org.objectweb.proactive.core.body.proxy.AbstractProxy;
import org.objectweb.proactive.core.body.proxy.BodyProxy;
import org.objectweb.proactive.core.body.request.BodyRequest;
import org.objectweb.proactive.core.body.rmi.RmiBodyAdapter;
import org.objectweb.proactive.core.body.rmi.SshRmiBodyAdapter;
import org.objectweb.proactive.core.component.ComponentParameters;
import org.objectweb.proactive.core.component.ContentDescription;
import org.objectweb.proactive.core.component.ControllerDescription;
import org.objectweb.proactive.core.component.factory.ProActiveGenericFactory;
import org.objectweb.proactive.core.config.ProActiveConfiguration;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
import org.objectweb.proactive.core.descriptor.data.VirtualNode;
import org.objectweb.proactive.core.descriptor.data.VirtualNodeImpl;
import org.objectweb.proactive.core.descriptor.xml.ProActiveDescriptorHandler;
import org.objectweb.proactive.core.event.NodeCreationEventProducerImpl;
import org.objectweb.proactive.core.exceptions.manager.ExceptionHandler;
import org.objectweb.proactive.core.exceptions.manager.NFEListener;
import org.objectweb.proactive.core.exceptions.manager.NFEManager;
import org.objectweb.proactive.core.group.Group;
import org.objectweb.proactive.core.group.ProActiveGroup;
import org.objectweb.proactive.core.group.ProxyForGroup;
import org.objectweb.proactive.core.mop.ClassNotReifiableException;
import org.objectweb.proactive.core.mop.ConstructionOfProxyObjectFailedException;
import org.objectweb.proactive.core.mop.MOP;
import org.objectweb.proactive.core.mop.MOPException;
import org.objectweb.proactive.core.mop.Proxy;
import org.objectweb.proactive.core.mop.StubObject;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.node.NodeFactory;
import org.objectweb.proactive.core.runtime.ProActiveRuntime;
import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
import org.objectweb.proactive.core.runtime.RuntimeFactory;
import org.objectweb.proactive.core.util.NodeCreationListenerForAoCreation;
import org.objectweb.proactive.core.util.NonFunctionalServices;
import org.objectweb.proactive.core.util.ProcessForAoCreation;
import org.objectweb.proactive.core.util.UrlBuilder;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.core.util.profiling.PAProfilerEngine;
import org.objectweb.proactive.core.util.profiling.Profiling;
import org.objectweb.proactive.core.util.timer.CompositeAverageMicroTimer;
import org.objectweb.proactive.core.xml.VariableContract;
import org.objectweb.proactive.ext.security.ProActiveSecurityManager;
import org.objectweb.proactive.ext.webservices.soap.ProActiveDeployer;
import ibis.rmi.RemoteException;
/**
* Provides static methods to manipulate or use Active Objects(creation, exception handling, migration,...), futures,
* deployment descritpors, components, groups.
* This class is the central point of the library.
* <p><a href="../../../../html/ActiveObjectCreation.html">Active Object Creation</a>
* <pre>
* newActive(...)
* turnActive(...)
* </pre>
* </p>
* <p>Active Object Manipulation
* <pre>
* getBodyOnThis()
* getActiveObjectNodeUrl(Object)
* getStubOnThis()
* migrateTo(...)
* lookupActive(String, String)
* register(Object, String)
* setImmediateService(...)
* </pre>
* </p>
* <p><a href="../../../../html/ActiveObjectCreation.html#FutureObjectCreation">Synchronization, Futures</a>
* <pre>
* isAwaited(Object)
* waitFor(Object)
* waitForAll(Vector)
* waitForAny(Vector)
* waitForPotentialException()
* waitForTheNth(Vector, int)
* Previous methods provide also the ability to pass a timeout value
*
* allAwaited(Vector)
* getFutureValue(Object)
* isException(Object)
* </pre>
* </p>
* <p><a href="../../../../html/TypedGroupCommunication.html">Groups Creation</a>
* <pre>
* newActiveAsGroup(...)
* </pre>
* </p>
* <p><a href="../../../../html/components/intro.html">Components</a>
* <pre>
* newActiveComponent(...)
* </pre>
* </p>
* <p><a href="../../../../html/XML_Descriptors.html">XML Descritpors</a>
* <pre>
* getProactiveDescriptor(String)
* </pre>
* </p>
* <p><a href="../../../../html/exceptions.html">Non Functionnal Exceptions</a>
* <pre>
* addNFEListenerOnAO(Object, NFEListener)
* addNFEListenerOnJVM(NFEListener)
* addNFEListenerOnProxy(Object, NFEListener)
* removeNFEListenerOnAO(Object, NFEListener)
* removeNFEListenerOnJVM(NFEListener)
* removeNFEListenerOnProxy(Object, NFEListener)
* </pre>
* </p>
* <p><a href="../../../../html/exceptions.html">Functionnal Exceptions</a>
* <pre>
* tryWithCatch(Class)
* removeTryWithCatch()
* endTryWithCatch()
* throwArrivedException()
* </pre>
* </p>
* <p><a href="../../../../html/ActiveObjectCreation.html#AC">Automatic Continuations</a>
* <pre>
* enableAC(Object)
* disableAC(Object)
* </pre>
* </p>
* <p><a href="../../../../html/WSDoc.html">Web Services</a>
* <pre>
* exposeAsWebService(Object, String, String, String[])
* exposeComponentAsWebService(Component, String, String)
* </pre>
* </p>
*
*
* @author ProActive Team
* @since ProActive 0.7
* @see ProActiveDescriptor
* @see ProActiveGroup
*
*/
public class ProActive {
protected final static Logger logger = ProActiveLogger.getLogger(Loggers.CORE);
public final static Logger loggerGroup = ProActiveLogger.getLogger(Loggers.GROUPS);
/** Used for profiling */
private static CompositeAverageMicroTimer timer;
static {
ProActiveConfiguration.load();
@SuppressWarnings("unused") // Execute RuntimeFactory's static blocks
Class c = org.objectweb.proactive.core.runtime.RuntimeFactory.class;
}
private ProActive() {
}
/**
*
* Launches the main method of the main class through the node node
* @param classname classname of the main method to launch
* @param mainParameters parameters
* @param node node in which launch the main method
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws ProActiveException
*/
public static void newMain(String classname, String[] mainParameters,
Node node)
throws ClassNotFoundException, NoSuchMethodException, ProActiveException {
ProActiveRuntime part = node.getProActiveRuntime();
part.launchMain(classname, mainParameters);
}
/**
* Creates an instance of the remote class. This instance is
* created with the default constructor
* @param classname
* @param node
* @throws ClassNotFoundException
* @throws ProActiveException
*/
public static void newRemote(String classname, Node node)
throws ClassNotFoundException, ProActiveException {
ProActiveRuntime part = node.getProActiveRuntime();
part.newRemote(classname);
}
/**
* Creates a new ActiveObject based on classname attached to a default node in the local JVM.
* @param classname the name of the class to instanciate as active
* @param constructorParameters the parameters of the constructor.
* @return a reference (possibly remote) on a Stub of the newly created active object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the DefaultNode cannot be created
*/
public static Object newActive(String classname,
Object[] constructorParameters)
throws ActiveObjectCreationException, NodeException {
return newActive(classname, null, constructorParameters, (Node) null,
null, null);
}
/**
* Creates a new ActiveObject based on classname attached to the node of the given URL.
* @param classname the name of the class to instanciate as active
* @param constructorParameters the parameters of the constructor.
* @param nodeURL the URL of the node where to create the active object. If null, the active object
* is created localy on a default node
* @return a reference (possibly remote) on a Stub of the newly created active object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node URL cannot be resolved as an existing Node
*/
public static Object newActive(String classname,
Object[] constructorParameters, String nodeURL)
throws ActiveObjectCreationException, NodeException {
if (nodeURL == null) {
return newActive(classname, null, constructorParameters,
(Node) null, null, null);
} else {
return newActive(classname, null, constructorParameters,
NodeFactory.getNode(nodeURL), null, null);
}
}
/**
* Creates a new ActiveObject based on classname attached to the given node or on
* a default node in the local JVM if the given node is null.
* @param classname the name of the class to instanciate as active
* @param constructorParameters the parameters of the constructor.
* @param node the possibly null node where to create the active object.
* @return a reference (possibly remote) on a Stub of the newly created active object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object newActive(String classname,
Object[] constructorParameters, Node node)
throws ActiveObjectCreationException, NodeException {
return newActive(classname, null, constructorParameters, node, null,
null);
}
/**
* <p>Create a set of active objects with given construtor parameters.
* The object activation is optimized by a thread pool.</p>
* <p>The total of active objects created is equal to the number of nodes
* and to the total of constructor paramaters also.</p>
* <p>The condition to use this method is that:
* <b>constructorParameters.length == nodes.length</b></p>
*
* @param className the name of the class to instanciate as active.
* @param constructorParameters the array that contains the parameters used
* to build the active objects. All active objects have the same constructor
* parameters.
* @param nodes the array of nodes where the active objects are created.
* @return an array of references (possibly remote) on Stubs of the newly
* created active objects.
* @throws ClassNotFoundException in the case of className is not a class.
*/
public static Object[] newActiveInParallel(String className,
Object[][] constructorParameters, Node[] nodes)
throws ClassNotFoundException {
return newActiveInParallel(className, null, constructorParameters, nodes);
}
/**
* <p>Create a set of identical active objects on a given virtual node. The
* object activation is optimized by a thread pool.</p>
* <p>When the given virtual node is not previously activated, this method
* employ the node creation event producer/listerner mechanism joined to the
* thread pool. That aims to create an active object just after the node
* deploying.</p>
*
* @param className the name of the class to instanciate as active.
* @param constructorParameters the array that contains the parameters used
* to build the active objects. All active objects have the same constructor
* parameters.
* @param virtualNode the virtual node where the active objects are created.
* @return an array of references (possibly remote) on Stubs of the newly
* created active objects.
* @throws NodeException happens when the given virtualNode is already
* activated and throws an exception.
* @throws ClassNotFoundException in the case of className is not a class.
*/
public static Object[] newActiveInParallel(String className,
Object[] constructorParameters, VirtualNode virtualNode)
throws NodeException, ClassNotFoundException {
return newActiveInParallel(className, null, constructorParameters,
virtualNode);
}
/**
* Creates a new group of Active Objects. The type of the group and the type of the active objects it contains
* correspond to the classname parameter.
* This group will contain one active object per node mapped onto the virtual node
* given as a parameter.
* @param classname classname the name of the class to instanciate as active
* @param constructorParameters constructorParameters the parameters of the constructor.
* @param virtualnode The virtualnode where to create active objects. Active objects will be created
* on each node mapped to the given virtualnode in XML deployment descriptor.
* @return Object a Group of references (possibly remote) on Stub of newly created active objects
* @throws ActiveObjectCreationException if a problem occur while creating the stub or the body
* @throws NodeException if the virtualnode was null
*/
public static Object newActiveAsGroup(String classname,
Object[] constructorParameters, VirtualNode virtualnode)
throws ActiveObjectCreationException, NodeException {
return ProActive.newActiveAsGroup(classname, null,
constructorParameters, virtualnode, null, null);
}
/**
* Creates a new group of Active Objects. The type of the group and the type of the active objects it contains
* correspond to the classname parameter.
* This group will contain one active object per node mapped onto the virtual node
* given as a parameter.
* @param className classname the name of the class to instanciate as active
* @param constructorParameters constructorParameters the parameters of the constructor.
* @param virtualNode The virtualnode where to create active objects. Active objects will be created
* on each node mapped to the given virtualnode in XML deployment descriptor.
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
* body associated to the reified object. If null the default ProActive MataObject factory is used.
* @return Object a Group of references (possibly remote) on Stubs of newly created active objects
* @throws ActiveObjectCreationException if a problem occur while creating the stub or the body
* @throws NodeException if the virtualnode was null
*
*/
public static Object newActiveAsGroup(String className,
Object[] constructorParameters, VirtualNode virtualNode,
Active activity, MetaObjectFactory factory)
throws ActiveObjectCreationException, NodeException {
return newActiveAsGroup(className, null, constructorParameters,
virtualNode, activity, factory);
}
/**
* Creates a new ProActive component over the specified base class, according to the
* given component parameters, and returns a reference on the component of type Component.
* A reference on the active object base class can be retreived through the component parameters controller's
* method "getStubOnReifiedObject".
*
* @param className the name of the base class. "Composite" if the component is a composite,
* "ParallelComposite" if the component is a parallel composite component
* @param constructorParameters the parameters of the constructor of the object
* to instantiate as active. If some parameters are primitive types, the wrapper
* class types should be given here. null can be used to specify that no parameter
* are passed to the constructor.
* @param node the possibly null node where to create the active object. If null, the active object
* is created localy on a default node
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory should be null for components (automatically created)
* @param componentParameters the parameters of the component
* @return a component representative of type Component
* @exception ActiveObjectCreationException if a problem occurs while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Component newActiveComponent(String className,
Object[] constructorParameters, Node node, Active activity,
MetaObjectFactory factory, ComponentParameters componentParameters)
throws ActiveObjectCreationException, NodeException {
return newActiveComponent(className, null, constructorParameters, node,
activity, factory, componentParameters);
}
/**
* Creates a new ProActive component over the specified base class, according to the
* given component parameters, and returns a reference on the component of type Component.
*
* This method allows automatic of primitive components on Virtual Nodes. In that case, the appendix
* -cyclicInstanceNumber-<b><i>number</i></b> is added to the name of each of these components.
* If the component is not a primitive, only one instance of the component is created, on the first node
* retreived from the specified virtual node.
*
* A reference on the active object base class can be retreived through the component parameters controller's
* method "getStubOnReifiedObject".
*
* @param className the name of the base class. "Composite" if the component is a composite,
* "ParallelComposite" if the component is a parallel composite component
* @param constructorParameters the parameters of the constructor of the object
* to instantiate as active. If some parameters are primitive types, the wrapper
* class types should be given here. null can be used to specify that no parameter
* are passed to the constructor.
* @param vn the possibly null node where to create the active object. If null, the active object
* is created localy on a default node
* @param componentParameters the parameters of the component
* @return a typed group of component representative elements, of type Component
* @exception ActiveObjectCreationException if a problem occurs while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Component newActiveComponent(String className,
Object[] constructorParameters, VirtualNode vn,
ComponentParameters componentParameters)
throws ActiveObjectCreationException, NodeException {
return newActiveComponent(className, null, constructorParameters, vn,
componentParameters);
}
/**
* Turns the target object into an ActiveObject attached to a default node in the local JVM.
* The type of the stub is is the type of the existing object.
* @param target The object to turn active
* @return a reference (possibly remote) on a Stub of the existing object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the DefaultNode cannot be created
*/
public static Object turnActive(Object target)
throws ActiveObjectCreationException, NodeException {
return turnActive(target, (Class[]) null, (Node) null);
}
/**
* Turns the target object into an Active Object and send it to the Node
* identified by the given url.
* The type of the stub is is the type of the existing object.
* @param target The object to turn active
* @param nodeURL the URL of the node where to create the active object on. If null, the active object
* is created localy on a default node
* @return a reference (possibly remote) on a Stub of the existing object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, String nodeURL)
throws ActiveObjectCreationException, NodeException {
if (nodeURL == null) {
return turnActive(target, null, target.getClass().getName(), null,
null, null);
} else {
return turnActive(target, null, target.getClass().getName(),
NodeFactory.getNode(nodeURL), null, null);
}
}
/**
* Turns the target object into an Active Object and send it to the given Node
* or to a default node in the local JVM if the given node is null.
* The type of the stub is is the type of the target object.
* @param target The object to turn active
* @param node The Node the object should be sent to or null to create the active
* object in the local JVM
* @return a reference (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, Node node)
throws ActiveObjectCreationException, NodeException {
return turnActive(target, null, target.getClass().getName(), node,
null, null);
}
/**
* Turns the target object into an Active Object and send it to the given Node
* or to a default node in the local JVM if the given node is null.
* The type of the stub is is the type of the target object.
* @param target The object to turn active
* @param node The Node the object should be sent to or null to create the active
* object in the local JVM
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
* body associated to the reified object. If null the default ProActive MataObject factory is used.
* @return a reference (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, Node node, Active activity,
MetaObjectFactory factory)
throws ActiveObjectCreationException, NodeException {
return turnActive(target, null, target.getClass().getName(), node,
activity, factory);
}
/**
* Turns a Java object into an Active Object and send it to a remote Node or to a
* local node if the given node is null.
* The type of the stub is given by the parameter <code>nameOfTargetType</code>.
* @param target The object to turn active
* @param nameOfTargetType the fully qualified name of the type the stub class should
* inherit from. That type can be less specific than the type of the target object.
* @param node The Node the object should be sent to or null to create the active
* object in the local JVM
* @return a reference (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, String nameOfTargetType,
Node node) throws ActiveObjectCreationException, NodeException {
return turnActive(target, null, nameOfTargetType, node, null, null);
}
/**
* Turns a Java object into an Active Object and send it to a remote Node or to a
* local node if the given node is null.
* The type of the stub is given by the parameter <code>nameOfTargetType</code>.
* A Stub is dynamically generated for the existing object. The result of the call
* will be an instance of the Stub class pointing to the proxy object pointing
* to the body object pointing to the existing object. The body can be remote
* or local depending if the existing is sent remotely or not.
* @param target The object to turn active
* @param nameOfTargetType the fully qualified name of the type the stub class should
* inherit from. That type can be less specific than the type of the target object.
* @param node The Node the object should be sent to or null to create the active
* object in the local JVM
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
* body associated to the reified object. If null the default ProActive MataObject factory is used.
* @return a reference (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, String nameOfTargetType,
Node node, Active activity, MetaObjectFactory factory)
throws ActiveObjectCreationException, NodeException {
return turnActive(target, null, nameOfTargetType, node, activity,
factory);
}
/**
* Turns a Java object into a group of Active Objects and sends the elements of the group
* to remote Nodes mapped to the given virtualnode in the XML deployment descriptor.
* The type of the stub is given by the parameter <code>nameOfTargetType</code>.
* @param target The object to turn active
* @param nameOfTargetType the fully qualified name of the type the stub class should
* inherit from. That type can be less specific than the type of the target object.
* @param virtualnode The VirtualNode where the target object will be turn into an Active Object
* Target object will be turned into an Active Object on each node mapped to the given virtualnode in XML deployment descriptor.
* @return an array of references (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActiveAsGroup(Object target,
String nameOfTargetType, VirtualNode virtualnode)
throws ActiveObjectCreationException, NodeException {
return turnActiveAsGroup(target, null, nameOfTargetType, virtualnode);
}
/////// constructors with generic types ////////////////////////////////////////////
/**
* Creates a new ActiveObject based on classname attached to a default node in the local JVM.
* @param classname the name of the class to instanciate as active
* @param genericParameters parameterizing types (of class @param classname)
* @param constructorParameters the parameters of the constructor.
* @return a reference (possibly remote) on a Stub of the newly created active object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the DefaultNode cannot be created
*/
public static Object newActive(String classname, Class[] genericParameters,
Object[] constructorParameters)
throws ActiveObjectCreationException, NodeException {
// avoid ambiguity for method parameters types
Node nullNode = null;
return newActive(classname, genericParameters, constructorParameters,
nullNode, null, null);
}
/**
* Creates a new ActiveObject based on classname attached to the node of the given URL.
* @param classname the name of the class to instanciate as active
* @param genericParameters parameterizing types (of class @param classname)
* @param constructorParameters the parameters of the constructor.
* @param nodeURL the URL of the node where to create the active object. If null, the active object
* is created localy on a default node
* @return a reference (possibly remote) on a Stub of the newly created active object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node URL cannot be resolved as an existing Node
*/
public static Object newActive(String classname, Class[] genericParameters,
Object[] constructorParameters, String nodeURL)
throws ActiveObjectCreationException, NodeException {
if (nodeURL == null) {
// avoid ambiguity for method parameters types
Node nullNode = null;
return newActive(classname, genericParameters,
constructorParameters, nullNode, null, null);
} else {
return newActive(classname, genericParameters,
constructorParameters, NodeFactory.getNode(nodeURL), null, null);
}
}
/**
* Creates a new ActiveObject based on classname attached to the given node or on
* a default node in the local JVM if the given node is null.
* @param classname the name of the class to instanciate as active
* @param genericParameters parameterizing types (of class @param classname)
* @param constructorParameters the parameters of the constructor.
* @param node the possibly null node where to create the active object.
* @return a reference (possibly remote) on a Stub of the newly created active object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object newActive(String classname, Class[] genericParameters,
Object[] constructorParameters, Node node)
throws ActiveObjectCreationException, NodeException {
return newActive(classname, genericParameters, constructorParameters,
node, null, null);
}
/**
* Creates a new ActiveObject based on classname attached to the given node or on
* a default node in the local JVM if the given node is null.
* The object returned is a stub class that extends the target class and that is automatically
* generated on the fly. The Stub class reference a the proxy object that reference the body
* of the active object. The body referenced by the proxy can either be local of remote,
* depending or the respective location of the object calling the newActive and the active object
* itself.
* @param classname the name of the class to instanciate as active
* @param genericParameters parameterizing types (of class @param classname)
* @param constructorParameters the parameters of the constructor of the object
* to instantiate as active. If some parameters are primitive types, the wrapper
* class types should be given here. null can be used to specify that no parameter
* are passed to the constructor.
* @param node the possibly null node where to create the active object. If null, the active object
* is created localy on a default node
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
* body associated to the reified object. If null the default ProActive MetaObject factory is used.
* @return a reference (possibly remote) on a Stub of the newly created active object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object newActive(String classname, Class[] genericParameters,
Object[] constructorParameters, Node node, Active activity,
MetaObjectFactory factory)
throws ActiveObjectCreationException, NodeException {
if (factory == null) {
factory = ProActiveMetaObjectFactory.newInstance();
if (factory.getProActiveSecurityManager() == null) {
factory.setProActiveSecurityManager(((AbstractBody) ProActive.getBodyOnThis()).getProActiveSecurityManager());
}
}
if (Profiling.SECURITY) {
if (timer == null) {
timer = new CompositeAverageMicroTimer("newActiveSecurityTimer");
PAProfilerEngine.registerTimer(timer);
}
timer.setTimer("constructing certificate");
timer.start();
}
MetaObjectFactory clonedFactory = factory;
ProActiveSecurityManager factorySM = factory.getProActiveSecurityManager();
if (factorySM != null) {
try {
clonedFactory = (MetaObjectFactory) factory.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
ProActiveSecurityManager psm = clonedFactory.getProActiveSecurityManager();
psm = psm.generateSiblingCertificate(classname);
clonedFactory.setProActiveSecurityManager(psm);
}
if (Profiling.SECURITY) {
timer.stop();
}
//using default proactive node
if (node == null) {
node = NodeFactory.getDefaultNode();
}
try {
// create stub object
Object stub = createStubObject(classname, genericParameters,
constructorParameters, node, activity, clonedFactory);
return stub;
} catch (MOPException e) {
Throwable t = e;
if (e.getTargetException() != null) {
t = e.getTargetException();
}
throw new ActiveObjectCreationException(t);
}
}
/**
* <p>Create a set of active objects with given construtor parameters.
* The object activation is optimized by a thread pool.</p>
* <p>The total of active objects created is equal to the number of nodes
* and to the total of constructor paramaters also.</p>
* <p>The condition to use this method is that:
* <b>constructorParameters.length == nodes.length</b></p>
*
* @param className the name of the class to instanciate as active.
* @param genericParameters genericParameters parameterizing types
* @param constructorParameters the array that contains the parameters used
* to build the active objects. All active objects have the same constructor
* parameters.
* @param nodes the array of nodes where the active objects are created.
* @return an array of references (possibly remote) on Stubs of the newly
* created active objects.
* @throws ClassNotFoundException in the case of className is not a class.
*/
public static Object[] newActiveInParallel(String className,
Class[] genericParameters, Object[][] constructorParameters,
Node[] nodes) throws ClassNotFoundException {
if (constructorParameters.length != nodes.length) {
throw new ProActiveRuntimeException(
"The total of constructors must" +
" be equal to the total of nodes");
}
ExecutorService threadPool = Executors.newCachedThreadPool();
Vector result = new Vector();
// TODO execute tasks
// The Virtual Node is already activate
for (int i = 0; i < constructorParameters.length; i++) {
threadPool.execute(new ProcessForAoCreation(result, className,
genericParameters, constructorParameters[i],
nodes[i % nodes.length]));
}
threadPool.shutdown();
try {
threadPool.awaitTermination(new Integer(System.getProperty(
"components.creation.timeout")), TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Class classForResult = Class.forName(className);
return result.toArray((Object[]) Array.newInstance(classForResult,
result.size()));
}
/**
* <p>Create a set of identical active objects on a given virtual node. The
* object activation is optimized by a thread pool.</p>
*
* @param className the name of the class to instanciate as active.
* @param genericParameters genericParameters parameterizing types
* @param constructorParameters the array that contains the parameters used
* to build the active objects. All active objects have the same constructor
* parameters.
* @param virtualNode the virtual node where the active objects are created.
* @return an array of references (possibly remote) on Stubs of the newly
* created active objects.
* @throws NodeException happens when the given virtualNode is already
* activated and throws an exception.
* @throws ClassNotFoundException in the case of className is not a class.
*/
public static Object[] newActiveInParallel(String className,
Class[] genericParameters, Object[] constructorParameters,
VirtualNode virtualNode) throws NodeException, ClassNotFoundException {
// Creation of the thread pool
ExecutorService threadPool = Executors.newCachedThreadPool();
Vector result = new Vector();
if (virtualNode.isActivated()) {
// The Virtual Node is already activate
Node[] nodes = virtualNode.getNodes();
for (int i = 0; i < nodes.length; i++) {
threadPool.execute(new ProcessForAoCreation(result, className,
genericParameters, constructorParameters, nodes[i]));
}
} else {
// Use the node creation event mechanism
((NodeCreationEventProducerImpl) virtualNode).addNodeCreationEventListener(new NodeCreationListenerForAoCreation(
result, className, genericParameters,
constructorParameters, threadPool));
virtualNode.activate();
((VirtualNodeImpl) virtualNode).waitForAllNodesCreation();
}
threadPool.shutdown();
try {
threadPool.awaitTermination(new Integer(System.getProperty(
"components.creation.timeout")), TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Class classForResult = Class.forName(className);
return result.toArray((Object[]) Array.newInstance(classForResult,
result.size()));
}
/**
* Creates a new group of Active Objects. The type of the group and the type of the active objects it contains
* correspond to the classname parameter.
* This group will contain one active object per node mapped onto the virtual node
* given as a parameter.
* @param classname classname the name of the class to instanciate as active
* @param genericParameters genericParameters parameterizing types
* @param constructorParameters constructorParameters the parameters of the constructor.
* @param virtualnode The virtualnode where to create active objects. Active objects will be created
* on each node mapped to the given virtualnode in XML deployment descriptor.
* @return Object a Group of references (possibly remote) on Stub of newly created active objects
* @throws ActiveObjectCreationException if a problem occur while creating the stub or the body
* @throws NodeException if the virtualnode was null
*/
public static Object newActiveAsGroup(String classname,
Class[] genericParameters, Object[] constructorParameters,
VirtualNode virtualnode)
throws ActiveObjectCreationException, NodeException {
return ProActive.newActiveAsGroup(classname, genericParameters,
constructorParameters, virtualnode, null, null);
}
/**
* Creates a new group of Active Objects. The type of the group and the type of the active objects it contains
* correspond to the classname parameter.
* This group will contain one active object per node mapped onto the virtual node
* given as a parameter.
* @param classname classname the name of the class to instanciate as active
* @param genericParameters genericParameters parameterizing types
* @param constructorParameters constructorParameters the parameters of the constructor.
* @param virtualnode The virtualnode where to create active objects. Active objects will be created
* on each node mapped to the given virtualnode in XML deployment descriptor.
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
* body associated to the reified object. If null the default ProActive MataObject factory is used.
* @return Object a Group of references (possibly remote) on Stubs of newly created active objects
* @throws ActiveObjectCreationException if a problem occur while creating the stub or the body
* @throws NodeException if the virtualnode was null
*
*/
public static Object newActiveAsGroup(String classname,
Class[] genericParameters, Object[] constructorParameters,
VirtualNode virtualnode, Active activity, MetaObjectFactory factory)
throws ActiveObjectCreationException, NodeException {
if (virtualnode != null) {
if (!virtualnode.isActivated()) {
virtualnode.activate();
}
Node[] nodeTab = virtualnode.getNodes();
Group aoGroup = null;
try {
aoGroup = ProActiveGroup.getGroup(ProActiveGroup.newGroup(
classname, genericParameters));
} catch (ClassNotFoundException e) {
throw new ActiveObjectCreationException(
"Cannot create group of active objects" + e);
} catch (ClassNotReifiableException e) {
throw new ActiveObjectCreationException(
"Cannot create group of active objects" + e);
}
for (int i = 0; i < nodeTab.length; i++) {
Object tmp = newActive(classname, null, constructorParameters,
(Node) nodeTab[i], activity, factory);
aoGroup.add(tmp);
}
return aoGroup.getGroupByType();
} else {
throw new NodeException(
"VirtualNode is null, unable to activate the object");
}
}
/**
* Turns a Java object into an Active Object and send it to a remote Node or to a
* local node if the given node is null.
* The type of the stub is given by the parameter <code>nameOfTargetType</code>.
* A Stub is dynamically generated for the existing object. The result of the call
* will be an instance of the Stub class pointing to the proxy object pointing
* to the body object pointing to the existing object. The body can be remote
* or local depending if the existing is sent remotely or not.
* @param target The object to turn active
* @param genericParameters parameterizing types (of class @param classname)
* @param nameOfTargetType the fully qualified name of the type the stub class should
* inherit from. That type can be less specific than the type of the target object.
* @param node The Node the object should be sent to or null to create the active
* object in the local JVM
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
* body associated to the reified object. If null the default ProActive MataObject factory is used.
* @return a reference (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, String nameOfTargetType,
Class[] genericParameters, Node node, Active activity,
MetaObjectFactory factory)
throws ActiveObjectCreationException, NodeException {
if (factory == null) {
factory = ProActiveMetaObjectFactory.newInstance();
if (factory.getProActiveSecurityManager() == null) {
factory.setProActiveSecurityManager(((AbstractBody) ProActive.getBodyOnThis()).getProActiveSecurityManager());
}
}
ProActiveSecurityManager factorySM = factory.getProActiveSecurityManager();
MetaObjectFactory clonedFactory = factory;
if (factorySM != null) {
try {
clonedFactory = (MetaObjectFactory) factory.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
clonedFactory.setProActiveSecurityManager(factory.getProActiveSecurityManager()
.generateSiblingCertificate(nameOfTargetType));
ProActiveLogger.getLogger(Loggers.SECURITY)
.debug("new active object with security manager");
}
if (node == null) {
//using default proactive node
node = NodeFactory.getDefaultNode();
}
try {
return createStubObject(target, nameOfTargetType,
genericParameters, node, activity, clonedFactory);
} catch (MOPException e) {
Throwable t = e;
if (e.getTargetException() != null) {
t = e.getTargetException();
}
throw new ActiveObjectCreationException(t);
}
}
/**
* Creates a new ProActive component over the specified base class, according to the
* given component parameters, and returns a reference on the component of type Component.
* A reference on the active object base class can be retreived through the component parameters controller's
* method "getStubOnReifiedObject".
*
* @param classname the name of the base class. "Composite" if the component is a composite,
* "ParallelComposite" if the component is a parallel composite component
* @param genericParameters genericParameters parameterizing types
* @param constructorParameters the parameters of the constructor of the object
* to instantiate as active. If some parameters are primitive types, the wrapper
* class types should be given here. null can be used to specify that no parameter
* are passed to the constructor.
* @param node the possibly null node where to create the active object. If null, the active object
* is created localy on a default node
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory should be null for components (automatically created)
* @param componentParameters the parameters of the component
* @return a component representative of type Component
* @exception ActiveObjectCreationException if a problem occurs while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Component newActiveComponent(String classname,
Class[] genericParameters, Object[] constructorParameters, Node node,
Active activity, MetaObjectFactory factory,
ComponentParameters componentParameters)
throws ActiveObjectCreationException, NodeException {
try {
Component boot = Fractal.getBootstrapComponent();
GenericFactory cf = Fractal.getGenericFactory(boot);
return cf.newFcInstance(componentParameters.getComponentType(),
new ControllerDescription(componentParameters.getName(),
componentParameters.getHierarchicalType()),
new ContentDescription(classname, constructorParameters,
activity, factory));
} catch (NoSuchInterfaceException e) {
throw new ActiveObjectCreationException(e);
} catch (InstantiationException e) {
if (e.getCause() instanceof NodeException) {
throw new NodeException(e);
} else {
throw new ActiveObjectCreationException(e);
}
}
}
/**
* Creates a new ProActive component over the specified base class, according to the
* given component parameters, and returns a reference on the component of type Component.
*
* This method allows automatic of primitive components on Virtual Nodes. In that case, the appendix
* -cyclicInstanceNumber-<b><i>number</i></b> is added to the name of each of these components.
* If the component is not a primitive, only one instance of the component is created, on the first node
* retreived from the specified virtual node.
*
* A reference on the active object base class can be retreived through the component parameters controller's
* method "getStubOnReifiedObject".
*
* @param className the name of the base class. "Composite" if the component is a composite,
* "ParallelComposite" if the component is a parallel composite component
* @param genericParameters genericParameters parameterizing types
* @param constructorParameters the parameters of the constructor of the object
* to instantiate as active. If some parameters are primitive types, the wrapper
* class types should be given here. null can be used to specify that no parameter
* are passed to the constructor.
* @param vn the possibly null node where to create the active object. If null, the active object
* is created localy on a default node
* @param componentParameters the parameters of the component
* @return a typed group of component representative elements, of type Component
* @exception ActiveObjectCreationException if a problem occurs while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Component newActiveComponent(String className,
Class[] genericParameters, Object[] constructorParameters,
VirtualNode vn, ComponentParameters componentParameters)
throws ActiveObjectCreationException, NodeException {
try {
Component boot = Fractal.getBootstrapComponent();
ProActiveGenericFactory cf = (ProActiveGenericFactory) Fractal.getGenericFactory(boot);
return cf.newFcInstance(componentParameters.getComponentType(),
new ControllerDescription(componentParameters.getName(),
componentParameters.getHierarchicalType()),
new ContentDescription(className, constructorParameters));
} catch (NoSuchInterfaceException e) {
throw new ActiveObjectCreationException(e);
} catch (InstantiationException e) {
if (e.getCause() instanceof NodeException) {
throw new NodeException(e);
} else {
throw new ActiveObjectCreationException(e);
}
}
}
/**
* Turns the target object into an ActiveObject attached to a default node in the local JVM.
* The type of the stub is is the type of the existing object.
* @param target The object to turn active
* @param genericParameters genericParameters parameterizing types
* @return a reference (possibly remote) on a Stub of the existing object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the DefaultNode cannot be created
*/
public static Object turnActive(Object target, Class[] genericParameters)
throws ActiveObjectCreationException, NodeException {
return turnActive(target, genericParameters, (Node) null,
(Active) null, (MetaObjectFactory) null);
}
/**
* Turns the target object into an Active Object and send it to the Node
* identified by the given url.
* The type of the stub is is the type of the existing object.
* @param target The object to turn active
* @param genericParameters genericParameters parameterizing types
* @param nodeURL the URL of the node where to create the active object on. If null, the active object
* is created localy on a default node
* @return a reference (possibly remote) on a Stub of the existing object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, Class[] genericParameters,
String nodeURL) throws ActiveObjectCreationException, NodeException {
if (nodeURL == null) {
return turnActive(target, genericParameters,
target.getClass().getName(), null, null, null);
} else {
return turnActive(target, genericParameters,
target.getClass().getName(), NodeFactory.getNode(nodeURL),
null, null);
}
}
/**
* Turns the target object into an Active Object and send it to the given Node
* or to a default node in the local JVM if the given node is null.
* The type of the stub is is the type of the target object.
* @param target The object to turn active
* @param genericParameters genericParameters parameterizing types
* @param node The Node the object should be sent to or null to create the active
* object in the local JVM
* @return a reference (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, Class[] genericParameters,
Node node) throws ActiveObjectCreationException, NodeException {
return turnActive(target, genericParameters,
target.getClass().getName(), node, null, null);
}
/**
* Turns the target object into an Active Object and send it to the given Node
* or to a default node in the local JVM if the given node is null.
* The type of the stub is is the type of the target object.
* @param target The object to turn active
* @param genericParameters genericParameters parameterizing types
* @param node The Node the object should be sent to or null to create the active
* object in the local JVM
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
* body associated to the reified object. If null the default ProActive MataObject factory is used.
* @return a reference (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, Class[] genericParameters,
Node node, Active activity, MetaObjectFactory factory)
throws ActiveObjectCreationException, NodeException {
return turnActive(target, genericParameters,
target.getClass().getName(), node, activity, factory);
}
/**
* Turns a Java object into an Active Object and send it to a remote Node or to a
* local node if the given node is null.
* The type of the stub is given by the parameter <code>nameOfTargetType</code>.
* @param target The object to turn active
* @param genericParameters genericParameters parameterizing types
* @param nameOfTargetType the fully qualified name of the type the stub class should
* inherit from. That type can be less specific than the type of the target object.
* @param node The Node the object should be sent to or null to create the active
* object in the local JVM
* @return a reference (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, Class[] genericParameters,
String nameOfTargetType, Node node)
throws ActiveObjectCreationException, NodeException {
return turnActive(target, genericParameters, nameOfTargetType, node,
null, null);
}
/**
* Turns a Java object into an Active Object and send it to a remote Node or to a
* local node if the given node is null.
* The type of the stub is given by the parameter <code>nameOfTargetType</code>.
* A Stub is dynamically generated for the existing object. The result of the call
* will be an instance of the Stub class pointing to the proxy object pointing
* to the body object pointing to the existing object. The body can be remote
* or local depending if the existing is sent remotely or not.
* @param target The object to turn active
* @param genericParameters genericParameters parameterizing types
* @param nameOfTargetType the fully qualified name of the type the stub class should
* inherit from. That type can be less specific than the type of the target object.
* @param node The Node the object should be sent to or null to create the active
* object in the local JVM
* @param activity the possibly null activity object defining the different step in the activity of the object.
* see the definition of the activity in the javadoc of this classe for more information.
* @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the
* body associated to the reified object. If null the default ProActive MataObject factory is used.
* @return a reference (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActive(Object target, Class[] genericParameters,
String nameOfTargetType, Node node, Active activity,
MetaObjectFactory factory)
throws ActiveObjectCreationException, NodeException {
if (factory == null) {
factory = ProActiveMetaObjectFactory.newInstance();
}
ProActiveSecurityManager factorySM = factory.getProActiveSecurityManager();
MetaObjectFactory clonedFactory = factory;
if (factorySM != null) {
try {
clonedFactory = (MetaObjectFactory) factory.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
clonedFactory.setProActiveSecurityManager(factory.getProActiveSecurityManager()
.generateSiblingCertificate(nameOfTargetType));
ProActiveLogger.getLogger(Loggers.SECURITY)
.debug("new active object with security manager");
}
if (node == null) {
//using default proactive node
node = NodeFactory.getDefaultNode();
}
try {
return createStubObject(target, nameOfTargetType,
genericParameters, node, activity, clonedFactory);
} catch (MOPException e) {
Throwable t = e;
if (e.getTargetException() != null) {
t = e.getTargetException();
}
throw new ActiveObjectCreationException(t);
}
}
/**
* Turns a Java object into a group of Active Objects and sends the elements of the group
* to remote Nodes mapped to the given virtualnode in the XML deployment descriptor.
* The type of the stub is given by the parameter <code>nameOfTargetType</code>.
* @param target The object to turn active
* @param genericParameters parameterizing types (of class @param classname)
* @param nameOfTargetType the fully qualified name of the type the stub class should
* inherit from. That type can be less specific than the type of the target object.
* @param virtualnode The VirtualNode where the target object will be turn into an Active Object
* Target object will be turned into an Active Object on each node mapped to the given virtualnode in XML deployment descriptor.
* @return an array of references (possibly remote) on a Stub of the target object
* @exception ActiveObjectCreationException if a problem occur while creating the stub or the body
* @exception NodeException if the node was null and that the DefaultNode cannot be created
*/
public static Object turnActiveAsGroup(Object target,
Class[] genericParameters, String nameOfTargetType,
VirtualNode virtualnode)
throws ActiveObjectCreationException, NodeException {
if (virtualnode != null) {
Node[] nodeTab = virtualnode.getNodes();
Group aoGroup = null;
try {
aoGroup = ProActiveGroup.getGroup(ProActiveGroup.newGroup(
target.getClass().getName(), genericParameters));
} catch (ClassNotFoundException e) {
throw new ActiveObjectCreationException(
"Cannot create group of active objects" + e);
} catch (ClassNotReifiableException e) {
throw new ActiveObjectCreationException(
"Cannot create group of active objects" + e);
}
for (int i = 0; i < nodeTab.length; i++) {
Object tmp = turnActive(target, genericParameters,
nameOfTargetType, (Node) nodeTab[i], null, null);
aoGroup.add(tmp);
}
return aoGroup;
} else {
throw new NodeException(
"VirtualNode is null, unable to active the object");
}
}
/**
* Registers an active object into a registry(RMI or IBIS or HTTP, default is RMI).
* In fact it is the remote version of the body of the active object that is registered
* into the registry under the given URL. According to the type of the associated body(default is Rmi),
* the registry in which to register is automatically found.
* @param obj the active object to register.
* @param url the url under which the remote body is registered. The url must point to the localhost
* since registering is always a local action. The url can take the form:protocol://localhost:port/nam
* or //localhost:port/name if protocol is RMI or //localhost/name if port is 1099 or only the name.
* The registered object will be reachable with the following url: protocol://machine_name:port/name
* using lookupActive method. Protocol and port can be removed if default
* @exception java.io.IOException if the remote body cannot be registered
*/
public static void register(Object obj, String url)
throws java.io.IOException {
BodyAdapter body = getRemoteBody(obj);
body.register(url);
body.setRegistered(true);
if (logger.isInfoEnabled()) {
logger.info("Success at binding url " + url);
}
}
/**
* Unregisters an active object previously registered into a registry.
* @param url the url under which the active object is registered.
* @exception java.io.IOException if the remote object cannot be removed from the registry
*/
public static void unregister(String url) throws java.io.IOException {
String protocol = UrlBuilder.getProtocol(url);
// First step towards Body factory, will be introduced after the release
BodyAdapter ba;
if (protocol.equals("rmi:")) {
ba = new RmiBodyAdapter();
} else if (protocol.equals("rmissh:")) {
ba = new SshRmiBodyAdapter();
} else if (protocol.equals("http:")) {
ba = new HttpBodyAdapter();
} else if (protocol.equals("ibis:")) {
ba = new IbisBodyAdapter();
} else {
throw new IOException("Protocol " + protocol + " not defined");
}
UniversalBody ub = ba.lookup(url);
ba.unregister(url);
ub.setRegistered(false);
if (logger.isDebugEnabled()) {
logger.debug("Success at unbinding url " + url);
}
}
/**
* Looks-up an active object previously registered in a registry(RMI, IBIS, HTTP). In fact it is the
* remote version of the body of an active object that can be registered into the Registry
* under a given URL. If the lookup is successful, the method reconstructs a Stub-Proxy couple and
* point it to the RmiRemoteBody found.
* The registry where to look for is fully determined with the protocol included in the url
* @param classname the fully qualified name of the class the stub should inherit from.
* @param url the url under which the remote body is registered. The url takes the following form:
* protocol://machine_name:port/name. Protocol and port can be ommited if respectively RMI and 1099:
* //machine_name/name
* @return a remote reference on a Stub of type <code>classname</code> pointing to the
* remote body found
* @exception java.io.IOException if the remote body cannot be found under the given url
* or if the object found is not of type RmiRemoteBody
* @exception ActiveObjectCreationException if the stub-proxy couple cannot be created
*/
public static Object lookupActive(String classname, String url)
throws ActiveObjectCreationException, java.io.IOException {
// try {
// // this ensures the class server is initialized,
// // which ensures that the java.rmi.server.codebase property is initialized,
// // which ensures parameters are annotated with the correct codebase in RMI communications
// RuntimeFactory.getDefaultRuntime();
// } catch (ProActiveException e1) {
// throw new ActiveObjectCreationException("Exception occured when trying to get default runtime",e1);
UniversalBody b = null;
String protocol = UrlBuilder.getProtocol(url);
// First step towards Body factory, will be introduced after the release
if (protocol.equals("rmi:")) {
b = new RmiBodyAdapter().lookup(url);
} else if (protocol.equals("rmissh:")) {
b = new SshRmiBodyAdapter().lookup(url);
} else if (protocol.equals("http:")) {
b = new HttpBodyAdapter().lookup(url);
} else if (protocol.equals("ibis:")) {
b = new IbisBodyAdapter().lookup(url);
} else {
throw new IOException("Protocol " + protocol + " not defined");
}
try {
return createStubObject(classname, b);
} catch (MOPException e) {
Throwable t = e;
if (e.getTargetException() != null) {
t = e.getTargetException();
}
throw new ActiveObjectCreationException("Exception occured when trying to create stub-proxy",
t);
}
}
/**
* Looks-up all Active Objects registered on a host, using a registry(RMI or JINI or HTTP or IBIS)
* The registry where to look for is fully determined with the protocol included in the url.
* @param url The url where to perform the lookup. The url takes the following form:
* protocol://machine_name:port. Protocol and port can be ommited if respectively RMI and 1099:
* //machine_name
* @return String [] the list of names registered on the host; if no Registry found, returns {}
* @throws IOException If the given url does not map to a physical host, or if the connection is refused.
*/
public static String[] listActive(String url) throws java.io.IOException {
String[] activeNames = null;
String protocol = UrlBuilder.getProtocol(url);
// First step towards Body factory, will be introduced after the release
if (protocol.equals("rmi:")) {
activeNames = new RmiBodyAdapter().list(url);
} else if (protocol.equals("rmissh:")) {
activeNames = new SshRmiBodyAdapter().list(url);
} else if (protocol.equals("http:")) {
activeNames = new HttpBodyAdapter().list(url);
} else if (protocol.equals("ibis:")) {
activeNames = new IbisBodyAdapter().list(url);
} else {
throw new IOException("Protocol " + protocol + " not defined");
}
return activeNames;
}
/**
* Return the URL of the remote <code>activeObject</code>.
* @param activeObject the remote active object.
* @return the URL of <code>activeObject</code>.
*/
public static String getActiveObjectNodeUrl(Object activeObject) {
UniversalBody body = getRemoteBody(activeObject);
return body.getNodeURL();
}
/**
* Find out if the object contains an exception that should be thrown
* @param future the future object that is examinated
* @return true iff an exception should be thrown when accessing the object
*/
public static boolean isException(Object future) {
// If the object is not reified, it cannot be a future
if ((MOP.isReifiedObject(future)) == false) {
return false;
} else {
org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy();
// If it is reified but its proxy is not of type future it's not an exception
if (!(theProxy instanceof Future)) {
return false;
} else {
return ((Future) theProxy).getRaisedException() != null;
}
}
}
/**
* Blocks the calling thread until the object <code>future</code>
* is available. <code>future</code> must be the result object of an
* asynchronous call. Usually the the wait by necessity model take care
* of blocking the caller thread asking for a result not yet available.
* This method allows to block before the result is first used.
* @param future object to wait for
*/
public static void waitFor(Object future) {
// If the object is not reified, it cannot be a future
if ((MOP.isReifiedObject(future)) == false) {
return;
} else {
org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy();
// If it is reified but its proxy is not of type future, we cannot wait
if (!(theProxy instanceof Future)) {
return;
} else {
((Future) theProxy).waitFor();
}
}
}
/**
* Blocks the calling thread until the object <code>future</code>
* is available or until the timeout expires. <code>future</code> must be the result object of an
* asynchronous call. Usually the the wait by necessity model take care
* of blocking the caller thread asking for a result not yet available.
* This method allows to block before the result is first used.
* @param future object to wait for
* @param timeout to wait in ms
* @throws ProActiveException if the timeout expire
*/
public static void waitFor(Object future, long timeout)
throws ProActiveException {
// If the object is not reified, it cannot be a future
if ((MOP.isReifiedObject(future)) == false) {
return;
} else {
org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy();
// If it is reified but its proxy is not of type future, we cannot wait
if (!(theProxy instanceof Future)) {
return;
} else {
((Future) theProxy).waitFor(timeout);
}
}
}
/**
* Returns a <code>ProActiveDescriptor</code> that gives an object representation
* of the XML document located at the url given by proactive.pad system's property.
* @return the pad located at the url given by proactive.pad system's property
* @throws ProActiveException
* @throws RemoteException
*/
public static ProActiveDescriptor getProactiveDescriptor()
throws ProActiveException, IOException {
String padURL = System.getProperty("proactive.pad");
//System.out.println("pad propertie : " + padURL) ;
if (padURL == null) {
//System.out.println("pad null");
return null;
} else {
return getProActiveDescriptor(padURL, new VariableContract(), true);
}
}
/**
* Returns a <code>ProActiveDescriptor</code> that gives an object representation
* of the XML document located at the given url.
* @param xmlDescriptorUrl The url of the XML document
* @return ProActiveDescriptor. The object representation of the XML document
* @throws ProActiveException if a problem occurs during the creation of the object
* @see org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor
* @see org.objectweb.proactive.core.descriptor.data.VirtualNode
* @see org.objectweb.proactive.core.descriptor.data.VirtualMachine
*/
public static ProActiveDescriptor getProactiveDescriptor(
String xmlDescriptorUrl) throws ProActiveException {
return getProActiveDescriptor(xmlDescriptorUrl, new VariableContract(),
false);
}
/**
* Returns a <code>ProActiveDescriptor</code> that gives an object representation
* of the XML document located at the given url, and uses the given Variable Contract.
* @param xmlDescriptorUrl The url of the XML document
* @return ProActiveDescriptor. The object representation of the XML document
* @throws ProActiveException if a problem occurs during the creation of the object
* @see org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor
* @see org.objectweb.proactive.core.descriptor.data.VirtualNode
* @see org.objectweb.proactive.core.descriptor.data.VirtualMachine
*/
public static ProActiveDescriptor getProactiveDescriptor(
String xmlDescriptorUrl, VariableContract variableContract)
throws ProActiveException {
if (variableContract == null) {
throw new NullPointerException(
"Argument variableContract can not be null");
}
return getProActiveDescriptor(xmlDescriptorUrl, variableContract, false);
}
private static ProActiveDescriptor getProActiveDescriptor(
String xmlDescriptorUrl, VariableContract variableContract,
boolean hierarchicalSearch) throws ProActiveException {
//Get lock on XMLProperties global static variable
org.objectweb.proactive.core.xml.VariableContract.lock.aquire();
org.objectweb.proactive.core.xml.VariableContract.xmlproperties = variableContract;
//Get the pad
ProActiveDescriptor pad;
try {
pad = internalGetProActiveDescriptor(xmlDescriptorUrl,
variableContract, hierarchicalSearch);
} catch (ProActiveException e) {
org.objectweb.proactive.core.xml.VariableContract.lock.release();
throw e;
}
//No further modifications can be donde on the xmlproperties, thus we close the contract
variableContract.close();
//Check the contract (proposed optimization: Do this when parsing </variable> tag instead of here!)
if (!variableContract.checkContract()) {
logger.error(variableContract.toString());
org.objectweb.proactive.core.xml.VariableContract.lock.release();
throw new ProActiveException("Variable Contract has not been met!");
}
//Release lock on static global variable XMLProperties
VariableContract.xmlproperties = new VariableContract();
org.objectweb.proactive.core.xml.VariableContract.lock.release();
return pad;
//return getProactiveDescriptor(xmlDescriptorUrl, false);
}
/**
* return the pad matching with the given url or parse it from the file system
* @param xmlDescriptorUrl url of the pad
* @param hierarchicalSearch must search in hierarchy ?
* @return the pad found or a new pad parsed from xmlDescriptorUrl
* @throws ProActiveException
* @throws RemoteException
*/
private static ProActiveDescriptor internalGetProActiveDescriptor(
String xmlDescriptorUrl, VariableContract variableContract,
boolean hierarchicalSearch) throws ProActiveException {
RuntimeFactory.getDefaultRuntime();
if (xmlDescriptorUrl.indexOf(':') == -1) {
xmlDescriptorUrl = "file:" + xmlDescriptorUrl;
}
ProActiveRuntimeImpl part = (ProActiveRuntimeImpl) ProActiveRuntimeImpl.getProActiveRuntime();
ProActiveDescriptor pad;
try {
if (!hierarchicalSearch) {
//if not hierarchical search, we assume that the descriptor might has been
//register with the default jobID
pad = part.getDescriptor(xmlDescriptorUrl +
ProActive.getJobId(), hierarchicalSearch);
} else {
pad = part.getDescriptor(xmlDescriptorUrl, hierarchicalSearch);
}
} catch (Exception e) {
throw new ProActiveException(e);
}
// if pad found, returns it
if (pad != null) {
return pad;
}
// else parses it
try {
if (logger.isInfoEnabled()) {
logger.info("************* Reading deployment descriptor: " +
xmlDescriptorUrl + " ********************");
}
ProActiveDescriptorHandler proActiveDescriptorHandler = ProActiveDescriptorHandler.createProActiveDescriptor(xmlDescriptorUrl,
variableContract);
pad = (ProActiveDescriptor) proActiveDescriptorHandler.getResultObject();
part.registerDescriptor(pad.getUrl(), pad);
return pad;
} catch (org.xml.sax.SAXException e) {
//e.printStackTrace(); hides errors when testing parameters in xml descriptors
logger.fatal(
"A problem occured when getting the proActiveDescriptor at location \"" +
xmlDescriptorUrl + "\".");
throw new ProActiveException(
"A problem occured when getting the proActiveDescriptor at location \"" +
xmlDescriptorUrl + "\"." + e);
} catch (java.io.IOException e) {
//e.printStackTrace(); hides errors when testing parameters in xml descriptors
logger.fatal(
"A problem occured when getting the proActiveDescriptor at location \"" +
xmlDescriptorUrl + "\".");
throw new ProActiveException(e);
}
}
/**
* Registers locally the given VirtualNode in a registry such RMIRegistry or JINI Lookup Service or HTTP registry.
* The VirtualNode to register must exist on the local runtime. This is done when using XML Deployment Descriptors
* @param virtualNode the VirtualNode to register.
* @param registrationProtocol The protocol used for registration or null in order to use the protocol used to start the jvm.
* At this time RMI, JINI, HTTP, IBIS are supported. If set to null, the registration protocol will be set to the system property:
* proactive.communication.protocol
* @param replacePreviousBinding
* @throws ProActiveException If the VirtualNode with the given name has not been yet activated or does not exist on the local runtime
*/
public static void registerVirtualNode(VirtualNode virtualNode,
String registrationProtocol, boolean replacePreviousBinding)
throws ProActiveException, AlreadyBoundException {
if (!(virtualNode instanceof VirtualNodeImpl)) {
throw new ProActiveException(
"Cannot register such virtualNode since it results from a lookup!");
}
if (registrationProtocol == null) {
registrationProtocol = System.getProperty(
"proactive.communication.protocol");
}
String virtualnodeName = virtualNode.getName();
ProActiveRuntime part = RuntimeFactory.getProtocolSpecificRuntime(registrationProtocol);
VirtualNode vn = part.getVirtualNode(virtualnodeName);
if (vn == null) {
throw new ProActiveException("VirtualNode " + virtualnodeName +
" has not been yet activated or does not exist! Try to activate it first !");
}
part.registerVirtualNode(UrlBuilder.appendVnSuffix(virtualnodeName),
replacePreviousBinding);
}
/**
* Looks-up a VirtualNode previously registered in a registry(RMI or JINI or HTTP or IBIS)
* The registry where to look for is fully determined with the protocol included in the url
* @param url The url where to perform the lookup. The url takes the following form:
* protocol://machine_name:port/name. Protocol and port can be ommited if respectively RMI and 1099:
* //machine_name/name
* @return VirtualNode The virtualNode returned by the lookup
* @throws ProActiveException If no objects are bound with the given url
*/
public static VirtualNode lookupVirtualNode(String url)
throws ProActiveException {
ProActiveRuntime remoteProActiveRuntime = null;
try {
remoteProActiveRuntime = RuntimeFactory.getRuntime(UrlBuilder.buildVirtualNodeUrl(
url), UrlBuilder.getProtocol(url));
} catch (UnknownHostException ex) {
throw new ProActiveException(ex);
}
return remoteProActiveRuntime.getVirtualNode(UrlBuilder.getNameFromUrl(
url));
}
/**
* Unregisters the virtualNode previoulsy registered in a registry such as JINI or RMI.
* Calling this method removes the VirtualNode from the local runtime.
* @param virtualNode The VirtualNode to unregister
* @throws ProActiveException if a problem occurs whle unregistering the VirtualNode
*/
public static void unregisterVirtualNode(VirtualNode virtualNode)
throws ProActiveException {
//VirtualNode vn = ((VirtualNodeStrategy)virtualNode).getVirtualNode();
if (!(virtualNode instanceof VirtualNodeImpl)) {
throw new ProActiveException(
"Cannot unregister such virtualNode since it results from a lookup!");
}
String virtualNodeName = virtualNode.getName();
ProActiveRuntime part = RuntimeFactory.getProtocolSpecificRuntime(((VirtualNodeImpl) virtualNode).getRegistrationProtocol());
part.unregisterVirtualNode(UrlBuilder.appendVnSuffix(
virtualNode.getName()));
if (logger.isInfoEnabled()) {
logger.info("Success at unbinding " + virtualNodeName);
}
}
/**
* When an active object is created, it is associated with a Body that takes care
* of all non fonctionnal properties. Assuming that the active object is only
* accessed by the different Stub objects, all method calls end-up as Requests sent
* to this Body. Therefore the only thread calling the method of the active object
* is the active thread managed by the body. There is an unique mapping between the
* active thread and the body responsible for it. From any method in the active object
* the current thread caller of the method is the active thread. When a reified method wants
* to get a reference to the Body associated to the active object, it can invoke this
* method. Assuming that the current thread is the active thread, the associated body
* is returned.
* @return the body associated to the active object whose active thread is calling
* this method.
*/
public static Body getBodyOnThis() {
return LocalBodyStore.getInstance().getCurrentThreadBody();
}
/**
* Returns a Stub-Proxy couple pointing to the local body associated to the active
* object whose active thread is calling this method.
* @return a Stub-Proxy couple pointing to the local body.
* @see #getBodyOnThis
*/
public static StubObject getStubOnThis() {
Body body = getBodyOnThis();
if (logger.isDebugEnabled()) {
//logger.debug("ProActive: getStubOnThis() returns " + body);
}
if (body == null) {
return null;
}
return getStubForBody(body);
}
/**
* Migrates the active object whose active thread is calling this method to the
* same location as the active object given in parameter.
* This method must be called from an active object using the active thread as the
* current thread will be used to find which active object is calling the method.
* The object given as destination must be an active object.
* @param activeObject the active object indicating the destination of the migration.
* @exception MigrationException if the migration fails
* @see #getBodyOnThis
*/
public static void migrateTo(Object activeObject) throws MigrationException {
migrateTo(getNodeFromURL(getNodeURLFromActiveObject(activeObject)));
}
/**
* Migrates the active object whose active thread is calling this method to the
* node caracterized by the given url.
* This method must be called from an active object using the active thread as the
* current thread will be used to find which active object is calling the method.
* The url must be the url of an existing node.
* @param nodeURL the url of an existing where to migrate to.
* @exception MigrationException if the migration fails
* @see #getBodyOnThis
*/
public static void migrateTo(String nodeURL) throws MigrationException {
if (logger.isDebugEnabled()) {
logger.debug("migrateTo " + nodeURL);
}
ProActive.migrateTo(getNodeFromURL(nodeURL));
}
/**
* Migrates the active object whose active thread is calling this method to the
* given node.
* This method must be called from an active object using the active thread as the
* current thread will be used to find which active object is calling the method.
* @param node an existing node where to migrate to.
* @exception MigrationException if the migration fails
* @see #getBodyOnThis
*/
public static void migrateTo(Node node) throws MigrationException {
if (logger.isDebugEnabled()) {
logger.debug("migrateTo " + node);
}
Body bodyToMigrate = getBodyOnThis();
if (!(bodyToMigrate instanceof Migratable)) {
throw new MigrationException(
"This body cannot migrate. It doesn't implement Migratable interface");
}
((Migratable) bodyToMigrate).migrateTo(node);
}
/**
* Migrates the given body to the same location as the active object given in parameter.
* This method can be called from any object and does not perform the migration.
* Instead it generates a migration request that is sent to the targeted body.
* The object given as destination must be an active object.
* @param bodyToMigrate the body to migrate.
* @param activeObject the active object indicating the destination of the migration.
* @param isNFRequest a boolean indicating that the request is not functional i.e it does not modify the application's computation
* @exception MigrationException if the migration fails
*/
public static void migrateTo(Body bodyToMigrate, Object activeObject,
boolean isNFRequest) throws MigrationException {
ProActive.migrateTo(bodyToMigrate,
getNodeFromURL(getNodeURLFromActiveObject(activeObject)),
isNFRequest);
}
/**
* Migrates the given body to the node caracterized by the given url.
* This method can be called from any object and does not perform the migration.
* Instead it generates a migration request that is sent to the targeted body.
* The object given as destination must be an active object.
* @param bodyToMigrate the body to migrate.
* @param nodeURL the url of an existing where to migrate to.
* @param isNFRequest a boolean indicating that the request is not functional i.e it does not modify the application's computation
* @exception MigrationException if the migration fails
*/
public static void migrateTo(Body bodyToMigrate, String nodeURL,
boolean isNFRequest) throws MigrationException {
ProActive.migrateTo(bodyToMigrate, getNodeFromURL(nodeURL), isNFRequest);
}
/**
* Migrates the body <code>bodyToMigrate</code> to the given node.
* This method can be called from any object and does not perform the migration.
* Instead it generates a migration request that is sent to the targeted body.
* The object given as destination must be an active object.
* @param bodyToMigrate the body to migrate.
* @param node an existing node where to migrate to.
* @param isNFRequest a boolean indicating that the request is not functional i.e it does not modify the application's computation
* @exception MigrationException if the migration fails
*/
public static void migrateTo(Body bodyToMigrate, Node node,
boolean isNFRequest) throws MigrationException {
//In the context of ProActive, migration of an active object is considered as a non functional request.
//That's why "true" is set by default for the "isNFRequest" parameter.
ProActive.migrateTo(bodyToMigrate, node, true,
org.objectweb.proactive.core.body.request.Request.NFREQUEST_IMMEDIATE_PRIORITY);
}
/**
* Migrates the body <code>bodyToMigrate</code> to the given node.
* This method can be called from any object and does not perform the migration.
* Instead it generates a migration request that is sent to the targeted body.
* The object given as destination must be an active object.
* @param bodyToMigrate the body to migrate.
* @param node an existing node where to migrate to.
* @param isNFRequest a boolean indicating that the request is not functional i.e it does not modify the application's computation
* @param priority the level of priority of the non functional request. Levels are defined in Request interface of ProActive.
* @exception MigrationException if the migration fails
*/
public static void migrateTo(Body bodyToMigrate, Node node,
boolean isNFRequest, int priority) throws MigrationException {
if (!(bodyToMigrate instanceof Migratable)) {
throw new MigrationException(
"This body cannot migrate. It doesn't implement Migratable interface");
}
Object[] arguments = { node };
try {
BodyRequest request = new BodyRequest(bodyToMigrate, "migrateTo",
new Class[] { Node.class }, arguments, isNFRequest, priority);
request.send(bodyToMigrate);
} catch (NoSuchMethodException e) {
throw new MigrationException("Cannot find method migrateTo this body. Non sense since the body is instance of Migratable",
e);
} catch (java.io.IOException e) {
throw new MigrationException("Cannot send the request to migrate", e);
}
}
/**
* Blocks the calling thread until one of the futures in the vector is available.
* THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT.
* @param futures vector of futures
* @return index of the available future in the vector
*/
public static int waitForAny(java.util.Vector futures) {
try {
return waitForAny(futures, 0);
} catch (ProActiveException e) {
//Exception above should never be thrown since timeout=0 means no timeout
e.printStackTrace();
return -1;
}
}
/**
* Blocks the calling thread until one of the futures in the vector is available
* or until the timeout expires.
* THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT.
* @param futures vector of futures
* @param timeout to wait in ms
* @return index of the available future in the vector
* @throws ProActiveException if the timeout expires
*/
public static int waitForAny(java.util.Vector futures, long timeout)
throws ProActiveException {
FuturePool fp = getBodyOnThis().getFuturePool();
synchronized (fp) {
while (true) {
java.util.Iterator it = futures.iterator();
int index = 0;
while (it.hasNext()) {
Object current = it.next();
if (!isAwaited(current)) {
return index;
}
index++;
}
fp.waitForReply(timeout);
}
}
}
/**
* Blocks the calling thread until all futures in the vector are available.
* THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT.
* @param futures vector of futures
*/
public static void waitForAll(java.util.Vector futures) {
try {
ProActive.waitForAll(futures, 0);
} catch (ProActiveException e) {
//Exception above should never be thrown since timeout=0 means no timeout
e.printStackTrace();
}
}
/**
* Blocks the calling thread until all futures in the vector are available or until
* the timeout expires.
* THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT.
* @param futures vector of futures
* @param timeout to wait in ms
* @throws ProActiveException if the timeout expires
*/
public static void waitForAll(java.util.Vector futures, long timeout)
throws ProActiveException {
FuturePool fp = getBodyOnThis().getFuturePool();
synchronized (fp) {
boolean oneIsMissing = true;
while (oneIsMissing) {
oneIsMissing = false;
java.util.Iterator it = futures.iterator();
while (it.hasNext()) {
Object current = it.next();
if (isAwaited(current)) {
oneIsMissing = true;
}
}
if (oneIsMissing) {
fp.waitForReply(timeout);
}
}
}
}
/**
* Blocks the calling thread until the N-th of the futures in the vector is available.
* THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT.
* @param futures vector of futures
*/
public static void waitForTheNth(java.util.Vector futures, int n) {
FuturePool fp = getBodyOnThis().getFuturePool();
synchronized (fp) {
Object current = futures.get(n);
if (isAwaited(current)) {
waitFor(current);
}
}
}
/**
* Blocks the calling thread until the N-th of the futures in the vector is available.
* THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT.
* @param futures vector of futures
* @param n
* @param timeout to wait in ms
* @throws ProActiveException if the timeout expires
*/
public static void waitForTheNth(java.util.Vector futures, int n,
long timeout) throws ProActiveException {
FuturePool fp = getBodyOnThis().getFuturePool();
synchronized (fp) {
Object current = futures.get(n);
if (isAwaited(current)) {
waitFor(current, timeout);
}
}
}
/**
* Return <code>false</code> if one object of <code>futures</code> is
* available.
* @param futures a table with futures.
* @return <code>true</code> if all futures are awaited, else <code>false
* </code>.
*/
public static boolean allAwaited(java.util.Vector futures) {
FuturePool fp = getBodyOnThis().getFuturePool();
synchronized (fp) {
java.util.Iterator it = futures.iterator();
while (it.hasNext()) {
Object current = it.next();
if (!isAwaited(current)) {
return false;
}
}
return true;
}
}
/**
* Return false if the object <code>future</code> is available.
* This method is recursive, i.e. if result of future is a future too,
* <CODE>isAwaited</CODE> is called again on this result, and so on.
*/
public static boolean isAwaited(Object future) {
// If the object is not reified, it cannot be a future
if ((MOP.isReifiedObject(future)) == false) {
return false;
} else {
org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy();
// If it is reified but its proxy is not of type future, we cannot wait
if (!(theProxy instanceof Future)) {
return false;
} else {
if (((Future) theProxy).isAwaited()) {
return true;
} else {
return isAwaited(((Future) theProxy).getResult());
}
}
}
}
/**
* Return the object contains by the future (ie its target).
* If parameter is not a future, it is returned.
* A wait-by-necessity occurs if future is not available.
* This method is recursive, i.e. if result of future is a future too,
* <CODE>getFutureValue</CODE> is called again on this result, and so on.
*/
public static Object getFutureValue(Object future) {
while (true) {
// If the object is not reified, it cannot be a future
if ((MOP.isReifiedObject(future)) == false) {
return future;
} else {
org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy();
// If it is reified but its proxy is not of type future, we cannot wait
if (!(theProxy instanceof Future)) {
return future;
} else {
future = ((Future) theProxy).getResult();
}
}
}
}
/**
* Enable the automatic continuation mechanism for this active object.
*/
public static void enableAC(Object obj) throws java.io.IOException {
UniversalBody body = getRemoteBody(obj);
body.enableAC();
}
/**
* Disable the automatic continuation mechanism for this active object.
*/
public static void disableAC(Object obj) throws java.io.IOException {
UniversalBody body = getRemoteBody(obj);
body.disableAC();
}
/**
* Kill an Active Object while calling terminate() method on its body.
* @param ao the active object to kill
* @param immediate if this boolean is true, this method is served as an immediate service.
* The active object dies immediatly. Else, the kill request is served as a normal request, it
* is put on the request queue.
*/
public static void terminateActiveObject(Object ao, boolean immediate) {
Proxy proxy = ((StubObject) ao).getProxy();
try {
if (immediate) {
NonFunctionalServices.terminateAOImmediately(proxy);
} else {
NonFunctionalServices.terminateAO(proxy);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
/**
* Set an immediate execution for the target active object obj of the method String,
* ie request of name methodName will be executed right away upon arrival at the target
* AO context.
* Warning: the execution of an Immediate Service method is achieved in parallel of the
* current services, so it is the programmer responsibility to ensure that Immediate Services
* do not interfere with any other methods.
* @param obj the object on which to set this immediate service
* @param methodName the name of the method
* @throws IOException
*/
public static void setImmediateService(Object obj, String methodName)
throws java.io.IOException {
UniversalBody body = getRemoteBody(obj);
body.setImmediateService(methodName);
}
/**
* Set an immediate execution for the target active object obj of the method String,
* ie request of name methodName will be executed right away upon arrival at the target
* AO context.
* Warning: the execution of an Immediate Service method is achieved in parallel of the
* current services, so it is the programmer responsibility to ensure that Immediate Services
* do not interfere with any other methods.
* @param obj the object on which to set this immediate service
* @param methodName the name of the method
* @param parametersTypes the types of the parameters of the method
* @throws IOException
*/
public static void setImmediateService(Object obj, String methodName,
Class[] parametersTypes) throws IOException {
UniversalBody body = getRemoteBody(obj);
body.setImmediateService(methodName, parametersTypes);
}
/**
* Removes an immmediate execution for the active object obj, i.e. requests corresponding to the name and types of parameters
* will be executed by the calling thread, and not added in the request queue.
* BE CAREFUL : for the first release of this method, do not make use of getCurrentThreadBody nor
* getStubOnThis in the method defined by methodName !!
*
* @param obj the object from which to remove this immediate service
* @param methodName the name of the method
* @param parametersTypes the types of the parameters of the method
* @throws IOException
*/
public static void removeImmediateService(Object obj, String methodName,
Class[] parametersTypes) throws IOException {
UniversalBody body = getRemoteBody(obj);
body.removeImmediateService(methodName, parametersTypes);
}
/**
* @param obj
* @return
*/
private static BodyAdapter getRemoteBody(Object obj) {
// Check if obj is really a reified object
if (!(MOP.isReifiedObject(obj))) {
throw new ProActiveRuntimeException("The given object " + obj +
" is not a reified object");
}
// Find the appropriate remoteBody
org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) obj).getProxy();
if (myProxy == null) {
throw new ProActiveRuntimeException(
"Cannot find a Proxy on the stub object: " + obj);
}
BodyProxy myBodyProxy = (BodyProxy) myProxy;
BodyAdapter body = myBodyProxy.getBody().getRemoteAdapter();
return body;
}
/**
* @return the jobId associated with the object calling this method
*/
public static String getJobId() {
return ProActive.getBodyOnThis().getJobID();
}
public static void exposeAsWebService(Object o, String url, String urn,
String[] methods) {
ProActiveDeployer.deploy(urn, url, o, methods);
}
/**
* Delete the service on a web server
* @param urn The name of the object
* @param url The url of the web server
*/
public static void unExposeAsWebService(String urn, String url) {
ProActiveDeployer.undeploy(urn, url);
}
public static void exposeComponentAsWebService(Component component,
String url, String componentName) {
ProActiveDeployer.deployComponent(componentName, url, component);
}
/**
* Undeploy component interfaces on a web server
* @param componentName The name of the component
* @param url The url of the web server
* @param component The component owning the services interfaces
*/
public static void unExposeComponentAsWebService(String componentName,
String url, Component component) {
ProActiveDeployer.undeployComponent(componentName, url, component);
}
private static String getNodeURLFromActiveObject(Object o)
throws MigrationException {
//first we check if the parameter is an active object,
if (!org.objectweb.proactive.core.mop.MOP.isReifiedObject(o)) {
throw new MigrationException(
"The parameter is not an active object");
}
//now we get a reference on the remoteBody of this guy
BodyProxy destProxy = (BodyProxy) ((org.objectweb.proactive.core.mop.StubObject) o).getProxy();
return destProxy.getBody().getNodeURL();
}
private static Node getNodeFromURL(String url) throws MigrationException {
try {
return NodeFactory.getNode(url);
} catch (NodeException e) {
throw new MigrationException("The node of given URL " + url +
" cannot be localized", e);
}
}
// STUB CREATION
private static StubObject getStubForBody(Body body) {
try {
return createStubObject(body.getReifiedObject(),
new Object[] { body },
body.getReifiedObject().getClass().getName(), null);
} catch (MOPException e) {
throw new ProActiveRuntimeException(
"Cannot create Stub for this Body e=" + e);
}
}
public static Object createStubObject(String className, UniversalBody body)
throws MOPException {
return createStubObject(className, null, null, new Object[] { body });
}
private static Object createStubObject(String className,
Class[] genericParameters, Object[] constructorParameters, Node node,
Active activity, MetaObjectFactory factory) throws MOPException {
return createStubObject(className, genericParameters,
constructorParameters,
new Object[] { node, activity, factory, ProActive.getJobId() });
}
private static Object createStubObject(String className,
Class[] genericParameters, Object[] constructorParameters,
Object[] proxyParameters) throws MOPException {
try {
return MOP.newInstance(className, genericParameters,
constructorParameters, Constants.DEFAULT_BODY_PROXY_CLASS_NAME,
proxyParameters);
} catch (ClassNotFoundException e) {
throw new ConstructionOfProxyObjectFailedException(
"Class can't be found e=" + e);
}
}
private static Object createStubObject(Object target,
String nameOfTargetType, Class[] genericParameters, Node node,
Active activity, MetaObjectFactory factory) throws MOPException {
return createStubObject(target,
new Object[] { node, activity, factory, ProActive.getJobId() },
nameOfTargetType, genericParameters);
}
private static StubObject createStubObject(Object object,
Object[] proxyParameters, String nameOfTargetType,
Class[] genericParameters) throws MOPException {
try {
return (StubObject) MOP.turnReified(nameOfTargetType,
Constants.DEFAULT_BODY_PROXY_CLASS_NAME, proxyParameters,
object, genericParameters);
} catch (ClassNotFoundException e) {
throw new ConstructionOfProxyObjectFailedException(
"Class can't be found e=" + e);
}
}
/*** <Exceptions> See ExceptionHandler.java for the documentation ***/
/**
* This has to be called just before a try block for a single exception.
*
* @param c the caught exception type in the catch block
*/
public static void tryWithCatch(Class c) {
tryWithCatch(new Class[] { c });
}
/**
* This has to be called just before a try block for many exceptions.
*
* @param c the caught exception types in the catch block
*/
public static void tryWithCatch(Class[] c) {
ExceptionHandler.tryWithCatch(c);
}
/**
* This has to be called at the end of the try block.
*/
public static void endTryWithCatch() {
ExceptionHandler.endTryWithCatch();
}
/**
* This has to be called at the beginning of the finally block, so
* it requires one.
*/
public static void removeTryWithCatch() {
ExceptionHandler.removeTryWithCatch();
}
/**
* This can be used to query a potential returned exception, and
* throw it if it exists.
*/
public static void throwArrivedException() {
ExceptionHandler.throwArrivedException();
}
/**
* This is used to wait for the return of every call, so that we know
* the execution can continue safely with no pending exception.
*/
public static void waitForPotentialException() {
ExceptionHandler.waitForPotentialException();
}
/**
* Add a listener for NFE reaching the local JVM
*
* @param listener The listener to add
*/
public static void addNFEListenerOnJVM(NFEListener listener) {
NFEManager.addNFEListener(listener);
}
/**
* Remove a listener for NFE reaching the local JVM
*
* @param listener The listener to remove
*/
public static void removeNFEListenerOnJVM(NFEListener listener) {
NFEManager.removeNFEListener(listener);
}
/**
* Add a listener for NFE reaching a given active object
*
* @param ao The active object receiving the NFE
* @param listener The listener to add
*/
public static void addNFEListenerOnAO(Object ao, NFEListener listener) {
/* Security hazard: arbitrary code execution by the ao... */
BodyAdapter body = getRemoteBody(ao);
body.addNFEListener(listener);
}
/**
* Remove a listener for NFE reaching a given active object
*
* @param ao The active object receiving the NFE
* @param listener The listener to remove
*/
public static void removeNFEListenerOnAO(Object ao, NFEListener listener) {
BodyAdapter body = getRemoteBody(ao);
body.removeNFEListener(listener);
}
/**
* Add a listener for NFE reaching the client side of a given active object
*
* @param ao The active object receiving the NFE
* @param listener The listener to add
*/
public static void addNFEListenerOnProxy(Object ao, NFEListener listener) {
try {
((AbstractProxy) ao).addNFEListener(listener);
} catch (ClassCastException cce) {
throw new IllegalArgumentException(
"The object must be a proxy to an active object");
}
}
/**
* Remove a listener for NFE reaching the client side of a given active object
*
* @param ao The active object receiving the NFE
* @param listener The listener to remove
*/
public static void removeNFEListenerOnProxy(Object ao, NFEListener listener) {
try {
((AbstractProxy) ao).removeNFEListener(listener);
} catch (ClassCastException cce) {
throw new IllegalArgumentException(
"The object must be a proxy to an active object");
}
}
private static ProxyForGroup getGroupProxy(Object group) {
ProxyForGroup pfg;
try {
pfg = (ProxyForGroup) ProActiveGroup.getGroup(group);
} catch (ClassCastException cce) {
pfg = null;
}
if (pfg == null) {
throw new IllegalArgumentException("The argument must be a group");
}
return pfg;
}
/**
* Add a listener for NFE regarding a group.
*
* @param group The group receiving the NFE
* @param listener The listener to add
*/
public static void addNFEListenerOnGroup(Object group, NFEListener listener) {
getGroupProxy(group).addNFEListener(listener);
}
/**
* Remove a listener for NFE regarding a group.
*
* @param group The group receiving the NFE
* @param listener The listener to remove
*/
public static void removeNFEListenerOnGroup(Object group,
NFEListener listener) {
getGroupProxy(group).removeNFEListener(listener);
}
/**
* Get the exceptions that have been caught in the current
* ProActive.tryWithCatch()/ProActive.removeTryWithCatch()
* block. This waits for every call in this block to return.
*
* @return a collection of these exceptions
*/
public static Collection getAllExceptions() {
return ExceptionHandler.getAllExceptions();
}
/**
* @return The node of the current active object.
* @throws NodeException problem with the node.
*/
public static Node getNode() throws NodeException {
BodyProxy destProxy = (BodyProxy) ((StubObject) getStubOnThis()).getProxy();
return NodeFactory.getNode(destProxy.getBody().getNodeURL());
}
/**
* Call this method at the end of the application if it completed
* successfully, for the launcher to be aware of it.
*/
public static void exitSuccess() {
System.exit(0);
}
/**
* Call this method at the end of the application if it did not complete
* successfully, for the launcher to be aware of it.
*/
public static void exitFailure() {
System.exit(1);
}
/**
* After this call, when the JVM has no more active objects
* it will be killed.
*
*/
public static void enableExitOnEmpty() {
LocalBodyStore.getInstance().enableExitOnEmpty();
}
/**
* Returns the number of this version
* @return String
*/
public static String getProActiveVersion() {
return "$Id$";
}
}
|
package org.postgresql.top;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Pattern;
import org.postgresql.top.PGTop.State;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class PGStatDatabase extends Activity implements Runnable {
private String pgDatabase;
private String url;
private String pgUser;
private String pgPassword;
private TextView headerTextView;
private TextView numbackendsTextView;
private TextView commitsTextView;
private TextView rollbacksTextView;
private TextView readTextView;
private TextView hitTextView;
private TextView returnedTextView;
private TextView fetchedTextView;
private TextView insertedTextView;
private TextView updatedTextView;
private TextView deletedTextView;
private String headerString;
private long numbackends = 0;
private long commits = 0;
private long rollbacks = 0;
private long read = 0;
private long hit = 0;
private long returned = 0;
private long fetched = 0;
private long inserted = 0;
private long updated = 0;
private long deleted = 0;
private long commitsOld = 0;
private long rollbacksOld = 0;
private long readOld = 0;
private long hitOld = 0;
private long returnedOld = 0;
private long fetchedOld = 0;
private long insertedOld = 0;
private long updatedOld = 0;
private long deletedOld = 0;
private String readPretty;
private String hitPretty;
private Boolean hasError;
private String errorMessage;
Thread thread = null;
private State state;
private Connection conn = null;
private Statement st;
private ResultSet rs;
private int major, branch;
private static String sql;
private void getDatabaseStats() throws SQLException {
try {
conn = DriverManager.getConnection(url, pgUser, pgPassword);
st = conn.createStatement();
rs = st.executeQuery(sql);
if (rs.next()) {
/* Save previous values. */
commitsOld = commits;
rollbacksOld = rollbacks;
readOld = read;
hitOld = hit;
returnedOld = returned;
fetchedOld = fetched;
insertedOld = inserted;
updatedOld = updated;
deletedOld = deleted;
/* Get new values. */
headerString = pgDatabase + " " + rs.getString(1);
numbackends = rs.getLong(2);
commits = rs.getLong(3);
rollbacks = rs.getLong(4);
read = rs.getLong(5);
hit = rs.getLong(6);
returned = rs.getLong(7);
fetched = rs.getLong(8);
inserted = rs.getLong(9);
updated = rs.getLong(10);
deleted = rs.getLong(11);
readPretty = rs.getString(12);
hitPretty = rs.getString(13);
}
rs.close();
st.close();
} finally {
if (conn != null) {
conn.close();
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pg_stat_database);
state = State.RUNNING;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
Toast
.makeText(PGStatDatabase.this, e.toString(),
Toast.LENGTH_LONG).show();
return;
}
SharedPreferences preferences = getSharedPreferences("PGTopPrefs", 0);
pgDatabase = preferences.getString("pgdatabase", "");
url = preferences.getString("pgurl", "");
pgUser = preferences.getString("pguser", "");
pgPassword = preferences.getString("pgpassword", "");
headerTextView = (TextView) findViewById(R.id.displayheader);
numbackendsTextView = (TextView) findViewById(R.id.numbackends);
commitsTextView = (TextView) findViewById(R.id.xact_commit);
rollbacksTextView = (TextView) findViewById(R.id.xact_rollback);
readTextView = (TextView) findViewById(R.id.blks_read);
hitTextView = (TextView) findViewById(R.id.blks_hit);
returnedTextView = (TextView) findViewById(R.id.tup_returned);
fetchedTextView = (TextView) findViewById(R.id.tup_fetched);
insertedTextView = (TextView) findViewById(R.id.tup_inserted);
updatedTextView = (TextView) findViewById(R.id.tup_updated);
deletedTextView = (TextView) findViewById(R.id.tup_deleted);
try {
conn = DriverManager.getConnection(url, pgUser, pgPassword);
st = conn.createStatement();
rs = st.executeQuery("SHOW server_version;");
if (rs.next()) {
Pattern p = Pattern.compile("\\.");
String version[] = p.split(rs.getString(1));
major = Integer.parseInt(version[0]);
branch = Integer.parseInt(version[1]);
}
rs.close();
st.close();
} catch (SQLException e) {
Toast
.makeText(PGStatDatabase.this, e.toString(),
Toast.LENGTH_LONG).show();
return;
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// Nothing to worry about now.
}
}
}
if (major >= 9 || (major == 8 && branch >= 4)) {
// This should be versions 8.4 and newer.
// FIXME: Use named parameters.
sql = ""
+ "SELECT NOW(), numbackends, xact_commit, xact_rollback, "
+ " blks_read, blks_hit, tup_returned, tup_fetched, "
+ " tup_inserted, tup_updated, tup_deleted, "
+ " PG_SIZE_PRETTY((blks_read - "
+ Long.toString(readOld) + ") * setting), "
+ " PG_SIZE_PRETTY((blks_hit - "
+ Long.toString(hitOld) + ") * setting) "
+ "FROM (SELECT setting::BIGINT "
+ " FROM pg_settings "
+ " WHERE name = 'block_size') AS pg_settings, "
+ " pg_stat_database " + "WHERE datname = '"
+ pgDatabase + "';";
} else {
// This should be all cases older than 8.4.
// FIXME: Use named parameters.
// FIXME: Don't display the data that doesn't exist as oppose to making zeros.
sql = ""
+ "SELECT NOW(), numbackends, xact_commit, xact_rollback, "
+ " blks_read, blks_hit, 0, 0, 0, 0, 0, "
+ " PG_SIZE_PRETTY((blks_read - "
+ Long.toString(readOld) + ") * setting), "
+ " PG_SIZE_PRETTY((blks_hit - "
+ Long.toString(hitOld) + ") * setting) "
+ "FROM (SELECT setting::BIGINT "
+ " FROM pg_settings "
+ " WHERE name = 'block_size') AS pg_settings, "
+ " pg_stat_database " + "WHERE datname = '"
+ pgDatabase + "';";
}
thread = new Thread(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
protected void onDestroy() {
super.onDestroy();
state = State.EXITING;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.stop:
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPause() {
super.onPause();
state = State.PAUSED;
}
@Override
protected void onResume() {
super.onResume();
state = State.RUNNING;
if (thread != null)
thread.start();
}
@Override
protected void onStop() {
super.onStop();
state = State.EXITING;
}
public void run() {
/*
* Loop to refresh the display of database statistics. Open and close a
* connection on each loop.
*/
while (state == State.RUNNING) {
try {
getDatabaseStats();
hasError = false;
} catch (SQLException e) {
errorMessage = e.toString();
hasError = true;
state = State.PAUSED;
}
handler.sendEmptyMessage(0);
try {
// FIXME: Make the refresh rate a configuration parameter.
Thread.sleep(2000);
} catch (InterruptedException e) {
errorMessage = e.toString();
hasError = true;
handler.sendEmptyMessage(0);
state = State.PAUSED;
}
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
headerTextView.setText(headerString);
if (hasError) {
Toast.makeText(PGStatDatabase.this, errorMessage,
Toast.LENGTH_LONG).show();
} else {
numbackendsTextView.setText("Database Connections: "
+ Long.toString(numbackends));
commitsTextView.setText("Commits: "
+ Long.toString(commits - commitsOld));
rollbacksTextView.setText("Rollbacks: "
+ Long.toString(rollbacks - rollbacksOld));
readTextView.setText("Blocks Read: "
+ Long.toString(read - readOld) + " (" + readPretty
+ ")");
hitTextView.setText("Blocks Hit: "
+ Long.toString(hit - hitOld) + " (" + hitPretty + ")");
returnedTextView.setText("Rows Returned: "
+ Long.toString(returned - returnedOld));
fetchedTextView.setText("Row Fetched: "
+ Long.toString(fetched - fetchedOld));
insertedTextView.setText("Rows Inserted: "
+ Long.toString(inserted - insertedOld));
updatedTextView.setText("Rows Updated: "
+ Long.toString(updated - updatedOld));
deletedTextView.setText("Rows Deleted: "
+ Long.toString(deleted - deletedOld));
}
}
};
}
|
package org.yuanheng.cookcc.parser;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Pattern;
import org.yuanheng.cookcc.Main;
import org.yuanheng.cookcc.dfa.DFARow;
import org.yuanheng.cookcc.dfa.DFATable;
import org.yuanheng.cookcc.doc.*;
import org.yuanheng.cookcc.exception.ParserException;
import org.yuanheng.cookcc.lexer.CCL;
/**
* @author Heng Yuan
* @version $Id$
*/
public class Parser
{
private final static String PROP_PARSER = "Parser";
private final static String PROP_PRODUCTION = "Production";
private static Pattern s_tokenNamePattern = Pattern.compile ("[a-zA-Z_][a-zA-Z_0-9]*");
public static String START = "@start";
public static int FINISH = 0;
public static int ERROR = 1;
// private static Token s_epsilon = new Token ("{e}", 0, EPSILON, Token.NONASSOC);
private static Token s_finish = new Token ("$", 0, FINISH, Token.NONASSOC);
private static Token s_error = new Token ("error", 0, ERROR, Token.NONASSOC);
public static Parser getParser (Document doc) throws IOException
{
if (doc == null)
return null;
ParserDoc parserDoc = doc.getParser ();
if (parserDoc == null)
return null;
Object obj = parserDoc.getProperty (PROP_PARSER);
Parser parser;
if (obj == null | !(obj instanceof Parser))
{
parser = new Parser (doc);
parser.parse ();
parserDoc.setProperty (PROP_PARSER, parser);
}
else
parser = (Parser)obj;
return parser;
}
int m_maxTerminal;
private short m_productionIdCounter = 1;
private final Document m_doc;
private int m_terminalCount;
private int m_nonTerminalCount;
private int m_usedTerminalCount;
private int m_usedSymbolCount;
/** symbols actually being used. This is the ecs of the input */
private int[] m_usedSymbols;
/** look up the index of a terminal in m_usedSymbols */
private int[] m_symbolGroups;
private final Map<String, Token> m_terminals = new HashMap<String, Token> ();
private final Map<Integer, Token> m_terminalMap = new HashMap<Integer, Token> ();
private final Map<String, Integer> m_nonTerminals = new HashMap<String, Integer> ();
private final Vector<Production> m_productions = new Vector<Production> ();
private final Map<Integer, String> m_symbolMap = new TreeMap<Integer, String> ();
// for a given symbol, its productions
private final Map<Integer, Production[]> m_productionMap = new HashMap<Integer, Production[]> ();
private final HashMap<Integer, int[]> m_firstSet = new HashMap<Integer, int[]> ();
private final HashMap<Integer, TokenSet> m_firstSetVal = new HashMap<Integer, TokenSet> ();
private final DFATable m_dfa = new DFATable ();
private final Vector<short[]> m_goto = new Vector<short[]> ();
private final LinkedList<Token> m_tokens = new LinkedList<Token> ();
private final HashMap<Integer, MessageFormat> m_formats = new HashMap<Integer, MessageFormat> ();
final Vector<ItemSet> _DFAStates = new Vector<ItemSet> ();
final Map<ItemSet, Short> _DFASet = new TreeMap<ItemSet, Short> ();
private int m_reduceConflict;
private int m_shiftConflict;
private PrintStream m_out;
private Parser (Document doc)
{
m_doc = doc;
}
private void verbose (String msg)
{
if (m_out == null)
return;
m_out.println (msg);
}
private void verboseSection (String section)
{
if (m_out == null)
return;
m_out.println ();
m_out.println ("
}
public void parse () throws IOException
{
File analysisFile = Main.getAnalysisFile ();
if (analysisFile != null)
m_out = new PrintStream (new FileOutputStream (analysisFile));
m_terminals.put (s_finish.name, s_finish);
m_terminals.put (s_error.name, s_error);
m_symbolMap.put (s_finish.value, s_finish.name);
m_symbolMap.put (s_error.value, s_error.name);
m_maxTerminal = parseTerminals ();
// add start condition
Production startProduction = new Production (getNonterminal (START), m_productionIdCounter++);
m_productions.add (startProduction);
m_productionMap.put (m_nonTerminals.get (START), new Production[]{ startProduction });
parseProductions ();
// make sure all the non-terminals have its production
for (int i = 0; i < m_nonTerminalCount; ++i)
{
if (m_productionMap.get (i + m_maxTerminal + 1) == null)
throw new ParserException (0, "Missing production for non-terminal " + m_symbolMap.get (i + m_maxTerminal + 1));
}
ParserDoc parserDoc = m_doc.getParser ();
Integer startNonTerminal = parserDoc.getStart () == null ? m_productions.get (0).getSymbol () : m_nonTerminals.get (parserDoc.getStart ());
if (startNonTerminal == null)
throw new ParserException (0, "Unable to find the start symbol for the parser.");
startProduction.setProduction (new int[]{ startNonTerminal });
// now we need to add the internal symbols
// the computed used tokens can be smaller than the symbol map
// if there are terminals that are declared but not used.
// other times, such as in case of Unary minus, a token is used
// merely to specify the precedence
m_terminalCount = computeUsedSymbols ();
m_usedSymbolCount = m_usedSymbols.length;
m_usedTerminalCount = m_usedSymbols.length - m_nonTerminalCount;
verboseSection ("used symbols");
for (int i = 0; i < m_usedSymbols.length; ++i)
verbose (i + "\t:\t" + m_usedSymbols[i] + "\t:\t" + m_symbolMap.get (m_usedSymbols[i]));
verboseSection ("statistics");
verbose ("max terminal = " + m_maxTerminal);
verbose ("non terminal count = " + m_nonTerminalCount);
verbose ("terminal count = " + m_terminalCount);
verbose ("used terminal count = " + m_usedTerminalCount);
verbose ("used symbol count = " + m_usedSymbolCount);
// verbose ("symbol map = " + m_symbolMap);
verboseSection ("productions");
for (Production p : m_productions)
verbose (toString (p));
computeFirstSet ();
new LALR (this).build ();
reduce ();
if (m_out != null)
{
m_out.close ();
m_out = null;
}
}
private int parseTerminals ()
{
int precedenceLevel = 0;
TokensDoc[] tokensDocs = m_doc.getTokens ();
int maxTerminalValue = 255;
int[] checkValue = new int[1];
for (TokensDoc tokensDoc : tokensDocs)
{
int level = precedenceLevel++;
for (String name : tokensDoc.getTokens ())
{
if (m_terminals.containsKey (name))
throw new ParserException (tokensDoc.getLineNumber (), "Duplicate token " + name + " specified.");
checkValue[0] = 0;
name = checkTerminalName (tokensDoc.getLineNumber (), name, checkValue, true);
int v = checkValue[0];
if (v == 0)
v = ++maxTerminalValue;
Token token = new Token (name, level, v, tokensDoc.getType ());
m_terminals.put (name, token);
m_terminalMap.put (v, token);
if (m_symbolMap.get (v) == null)
m_symbolMap.put (v, name);
if (checkValue[0] == 0)
m_tokens.add (token);
}
}
return maxTerminalValue;
}
private void parseProductions ()
{
int[] pos = new int[1];
for (GrammarDoc grammar : m_doc.getParser ().getGrammars ())
{
int lhs = getNonterminal (grammar.getRule ());
LinkedList<Production> prods = new LinkedList<Production> ();
for (RhsDoc rhs : grammar.getRhs ())
{
Production production = new Production (lhs, m_productionIdCounter++);
LinkedList<Integer> symbolList = new LinkedList<Integer> ();
String terms = rhs.getTerms ().trim ();
int lineNumber = rhs.getLineNumber ();
while (terms.length () > 0)
{
pos[0] = 0;
int sym = parseTerm (lineNumber, terms, pos);
if (sym <= m_maxTerminal)
production.setPrecedence (m_terminalMap.get (sym));
terms = terms.substring (pos[0]).trim ();
symbolList.add (sym);
}
int[] prod = new int[symbolList.size ()];
int i = 0;
for (Integer s : symbolList)
prod[i++] = s.intValue ();
production.setProduction (prod);
if (rhs.getPrecedence () != null)
{
String name = rhs.getPrecedence ().trim ();
if (name.length () > 0)
{
int[] value = new int[1];
checkTerminalName (lineNumber, name, value);
Token tok;
if (value[0] == 0)
tok = m_terminals.get (name);
else
tok = m_terminalMap.get (value[0]);
if (tok == null)
throw new ParserException (lineNumber, "Invalid terminal specified for %prec.");
production.setPrecedence (tok);
}
}
prods.add (production);
rhs.setCaseValue (production.getId ());
rhs.setProperty (PROP_PRODUCTION, production);
m_productions.add (production);
}
m_productionMap.put (lhs, prods.toArray (new Production[prods.size ()]));
}
}
private int parseTerm (int lineNumber, String terms, int[] pos)
{
if (terms.charAt (0) == '\'')
{
int index = terms.indexOf ('\'', 1);
if (index > 1)
{
String name = terms.substring (0, index + 1);
int symbol = getSymbol (lineNumber, name);
pos[0] = index + 1;
return symbol;
}
}
else
{
String name;
int index = terms.indexOf (' ');
if (index < 0)
index = terms.indexOf ('\t');
if (index < 0)
index = terms.indexOf ('\r');
if (index < 0)
index = terms.indexOf ('\n');
if (index < 0)
index = terms.length ();
name = terms.substring (0, index);
int symbol = getSymbol (lineNumber, name);
pos[0] = index;
return symbol;
}
throw new ParserException (lineNumber, "Invalid symbol: " + terms);
}
private String checkTerminalName (int lineNumber, String name, int[] value)
{
return checkTerminalName (lineNumber, name, value, false);
}
private String checkTerminalName (int lineNumber, String name, int[] value, boolean noInternal)
{
try
{
if (name.startsWith ("'"))
{
int[] pos = new int[1];
pos[0] = 1;
char ch = CCL.esc (name, pos);
if (name.length () == (pos[0] + 1) && name.charAt (pos[0]) == '\'')
{
value[0] = ch;
++pos[0];
if (m_symbolMap.get ((int)ch) == null)
m_symbolMap.put ((int)ch, name);
return String.valueOf ((int)ch);
}
}
else if (s_tokenNamePattern.matcher (name).matches ())
{
if (noInternal && "error".equals (name))
throw new ParserException (0, "error token is built-in");
return name;
}
}
catch (ParserException ex)
{
throw ex;
}
catch (Exception ex)
{
}
throw new ParserException (lineNumber, "Invalid token name: " + name);
}
private int getNonterminal (String name)
{
Integer value = m_nonTerminals.get (name);
if (value == null)
{
value = new Integer (m_maxTerminal + (++m_nonTerminalCount));
m_nonTerminals.put (name, value);
m_symbolMap.put (value, name);
}
return value.intValue ();
}
private int getSymbol (int lineNumber, String name)
{
int[] checkValue = new int[1];
name = checkTerminalName (lineNumber, name, checkValue);
if (checkValue[0] != 0)
return checkValue[0];
Token token = m_terminals.get (name);
if (token != null)
return token.value;
return getNonterminal (name);
}
// given a production alpha, return FIRST(alpha)
void computeFirst (int[] production, int begin, int end, TokenSet first)
{
// indicate first contain epsilon
boolean epsilon = true;
for (; begin < end; ++begin)
{
int sym = production[begin];
if (sym <= m_maxTerminal)
{
first.addSymbol (sym);
epsilon = false;
break;
}
TokenSet val = m_firstSetVal.get (sym);
first.or (val);
if (val.hasEpsilon () == false)
{
epsilon = false;
break;
}
}
first.setEpsilon (epsilon);
}
// This is a very expensive operation. Need to find a way to optimize it
// later.
private void computeFirstSet ()
{
for (int i = 0; i < m_nonTerminalCount; ++i)
m_firstSetVal.put (m_maxTerminal + 1 + i, createTokenSet ());
boolean changed;
do
{
changed = false;
for (Production production : m_productions)
{
int A = production.getSymbol ();
TokenSet current = m_firstSetVal.get (A);
TokenSet old = current.clone ();
for (int sym : production.getProduction ())
{
if (sym <= m_maxTerminal)
{
// for a terminal, first (X) is {X}
current.addSymbol (sym);
break;
}
// for a non-terminal, do or operation
TokenSet val = m_firstSetVal.get (sym);
current.or (val);
if (!val.hasEpsilon ())
break;
}
if (production.size () == 0)
current.setEpsilon (true);
// determine if anything got changed
if (old.compareTo (current) != 0)
changed = true;
}
}
while (changed);
for (int i = 0; i < m_nonTerminalCount; ++i)
{
int sym = m_maxTerminal + 1 + i;
TokenSet val = m_firstSetVal.get (sym);
int[] vec = new int[m_usedTerminalCount];
int count = 0;
for (int k = 0; k < m_usedTerminalCount; ++k)
if (val.hasSymbol (k))
vec[count++] = k;
int[] newVec = new int[count];
System.arraycopy (vec, 0, newVec, 0, count);
m_firstSet.put (sym, newVec);
}
if (m_out != null)
{
verboseSection ("First Sets");
for (int i = 0; i < m_nonTerminalCount; ++i)
{
// m_out.print ("FIRST(" + m_symbolMap.get (m_usedSymbols[m_usedTerminalCount + i]) + ") = {");
// for (int sym : m_firstSet.get (m_maxTerminal + 1 + i))
// m_out.print (" " + m_symbolMap.get (m_usedSymbols[sym]));
// m_out.println (" }");
m_out.println ("FIRST(" + m_symbolMap.get (m_usedSymbols[m_usedTerminalCount + i]) + ") = " + toString (m_firstSetVal.get (m_maxTerminal + 1 + i)) + (m_firstSetVal.get (m_maxTerminal + 1 + i).hasEpsilon () ? ", epsilon" : ""));
}
}
}
private int computeUsedSymbols ()
{
boolean[] used = new boolean[m_maxTerminal + 1];
for (Production production : m_productions)
{
for (int sym : production.getProduction ())
{
if (sym <= m_maxTerminal)
used[sym] = true;
}
}
used[FINISH] = true;
used[ERROR] = true;
int[] vec = new int[m_maxTerminal + m_nonTerminalCount + 1];
int count = 0;
for (int i = 0; i <= m_maxTerminal; ++i)
{
if (used[i] == true)
vec[count++] = i;
}
for (int i = 0; i < m_nonTerminalCount; ++i)
vec[count++] = m_maxTerminal + 1 + i;
m_usedSymbols = new int[count];
System.arraycopy (vec, 0, m_usedSymbols, 0, count);
m_symbolGroups = new int[m_maxTerminal + 1 + m_nonTerminalCount];
for (int i = 0; i < count; ++i)
m_symbolGroups[vec[i]] = i;
return count;
}
Item createItem (Production production, int pos, TokenSet lookahead)
{
return new Item (production, pos, lookahead.clone (), createTokenSet ());
}
/**
* Dummy items are for searching purpose.
* @param production
* the production to be used, can be null.
* @return a dummy Item with null lookahead and first
*/
Item createDummyItem (Production production)
{
return new Item (production, 0, null, null);
}
TokenSet createTokenSet ()
{
return new TokenSet (m_usedTerminalCount, m_symbolGroups, m_usedSymbols);
}
/**
* For output purpose.
* @return user defined tokens that needs value definitions.
*/
public LinkedList<Token> getTokens ()
{
return m_tokens;
}
// simpler version of closure, without the need of doing
// any first computations
void propagateClosure (ItemSet itemSet)
{
boolean changed;
Item dummyItem = createDummyItem (null);
do
{
changed = false;
for (Item item : itemSet.getItems ())
{
if (!item.isChanged ())
continue;
item.setChanged (false);
int[] production = item.getProduction ().getProduction ();
int pos = item.getPosition ();
if (pos >= production.length ||
production[pos] <= m_maxTerminal)
continue;
changed = true;
// okay a non-terminal is found,
int nonTerminal = production[pos];
// check if need to update this non-terminals lookahead
if (item.getFirst ().hasEpsilon () == false)
continue;
// hmm, needs update, so do the update
TokenSet first = item.getFirst ().clone ();
first.setEpsilon (false);
first.or (item.getLookahead ());
// check if that non-terminal's first contain epsilon
Production[] table = m_productionMap.get (nonTerminal);
for (Production k : table)
{
dummyItem.setProduction (k);
Item subItem = itemSet.find (dummyItem);
subItem.updateLookahead (first);
}
}
}
while (changed);
}
// does move operation
ItemSet move (Comparator<Item> kernelSorter, ItemSet src, int symbol)
{
ItemSet dest = null;
for (Item item : src.getItems ())
{
int[] production = item.getProduction ().getProduction ();
int pos = item.getPosition ();
if (pos < production.length && production[pos] == symbol)
{
if (dest == null)
dest = new ItemSet (kernelSorter);
dest.insertKernelItem (new Item (item, pos + 1));
}
}
return dest;
}
// it only takes care of shifts and no reduces
// depending on _compareLA and the closureFunction,
// the states built are quite different
void buildStates (Closure closureFunctor, Comparator<Item> kernelSorter)
{
// first build the first item,
// it has $ (FINISH) as its lookahead
TokenSet startLookahead = createTokenSet ();
startLookahead.addSymbol (FINISH);
Production startProduction = m_productionMap.get (m_nonTerminals.get (START))[0];
Item startItem = createItem (startProduction, 0, startLookahead);
// now build the first kernel ItemSet
ItemSet startItemSet = new ItemSet (kernelSorter);
startItemSet.insertKernelItem (startItem);
//DEBUGMSG ("startItemSet: " << startItemSet);
// do a closure operation
closureFunctor.closure (startItemSet);
//DEBUGMSG ("startItemSet: " << startItemSet);
// okay, finally built the first DFA state, the start state
_DFAStates.add (startItemSet);
_DFASet.put (startItemSet, (short)0);
// now the loops that build all DFA states
for (int i = 0; i < _DFAStates.size (); ++i)
{
ItemSet srcSet = _DFAStates.get (i);
DFARow currentDFA = new DFARow (m_usedTerminalCount);
m_dfa.add (currentDFA);
short[] currentGoto = new short[m_usedSymbols.length - m_usedTerminalCount];
m_goto.add (currentGoto);
//DEBUGMSG ("srcSet = " << srcSet);
for (int j = 0; j < m_usedSymbolCount; ++j)
{
//DEBUGMSG ("move/closure on symbol " << _tokens[j]);
ItemSet destSet = move (kernelSorter, srcSet, m_usedSymbols[j]);
if (destSet == null)
continue;
// manipulate the accept state in a special way to reduce
// an extra call to yyLex ()
if (m_usedSymbols[j] == FINISH)
{
// the only state that shift on FINISH lookahead is accept
// so just make it the accept state
currentDFA.getStates ()[j] = -1; // -1 is for case 1, which is accept
continue;
}
Short state = _DFASet.get (destSet);
if (state == null)
{
// ah, a new state
closureFunctor.closure (destSet);
if (j < m_usedTerminalCount)
currentDFA.getStates ()[j] = (short)_DFAStates.size ();
else
currentGoto[j - m_usedTerminalCount] = (short)_DFAStates.size ();
_DFAStates.add (destSet);
_DFASet.put (destSet, (short)(_DFAStates.size () - 1));
}
else
{
// the state existed
if (j < m_usedTerminalCount)
currentDFA.getStates ()[j] = state.shortValue ();
else
currentGoto[j - m_usedTerminalCount] = state.shortValue ();
}
}
}
}
// check if the ItemSet is contain a reducing state or not
// if all reducing states goes to one single production,
// return that state, other wise, return 0;
Production hasDefaultReduce (ItemSet itemSet)
{
Production reduceState = null;
// we check closure set as well since they may contain
// epsilon transitions
for (Item item : itemSet.getItems ())
{
if (item.getPosition () == item.getProduction ().getProduction ().length)
{
if (reduceState == null)
reduceState = item.getProduction ();
else if (item.getProduction ().getId () < reduceState.getId ()) // no problem in logic
reduceState = item.getProduction (); // pick earlier rule to reduce
}
}
return reduceState;
}
// check if an item contain reduced item,
// also check for reduce/reduce conflicts;
// A reduce/reduce conflict is if two reduce's share the same
// lookahead
// A shift/reduce conflict is if the shift's name token
// is the same as the reduce's lookahead
Production hasReduce (ItemSet itemSet, int symbol)
{
Set<Production> reduceSet = new TreeSet<Production> ();
for (Item item : itemSet.getItems ())
{
if (item.getPosition () == item.getProduction ().getProduction ().length)
{
if (item.getLookahead ().hasSymbol (symbol))
reduceSet.add (item.getProduction ());
}
}
if (reduceSet.size () > 0)
{
if (reduceSet.size () > 1)
{
++m_reduceConflict;
}
// pick the earlier rule to reduce
//return*(reduceSet.begin ());
return reduceSet.iterator ().next ();
}
return null;
}
public boolean getDefaultReduce ()
{
return m_doc.getParser ().getDefaultReduce ();
}
// check for reduced states and print states information.
// the reason to combine them is to produce conflicts message
private void reduce ()
{
verboseSection ("DFA states: " + _DFAStates.size ());
boolean defaultReduce = getDefaultReduce ();
verbose ("default reduce = " + defaultReduce);
for (int i = 0; i < _DFAStates.size (); ++i)
{
verbose ("");
verbose ("State " + i + ":");
verbose (toString (_DFAStates.get (i)));
short[] column = m_dfa.getRow (i).getStates ();
if (defaultReduce)
{
Production reduceState = hasDefaultReduce (_DFAStates.get (i));
if (reduceState != null)
{
for (int j = 0; j < column.length; ++j)
if (column[j] == 0)
column[j] = (short)-reduceState.getId ();
}
}
for (int j = 0; j < m_usedTerminalCount; ++j)
{
Production reduceState = hasReduce (_DFAStates.get (i), m_usedSymbols[j]);
String reason = "";
if (reduceState != null && column[j] > 0)
{
// possible shift reduce error, try to resolve
Token shiftPrecedence = Token.DEFAULT;
// we need to check the precedence of the rules of the destination
// kernel (important!) set, not the how set.
ItemSet destSet = _DFAStates.get (column[j]);
for (Item item : destSet.getKernelItems ())
{
Token prec = item.getProduction ().getPrecedence ();
if (shiftPrecedence.level < prec.level)
shiftPrecedence = prec;
}
Token reducePrecedence = reduceState.getPrecedence ();
if (shiftPrecedence.level < reducePrecedence.level)
{
// we go for the reduce
reason = ", due to precedence";
}
else if (shiftPrecedence.level > reducePrecedence.level)
{
// we go for the shift
reason = ", due to precedence";
reduceState = null;
}
else
{
// now check associativity
if (shiftPrecedence.type == Token.LEFT)
{
reason = ", due to left associativity";
}
else if (shiftPrecedence.type == Token.RIGHT)
{
// right associativity
if (shiftPrecedence.level > 0)
{
reason = ", due to right associativity";
reduceState = null;
}
else
{
reason = ", due to shift/reduce conflict";
reduceState = null;
++m_shiftConflict;
}
}
else // NONASSOC
{
reason = ", due to shift/reduce conflict on non-associative terminal";
++m_shiftConflict;
}
}
}
if (reduceState != null)
column[j] = (short)-reduceState.getId ();
if (m_out != null)
{
if (column[j] != 0)
{
m_out.print ('\t' + m_symbolMap.get (m_usedSymbols[j]));
if (column[j] > 0)
m_out.println ("\tshift, goto to state " + column[j] + reason);
else if (column[j] < -1)
m_out.println ("\treduce to rule " + (-column[j]) + reason);
else if (column[j] == -1)
m_out.println ("\tAccept");
}
}
}
if (m_out != null)
{
short[] gotoColumn = m_goto.get (i);
for (int j = 0; j < gotoColumn.length; ++j)
{
if (gotoColumn[j] != 0)
verbose ('\t' + m_symbolMap.get (m_usedSymbols[m_usedTerminalCount + j]) + "\tshift, goto to state " + gotoColumn[j]);
}
verbose ("");
}
}
if (m_shiftConflict > 0 || m_reduceConflict > 0)
Main.warn ("shift/reduce conflicts: " + m_shiftConflict + ", reduce/reduce conflicts: " + m_reduceConflict);
verbose ("shift/reduce conflicts: " + m_shiftConflict + ", reduce/reduce conflicts: " + m_reduceConflict);
}
Vector<Production> getProductions ()
{
return m_productions;
}
Map<Integer, Production[]> getProductionMap ()
{
return m_productionMap;
}
public DFATable getDFA ()
{
return m_dfa;
}
public Vector<short[]> getGoto ()
{
return m_goto;
}
public int[] getUsedSymbols ()
{
return m_usedSymbols;
}
public int[] getSymbolGroups ()
{
return m_symbolGroups;
}
public int[] getUsedTerminals ()
{
int[] usedTerminals = new int[m_usedTerminalCount];
System.arraycopy (m_usedSymbols, 0, usedTerminals, 0, m_usedTerminalCount);
return usedTerminals;
}
public int getTerminalCount ()
{
return m_terminalCount;
}
public int getNonTerminalCount ()
{
return m_nonTerminalCount;
}
public int getUsedTerminalCount ()
{
return m_usedTerminalCount;
}
int getUsedSymbolCount ()
{
return m_usedSymbolCount;
}
// debugging function
String toString (Production production)
{
StringBuffer buffer = new StringBuffer ();
buffer.append (production.getId ()).append ('\t');
buffer.append (m_symbolMap.get (production.getSymbol ())).append ("\t:\t");
for (int p : production.getProduction ())
buffer.append (" ").append (m_symbolMap.get (p));
return buffer.toString ();
}
String toString (TokenSet tokenSet)
{
StringBuffer buffer = new StringBuffer ();
buffer.append ("[");
boolean separator = false;
for (int i = 0; i < m_usedTerminalCount; ++i)
{
int sym = m_usedSymbols[i];
if (tokenSet.hasSymbol (sym))
{
if (separator)
buffer.append (" ");
separator = true;
buffer.append (m_symbolMap.get (sym));
}
}
buffer.append ("]");
return buffer.toString ();
}
String toString (Item item)
{
StringBuffer buffer = new StringBuffer ();
Production production = item.getProduction ();
buffer.append (m_symbolMap.get (production.getSymbol ())).append ("\t:");
int[] prods = production.getProduction ();
for (int i = 0; i < prods.length; ++i)
{
if (i == item.getPosition ())
buffer.append (" . ");
else
buffer.append (" ");
buffer.append (m_symbolMap.get (prods[i]));
}
if (item.getPosition () == prods.length)
buffer.append (" .");
buffer.append (" , ").append (toString (item.getLookahead ()));
return buffer.toString ();
}
String toString (ItemSet itemSet)
{
StringBuffer buffer = new StringBuffer ();
for (Item item : itemSet.getItems ())
{
if (itemSet.isKernelItem (item))
buffer.append (" *\t");
else
buffer.append (" -\t");
buffer.append (toString (item)).append ("\n");
}
return buffer.toString ();
}
String toString (Token token)
{
return token.name + "[" + token.level + "]";
}
public Vector<Production> getRules ()
{
return m_productions;
}
public short[] getDefaultReduces ()
{
if (!getDefaultReduce ())
return null;
short[] reduceStates = new short[_DFAStates.size ()];
for (int i = 0; i < _DFAStates.size (); ++i)
{
Production reduceState = hasDefaultReduce (_DFAStates.get (i));
if (reduceState != null)
reduceStates[i] = reduceState.getId ();
}
return reduceStates;
}
public int getCaseCount ()
{
return m_productionIdCounter;
}
public int getMaxTerminal ()
{
return m_maxTerminal;
}
public String[] getSymbols ()
{
String[] symbols = new String[m_usedSymbolCount];
for (int i = 0; i < symbols.length; ++i)
symbols[i] = m_symbolMap.get (m_usedSymbols[i]);
return symbols;
}
public Map<Integer, MessageFormat> getFormats ()
{
if (m_formats.size () > 0)
return m_formats;
int[] value = new int[1];
for (TypeDoc typeDoc : m_doc.getParser ().getTypes ())
{
MessageFormat format = typeDoc.getFormat ();
for (String name : typeDoc.getSymbols ())
{
checkTerminalName (0, name, value);
if (value[0] > 0)
m_formats.put (value[0], format);
else
{
Token token = m_terminals.get (name);
if (token != null)
m_formats.put (token.value, format);
else
{
Integer sym = m_nonTerminals.get (name);
if (sym != null)
m_formats.put (sym, format);
}
}
}
}
return m_formats;
}
}
|
package peergos.shared.user.fs;
import peergos.shared.*;
import peergos.shared.cbor.*;
import peergos.shared.crypto.*;
import peergos.shared.crypto.random.*;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.io.ipfs.multihash.*;
import peergos.shared.storage.*;
import peergos.shared.user.fs.cryptree.*;
import java.util.*;
import java.util.concurrent.*;
/** A FileAccess cryptree node controls read access to a section of a file, up to 5 MiB in size.
*
* It contains the following distinct keys {base, data}
* The serialized encrypted form stores links from the base key to the other keys. With the base key one can decrypt
* all the remaining keys. The base key is also the parent key and the metadata key. The parent key encrypts the link to
* the parent's parent key. The metadata key encrypts the name, size, thumbnail, modification times and any other
* properties of the file.
*
* The file retriever contains the merkle links to the encrypted file fragments of this file section, an optional
* erasure coding scheme, nonce and auth for this section as well as an encrypted link to the next section.
*/
public class FileAccess implements CryptreeNode {
private static final int META_DATA_PADDING_BLOCKSIZE = 16;
protected final MaybeMultihash lastCommittedHash;
protected final int version;
protected final SymmetricLink parent2data;
protected final PaddedCipherText properties;
protected final FileRetriever retriever;
protected final EncryptedCapability parentLink;
protected final Optional<SymmetricLinkToSigner> writerLink;
public FileAccess(MaybeMultihash lastCommittedHash,
int version,
SymmetricLink parent2Data,
PaddedCipherText fileProperties,
FileRetriever fileRetriever,
EncryptedCapability parentLink,
Optional<SymmetricLinkToSigner> writerLink) {
this.lastCommittedHash = lastCommittedHash;
this.version = version;
this.parent2data = parent2Data;
this.properties = fileProperties;
this.retriever = fileRetriever;
this.parentLink = parentLink;
this.writerLink = writerLink;
}
@Override
public MaybeMultihash committedHash() {
return lastCommittedHash;
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public int getVersion() {
return version;
}
@Override
public SymmetricKey getParentKey(SymmetricKey baseKey) {
return baseKey;
}
@Override
public EncryptedCapability getParentLink() {
return parentLink;
}
@Override
public SymmetricKey getMetaKey(SymmetricKey baseKey) {
return baseKey;
}
@Override
public FileProperties getProperties(SymmetricKey baseKey) {
return properties.decrypt(getMetaKey(baseKey), FileProperties::fromCbor);
}
public SymmetricKey getDataKey(SymmetricKey baseKey) {
return parent2data.target(baseKey);
}
@Override
public Optional<byte[]> getNextChunkLocation(SymmetricKey rBaseKey) {
return retriever.getNext(getDataKey(rBaseKey));
}
public FileRetriever retriever() {
return retriever;
}
@Override
public FileAccess withWriterLink(SymmetricLinkToSigner newWriterLink) {
return new FileAccess(lastCommittedHash, version, parent2data,
properties, retriever, parentLink, Optional.of(newWriterLink));
}
@Override
public FileAccess withParentLink(EncryptedCapability newParentLink) {
return new FileAccess(MaybeMultihash.empty(), version, parent2data, properties, retriever,
newParentLink, writerLink);
}
@Override
public Optional<SymmetricLinkToSigner> getWriterLink() {
return writerLink;
}
@Override
public CompletableFuture<FileAccess> updateProperties(WritableAbsoluteCapability us,
Optional<SigningPrivateKeyAndPublicHash> entryWriter,
FileProperties newProps,
NetworkAccess network) {
SymmetricKey metaKey = this.getMetaKey(us.rBaseKey);
PaddedCipherText encryptedProperties = PaddedCipherText.build(metaKey, newProps, META_DATA_PADDING_BLOCKSIZE);
FileAccess fa = new FileAccess(lastCommittedHash, version, this.parent2data, encryptedProperties,
this.retriever, this.parentLink, writerLink);
return IpfsTransaction.call(us.owner, tid ->
network.uploadChunk(fa, us.owner, us.getMapKey(), getSigner(us.wBaseKey.get(), entryWriter), tid)
.thenApply(b -> fa),
network.dhtClient);
}
public CompletableFuture<FileAccess> rotateBaseReadKey(WritableAbsoluteCapability us,
Optional<SigningPrivateKeyAndPublicHash> entryWriter,
RelativeCapability toParent,
SymmetricKey newBaseKey,
NetworkAccess network) {
// keep the same data key, just marked as dirty
SymmetricKey dataKey = this.getDataKey(us.rBaseKey).makeDirty();
SymmetricLink newParentToData = SymmetricLink.fromPair(newBaseKey, dataKey);
EncryptedCapability newParentLink = EncryptedCapability.create(newBaseKey, toParent);
PaddedCipherText newProperties = PaddedCipherText.build(newBaseKey, getProperties(us.rBaseKey), META_DATA_PADDING_BLOCKSIZE);
FileAccess fa = new FileAccess(committedHash(), version, newParentToData, newProperties,
this.retriever, newParentLink, writerLink);
return IpfsTransaction.call(us.owner, tid ->
network.uploadChunk(fa, us.owner, us.getMapKey(), getSigner(us.wBaseKey.get(), entryWriter), tid)
.thenApply(x -> fa),
network.dhtClient);
}
public CompletableFuture<FileAccess> rotateBaseWriteKey(WritableAbsoluteCapability us,
Optional<SigningPrivateKeyAndPublicHash> entryWriter,
SymmetricKey newBaseWriteKey,
NetworkAccess network) {
if (! writerLink.isPresent())
return CompletableFuture.completedFuture(this);
SigningPrivateKeyAndPublicHash signer = writerLink.get().target(us.wBaseKey.get());
FileAccess fa = this.withWriterLink(SymmetricLinkToSigner.fromPair(newBaseWriteKey, signer));
return IpfsTransaction.call(us.owner, tid ->
network.uploadChunk(fa, us.owner, us.getMapKey(), getSigner(us.wBaseKey.get(), entryWriter), tid)
.thenApply(x -> fa),
network.dhtClient);
}
@Override
public boolean isDirty(SymmetricKey baseKey) {
return getDataKey(baseKey).isDirty();
}
public CompletableFuture<FileAccess> cleanAndCommit(WritableAbsoluteCapability cap,
SigningPrivateKeyAndPublicHash writer,
Location parentLocation,
SymmetricKey parentParentKey,
NetworkAccess network,
SafeRandom random,
Fragmenter fragmenter) {
FileProperties props = getProperties(cap.rBaseKey);
Location nextLocation = cap.getLocation().withMapKey(getNextChunkLocation(cap.rBaseKey).get());
return retriever().getFile(network, random, getDataKey(cap.rBaseKey), props.size, cap.getLocation(), committedHash(), x -> {})
.thenCompose(data -> {
int chunkSize = (int) Math.min(props.size, Chunk.MAX_SIZE);
byte[] chunkData = new byte[chunkSize];
return data.readIntoArray(chunkData, 0, chunkSize)
.thenCompose(read -> {
byte[] nonce = cap.rBaseKey.createNonce();
byte[] mapKey = cap.getMapKey();
Chunk chunk = new Chunk(chunkData, cap.rBaseKey, mapKey, nonce);
LocatedChunk locatedChunk = new LocatedChunk(cap.getLocation(), lastCommittedHash, chunk);
return FileUploader.uploadChunk(writer, props, parentLocation, parentParentKey, cap.rBaseKey, locatedChunk,
fragmenter, nextLocation, network, x -> {});
});
}).thenCompose(h -> network.getMetadata(nextLocation)
.thenCompose(mOpt -> {
if (! mOpt.isPresent())
return CompletableFuture.completedFuture(null);
return ((FileAccess)mOpt.get()).cleanAndCommit(cap.withMapKey(nextLocation.getMapKey()),
writer, parentLocation, parentParentKey, network, random, fragmenter);
}).thenCompose(x -> network.getMetadata(cap.getLocation())).thenApply(opt -> (FileAccess) opt.get())
);
}
@Override
public CompletableFuture<? extends FileAccess> copyTo(AbsoluteCapability us,
SymmetricKey newBaseKey,
WritableAbsoluteCapability newParentCap,
Optional<SigningPrivateKeyAndPublicHash> newEntryWriter,
SymmetricKey parentparentKey,
byte[] newMapKey,
NetworkAccess network,
SafeRandom random) {
FileProperties props = getProperties(us.rBaseKey);
boolean isDirectory = isDirectory();
FileAccess fa = FileAccess.create(MaybeMultihash.empty(), newBaseKey,
isDirectory ? SymmetricKey.random() : getDataKey(us.rBaseKey),
props, this.retriever, newParentCap.getLocation(), parentparentKey);
return IpfsTransaction.call(newParentCap.owner,
tid -> network.uploadChunk(fa, newParentCap.owner, newMapKey, fa.getSigner(newParentCap.wBaseKey.get(), newEntryWriter), tid)
.thenApply(b -> fa),
network.dhtClient);
}
@Override
public CborObject toCbor() {
return new CborObject.CborList(
Arrays.asList(
new CborObject.CborLong(getVersionAndType()),
parent2data.toCbor(),
parentLink == null ? new CborObject.CborNull() : parentLink.toCbor(),
properties.toCbor(),
retriever == null ? new CborObject.CborNull() : retriever.toCbor(),
writerLink.isPresent() ? writerLink.get().toCbor() : new CborObject.CborNull()
));
}
public static FileAccess fromCbor(CborObject cbor, Multihash hash) {
if (! (cbor instanceof CborObject.CborList))
throw new IllegalStateException("Incorrect cbor for FileAccess: " + cbor);
List<? extends Cborable> value = ((CborObject.CborList) cbor).value;
int index = 0;
int versionAndType = (int) ((CborObject.CborLong) value.get(index++)).value;
SymmetricLink parentToData = SymmetricLink.fromCbor(value.get(index++));
Cborable parentLinkCbor = value.get(index++);
EncryptedCapability parentLink = parentLinkCbor instanceof CborObject.CborNull ?
null :
EncryptedCapability.fromCbor(parentLinkCbor);
PaddedCipherText properties = PaddedCipherText.fromCbor(value.get(index++));
Cborable retrieverCbor = value.get(index++);
FileRetriever retriever = retrieverCbor instanceof CborObject.CborNull ?
null :
FileRetriever.fromCbor(retrieverCbor);
Cborable writeLinkCbor = value.get(index++);
Optional<SymmetricLinkToSigner> writeLink = writeLinkCbor instanceof CborObject.CborNull ?
Optional.empty() :
Optional.of(writeLinkCbor).map(SymmetricLinkToSigner::fromCbor);
return new FileAccess(MaybeMultihash.of(hash), versionAndType >> 1, parentToData,
properties, retriever, parentLink, writeLink);
}
public static FileAccess create(MaybeMultihash existingHash,
SymmetricKey parentKey,
SymmetricKey dataKey,
FileProperties props,
FileRetriever retriever,
Location parentLocation,
SymmetricKey parentparentKey) {
return new FileAccess(
existingHash,
CryptreeNode.CURRENT_FILE_VERSION,
SymmetricLink.fromPair(parentKey, dataKey),
PaddedCipherText.build(parentKey, props, META_DATA_PADDING_BLOCKSIZE),
retriever,
EncryptedCapability.create(parentKey, parentparentKey, Optional.empty(), parentLocation.getMapKey()),
Optional.empty());
}
}
|
package plan_runner.storage;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import plan_runner.conversion.TypeConversion;
import plan_runner.utilities.SystemParameters;
public class KeyValueStore<K, V> extends BasicStore {
private static Logger LOG = Logger.getLogger(KeyValueStore.class);
private TypeConversion _tc = null;
private static int DEBUG_COUNTER = 0 ;
private HashMap<K, Object> _memstore;
protected static final int DEFAULT_HASH_INDICES = 256;
protected ReplacementAlgorithm<HashEntry<K, V>> _replAlg;
/* Constructors */
public KeyValueStore(Map conf) {
this(SystemParameters.getInt(conf, "STORAGE_MEMORY_SIZE_MB"), DEFAULT_HASH_INDICES, conf);
}
public KeyValueStore(int hash_indices, Map conf) {
this(SystemParameters.getInt(conf, "STORAGE_MEMORY_SIZE_MB"), hash_indices, conf);
}
public KeyValueStore(TypeConversion tc, Map conf) {
this(SystemParameters.getInt(conf, "STORAGE_MEMORY_SIZE_MB"), DEFAULT_HASH_INDICES, conf);
this._tc = tc;
}
public void setTypeConversion(TypeConversion tc) {
this._tc = tc;
}
public KeyValueStore(int storesizemb, int hash_indices, Map conf) {
super(storesizemb);
this._storageManager = new StorageManager<V>(this, conf);
this._memoryManager = new MemoryManager(storesizemb);
this._replAlg = new LRUList<HashEntry<K, V>>();
this._memstore = new HashMap<K, Object>(hash_indices);
}
@Override
public void onInsert(Object... data) {
K key = (K)data[0];
V value = (V)data[1];
ArrayList<V> values;
/* First, register this new value in the memoryManager */
this._memoryManager.allocateMemory(this._memoryManager.getSize(value));
/* Do we have an entry for this key? */
if (this._memstore.containsKey(key) == false) {
/* This is a new key -- register the new key as well.
* Note: we do that based on the fact that the
* underlying hashmap will itself save the key we
* provide. Thus, we need to take its space into account. */
this._memoryManager.allocateMemory(this._memoryManager.getSize(key));
/* No entry for this key--> create a new entry (key,
* values list pair) */
values = new ArrayList<V>();
values.add(value);
// Create the new hash entry
HashEntry<K, V> entry = new HashEntry<K, V>(key, values);
// Create a new lrunode and add to it the hashentry
Object lrunode = _replAlg.add(entry);
this._memstore.put(key, lrunode);
} else {
Object obj = this._memstore.get(key);
HashEntry<K, V> entry = _replAlg.get(obj);
entry.getValues().add(value);
((LRUList)_replAlg).moveToFront(obj);
}
}
protected V __update(boolean checkStorage, Object... data) {
K key = (K)data[0];
V oldValue = (V)data[1];
V newValue = (V)data[2];
ArrayList<V> values;
String groupId = key.toString();
boolean inMem = (this._memstore.containsKey(key) == true);
boolean inDisk = checkStorage ? (_storageManager.existsInStorage(groupId) == true) : false;
// If element is not in disk and not in mem, treat this as an insert instead
if (!inMem && !inDisk) {
data[1] = newValue;
this.onInsert(data);
return newValue;
}
// First update memory if necessary
if (inMem) {
Object obj = this._memstore.get(key);
HashEntry<K, V> entry = _replAlg.get(obj);
values = entry.getValues();
// Get the index of the old value (if it exists)
int index = values.indexOf(oldValue);
if (index != -1)
values.set(index, newValue);
else {
System.out.println("KeyValueStore: BUG: No element for key " + key + " found in store, but store's metadata register elements.");
System.exit(0);
}
}
// Now update storage if necessary
if (inDisk) {
_storageManager.update(groupId, oldValue, newValue);
}
return newValue;
}
@Override
public V update(Object... data) {
return __update(true, data);
}
@Override
public boolean contains(Object... data) {
K key = (K)data[0];
if (_memstore.containsKey(key) == true)
return true;
return _storageManager.existsInStorage(key.toString());
}
protected ArrayList<V> __access(boolean checkStorage, Object... data) {
K key = (K)data[0];
Object obj = this._memstore.get(key);
HashEntry<K, V> entry = _replAlg.get(obj);
boolean inMem = (entry != null);
boolean inDisk = checkStorage ? (_storageManager.existsInStorage(key.toString())) : false;
if (!inMem && !inDisk) {
return null;
} else if (inMem && !inDisk) {
return entry.getValues();
} else if (!inMem && inDisk) {
return this._storageManager.read(key.toString());
} else { // inmem && inDisk
ArrayList<V> resList = new ArrayList<V>();
resList.addAll(entry.getValues());
ArrayList<V> storageElems = this._storageManager.read(key.toString());
resList.addAll(storageElems);
return resList;
}
}
@Override
public ArrayList<V> access(Object... data) {
return __access(false, data);
}
@Override
public Object onRemove() {
HashEntry<K, V> entry = _replAlg.getLast();
K key = entry.getKey();
ArrayList<V> values = entry.getValues();
// Remove an entry from the list and free its memory
V value = values.remove(0);
this._memoryManager.releaseMemory(value);
// Written whole list to storage
if (values.size() == 0) {
_memstore.remove(key);
_replAlg.remove();
// Release memory for key and for values
this._memoryManager.releaseMemory(entry.getKey());
}
// Set the file to write
_objRemId = key.toString();
return value;
}
@Override
public void reset() {
this._memstore.clear();
this._replAlg.reset();
this._storageManager.deleteAllFilesRootDir();
}
@Override
public boolean equals(BasicStore bstore) {
if (!(bstore instanceof KeyValueStore)){
LOG.info("Compared stores are not of the same type!");
return false;
}
KeyValueStore store = (KeyValueStore) bstore;
int thisSize = this.keySet().size();
int otherSize = store.keySet().size();
if ( thisSize != otherSize) {
LOG.info("Stores differ in size: Computed store has " + thisSize +
" entries, and file store has " + otherSize + " entries.");
return false;
}
Set<K> keys = this.keySet();
for (Iterator<K> it = keys.iterator() ; it.hasNext() ; ) {
K key = it.next();
List<V> thisValues = this.access(key);
List<V> storeValues = (List<V>)store.access(key);
if(storeValues == null){
LOG.info("File does not contain values for key = " + key + ".\n");
return false;
}
Collections.sort((List)thisValues);
Collections.sort((List)storeValues);
// Compare value by value
int index = 0;
Iterator<V> iterator = thisValues.iterator();
while (iterator.hasNext()) {
V value1 = iterator.next();
V value2 = storeValues.get(index);
if (value1 instanceof Number) {
if (value1 != value2) {
if (Math.abs(((Number)value1).floatValue() - ((Number)value2).floatValue()) > 0.0001){
LOG.info("For key '" + key + "' computed value '" + value1 + "' differs from the value from the file '" + value2 +"'.\n");
return false;
}
}
} else {
if (!value1.equals(value1)){
LOG.info("For key '" + key + "' computed value '" + value1 + "' differs from the value from the file '" + value2 +"'.\n");
return false;
}
}
index++;
}
}
return true;
}
@Override
public void printStore(PrintStream stream, boolean printStorage) {
ArrayList<V> values;
Set<K> keys = this.keySet();
for (Iterator<K> it = keys.iterator(); it.hasNext(); ) {
K key = it.next();
// Check memory
Object obj = this._memstore.get(key);
if (obj != null) {
HashEntry<K, V> entry = _replAlg.get(obj);
stream.print(entry.getKey());
stream.print(" = ");
values = entry.getValues();
for (V v : values) {
if (this._tc != null) {
stream.print(_tc.toString(v));
} else {
stream.print(v.toString());
}
}
stream.println("");
}
// Check storage
values = this._storageManager.read(key.toString());
if (values != null) {
stream.print(key.toString());
stream.print(" = ");
for (V v : values) {
if (this._tc != null)
stream.print(_tc.toString(v));
else
stream.print(v.toString());
}
stream.println("");
}
}
}
protected Set<K> keySet() {
Set<K> memKeys = this._memstore.keySet();
//YANIS: TODO
//String[] storageGroupIds = this._storageManager.getGroupIds();
//Set<String> storageKeys = new HashSet<String>(Arrays.asList(storageGroupIds));
Set finalSet = new HashSet(memKeys);
//finalSet.addAll(storageKeys);
return finalSet;
}
/* Private class to store LRUNode along with key */
private class HashEntry<K, V> {
K _key;
ArrayList<V> _list;
public HashEntry(K key, ArrayList<V> list) {
this._key = key;
this._list = list;
}
public K getKey() {
return this._key;
}
public ArrayList<V> getValues() {
return this._list;
}
@Override
public String toString() {
return this._key.toString();
}
}
}
|
package cache;
import java.util.Date;
public class HistoryItem {
private String name;
private Date lastAccess;
private String url;
public HistoryItem() {
}
public HistoryItem(String _name, Date _lastAccess, String _url) {
name = _name;
lastAccess = _lastAccess;
url = _url;
}
public void delete() {
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public Date getLastAccess() {
return lastAccess;
}
public void setLastAccess( Date lastAccess ) {
this.lastAccess = lastAccess;
}
public String getUrl() {
return url;
}
public void setUrl( String url ) {
this.url = url;
}
}
|
package net.sf.cglib.proxy;
import java.io.*;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
/**
*
* this code returns Enhanced Vector to intercept all methods for tracing
* <pre>
* java.util.Vector vector = (java.util.Vector)Enhancer.enhance(
* java.util.Vector.<b>class</b>,
* new Class[]{java.util.List.<b>class</b>},
*
* new MethodInterceptor(){
*
*
* <b>public boolean invokeSuper</b>( Object obj,java.lang.reflect.Method method,
* Object args[])
* throws java.lang.Throwable{
* return true;
* }
*
*
* <b>public</b> Object <b>afterReturn</b>( Object obj, java.lang.reflect.Method method,
* Object args[],
* boolean invokedSuper, Object retValFromSuper,
* java.lang.Throwable e )throws java.lang.Throwable{
* System.out.println(method);
* return retValFromSuper;//return the same as supper
* }
*
* });
* </pre>
*@author Juozas Baliuka <a href="mailto:baliuka@mwm.lt">
* baliuka@mwm.lt</a>
*@version $Id: Enhancer.java,v 1.17 2002/09/30 18:36:16 baliuka Exp $
*/
public class Enhancer implements org.apache.bcel.Constants {
static final String INTERCEPTOR_CLASS_NAME = MethodInterceptor.class.getName();
static final ObjectType BOOLEAN_OBJECT =
new ObjectType(Boolean.class.getName());
static final ObjectType INTEGER_OBJECT =
new ObjectType(Integer.class.getName());
static final ObjectType CHARACTER_OBJECT =
new ObjectType(Character.class.getName());
static final ObjectType BYTE_OBJECT = new ObjectType(Byte.class.getName());
static final ObjectType SHORT_OBJECT = new ObjectType(Short.class.getName());
static final ObjectType LONG_OBJECT = new ObjectType(Long.class.getName());
static final ObjectType DOUBLE_OBJECT = new ObjectType(Double.class.getName());
static final ObjectType FLOAT_OBJECT = new ObjectType(Float.class.getName());
static final ObjectType METHOD_OBJECT =
new ObjectType(java.lang.reflect.Method.class.getName());
static final ObjectType CLASS_OBJECT = new ObjectType(Class.class.getName());
static final ObjectType NUMBER_OBJECT = new ObjectType(Number.class.getName());
static final String CONSTRUCTOR_NAME = "<init>";
static final String FIELD_NAME = "h";
static final String SOURCE_FILE = "<generated>";
static final String CLASS_SUFIX = "$$EnhancedByCGLIB$$";
static final String CLASS_PREFIX = "net.sf.cglib.proxy";
static int index = 0;
static java.util.Map factories = new java.util.HashMap();
private static int addAfterConstructionRef(ConstantPoolGen cp) {
return cp.addMethodref(
Enhancer.class.getName(),
"handleConstruction",
"(Ljava/lang/Object;[Ljava/lang/Object;)V");
}
private static int addNewInstanceRef(ConstantPoolGen cp,String name) {
return cp.addMethodref(
name,
"<init>",
"(L"+ INTERCEPTOR_CLASS_NAME.replace('.','/') +";)V");
}
private static int addWriteReplace(ConstantPoolGen cp){
return cp.addMethodref( Enhancer.InternalReplace.class.getName(),
"writeReplace",
"(Ljava/lang/Object;)Ljava/lang/Object;");
}
private static int addAfterRef(ConstantPoolGen cp) {
return cp.addInterfaceMethodref(
INTERCEPTOR_CLASS_NAME,
"afterReturn",
"(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;ZLjava/lang/Object;Ljava/lang/Throwable;)Ljava/lang/Object;");
}
private static int addInvokeSupperRef(ConstantPoolGen cp) {
return cp.addInterfaceMethodref(
INTERCEPTOR_CLASS_NAME,
"invokeSuper",
"(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Z");
}
private static java.util.List costructionHandlers = new java.util.Vector();
private static java.util.Map cache = new java.util.WeakHashMap();
private Enhancer() {}
public static MethodInterceptor getMethodInterceptor(Object enhanced){
try{
return (MethodInterceptor) enhanced.getClass().getField(FIELD_NAME).get(
enhanced);
}catch( NoSuchFieldException nsfe){
throw new NoSuchFieldError(enhanced + " is not enhanced :" + nsfe.getMessage());
}catch( java.lang.IllegalAccessException iae ){
throw new IllegalAccessError(enhanced.getClass().getName() + ":" + iae.getMessage());
}
}
/**
* implemented as
* return enhance(cls,interfaces,ih, null);
*/
public static Object enhance(
Class cls,
Class interfaces[],
MethodInterceptor ih)
throws Throwable {
return enhance(
cls,
interfaces,
ih,
null);
}
/** enhances public not final class,
* source class must have public no args constructor.
* Code generated for protected and public not final methods,
* package scope methods supported from source class package.
* Defines new class in source class package, if it not java*.
* @param cls class to extend, uses Object.class if null
* @param interfaces interfaces to implement, can be null
* @param ih valid interceptor implementation
* @param loader classloater for enhanced class, uses "current" if null
* @throws Throwable on error
* @return instanse of enhanced class
*/
public synchronized static Object enhance(
Class cls,
Class interfaces[],
MethodInterceptor ih,
ClassLoader loader)
throws Throwable {
if( ih == null ){
throw new NullPointerException("invalid interceptior");
}
if (cls == null) {
cls = Object.class;
}
if( loader == null ){
loader = Enhancer.class.getClassLoader();
}
StringBuffer keyBuff = new StringBuffer(cls.getName() + ";");
if(interfaces != null){
for(int i = 0; i< interfaces.length; i++ ){
keyBuff
.append(interfaces[i].getName() + ";");
}
}
String key = keyBuff.toString();
java.util.Map map = (java.util.Map) cache.get(loader);
if ( map == null ) {
map = new java.util.Hashtable();
cache.put(loader, map);
}
Class result = (Class) map.get(key);
if ( result == null ) {
try{
loader.loadClass(cls.getName());
if( interfaces != null ){
for( int i = 0; i< interfaces.length; i++ ){
loader.loadClass( interfaces[i].getName() );
}
}
}catch( ClassNotFoundException cnfe ){
throw new IllegalArgumentException( cnfe.getMessage() );
}
String class_name = cls.getName() + CLASS_SUFIX;
if (class_name.startsWith("java")) {
class_name = CLASS_PREFIX + class_name;
}
class_name += index++;
JavaClass clazz = enhance(cls, class_name, interfaces );
byte b[] = clazz.getBytes();
java.lang.reflect.Method m =
ClassLoader.class.getDeclaredMethod(
"defineClass",
new Class[] { String.class, byte[].class, int.class, int.class });
// protected method invocaton
boolean flag = m.isAccessible();
m.setAccessible(true);
result =
(Class) m.invoke(
loader,
new Object[] { clazz.getClassName(), b, new Integer(0), new Integer(b.length)});
m.setAccessible(flag);
map.put(key, result);
}
Factory factory = (Factory)factories.get(result);
if( factory == null ){
factory = (Factory)result.getConstructor(
new Class[] {
Class.forName(MethodInterceptor.class.getName(), true, loader)
}).newInstance(new Object[] { null });
factories.put(result,factory);
}
return factory.newInstance(ih);
}
private static void addConstructor(ClassGen cg) throws Throwable {
//single arg constructor
String parentClass = cg.getSuperclassName();
InstructionFactory factory = new InstructionFactory(cg);
ConstantPoolGen cp = cg.getConstantPool(); // cg creates constant pool
InstructionList il = new InstructionList();
MethodGen costructor = new MethodGen(ACC_PUBLIC, // access flags
Type.VOID, // return type
new Type[] { // argument types
new ObjectType(INTERCEPTOR_CLASS_NAME)}, null, // arg names
CONSTRUCTOR_NAME, cg.getClassName(), il, cp);
il.append(new ALOAD(0));
il.append(
factory.createInvoke(
parentClass,
CONSTRUCTOR_NAME,
Type.VOID,
new Type[] {},
INVOKESPECIAL));
il.append(new ALOAD(0));
il.append(new ALOAD(1));
il.append(
factory.createFieldAccess(
cg.getClassName(),
FIELD_NAME,
new ObjectType(INTERCEPTOR_CLASS_NAME),
PUTFIELD));
il.append(new RETURN());
cg.addMethod(getMethod(costructor));
//factory sometimes usefull and has meaning for performance
il = new InstructionList();
MethodGen newInstance = toMethodGen(
Factory.class.getMethod("newInstance",
new Class[]{ MethodInterceptor.class } ),
cg.getClassName(),
il,
cp
);
il.append( new NEW(cp.addClass( new ObjectType(cg.getClassName()) )) );
il.append( new DUP());
il.append( new ALOAD(1) );
il.append( new INVOKESPECIAL( addNewInstanceRef(cp, cg.getClassName()) ) ) ;
il.append( new ARETURN());
cg.addMethod(getMethod(newInstance));
//serialization support
il = new InstructionList();
MethodGen writeReplace = new MethodGen(ACC_PRIVATE, // access flags
Type.OBJECT, // return type
new Type[] {}, null, // arg names
"writeReplace", cg.getClassName(), il, cp);
il.append(new ALOAD(0));
il.append(new INVOKESTATIC( addWriteReplace(cp) ) );
il.append(new ARETURN());
cg.addMethod(getMethod(writeReplace));
}
private static void addHandlerField(ClassGen cg) {
// TODO: ACC_PRIVATE
ConstantPoolGen cp = cg.getConstantPool();
FieldGen fg =
new FieldGen(ACC_PUBLIC, new ObjectType(INTERCEPTOR_CLASS_NAME), FIELD_NAME, cp);
cg.addField(fg.getField());
}
private static ClassGen getClassGen(
String class_name,
Class parentClass,
Class[] interfaces) {
ClassGen gen =
new ClassGen(class_name, parentClass.getName(), SOURCE_FILE,
ACC_PUBLIC | ACC_FINAL , null );
if (interfaces != null) {
for (int i = 0; i < interfaces.length; i++) {
gen.addInterface(interfaces[i].getName());
}
}
gen.addInterface( Factory.class.getName() );
return gen;
}
private static JavaClass enhance(
Class parentClass,
String class_name,
Class interfaces[]
) throws Throwable {
java.util.HashMap methodTable = new java.util.HashMap();
ClassGen cg = getClassGen(class_name, parentClass, interfaces);
ConstantPoolGen cp = cg.getConstantPool(); // cg creates constant pool
addHandlerField(cg);
addConstructor(cg);
int after = addAfterRef(cp);
int invokeSuper = addInvokeSupperRef(cp);
java.util.Set methodSet = new java.util.HashSet();
java.util.List allMethods = new java.util.ArrayList();
String packageName = getPackageName( class_name );
// Order is very important: must add parentClass, then
// its superclass chain, then each interface and
// its superinterfaces.
addDeclaredMethods(allMethods, parentClass);
if (interfaces != null) {
for (int j = 0; j < interfaces.length; j++) {
addDeclaredMethods(allMethods, interfaces[j]);
}
}
for (java.util.Iterator i = allMethods.iterator(); i.hasNext(); ) {
java.lang.reflect.Method m = (java.lang.reflect.Method) i.next();
int mod = m.getModifiers();
if (!java.lang.reflect.Modifier.isStatic(mod)
&& !java.lang.reflect.Modifier.isFinal(mod)
&& isVisible( m , packageName ) ) {
methodSet.add(new MethodWrapper(m));
}
}
int cntr = 0;
for (java.util.Iterator i = methodSet.iterator(); i.hasNext();) {
java.lang.reflect.Method method = ((MethodWrapper) i.next()).method;
String fieldName = "METHOD_" + (cntr++);
cg.addMethod(generateMethod(method, fieldName, cg, after, invokeSuper));
methodTable.put(fieldName, method);
}
generateClInit(cg, cp, methodTable);
JavaClass jcl = cg.getJavaClass();
return jcl;
}
private static String getPackageName( String className )
throws Throwable{
int index = className.lastIndexOf('.');
if( index == -1 ){
return "";
}
return className.substring( 0, index );
}
private static boolean isVisible(java.lang.reflect.Method m ,
String packageName )throws Throwable{
int mod = m.getModifiers();
if( java.lang.reflect.Modifier.isPrivate( mod )){
return false;
}
if( java.lang.reflect.Modifier.isProtected( mod ) ||
java.lang.reflect.Modifier.isPublic( mod ) ){
return true;
}
//package scope:
return getPackageName( m.getDeclaringClass().getName()
).equals( packageName );
}
private static void addDeclaredMethods(java.util.List methodList, Class clazz) {
methodList.addAll(java.util.Arrays.asList(clazz.getDeclaredMethods()));
if (clazz.isInterface()) {
Class[] interfaces = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
addDeclaredMethods(methodList, interfaces[i]);
}
} else {
Class superclazz = clazz.getSuperclass();
if (superclazz != null) {
addDeclaredMethods(methodList, superclazz);
}
}
}
private static void addMethodField(String fieldName, ClassGen cg) {
ConstantPoolGen cp = cg.getConstantPool();
FieldGen fg =
new FieldGen( ACC_FINAL | ACC_STATIC, METHOD_OBJECT, fieldName, cp );
cg.addField(fg.getField());
}
private static int createArgArray(
InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp,
Type[] args) {
int argCount = args.length;
if (argCount > 5)
il.append(new BIPUSH((byte) argCount));
else
il.append(new ICONST((byte) argCount));
il.append(new ANEWARRAY(cp.addClass(Type.OBJECT)));
int load = 1;
for (int i = 0; i < argCount; i++) {
il.append(new DUP());
if (i > 5)
il.append(new BIPUSH((byte) i));
else
il.append(new ICONST((byte) i));
if (args[i] instanceof BasicType) {
if (args[i].equals(Type.BOOLEAN)) {
il.append(new NEW(cp.addClass(BOOLEAN_OBJECT)));
il.append(new DUP());
il.append(new ILOAD(load++));
il.append(
new INVOKESPECIAL(
cp.addMethodref(Boolean.class.getName(), CONSTRUCTOR_NAME, "(Z)V")));
} else if (args[i].equals(Type.INT)) {
il.append(new NEW(cp.addClass(INTEGER_OBJECT)));
il.append(new DUP());
il.append(new ILOAD(load++));
il.append(
new INVOKESPECIAL(
cp.addMethodref(Integer.class.getName(), CONSTRUCTOR_NAME, "(I)V")));
} else if (args[i].equals(Type.CHAR)) {
il.append(new NEW(cp.addClass(CHARACTER_OBJECT)));
il.append(new DUP());
il.append(new ILOAD(load++));
il.append(
new INVOKESPECIAL(
cp.addMethodref(Character.class.getName(), CONSTRUCTOR_NAME, "(C)V")));
} else if (args[i].equals(Type.BYTE)) {
il.append(new NEW(cp.addClass(BYTE_OBJECT)));
il.append(new DUP());
il.append(new ILOAD(load++));
il.append(
new INVOKESPECIAL(
cp.addMethodref(Byte.class.getName(), CONSTRUCTOR_NAME, "(B)V")));
} else if (args[i].equals(Type.SHORT)) {
il.append(new NEW(cp.addClass(SHORT_OBJECT)));
il.append(new DUP());
il.append(new ILOAD(load++));
il.append(
new INVOKESPECIAL(
cp.addMethodref(Short.class.getName(), CONSTRUCTOR_NAME, "(S)V")));
} else if (args[i].equals(Type.LONG)) {
il.append(new NEW(cp.addClass(LONG_OBJECT)));
il.append(new DUP());
il.append(new LLOAD(load));
load += 2;
il.append(
new INVOKESPECIAL(
cp.addMethodref(Long.class.getName(), CONSTRUCTOR_NAME, "(J)V")));
} else if (args[i].equals(Type.DOUBLE)) {
il.append(new NEW(cp.addClass(DOUBLE_OBJECT)));
il.append(new DUP());
il.append(new DLOAD(load));
load += 2;
il.append(
new INVOKESPECIAL(
cp.addMethodref(Double.class.getName(), CONSTRUCTOR_NAME, "(D)V")));
} else if (args[i].equals(Type.FLOAT)) {
il.append(new NEW(cp.addClass(FLOAT_OBJECT)));
il.append(new DUP());
il.append(new FLOAD(load++));
il.append(
new INVOKESPECIAL(
cp.addMethodref(Float.class.getName(), CONSTRUCTOR_NAME, "(F)V")));
}
il.append(new AASTORE());
} else {
il.append(new ALOAD(load++));
il.append(new AASTORE());
}
}
return load;
}
private static Method getMethod(MethodGen mg) {
mg.stripAttributes(true);
mg.setMaxLocals();
mg.setMaxStack();
return mg.getMethod();
}
private static InstructionHandle generateReturnValue(
InstructionList il,
InstructionFactory factory,
ConstantPoolGen cp,
Type returnType,
int stack) {
if (returnType.equals(Type.VOID)) {
return il.append(new RETURN());
}
il.append(new ASTORE(stack));
il.append(new ALOAD(stack));
if ((returnType instanceof ObjectType) || ( returnType instanceof ArrayType) ) {
if (returnType instanceof ArrayType){
il.append(new CHECKCAST(cp.addArrayClass((ArrayType)returnType)));
return il.append(new ARETURN());
}
if (!returnType.equals(Type.OBJECT)){
il.append(new CHECKCAST(cp.addClass((ObjectType) returnType)));
return il.append(new ARETURN());
}else {
return il.append(new ARETURN());
}
}
if (returnType instanceof BasicType) {
if (returnType.equals(Type.BOOLEAN)) {
IFNONNULL ifNNull = new IFNONNULL(null);
il.append(ifNNull);
il.append(new ICONST(0) );
il.append(new IRETURN());
ifNNull.setTarget(il.append(new ALOAD(stack)));
il.append(new CHECKCAST(cp.addClass(BOOLEAN_OBJECT)));
il.append(
factory.createInvoke(
Boolean.class.getName(),
"booleanValue",
Type.BOOLEAN,
new Type[] {},
INVOKEVIRTUAL));
return il.append(new IRETURN());
} else if (returnType.equals(Type.CHAR)) {
IFNONNULL ifNNull = new IFNONNULL(null);
il.append(ifNNull);
il.append(new ICONST(0) );
il.append(new IRETURN());
ifNNull.setTarget(il.append(new ALOAD(stack)));
il.append(new CHECKCAST(cp.addClass(CHARACTER_OBJECT)));
il.append(
factory.createInvoke(
Character.class.getName(),
"charValue",
Type.CHAR,
new Type[] {},
INVOKEVIRTUAL));
return il.append(new IRETURN());
} else if (returnType.equals(Type.LONG)) {
IFNONNULL ifNNull = new IFNONNULL(null);
il.append(ifNNull);
il.append(new LCONST(0) );
il.append(new LRETURN());
ifNNull.setTarget(il.append(new ALOAD(stack)));
il.append(new CHECKCAST(cp.addClass(NUMBER_OBJECT)));
il.append(
factory.createInvoke(
Number.class.getName(),
"longValue",
Type.LONG,
new Type[] {},
INVOKEVIRTUAL));
return il.append(new LRETURN());
} else if (returnType.equals(Type.DOUBLE)) {
IFNONNULL ifNNull = new IFNONNULL(null);
il.append(ifNNull);
il.append(new DCONST(0) );
il.append(new DRETURN());
ifNNull.setTarget(il.append(new ALOAD(stack)));
il.append(new CHECKCAST(cp.addClass(NUMBER_OBJECT)));
il.append(
factory.createInvoke(
Number.class.getName(),
"doubleValue",
Type.DOUBLE,
new Type[] {},
INVOKEVIRTUAL));
return il.append(new DRETURN());
} else if (returnType.equals(Type.FLOAT)) {
IFNONNULL ifNNull = new IFNONNULL(null);
il.append(ifNNull);
il.append(new FCONST(0) );
il.append(new FRETURN());
ifNNull.setTarget(il.append(new ALOAD(stack)));
il.append(new CHECKCAST(cp.addClass(NUMBER_OBJECT)));
il.append(
factory.createInvoke(
java.lang.Number.class.getName(),
"floatValue",
Type.FLOAT,
new Type[] {},
INVOKEVIRTUAL));
return il.append(new FRETURN());
} else {
IFNONNULL ifNNull = new IFNONNULL(null);
il.append(ifNNull);
il.append(new ICONST(0) );
il.append(new IRETURN());
ifNNull.setTarget(il.append(new ALOAD(stack)));
il.append(new CHECKCAST(cp.addClass(NUMBER_OBJECT)));
il.append(
factory.createInvoke(
Number.class.getName(),
"intValue",
Type.INT,
new Type[] {},
INVOKEVIRTUAL));
return il.append(new IRETURN());
}
}
throw new java.lang.InternalError(returnType.toString());
}
private static Instruction newWrapper(Type type, ConstantPoolGen cp) {
if (type instanceof BasicType) {
if (type.equals(Type.BOOLEAN)) {
return new NEW(cp.addClass(BOOLEAN_OBJECT));
} else if (type.equals(Type.INT)) {
return new NEW(cp.addClass(INTEGER_OBJECT));
} else if (type.equals(Type.CHAR)) {
return new NEW(cp.addClass(CHARACTER_OBJECT));
} else if (type.equals(Type.BYTE)) {
return new NEW(cp.addClass(BYTE_OBJECT));
} else if (type.equals(Type.SHORT)) {
return new NEW(cp.addClass(SHORT_OBJECT));
} else if (type.equals(Type.LONG)) {
return new NEW(cp.addClass(LONG_OBJECT));
} else if (type.equals(Type.DOUBLE)) {
return new NEW(cp.addClass(DOUBLE_OBJECT));
} else if (type.equals(Type.FLOAT)) {
return new NEW(cp.addClass(FLOAT_OBJECT));
}
}
return null;
}
private static Instruction initWrapper(Type type, ConstantPoolGen cp) {
if (type instanceof BasicType) {
if (type.equals(Type.BOOLEAN)) {
return new INVOKESPECIAL(
cp.addMethodref(Boolean.class.getName(), CONSTRUCTOR_NAME, "(Z)V"));
} else if (type.equals(Type.INT)) {
return new INVOKESPECIAL(
cp.addMethodref(Integer.class.getName(), CONSTRUCTOR_NAME, "(I)V"));
} else if (type.equals(Type.CHAR)) {
return new INVOKESPECIAL(
cp.addMethodref(Character.class.getName(), CONSTRUCTOR_NAME, "(C)V"));
} else if (type.equals(Type.BYTE)) {
return new INVOKESPECIAL(
cp.addMethodref(Byte.class.getName(), CONSTRUCTOR_NAME, "(B)V"));
} else if (type.equals(Type.SHORT)) {
return new INVOKESPECIAL(
cp.addMethodref(Short.class.getName(), CONSTRUCTOR_NAME, "(S)V"));
} else if (type.equals(Type.LONG)) {
return new INVOKESPECIAL(
cp.addMethodref(Long.class.getName(), CONSTRUCTOR_NAME, "(J)V"));
} else if (type.equals(Type.DOUBLE)) {
return new INVOKESPECIAL(
cp.addMethodref(Double.class.getName(), CONSTRUCTOR_NAME, "(D)V"));
} else if (type.equals(Type.FLOAT)) {
return new INVOKESPECIAL(
cp.addMethodref(Float.class.getName(), CONSTRUCTOR_NAME, "(F)V"));
}
}
throw new InternalError(type.toString());
}
private static int loadArg(InstructionList il, Type t, int index, int pos) {
if (t instanceof BasicType) {
if (t.equals(Type.LONG)) {
il.append(new LLOAD(pos));
pos += 2;
return pos;
} else if (t.equals(Type.DOUBLE)) {
il.append(new DLOAD(pos));
pos += 2;
return pos;
} else if (t.equals(Type.FLOAT)) {
il.append(new FLOAD(pos));
return ++pos;
} else {
il.append(new ILOAD(pos));
return ++pos;
}
} else {
il.append(new ALOAD(pos));
return ++pos;
}
}
private static Type[] toType(Class cls[]) {
Type tp[] = new Type[cls.length];
for (int i = 0; i < cls.length; i++) {
tp[i] = toType(cls[i]);
}
return tp;
}
private static Type toType(Class cls) {
if (cls.equals(void.class)) {
return Type.VOID;
}
if (cls.isPrimitive()) {
if (int.class.equals(cls)) {
return Type.INT;
} else if (char.class.equals(cls)) {
return Type.CHAR;
} else if (short.class.equals(cls)) {
return Type.SHORT;
} else if (byte.class.equals(cls)) {
return Type.BYTE;
} else if (long.class.equals(cls)) {
return Type.LONG;
} else if (float.class.equals(cls)) {
return Type.FLOAT;
} else if (double.class.equals(cls)) {
return Type.DOUBLE;
} else if (boolean.class.equals(cls)) {
return Type.BOOLEAN;
}
} else if (cls.isArray()) {
return new ArrayType( toType(cls.getComponentType()),cls.getName().lastIndexOf('[') + 1);
} else
return new ObjectType(cls.getName());
throw new java.lang.InternalError(cls.getName());
}
private static void invokeSuper(ClassGen cg, MethodGen mg, Type args[]) {
ConstantPoolGen cp = cg.getConstantPool();
InstructionList il = mg.getInstructionList();
int pos = 1;
il.append(new ALOAD(0)); //this
for (int i = 0; i < args.length; i++) { //load args to stack
pos = loadArg(il, args[i], i, pos);
}
il.append(
new INVOKESPECIAL(
cp.addMethodref(cg.getSuperclassName(), mg.getName(), mg.getSignature())));
}
private static void invokeStatic( String className, ClassGen cg, MethodGen mg, Type args[]) {
ConstantPoolGen cp = cg.getConstantPool();
InstructionList il = mg.getInstructionList();
int pos = 1;
for (int i = 0; i < args.length; i++) { //load args to stack
pos = loadArg(il, args[i], i, pos);
}
il.append(
new INVOKESTATIC(
cp.addMethodref(className, mg.getName(), mg.getSignature())));
}
private static MethodGen toMethodGen(
java.lang.reflect.Method mtd,
String className,
InstructionList il,
ConstantPoolGen cp) {
MethodGen mg = new MethodGen(
ACC_FINAL | ( mtd.getModifiers()
& ~ACC_ABSTRACT & ~ACC_NATIVE & ~ACC_SYNCHRONIZED ),
toType(mtd.getReturnType()),
toType(mtd.getParameterTypes()),
null,
mtd.getName(),
className,
il,
cp);
Class [] exeptions = mtd.getExceptionTypes();
for( int i = 0 ; i< exeptions.length; i++ ){
mg.addException( exeptions[i].getName() );
}
return mg;
}
private static Method generateMethod(
java.lang.reflect.Method method,
String fieldName,
ClassGen cg,
int after,
int invokeSuper) {
InstructionList il = new InstructionList();
InstructionFactory factory = new InstructionFactory(cg);
ConstantPoolGen cp = cg.getConstantPool();
MethodGen mg = toMethodGen(method, cg.getClassName(), il, cp);
Type types[] = mg.getArgumentTypes();
int argCount = types.length;
addMethodField(fieldName, cg);
boolean returnsValue = !mg.getReturnType().equals(Type.VOID);
boolean abstractM = java.lang.reflect.Modifier.isAbstract(method.getModifiers());
InstructionHandle ehEnd = null;
GOTO gotoHandled = null;
IFEQ ifInvoke = null;
InstructionHandle condition = null;
InstructionHandle ehHandled = null;
InstructionHandle ehStart = null;
InstructionHandle start = il.getStart();
//GENERATE ARG ARRAY
//generates:
/*
Object args[]= new Object[]{ arg1, new Integer(arg2) };
*/
int loaded = createArgArray(il, factory, cp, mg.getArgumentTypes());
int argArray = loaded;
il.append(new ASTORE(argArray));
//DEFINE LOCAL VARIABLES
il.append(new ACONST_NULL());
int resultFromSuper = ++loaded;
il.append(new ASTORE(resultFromSuper));
il.append(new ICONST(0));
int superInvoked = ++loaded;
il.append(new ISTORE(superInvoked));
il.append(new ACONST_NULL());
int error = ++loaded;
il.append(new ASTORE(error));
if (!abstractM) {
il.append(new ALOAD(0)); //this.handler
il.append(
factory.createFieldAccess(
cg.getClassName(),
FIELD_NAME,
new ObjectType(INTERCEPTOR_CLASS_NAME),
GETFIELD));
//GENERATE INVOKE SUPER
il.append(new ALOAD(0)); //this
il.append(factory.createGetStatic(cg.getClassName(), fieldName, METHOD_OBJECT));
il.append(new ALOAD(argArray));
il.append(new INVOKEINTERFACE(invokeSuper, 4));
//test returned true
ifInvoke = new IFEQ(null);
condition = il.append(ifInvoke);
il.append(new ICONST(1));
ehStart = il.append(new ISTORE(superInvoked)); // Ivoked = true
Instruction wrapper = newWrapper(mg.getReturnType(), cp);
if (wrapper != null) {
ehStart = il.append(wrapper);
il.append(new DUP());
}
invokeSuper(cg, mg, types);
if (wrapper != null) {
il.append(initWrapper(mg.getReturnType(), cp));
}
if (returnsValue) {
ehEnd = il.append(new ASTORE(resultFromSuper));
}
gotoHandled = new GOTO(null);
if (!returnsValue) {
ehEnd = il.append(gotoHandled);
} else {
il.append(gotoHandled);
}
ehHandled = il.append(new ASTORE(error));
}
InstructionHandle endif = il.append(new ALOAD(0)); //this.handler
if (!abstractM) {
ifInvoke.setTarget(endif);
gotoHandled.setTarget(endif);
}
il.append(
factory.createFieldAccess(
cg.getClassName(),
FIELD_NAME,
new ObjectType(INTERCEPTOR_CLASS_NAME),
GETFIELD));
// INVOKE AFTER RETURN
il.append(new ALOAD(0)); //this
il.append(factory.createGetStatic(cg.getClassName(), fieldName, METHOD_OBJECT));
il.append(new ALOAD(argArray));
il.append(new ILOAD(superInvoked));
il.append(new ALOAD(resultFromSuper));
il.append(new ALOAD(error));
il.append(new INVOKEINTERFACE(after, 7));
//GENERATE RETURN VALUE
//generates :
/*
if( result == null ){
return 0;
} else {
return ((Number)result).intValue();
}
*/
InstructionHandle exitMethod =
generateReturnValue(il, factory, cp, mg.getReturnType(), ++loaded);
if (!abstractM) {
mg.addExceptionHandler(ehStart, ehEnd, ehHandled, Type.THROWABLE);
}
//Exception handlers:
/*
}catch( RuntimeException re ){
throw re;
}
*/
ehHandled = il.append( new ASTORE( ++loaded ) );
ehEnd = ehHandled;
ehStart = il.getStart();
il.append( new ALOAD(loaded) );
il.append( new ATHROW() );
mg.addExceptionHandler(ehStart, ehEnd, ehHandled, new ObjectType(RuntimeException.class.getName()) );
//Error :
ehHandled = il.append( new ASTORE( ++loaded ) );
il.append( new ALOAD(loaded) );
il.append( new ATHROW() );
mg.addExceptionHandler(ehStart, ehEnd, ehHandled, new ObjectType(Error.class.getName()) );
Class exeptions[] = method.getExceptionTypes();
for( int i = 0; i < exeptions.length; i++ ){
// generates :
/*
}catch( DeclaredException re ){
throw re;
}
*/
ehHandled = il.append( new ASTORE( ++loaded ) );
il.append( new ALOAD(loaded) );
il.append( new ATHROW() );
mg.addExceptionHandler(ehStart, ehEnd, ehHandled, new ObjectType(exeptions[i].getName()) );
}
//generates :
/* }catch( Exception e){
throw new java.lang.reflect.UndeclaredThrowableException(e);
}*/
ehHandled = il.append( new ASTORE( ++loaded ) );
il.append( new NEW( cp.addClass("java.lang.reflect.UndeclaredThrowableException") ) );
il.append( new DUP() );
il.append( new ALOAD(loaded ) );
il.append( new INVOKESPECIAL(
cp.addMethodref("java.lang.reflect.UndeclaredThrowableException",
"<init>","(Ljava/lang/Throwable;)V") ) );
il.append( new ATHROW() );
mg.addExceptionHandler(ehStart, ehEnd, ehHandled, new ObjectType(Throwable.class.getName()) );
mg.setMaxStack();
mg.setMaxLocals();
Method result = getMethod(mg);
return result;
}
private static void loadClass(InstructionList il, ClassGen cg, ConstantPoolGen cp,Class cls ){
Instruction instruction = null;
String cln = "Ljava/lang/Class;";
String t = "TYPE";
if(cls == int.class){
instruction = new GETSTATIC( cp.addFieldref(Integer.class.getName(), t, cln ));
}
if(cls == byte.class){
instruction = new GETSTATIC( cp.addFieldref(Byte.class.getName(), t, cln ));
}
if(cls == char.class){
instruction = new GETSTATIC( cp.addFieldref(Character.class.getName(), t, cln ));
}
if( cls == short.class){
instruction = new GETSTATIC( cp.addFieldref(Short.class.getName(), t, cln ));
}
if( cls == boolean.class){
instruction = new GETSTATIC( cp.addFieldref( Boolean.class.getName(), t, cln) );
}
if( cls == long.class){
instruction = new GETSTATIC( cp.addFieldref( Long.class.getName(), t, cln) );
}
if( cls == float.class ){
instruction = new GETSTATIC( cp.addFieldref( Float.class.getName(), t, cln) );
}
if( cls == double.class ){
instruction = new GETSTATIC( cp.addFieldref( Double.class.getName(), t, cln ));
}
if( instruction != null ){
il.append(instruction);
}else{
il.append( new LDC( cp.addString( cls.getName()) ) );
il.append( new INVOKESTATIC( cp.addMethodref( cg.getClassName(),
"findClass","(Ljava/lang/String;)Ljava/lang/Class;")
)
) ;
}
}
private static void generateClInit(ClassGen cg, ConstantPoolGen cp, java.util.HashMap methods){
//generates :
/*
static{
Class [] args;
Class cls = findClass("java.lang.Object");
args = new Class[0];
METHOD_1 = cls.getDeclaredMethod("toString", args );
.............
}
*/
InstructionList il = new InstructionList();
MethodGen cinit = new MethodGen(
ACC_STATIC , // access flags
Type.VOID, // return type
new Type[] { }, null, // arg names
"<clinit>", cg.getClassName(), il, cp );
MethodGen findClass = generateFindClass( cg, cp );
for( java.util.Iterator i = methods.keySet().iterator(); i.hasNext(); ){
String fieldName = (String)i.next();
java.lang.reflect.Method method =
(java.lang.reflect.Method)methods.get( fieldName );
Class[] args = method.getParameterTypes();
String declaring = method.getDeclaringClass().getName();
il.append( new LDC( cp.addString(declaring) ));
il.append( new INVOKESTATIC(
cp.addMethodref( findClass ) ) );
il.append( new ASTORE(1) );
il.append( new ICONST( args.length ) );
il.append( new ANEWARRAY( cp.addClass( CLASS_OBJECT ) ) );
for( int j = 0; j < args.length; j++ ){
il.append( new DUP() );
il.append( new ICONST(j) );
loadClass( il, cg, cp, args[j] );
il.append( new AASTORE() );
}
il.append( new ASTORE(0) );
il.append( new ALOAD(1) );
il.append( new LDC( cp.addString(method.getName() ) ) );
il.append( new ALOAD(0) );
il.append( new INVOKEVIRTUAL(
cp.addMethodref("java.lang.Class","getDeclaredMethod",
"(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;")
)
);
il.append( new PUTSTATIC(
cp.addFieldref( cg.getClassName(), fieldName,
"Ljava/lang/reflect/Method;" ) )
);
}
il.append( new RETURN() );
cg.addMethod( getMethod( cinit ) );
}
private static MethodGen generateFindClass( ClassGen cg, ConstantPoolGen cp ){
// generates:
/*
static private Class findClass(String name ) throws Exception{
try{
return Class.forName(name);
}catch( java.lang.ClassNotFoundException cne ){
throw new java.lang.NoClassDefFoundError( cne.getMessage() );
}
}
*/
InstructionList il = new InstructionList();
MethodGen findClass = new MethodGen( ACC_PRIVATE | ACC_STATIC , // access flags
CLASS_OBJECT, // return type
new Type[] { Type.STRING }, null, // arg names
"findClass", cg.getClassName(), il, cp);
InstructionHandle start = il.append( new ALOAD(0));
il.append( new INVOKESTATIC( cp.addMethodref("java.lang.Class",
"forName",
"(Ljava/lang/String;)Ljava/lang/Class;" )
)
);
InstructionHandle h1 = il.append( new ARETURN() );
InstructionHandle h2 = il.append( new ASTORE(1) );
il.append( new NEW(cp.addClass("java.lang.NoClassDefFoundError") ) );
il.append( new DUP() );
il.append( new ALOAD(1) );
il.append( new INVOKEVIRTUAL( cp.addMethodref("java.lang.ClassNotFoundException",
"getMessage","()Ljava/lang/String;") )
);
il.append( new INVOKESPECIAL( cp.addMethodref("java.lang.NoClassDefFoundError",
CONSTRUCTOR_NAME,
"(Ljava/lang/String;)V" ))
);
il.append( new ATHROW() );
findClass.addExceptionHandler( start, h1, h2,
new ObjectType("java.lang.ClassNotFoundException") );
cg.addMethod( getMethod( findClass ) );
return findClass;
}
static public class InternalReplace implements java.io.Serializable{
private String parentClassName;
private String [] interfaceNameList;
private MethodInterceptor mi;
public InternalReplace(){
}
private InternalReplace( String parentClassName,
String [] interfaceList, MethodInterceptor mi ){
this.parentClassName = parentClassName;
this.interfaceNameList = interfaceNameList;
this.mi = mi;
}
static public Object writeReplace( Object enhanced ) throws ObjectStreamException{
MethodInterceptor mi = Enhancer.getMethodInterceptor( enhanced );
String parentClassName = enhanced.getClass().getSuperclass().getName();
Class interfaces[] = enhanced.getClass().getInterfaces();
String [] interfaceNameList = new String[ interfaces.length ];
for( int i = 0 ; i < interfaces.length; i++ ) {
interfaceNameList[i] = interfaces[i].getName();
}
return new InternalReplace( parentClassName, interfaceNameList, mi );
}
Object readResolve() throws ObjectStreamException{
try{
ClassLoader loader = this.getClass().getClassLoader();
Class parent = loader.loadClass(parentClassName);
Class interfaceList[] = null;
if( interfaceNameList != null ){
interfaceList = new Class[interfaceNameList.length];
for( int i = 0; i< interfaceNameList.length; i++ ){
interfaceList[i] = loader.loadClass( interfaceNameList[i] );
}
}
return Enhancer.enhance( parent, interfaceList, mi, loader );
}catch( Throwable t ){
throw new ObjectStreamException(t.getMessage()){};
}
}
}
static class MethodWrapper {
java.lang.reflect.Method method;
MethodWrapper(java.lang.reflect.Method method) {
if (method == null) {
throw new NullPointerException();
}
this.method = method;
}
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof MethodWrapper)) {
return false;
}
return Enhancer.equals(method, ((MethodWrapper) obj).method );
}
public int hashCode() {
return method.getName().hashCode();
}
}
private static boolean equals(
java.lang.reflect.Method m1,
java.lang.reflect.Method m2) {
if (m1 == m2) {
return true;
}
if (m1.getName().equals(m2.getName())) {
Class[] params1 = m1.getParameterTypes();
Class[] params2 = m2.getParameterTypes();
if (params1.length == params2.length) {
for (int i = 0; i < params1.length; i++) {
if (!params1[i].getName().equals( params2[i].getName() ) ) {
return false;
}
}
if(!m1.getReturnType().getName().
equals(m2.getReturnType().getName()) ){
throw new java.lang.IllegalStateException(
"Can't implement:\n" + m1.getDeclaringClass().getName() +
"\n and\n" + m2.getDeclaringClass().getName() + "\n"+
m1.toString() + "\n" + m2.toString());
}
return true;
}
}
return false;
}
}
|
package edu.cmu.cs.diamond.opendiamond;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
class Cookie {
final static String BEGIN_COOKIE = "
final static String END_COOKIE = "
private final List<String> servers;
private final String rawCookie;
private final int version;
private final UUID serial;
private final byte[] keyId;
private final String expires;
private final String scopeData;
public Cookie(String s) throws IOException {
if (!s.startsWith(BEGIN_COOKIE)) {
throw new IllegalArgumentException("String does not begin with "
+ BEGIN_COOKIE);
}
rawCookie = s;
int end = s.indexOf(END_COOKIE);
s = s.substring(BEGIN_COOKIE.length(), end);
String cookie = new String(Base64.decode(s), "UTF-8");
// System.out.println(cookie);
// split into header and body
int boundary = cookie.indexOf("\n\n");
String header = cookie.substring(0, boundary);
scopeData = cookie.substring(boundary + 2);
// get properties
boolean hasVersion = false;
int version = 0;
UUID serial = null;
byte keyId[] = null;
String expires = null;
List<String> servers = null;
for (String line : header.split("\n")) {
String ss[] = line.split(":", 2);
String key = ss[0];
String val = null;
if (ss.length > 1) {
val = ss[1].trim();
}
if (key.equals("Version")) {
hasVersion = true;
version = Integer.parseInt(val);
} else if (key.equals("Serial")) {
serial = UUID.fromString(val);
} else if (key.equals("KeyId")) {
keyId = hexDecode(val);
} else if (key.equals("Expires")) {
expires = val;
} else if (key.equals("Servers")) {
servers = Arrays.asList(val.split(";|,"));
}
}
// commit
this.version = version;
this.serial = serial;
this.servers = Collections.unmodifiableList(servers);
this.keyId = keyId;
this.expires = expires;
// check
if (!hasVersion) {
throw new IllegalArgumentException("missing Version");
}
if (serial == null) {
throw new IllegalArgumentException("missing Serial");
}
if (servers == null) {
throw new IllegalArgumentException("missing Servers");
}
if (keyId == null) {
throw new IllegalArgumentException("missing KeyId");
}
if (expires == null) {
throw new IllegalArgumentException("missing Expires");
}
}
private byte[] hexDecode(String string) throws IOException {
byte input[] = string.getBytes();
byte result[] = new byte[input.length / 2];
for (int i = 0; i < input.length; i += 2) {
String s = new String(input, i, 2, "UTF-8");
result[i / 2] = (byte) Integer.parseInt(s, 16);
}
return result;
}
public List<String> getServers() {
return servers;
}
public String getCookie() {
return rawCookie;
}
@Override
public String toString() {
return "servers: " + servers + ", version: " + version + ", serial: "
+ serial + ", keyId: " + Arrays.toString(keyId) + ", expires: "
+ expires;
}
public String getScopeData() {
return scopeData;
}
}
|
package edu.utdallas.robotchess.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import edu.utdallas.robotchess.manager.*;
import edu.utdallas.robotchess.game.*;
public class MainFrame extends JFrame
{
public final static int SQUARE_SIZE = 100;
private static final long serialVersionUID = 3;
Manager manager;
BoardPanel boardPanel;
JMenuBar menuBar;
JMenu gameMenu;
JMenu chessbotMenu;
JMenu optionsMenu;
JMenuItem newGameMenuItem;
JMenuItem newChessDemoMenuItem;
JRadioButton playWithChessbotsButton;
JRadioButton playWithoutChessbotsButton;
ButtonGroup chessbotButtonGroup;
JButton showConnectedChessbotButton;
JButton connectToXbeeButton;
JCheckBoxMenuItem enableChessAIMenuItem;
MenuItemListener menuListener;
public MainFrame()
{
boardPanel = new BoardPanel(new NullManager());
manager = new NullManager();
setTitle("Robot Chess");
setSize(8 * SQUARE_SIZE, 8 * SQUARE_SIZE);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setupMenuBar();
add(boardPanel);
setVisible(true);
}
private void setupMenuBar()
{
menuBar = new JMenuBar();
menuListener = new MenuItemListener();
gameMenu = new JMenu("Play Game");
chessbotMenu = new JMenu("Chessbots");
optionsMenu = new JMenu("Options");
newGameMenuItem = new JMenuItem("New Chessgame");
newChessDemoMenuItem = new JMenuItem("New Chessbot Demo");
showConnectedChessbotButton = new JButton("Show Chessbot Info");
playWithChessbotsButton = new JRadioButton("Play with Chessbots");
playWithoutChessbotsButton = new JRadioButton("Play without Chessbots");
connectToXbeeButton = new JButton("Connect to Xbee");
enableChessAIMenuItem = new JCheckBoxMenuItem("Enable Chess AI");
chessbotButtonGroup = new ButtonGroup();
chessbotButtonGroup.add(playWithChessbotsButton);
chessbotButtonGroup.add(playWithoutChessbotsButton);
gameMenu.add(newGameMenuItem);
gameMenu.add(newChessDemoMenuItem);
chessbotMenu.add(playWithChessbotsButton);
chessbotMenu.add(playWithoutChessbotsButton);
chessbotMenu.add(showConnectedChessbotButton);
optionsMenu.add(enableChessAIMenuItem);
gameMenu.setEnabled(false);
showConnectedChessbotButton.setEnabled(false);
connectToXbeeButton.setEnabled(false);
enableChessAIMenuItem.setEnabled(false);
newGameMenuItem.addActionListener(menuListener);
newChessDemoMenuItem.addActionListener(menuListener);
showConnectedChessbotButton.addActionListener(menuListener);
playWithChessbotsButton.addActionListener(menuListener);
playWithoutChessbotsButton.addActionListener(menuListener);
connectToXbeeButton.addActionListener(menuListener);
enableChessAIMenuItem.addActionListener(menuListener);
menuBar.add(gameMenu);
menuBar.add(chessbotMenu);
menuBar.add(optionsMenu);
menuBar.add(connectToXbeeButton);
setJMenuBar(menuBar);
}
class MenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == playWithChessbotsButton) {
gameMenu.setEnabled(true);
connectToXbeeButton.setEnabled(true);
enableChessAIMenuItem.setEnabled(true);
showConnectedChessbotButton.setEnabled(true);
newChessDemoMenuItem.setEnabled(true);
}
if (e.getSource() == playWithoutChessbotsButton) {
gameMenu.setEnabled(true);
connectToXbeeButton.setEnabled(false);
enableChessAIMenuItem.setEnabled(true);
showConnectedChessbotButton.setEnabled(false);
newChessDemoMenuItem.setEnabled(false);
}
if (e.getSource() == newGameMenuItem) {
if (playWithChessbotsButton.isSelected())
{
if(manager.checkIfAllChessbotsAreConnected())
manager = new RobotChessManager();
else
JOptionPane.showMessageDialog(null, "All Chessbots need to be connected " +
"in order to play a chessgame with them. To check how many are " +
"currently connected, go to Options > Show Chessbot Info",
"Not enough Chessbots connected",
JOptionPane.WARNING_MESSAGE);
}
else
manager = new ChessManager();
//We may run into problems here since we are creating new
//managers but want to keep the same xbee object. Look at
//Manager class to investigate
boardPanel.setManager(manager);
boardPanel.updateDisplay();
}
if (e.getSource() == enableChessAIMenuItem) {
if (manager instanceof ChessManager) {
boolean state = enableChessAIMenuItem.getState();
((ChessManager) manager).setComputerControlsTeam(state, Team.GREEN);
}
//Add dialogue later for choosing team for AI as well as
//choosing difficulty
}
if (e.getSource() == newChessDemoMenuItem) {
int[] robotsPresent = determineRobotsPresent();
int[] initialLocations = generateInitialLocations(robotsPresent);
manager = new RobotDemoManager(initialLocations);
int boardRows = determineBoardRows();
int boardColumns = determineBoardColumns();
manager.setBoardRowCount(boardRows);
manager.setBoardColumnCount(boardColumns);
remove(boardPanel);
boardPanel = new BoardPanel(manager);
add(boardPanel);
boardPanel.updateDisplay();
setSize(boardColumns * SQUARE_SIZE, boardRows * SQUARE_SIZE);
}
if (e.getSource() == connectToXbeeButton) {
boolean xbeeConnected = manager.isXbeeConnected();
if(manager.isXbeeConnected())
JOptionPane.showMessageDialog(null, "Xbee is connected");
else
{
xbeeConnected = manager.connectToXbee();
if(xbeeConnected)
JOptionPane.showMessageDialog(null, "Successfully connected to Xbee");
else
JOptionPane.showMessageDialog(null, "Could not connect to Xbee. " +
"Try again after unplugging and plugging in the Xbee. " +
"If this does not work, restart the app.",
"Cannot find Xbee",
JOptionPane.WARNING_MESSAGE);
}
}
}
private int[] determineRobotsPresent()
{
String robotsPresentStr = (String) JOptionPane.showInputDialog(
"Please enter space-separated list of robots present",
"e.g. 1 2 4 6");
String[] robotsPresentStrArr = robotsPresentStr.split(" ");
int[] robotsPresentIntArr = new int[robotsPresentStrArr.length];
for (int i = 0; i < robotsPresentIntArr.length; i++)
robotsPresentIntArr[i] = Integer.parseInt(robotsPresentStrArr[i]);
return robotsPresentIntArr;
}
private int[] generateInitialLocations(int[] robotsPresent)
{
int[] locations = new int[32];
for (int i = 0; i < locations.length; i++)
locations[i] = -1;
for (int i = 0; i < robotsPresent.length; i++)
locations[robotsPresent[i]] = robotsPresent[i];
return locations;
}
private int determineBoardRows()
{
Object[] possibleDimensions = {"2", "3", "4", "5", "6", "7", "8"};
String boardRows = (String) JOptionPane.showInputDialog(
(Component) null,
"Please enter the number of board rows",
"Board Rows",
JOptionPane.PLAIN_MESSAGE,
(Icon) null,
possibleDimensions,
"8");
int boardRowCount = Integer.parseInt(boardRows);
return boardRowCount;
}
private int determineBoardColumns()
{
Object[] possibleDimensions = {"2", "3", "4", "5", "6", "7", "8"};
String boardColumns = (String) JOptionPane.showInputDialog(
(Component) null,
"Please enter the number of board columns",
"Board Columns",
JOptionPane.PLAIN_MESSAGE,
(Icon) null,
possibleDimensions,
"8");
int boardColumnCount = Integer.parseInt(boardColumns);
return boardColumnCount;
}
}
public static void main(String[] args)
{
@SuppressWarnings("unused")
MainFrame frame = new MainFrame();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.*;
/**
*
* @author RoboHawks
*/
public class drive {
Team3373 testing = new Team3373();
Joystick drivestick = new Joystick(1);
RobotDrive drive = new RobotDrive(1,2);
boolean DRIVE_A = drivestick.getRawButton(1);
double DRIVE_LSTICK = drivestick.getRawAxis(2);
public void Driving(){
if (DRIVE_LSTICK >= -1 & DRIVE_LSTICK <= 0 ){
}
}
}
|
package es.tid.bgp.bgp4Peer.peer;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.logging.Logger;
import es.tid.bgp.bgp4.messages.BGP4Update;
import es.tid.bgp.bgp4.update.fields.LinkNLRI;
import es.tid.bgp.bgp4.update.fields.NodeNLRI;
import es.tid.bgp.bgp4.update.fields.PathAttribute;
import es.tid.bgp.bgp4.update.fields.pathAttributes.AS_Path_Attribute;
import es.tid.bgp.bgp4.update.fields.pathAttributes.BGP_LS_MP_Reach_Attribute;
import es.tid.bgp.bgp4.update.fields.pathAttributes.LinkStateAttribute;
import es.tid.bgp.bgp4.update.fields.pathAttributes.OriginAttribute;
import es.tid.bgp.bgp4.update.fields.pathAttributes.PathAttributesTypeCode;
import es.tid.bgp.bgp4.update.tlv.LocalNodeDescriptorsTLV;
import es.tid.bgp.bgp4.update.tlv.ProtocolIDCodes;
import es.tid.bgp.bgp4.update.tlv.RemoteNodeDescriptorsTLV;
import es.tid.bgp.bgp4.update.tlv.linkstate_attribute_tlvs.DefaultTEMetricLinkAttribTLV;
import es.tid.bgp.bgp4.update.tlv.linkstate_attribute_tlvs.MF_OTPAttribTLV;
import es.tid.bgp.bgp4.update.tlv.linkstate_attribute_tlvs.MaxReservableBandwidthLinkAttribTLV;
import es.tid.bgp.bgp4.update.tlv.linkstate_attribute_tlvs.MaximumLinkBandwidthLinkAttribTLV;
import es.tid.bgp.bgp4.update.tlv.linkstate_attribute_tlvs.SidLabelNodeAttribTLV;
import es.tid.bgp.bgp4.update.tlv.linkstate_attribute_tlvs.UnreservedBandwidthLinkAttribTLV;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.AreaIDNodeDescriptorSubTLV;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.AutonomousSystemNodeDescriptorSubTLV;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.BGPLSIdentifierNodeDescriptorSubTLV;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.IGPRouterIDNodeDescriptorSubTLV;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.IPv4InterfaceAddressLinkDescriptorsSubTLV;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.IPv4NeighborAddressLinkDescriptorSubTLV;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.LinkLocalRemoteIdentifiersLinkDescriptorSubTLV;
import es.tid.bgp.bgp4.update.tlv.node_link_prefix_descriptor_subTLVs.NodeDescriptorsSubTLV;
import es.tid.bgp.bgp4Peer.bgp4session.BGP4SessionsInformation;
import es.tid.bgp.bgp4Peer.bgp4session.GenericBGP4Session;
import es.tid.ospf.ospfv2.OSPFv2LinkStateUpdatePacket;
import es.tid.ospf.ospfv2.lsa.LSA;
import es.tid.ospf.ospfv2.lsa.LSATypes;
import es.tid.ospf.ospfv2.lsa.OSPFTEv2LSA;
import es.tid.ospf.ospfv2.lsa.tlv.LinkTLV;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.AvailableLabels;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.LinkID;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.LocalInterfaceIPAddress;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.MaximumBandwidth;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.RemoteInterfaceIPAddress;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.UnreservedBandwidth;
import es.tid.ospf.ospfv2.lsa.tlv.subtlv.complexFields.BitmapLabelSet;
import es.tid.tedb.DomainTEDB;
import es.tid.tedb.InterDomainEdge;
import es.tid.tedb.IntraDomainEdge;
import es.tid.tedb.MultiDomainTEDB;
import es.tid.tedb.Node_Info;
import es.tid.tedb.SimpleTEDB;
import es.tid.tedb.TE_Information;
/**
* Class to send periodically the topology. It sends the topology to the active BGP4 sessions.
* @author pac
*
*/
public class SendTopology implements Runnable {
/**
* 1= optical
* 0= L3
*/
private int identifier=1;
//TEDBs
private Hashtable<Inet4Address,SimpleTEDB> intraTEDBs;
// Multi-domain TEDB to redistribute Multi-domain Topology
private MultiDomainTEDB multiDomainTEDB;
private boolean sendTopology;
private BGP4SessionsInformation bgp4SessionsInformation;
private Logger log;
private int instanceId=1;
private boolean sendIntraDomainLinks=false;
private Inet4Address localBGPLSIdentifer;
private Inet4Address localAreaID;
public SendTopology(){
log = Logger.getLogger("BGP4Parser");
}
public void configure( Hashtable<Inet4Address,SimpleTEDB> intraTEDBs,BGP4SessionsInformation bgp4SessionsInformation,boolean sendTopology,int instanceId,boolean sendIntraDomainLinks, MultiDomainTEDB multiTED){
this.intraTEDBs=intraTEDBs;
this.bgp4SessionsInformation=bgp4SessionsInformation;
this.sendTopology= sendTopology;
this.instanceId = instanceId;
this.sendIntraDomainLinks=sendIntraDomainLinks;
this.multiDomainTEDB=multiTED;
try {
this.localAreaID=(Inet4Address)Inet4Address.getByName("0.0.0.0");
this.localBGPLSIdentifer=(Inet4Address)Inet4Address.getByName("1.1.1.1");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Function to send the topology database.
*/
public void run(){
try {
if (sendTopology){
if (!(bgp4SessionsInformation.getSessionList().isEmpty())){
if (multiDomainTEDB!=null){
log.info("Sending Multi-Domain TEDB");
sendLinkNLRI( multiDomainTEDB.getInterDomainLinks());
}
else {
log.info("Sending form TEDB");
Enumeration<SimpleTEDB> iter = intraTEDBs.elements();
while (iter.hasMoreElements()){
sendLinkNLRI( iter.nextElement().getInterDomainLinks());
}
}
if (sendIntraDomainLinks){//Intradomain Links
log.info("sendIntraDomainLinks activated");
Enumeration<Inet4Address> iter = intraTEDBs.keys();
while (iter.hasMoreElements()){
Inet4Address domainID = iter.nextElement();
log.info("Sending TED from domain "+domainID);
SimpleTEDB ted=intraTEDBs.get(domainID);
sendLinkNLRI( ted.getNetworkGraph().edgeSet(),domainID);
sendNodeNLRI(ted.getNetworkGraph().vertexSet(), ted.getNodeTable());
}
}
}
}
}catch (Exception e) {
e.printStackTrace();
log.severe("PROBLEM SENDING TOPOLOGY: "+e.toString());
}
}
/**
* This function sends a BGP4 update message (encoded in a NodeNLRI) for each node in the set
* @param vertexIt
*/
private void sendNodeNLRI(Set<Object> vertexSet, Hashtable<Object , Node_Info> NodeTable){
Iterator<Object> vertexIt = vertexSet.iterator();
//Enviamos primero los nodos. Un Node NLRI por cada nodo.
while (vertexIt.hasNext()){
Inet4Address node = (Inet4Address)vertexIt.next();
Node_Info node_info = NodeTable.get(node);
if (node_info!=null){
log.fine("Sending node: ("+node+")");
//Mandamos NodeNLRI
BGP4Update update = createMsgUpdateNodeNLRI(node_info);
sendMessage(update);
}else {
log.severe("Node "+node+ " HAS NO node_info in NodeTable");
}
}
}
/**
* This function sends a BGP4 update message (encoded in a LinkNLRI) for each link in the list
* @param interdomainLinks
*/
private void sendLinkNLRI(LinkedList<InterDomainEdge> interdomainLinks){
if (true){
int lanID = 1; ///INVENTADOO
ArrayList<Inet4Address> addressList = new ArrayList<Inet4Address>();
Iterator<InterDomainEdge> edgeIt = interdomainLinks.iterator();
while (edgeIt.hasNext()){
InterDomainEdge edge = edgeIt.next();
Inet4Address source = (Inet4Address)edge.getSrc_router_id();
Inet4Address dst = (Inet4Address)edge.getDst_router_id();
log.info("Sending: ("+source.toString() +","+dst.toString()+")");
addressList = new ArrayList<Inet4Address>();
addressList.add(0,source);
addressList.add(1,dst);
//Link Local Remote Identifiers
ArrayList<Long> localRemoteIfList =null;
localRemoteIfList= new ArrayList<Long> ();
localRemoteIfList.add(0,((InterDomainEdge) edge).getSrc_if_id());//te_info.getLinkLocalRemoteIdentifiers().getLinkLocalIdentifier());
localRemoteIfList.add(0,((InterDomainEdge) edge).getDst_if_id());//te_info.getLinkLocalRemoteIdentifiers().getLinkRemoteIdentifier());
//MPLS
float maximumBandwidth = 0;
float[] unreservedBandwidth = null;
float maximumReservableBandwidth = 0;
//GMPLS
AvailableLabels availableLabels = null;
MF_OTPAttribTLV mfOTP = null;
int metric = 0;
TE_Information te_info = ((InterDomainEdge) edge).getTE_info();
if (te_info != null){
if (te_info.getLinkLocalRemoteIdentifiers() != null){
}
//MPLS
if (te_info.getMaximumBandwidth() != null) {
maximumBandwidth = te_info.getMaximumBandwidth().getMaximumBandwidth();
}
if (te_info.getUnreservedBandwidth() != null)
unreservedBandwidth = te_info.getUnreservedBandwidth().getUnreservedBandwidth();
if (te_info.getMaximumReservableBandwidth() != null)
maximumReservableBandwidth = te_info.getMaximumReservableBandwidth().getMaximumReservableBandwidth();
//GMPLS
if (te_info.getAvailableLabels() != null)
availableLabels = te_info.getAvailableLabels();
if(te_info.getDefaultTEMetric()!=null){
metric = (int) te_info.getDefaultTEMetric().getLinkMetric();
log.info("Metric en el metodo sendLinkNLRI es: " + metric);
}
if(te_info.getMfOTF()!=null){
mfOTP = te_info.getMfOTF();
}
}else{
log.info("TE_Info es null");
}
ArrayList<Inet4Address> domainList = new ArrayList<Inet4Address>(2);
//FIXME: chequear
domainList.add((Inet4Address)edge.getDomain_src_router());
domainList.add((Inet4Address)edge.getDomain_dst_router());
BGP4Update update = createMsgUpdateLinkNLRI(addressList,localRemoteIfList, lanID, maximumBandwidth, unreservedBandwidth, maximumReservableBandwidth , availableLabels, metric, domainList, false, mfOTP);
log.fine("Update message Created");
sendMessage(update);
}
}
}
/**
* This function sends a BGP4 update message (encoded in a LinkNLRI) for each link in the set
* @param edgeIt
*/
private void sendLinkNLRI(Set<IntraDomainEdge> edgeSet, Inet4Address domainID){
int lanID = 1; ///INVENTADOO
ArrayList<Inet4Address> addressList = new ArrayList<Inet4Address>();
Iterator<IntraDomainEdge> edgeIt = edgeSet.iterator();
while (edgeIt.hasNext()){
IntraDomainEdge edge = edgeIt.next();
Inet4Address source = (Inet4Address)edge.getSource();
Inet4Address dst = (Inet4Address)edge.getTarget();
log.info("Sending: ("+source.toString() +","+dst.toString()+")");
addressList = new ArrayList<Inet4Address>();
addressList.add(0,source);
addressList.add(1,dst);
//Link Local Remote Identifiers
ArrayList<Long> localRemoteIfList =null;
localRemoteIfList= new ArrayList<Long> ();
localRemoteIfList.add(0,((IntraDomainEdge) edge).getSrc_if_id());//te_info.getLinkLocalRemoteIdentifiers().getLinkLocalIdentifier());
localRemoteIfList.add(1,((IntraDomainEdge) edge).getDst_if_id());//te_info.getLinkLocalRemoteIdentifiers().getLinkRemoteIdentifier());
//MPLS
float maximumBandwidth = 0;
float[] unreservedBandwidth = null;
float maximumReservableBandwidth = 0;
int metric = 0;
//GMPLS
AvailableLabels availableLabels = null;
MF_OTPAttribTLV mfOTP = null;
TE_Information te_info = ((IntraDomainEdge) edge).getTE_info();
if (te_info != null){
if (te_info.getLinkLocalRemoteIdentifiers() != null){
}
//MPLS
if (te_info.getMaximumBandwidth() != null) {
maximumBandwidth = te_info.getMaximumBandwidth().getMaximumBandwidth();
}
if (te_info.getUnreservedBandwidth() != null)
unreservedBandwidth = te_info.getUnreservedBandwidth().getUnreservedBandwidth();
if (te_info.getMaximumReservableBandwidth() != null)
maximumReservableBandwidth = te_info.getMaximumReservableBandwidth().getMaximumReservableBandwidth();
//GMPLS
if (te_info.getAvailableLabels() != null){
availableLabels = te_info.getAvailableLabels();
}
if(te_info.getDefaultTEMetric()!=null){
metric = (int) te_info.getDefaultTEMetric().getLinkMetric();
log.info("Metric en el metodo sendLinkNLRI 2 es: " + metric);
}
if(te_info.getMfOTF()!=null){
mfOTP = te_info.getMfOTF();
}
}else{
log.info("TE_Info es null");
}
ArrayList<Inet4Address> domainList = new ArrayList<Inet4Address>(2);
domainList.add(domainID);
domainList.add(domainID);
BGP4Update update = createMsgUpdateLinkNLRI(addressList,localRemoteIfList, lanID, maximumBandwidth, unreservedBandwidth, maximumReservableBandwidth , availableLabels, metric, domainList, true, mfOTP);
update.setLearntFrom(edge.getLearntFrom());
sendMessage(update);
}
}
/**
* Function to send a BGP4 update message to the connected peers.
* @param update
*/
private void sendMessage (BGP4Update update){
Enumeration <GenericBGP4Session > sessions = bgp4SessionsInformation.getSessionList().elements();
log.fine("Sending a BGP4 update message:"+update.toString());
while (sessions.hasMoreElements()){
GenericBGP4Session session = sessions.nextElement();
if (session==null) {
log.severe("SESSION NULL");
}else {
if (session.getSendTo()) {
String destination = session.getRemotePeerIP().getHostAddress();
log.info("BGP4 Update learnt from:" + update.getLearntFrom());
try{
if (!destination.equals(update.getLearntFrom())){
log.info("Sending BGP4 update to:" + destination);
session.sendBGP4Message(update);
}
else
log.info("destination " + destination + " and source of information " + update.getLearntFrom() + " are equal");
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
/**
* This function create a BGP4 Message with NodeNLRI field
* @param addressList
* @param node_info
* @return
*/
private BGP4Update createMsgUpdateNodeNLRI(Node_Info node_info){
try{
BGP4Update update= new BGP4Update();
//Path Attributes
ArrayList<PathAttribute> pathAttributes = update.getPathAttributes();
//Origin
OriginAttribute or = new OriginAttribute();
or.setValue(PathAttributesTypeCode.PATH_ATTRIBUTE_ORIGIN_IGP);
pathAttributes.add(or);
//AS_PATH
AS_Path_Attribute as_path = new AS_Path_Attribute();
as_path.setType(PathAttributesTypeCode.PATH_ATTRIBUTE_ASPATH_AS_SEQUENCE);
as_path.setNumberASes(1);
as_path.setValue(65002);
pathAttributes.add(as_path);
//Node Attribute
LinkStateAttribute linkStateAttribute = new LinkStateAttribute();
boolean linkStateNeeded=false;
if (node_info.getSid()!=0){
int sid = node_info.getSid();
SidLabelNodeAttribTLV sidLabelTLV = new SidLabelNodeAttribTLV();
sidLabelTLV.setSid(sid);
linkStateAttribute.setSidLabelTLV(sidLabelTLV);
linkStateNeeded=true;
}
if (linkStateNeeded){
log.info("Node Attribute added....");
pathAttributes.add(linkStateAttribute);
}
//NLRI
NodeNLRI nodeNLRI = new NodeNLRI();
nodeNLRI.setProtocolID(ProtocolIDCodes.Unknown_Protocol_ID);
nodeNLRI.setRoutingUniverseIdentifier(identifier);
LocalNodeDescriptorsTLV localNodeDescriptors = new LocalNodeDescriptorsTLV();
//igp router id
if(node_info.getIpv4Address()!=null){
IGPRouterIDNodeDescriptorSubTLV igpRouterIDLNSubTLV = new IGPRouterIDNodeDescriptorSubTLV();
igpRouterIDLNSubTLV.setIpv4AddressOSPF(node_info.getIpv4Address());
igpRouterIDLNSubTLV.setIGP_router_id_type(IGPRouterIDNodeDescriptorSubTLV.IGP_ROUTER_ID_TYPE_OSPF_NON_PSEUDO);
localNodeDescriptors.setIGPRouterID(igpRouterIDLNSubTLV);
}
//as number
if(node_info.getAs_number()!=null){
AutonomousSystemNodeDescriptorSubTLV asNodeDescrSubTLV = new AutonomousSystemNodeDescriptorSubTLV();
asNodeDescrSubTLV.setAS_ID(node_info.getAs_number());
localNodeDescriptors.setAutonomousSystemSubTLV(asNodeDescrSubTLV);
}
//Complete Dummy TLVs
BGPLSIdentifierNodeDescriptorSubTLV bGPLSIDSubTLV =new BGPLSIdentifierNodeDescriptorSubTLV();
bGPLSIDSubTLV.setBGPLS_ID(this.localBGPLSIdentifer);
localNodeDescriptors.setBGPLSIDSubTLV(bGPLSIDSubTLV);
AreaIDNodeDescriptorSubTLV areaID = new AreaIDNodeDescriptorSubTLV();
areaID.setAREA_ID(this.localAreaID);
localNodeDescriptors.setAreaID(areaID);
nodeNLRI.setLocalNodeDescriptors(localNodeDescriptors);
BGP_LS_MP_Reach_Attribute ra= new BGP_LS_MP_Reach_Attribute();
ra.setLsNLRI(nodeNLRI);
pathAttributes.add(ra);
update.setLearntFrom(node_info.getLearntFrom());
return update;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Function to create a BGP4 update message with a link NRLI field. To send the links.
*
* @param addressList
* @param addressInterfaceList
* @param localRemoteIfList
* @param lanID
* @param maximumBandwidth
* @param unreservedBandwidth
* @param maximumReservableBandwidth
* @param availableLabels
* @param metric
* @param domainList
* @param intradomain
* @return
*/
private BGP4Update createMsgUpdateLinkNLRI(ArrayList<Inet4Address> addressList,ArrayList<Long> localRemoteIfList,int lanID, float maximumBandwidth, float[] unreservedBandwidth, float maximumReservableBandwidth , AvailableLabels availableLabels, int metric, ArrayList<Inet4Address> domainList, boolean intradomain, MF_OTPAttribTLV mfOTP ){
BGP4Update update= new BGP4Update();
//1. Path Attributes
ArrayList<PathAttribute> pathAttributes = update.getPathAttributes();
//1.1. Origin
OriginAttribute or = new OriginAttribute();
if (intradomain)
or.setValue(PathAttributesTypeCode.PATH_ATTRIBUTE_ORIGIN_IGP);
else
or.setValue(PathAttributesTypeCode.PATH_ATTRIBUTE_ORIGIN_EGP);
pathAttributes.add(or);
//1.2. AS-PATH
AS_Path_Attribute as_path = new AS_Path_Attribute();
as_path.setType(PathAttributesTypeCode.PATH_ATTRIBUTE_ASPATH_AS_SEQUENCE);
as_path.setNumberASes(1);
as_path.setValue(300);
pathAttributes.add(as_path);
//1.2. LINK-STATE
boolean linkStateNeeded = false;
LinkStateAttribute linkStateAttribute = new LinkStateAttribute();
//1.2.1. MaxReservableBandwidth
if (maximumReservableBandwidth != 0){
MaxReservableBandwidthLinkAttribTLV maxReservableBandwidthTLV = new MaxReservableBandwidthLinkAttribTLV();
maxReservableBandwidthTLV.setMaximumReservableBandwidth(maximumReservableBandwidth);
linkStateAttribute.setMaxReservableBandwidthTLV(maxReservableBandwidthTLV);
linkStateNeeded=true;
}
//1.2.2. maxBandwidth
if (maximumBandwidth != 0){
MaximumLinkBandwidthLinkAttribTLV maximumLinkBandwidthTLV = new MaximumLinkBandwidthLinkAttribTLV();
maximumLinkBandwidthTLV.setMaximumBandwidth(maximumBandwidth);
linkStateAttribute.setMaximumLinkBandwidthTLV(maximumLinkBandwidthTLV);
linkStateNeeded=true;
}
//1.2.3. unreservedBandwidth
if (unreservedBandwidth != null){
UnreservedBandwidthLinkAttribTLV unreservedBandwidthTLV = new UnreservedBandwidthLinkAttribTLV();
unreservedBandwidthTLV.setUnreservedBandwidth(unreservedBandwidth);
linkStateAttribute.setUnreservedBandwidthTLV(unreservedBandwidthTLV);
linkStateNeeded=true;
}
//1.2.4. AvailableLabels
if (availableLabels != null){
log.fine("Available labels fields: "+availableLabels.getLabelSet().getNumLabels());
AvailableLabels al = new AvailableLabels();
BitmapLabelSet bl = new BitmapLabelSet();
bl.setBytesBitmap(((BitmapLabelSet)availableLabels.getLabelSet()).getBytesBitMap());
bl.setNumLabels(availableLabels.getLabelSet().getNumLabels());
bl.setDwdmWavelengthLabel(((BitmapLabelSet)availableLabels.getLabelSet()).getDwdmWavelengthLabel());
bl.setBytesBitmapReserved(((BitmapLabelSet)availableLabels.getLabelSet()).getBytesBitmapReserved());
al.setLabelSet(bl);
log.fine("Campo BytesBitmap: "+Integer.toHexString(((int)bl.getBytesBitMap()[0])&0xFF));
log.fine("Campo DwdmWavelengthLabel: "+bl.getDwdmWavelengthLabel());
if (bl.getBytesBitmapReserved()!=null){
log.fine("Campo BytesBitmapReserved: "+bl.getBytesBitmapReserved()[0]);
}
linkStateAttribute.setAvailableLabels(al);
linkStateNeeded=true;
}
//1.2.5 metric
if (metric != 0){
DefaultTEMetricLinkAttribTLV defaultMetric = new DefaultTEMetricLinkAttribTLV();
defaultMetric.setLinkMetric(metric);
log.info("Metric en el metodo createMsgUpdateLinkNLRI es: " + metric);
linkStateAttribute.setTEMetricTLV(defaultMetric);
linkStateNeeded=true;
}
//1.2.6 MF_OPT
if (mfOTP != null){
MF_OTPAttribTLV mfOTPTLV = mfOTP.duplicate();
linkStateNeeded=true;
}
if (linkStateNeeded){
pathAttributes.add(linkStateAttribute);
}
//2. NLRI
LinkNLRI linkNLRI = new LinkNLRI();
linkNLRI.setProtocolID(ProtocolIDCodes.Unknown_Protocol_ID);
linkNLRI.setIdentifier(instanceId);
//2.1. Local Y Remote Descriptors
LocalNodeDescriptorsTLV localNodeDescriptors = new LocalNodeDescriptorsTLV();
RemoteNodeDescriptorsTLV remoteNodeDescriptors = new RemoteNodeDescriptorsTLV();
//2.1.1. IPv4
IGPRouterIDNodeDescriptorSubTLV igpRouterIDLNSubTLV = new IGPRouterIDNodeDescriptorSubTLV();
igpRouterIDLNSubTLV.setIpv4AddressOSPF(addressList.get(0));
igpRouterIDLNSubTLV.setIGP_router_id_type(IGPRouterIDNodeDescriptorSubTLV.IGP_ROUTER_ID_TYPE_OSPF_NON_PSEUDO);
localNodeDescriptors.setIGPRouterID(igpRouterIDLNSubTLV);
//Complete Dummy TLVs
BGPLSIdentifierNodeDescriptorSubTLV bGPLSIDSubTLV =new BGPLSIdentifierNodeDescriptorSubTLV();
bGPLSIDSubTLV.setBGPLS_ID(this.localBGPLSIdentifer);
localNodeDescriptors.setBGPLSIDSubTLV(bGPLSIDSubTLV);
AreaIDNodeDescriptorSubTLV areaID = new AreaIDNodeDescriptorSubTLV();
areaID.setAREA_ID(this.localAreaID);
localNodeDescriptors.setAreaID(areaID);
IGPRouterIDNodeDescriptorSubTLV igpRouterIDDNSubTLV = new IGPRouterIDNodeDescriptorSubTLV();
igpRouterIDDNSubTLV.setIpv4AddressOSPF(addressList.get(1));
igpRouterIDDNSubTLV.setIGP_router_id_type(IGPRouterIDNodeDescriptorSubTLV.IGP_ROUTER_ID_TYPE_OSPF_NON_PSEUDO);
remoteNodeDescriptors.setIGPRouterID(igpRouterIDDNSubTLV);
//2.1.2. AS
if (domainList != null){
AutonomousSystemNodeDescriptorSubTLV as_local = new AutonomousSystemNodeDescriptorSubTLV();
as_local.setAS_ID(domainList.get(0));
localNodeDescriptors.setAutonomousSystemSubTLV(as_local);
AutonomousSystemNodeDescriptorSubTLV as_remote = new AutonomousSystemNodeDescriptorSubTLV();
as_remote.setAS_ID(domainList.get(1));
remoteNodeDescriptors.setAutonomousSystemSubTLV(as_remote);
}
//Complete Dummy TLVs
remoteNodeDescriptors.setBGPLSIDSubTLV(bGPLSIDSubTLV);
remoteNodeDescriptors.setAreaID(areaID);
linkNLRI.setLocalNodeDescriptors(localNodeDescriptors);
linkNLRI.setRemoteNodeDescriptorsTLV(remoteNodeDescriptors);
//2.2. Link NLRI TLVs
//2.2.1. Ipv4 interface and neighbour address
IPv4InterfaceAddressLinkDescriptorsSubTLV ipv4InterfaceAddressTLV = new IPv4InterfaceAddressLinkDescriptorsSubTLV();
IPv4NeighborAddressLinkDescriptorSubTLV ipv4NeighborAddressTLV = new IPv4NeighborAddressLinkDescriptorSubTLV();
ipv4InterfaceAddressTLV.setIpv4Address(addressList.get(0));
ipv4NeighborAddressTLV.setIpv4Address(addressList.get(1));
linkNLRI.setIpv4InterfaceAddressTLV(ipv4InterfaceAddressTLV);
linkNLRI.setIpv4NeighborAddressTLV(ipv4NeighborAddressTLV);
//2.2.2. Link Local/Remote identifiers TLV
if (localRemoteIfList != null){
LinkLocalRemoteIdentifiersLinkDescriptorSubTLV linkIdentifiersTLV = new LinkLocalRemoteIdentifiersLinkDescriptorSubTLV();
linkIdentifiersTLV.setLinkLocalIdentifier(localRemoteIfList.get(0));
linkIdentifiersTLV.setLinkRemoteIdentifier(localRemoteIfList.get(1));
linkNLRI.setLinkIdentifiersTLV(linkIdentifiersTLV);
}
linkNLRI.setIdentifier(this.identifier);
BGP_LS_MP_Reach_Attribute ra= new BGP_LS_MP_Reach_Attribute();
ra.setLsNLRI(linkNLRI);
pathAttributes.add(ra);
return update;
}
/**
* Funcion que crea un mensaje OSPF inventado desde cero.
* Solo se meten en el mensaje los campos:
* - source
* - destino
* - maximun bandwithd
*/
public static OSPFv2LinkStateUpdatePacket createMsgOSPF(){
Inet4Address src = null;
Inet4Address dst = null;
MaximumBandwidth maximumBandwidth = new MaximumBandwidth();
maximumBandwidth.setMaximumBandwidth(100);
UnreservedBandwidth unreservedBandwidth = new UnreservedBandwidth();
float[] unReservedB = new float[8];
unReservedB[0]=18309;
unReservedB[1]=130;
unreservedBandwidth.setUnreservedBandwidth(unReservedB);
try {
src = (Inet4Address) Inet4Address.getByName( "179.123.123.123");
dst = (Inet4Address) Inet4Address.getByName( "179.123.123.111");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OSPFv2LinkStateUpdatePacket ospfv2Packet = new OSPFv2LinkStateUpdatePacket();
ospfv2Packet.setRouterID(src);
LinkedList<LSA> lsaList = new LinkedList<LSA>();
OSPFTEv2LSA lsa = new OSPFTEv2LSA();
LinkTLV linkTLV=new LinkTLV();
lsa.setLinkTLV(linkTLV);
linkTLV.setMaximumBandwidth(maximumBandwidth);
linkTLV.setUnreservedBandwidth(unreservedBandwidth);
LocalInterfaceIPAddress localInterfaceIPAddress= new LocalInterfaceIPAddress();
LinkedList<Inet4Address> lista =localInterfaceIPAddress.getLocalInterfaceIPAddressList();
lista.add(src);
linkTLV.setLocalInterfaceIPAddress(localInterfaceIPAddress);
RemoteInterfaceIPAddress remoteInterfaceIPAddress= new RemoteInterfaceIPAddress();
LinkedList<Inet4Address> listar = remoteInterfaceIPAddress.getRemoteInterfaceIPAddressList();
listar.add(dst);
linkTLV.setRemoteInterfaceIPAddress(remoteInterfaceIPAddress);
LinkID linkID = new LinkID();
linkID.setLinkID(dst);
linkTLV.setLinkID(linkID);
// if (edge.getTE_info().getAvailableLabels() != null){
// linkTLV.setAvailableLabels(edge.getTE_info().getAvailableLabels());
lsaList.add(lsa);
ospfv2Packet.setLSAlist(lsaList);
return ospfv2Packet;
}
/**
* Funcin que decodifica un mensaje OSPFv2LinkStateUpdatePacket creando con los campos extraidos un mensaje BGP4 update.
* @param ospfv2Packet
* @return
*/
public BGP4Update decodificarMsgOSPF(OSPFv2LinkStateUpdatePacket ospfv2Packet){
boolean intradomain = true;
Inet4Address localIPAddress = ospfv2Packet.getRouterID();
Inet4Address remoteIPAddress = null;
long localInterfaceIPAddress = -1;
long remoteInterfaceIPAddress = -1;
Inet4Address remoteASNumber = null;
LinkedList<LSA> lsaList;
OSPFTEv2LSA lsa;
//GMPLS Parameter
AvailableLabels al = null;
//MPLS Parameter
float maxBandwidth = 0;
float[] unBandwidth = null;
float maximumReservableBandwidth=0;
lsaList = ((OSPFv2LinkStateUpdatePacket)ospfv2Packet).getLSAlist();
for (int i =0;i< lsaList.size();i++){
if (lsaList.get(i).getLStype() == LSATypes.TYPE_10_OPAQUE_LSA){
lsa=(OSPFTEv2LSA)lsaList.get(i);
log.fine("Starting to process LSA");
LinkTLV linkTLV = lsa.getLinkTLV();
if (linkTLV!=null){
//Local and Remote interface IP address
remoteIPAddress = linkTLV.getLinkID().getLinkID();
log.fine("Remote IP Address: "+remoteIPAddress);
localInterfaceIPAddress = linkTLV.getLinkLocalRemoteIdentifiers().getLinkLocalIdentifier();
log.fine("Local Interface: "+localInterfaceIPAddress);
remoteInterfaceIPAddress =linkTLV.getLinkLocalRemoteIdentifiers().getLinkRemoteIdentifier();
log.fine("Remote Interface: "+remoteInterfaceIPAddress);
//MPLS fields
if (linkTLV.getMaximumBandwidth() != null)
maxBandwidth = linkTLV.getMaximumBandwidth().getMaximumBandwidth();
if (linkTLV.getUnreservedBandwidth() != null)
unBandwidth = linkTLV.getUnreservedBandwidth().getUnreservedBandwidth();
if (linkTLV.getMaximumReservableBandwidth()!= null)
maximumReservableBandwidth = linkTLV.getMaximumReservableBandwidth().getMaximumReservableBandwidth();
//GMPLS
al = linkTLV.getAvailableLabels();
//FIXME: Como ver si es inter o intra domain
if (linkTLV.getRemoteASNumber() != null)
remoteASNumber = linkTLV.getRemoteASNumber().getRemoteASNumber();
}
}
}
//Create the address list
ArrayList<Inet4Address> addressList = new ArrayList<Inet4Address>();
addressList.add(localIPAddress);
addressList.add(remoteIPAddress);
//Create the interface list
ArrayList<Long> localRemoteIfList = new ArrayList<Long>();
localRemoteIfList.add(localInterfaceIPAddress);
localRemoteIfList.add(remoteInterfaceIPAddress);
//Create the domain List
ArrayList<Inet4Address> domainList = new ArrayList<Inet4Address>(2);
return createMsgUpdateLinkNLRI(addressList,localRemoteIfList,23,maxBandwidth,unBandwidth,maximumReservableBandwidth,al, 0, domainList, intradomain, null);
}
public boolean isSendTopology() {
return sendTopology;
}
public void setSendTopology(boolean sendTopology) {
this.sendTopology = sendTopology;
}
public BGP4SessionsInformation getBgp4SessionsInformation() {
return bgp4SessionsInformation;
}
public void setBgp4SessionsInformation(
BGP4SessionsInformation bgp4SessionsInformation) {
this.bgp4SessionsInformation = bgp4SessionsInformation;
}
public void setInstanceId(int instanceId) {
this.instanceId = instanceId;
}
}
|
package eventdetection.downloader;
import java.util.List;
import java.util.Properties;
import java.util.function.Function;
import edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;
import eventdetection.common.Article;
public class NLPFunction implements Function<RawArticle, Article> {
private static final String delimiter = "_";
private static final StanfordCoreNLP pipeline;
static {
// creates a StanfordCoreNLP object, with POS tagging, lemmatization,
// NER, parsing, and coreference resolution
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
pipeline = new StanfordCoreNLP(props);
}
@Override
public Article apply(RawArticle t) {
// read some text in the text variable
String text = t.getText();
// create an empty Annotation just with the given text
Annotation document = new Annotation(text);
// run all Annotators on this text
pipeline.annotate(document);
// these are all the sentences in this document
// a CoreMap is essentially a Map that uses class objects as keys and
// has values with custom types
List<CoreMap> sentences = document.get(SentencesAnnotation.class);
StringBuilder sb = new StringBuilder((int) (t.getText().length() * 1.5));
for (CoreMap sentence : sentences) {
// traversing the words in the current sentence
// a CoreLabel is a CoreMap with additional token-specific methods
for (CoreLabel token : sentence.get(TokensAnnotation.class))
sb.append(token.word()).append(delimiter).append(token.get(PartOfSpeechAnnotation.class)).append(" ");
// this is the parse tree of the current sentence
// Tree tree = sentence.get(TreeAnnotation.class);
// System.out.println(tree.toString());
}
return new Article(t.getTitle(), sb.toString().trim(), t.getText(), t.getUrl(), t.getSource());
}
}
|
package samples;
import choco.kernel.ResolutionPolicy;
import org.kohsuke.args4j.Option;
import solver.Solver;
import solver.constraints.ConstraintFactory;
import solver.constraints.nary.AllDifferent;
import solver.constraints.nary.Sum;
import solver.propagation.engines.IPropagationEngine;
import solver.propagation.engines.comparators.predicate.MemberV;
import solver.propagation.engines.group.Group;
import solver.search.strategy.StrategyFactory;
import solver.variables.IntVar;
import solver.variables.VariableFactory;
import java.util.Arrays;
import java.util.HashSet;
/**
* <br/>
*
* @author Charles Prud'homme
* @since 31/03/11
*/
public class GolombRuler extends AbstractProblem {
@Option(name = "-o", usage = "Golomb ruler order.", required = false)
private int m = 10;
@Option(name = "-allDiff", usage = "Use allDifferent constraint", required = false)
private boolean useAllDiff = false;
IntVar[] ticks;
@Override
public void buildModel() {
solver = new Solver("Golomb Ruler " + m);
ticks = new IntVar[m];
for (int i = 0; i < ticks.length; i++) {
ticks[i] = VariableFactory.bounded("a_" + i, 0, ((m < 31) ? (1 << (m + 1)) - 1 : 9999), solver);
}
solver.post(ConstraintFactory.eq(ticks[0], 0, solver));
for (int i = 0; i < ticks.length - 1; i++) {
solver.post(ConstraintFactory.lt(ticks[i], ticks[i + 1], solver));
}
IntVar[] diff = new IntVar[(m * m - m) / 2];
// IntVar[][] diff_ = new IntVar[m][m];
for (int k = 0, i = 0; i < m - 1; i++) {
for (int j = i + 1; j < m; j++, k++) {
diff[k] = VariableFactory.bounded("d_" + i, 0, ((m < 31) ? (1 << (m + 1)) - 1 : 9999), solver);
// diff_[i][j] = diff[k];
}
}
for (int k = 0, i = 0; i < m - 1; i++) {
for (int j = i + 1; j < m; j++, k++) {
// d[k] is m[j]-m[i] and must be at least sum of first j-i integers
solver.post(Sum.eq(new IntVar[]{ticks[j], ticks[i], diff[k]}, new int[]{1, -1, -1}, 0, solver));
solver.post(Sum.geq(new IntVar[]{diff[k]}, new int[]{1}, (j - i) * (j - i + 1) / 2, solver));
solver.post(Sum.leq(new IntVar[]{diff[k], ticks[m - 1]}, new int[]{1, -1}, -((m - 1 - j + i) * (m - j + i)) / 2, solver));
}
}
if (useAllDiff) {
solver.post(new AllDifferent(diff, solver));
} else {
// d_ij != d_kl
for (int i = 0; i < diff.length; i++) {
for (int j = i + 1; j < diff.length; j++) {
solver.post(ConstraintFactory.neq(diff[i], diff[j], solver));
}
}
}
// break symetries
if (m > 2) {
solver.post(ConstraintFactory.lt(diff[0], diff[diff.length - 1], solver));
}
}
@Override
public void configureSolver() {
solver.set(StrategyFactory.inputOrderMinVal(ticks, solver.getEnvironment()));
// SearchMonitorFactory.log(solver, false, true);
IPropagationEngine engine = solver.getEngine();
engine.addGroup(Group.buildQueue(
new MemberV<IntVar>(new HashSet<IntVar>(Arrays.asList(ticks)))
));
}
@Override
public void solve() {
solver.findOptimalSolution(ResolutionPolicy.MINIMIZE, (IntVar) solver.getVars()[m - 1]);
}
@Override
public void prettyOut() {
}
public static void main(String[] args) {
new GolombRuler().execute(args);
}
}
|
package foam.core;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
public abstract class AbstractFObjectPropertyInfo
extends AbstractObjectPropertyInfo
{
// public int compareValues(FObject o1, FObject o2) {
// return o1.compareTo(o2);
@Override
public Object fromXML(X x, XMLStreamReader reader) {
FObject obj = null;
try {
while ( reader.hasNext() ) {
int eventType;
eventType = reader.next();
switch ( eventType ) {
case XMLStreamConstants.START_ELEMENT:
if (reader.getLocalName() == "object") {
XMLSupport.createObj(x, reader);
}
// Enum Specific Case
if (reader.getLocalName() == "ordinal" ) {
Class cls = Class.forName(this.of);
reader.next();
Integer ordinalVal = Integer.parseInt(reader.getText());
return ((java.lang.Class<Enum>)cls).getEnumConstants()[ordinalVal];
}
case XMLStreamConstants.END_ELEMENT:
break;
}
}
} catch ( XMLStreamException ex) {
}
return obj;
}
@Override
public void toXML(FObject obj, Document doc, Element objElement) {
Object nestObj = this.f(obj);
String objName = nestObj.getClass().getName();
Element objTag = doc.createElement(objName.substring(objName.lastIndexOf(".")).replace(".",""));
objElement.appendChild(objTag);
if ( nestObj.getClass().isEnum() ) {
XMLSupport.enumXML( (Enum) nestObj, doc, objTag);
} else {
XMLSupport.toXML((FObject) nestObj, doc, objTag);
}
}
}
|
package org.voltcore.utils;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import jsr166y.LinkedTransferQueue;
import org.voltcore.logging.VoltLogger;
import vanilla.java.affinity.impl.PosixJNAAffinity;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
public class CoreUtils {
private static final VoltLogger hostLog = new VoltLogger("HOST");
public static final int SMALL_STACK_SIZE = 1024 * 128;
public static final int MEDIUM_STACK_SIZE = 1024 * 512;
/**
* Get a single thread executor that caches it's thread meaning that the thread will terminate
* after keepAlive milliseconds. A new thread will be created the next time a task arrives and that will be kept
* around for keepAlive milliseconds. On creation no thread is allocated, the first task creates a thread.
*
* Uses LinkedTransferQueue to accept tasks and has a small stack.
*/
public static ListeningExecutorService getCachedSingleThreadExecutor(String name, long keepAlive) {
return MoreExecutors.listeningDecorator(new ThreadPoolExecutor(
0,
1,
keepAlive,
TimeUnit.MILLISECONDS,
new LinkedTransferQueue<Runnable>(),
CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null)));
}
/**
* Create an unbounded single threaded executor
*/
public static ListeningExecutorService getSingleThreadExecutor(String name) {
ExecutorService ste =
Executors.newSingleThreadExecutor(CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null));
return MoreExecutors.listeningDecorator(ste);
}
public static ListeningExecutorService getSingleThreadExecutor(String name, int size) {
ExecutorService ste =
Executors.newSingleThreadExecutor(CoreUtils.getThreadFactory(null, name, size, false, null));
return MoreExecutors.listeningDecorator(ste);
}
/**
* Create a bounded single threaded executor that rejects requests if more than capacity
* requests are outstanding.
*/
public static ListeningExecutorService getBoundedSingleThreadExecutor(String name, int capacity) {
LinkedBlockingQueue<Runnable> lbq = new LinkedBlockingQueue<Runnable>(capacity);
ThreadPoolExecutor tpe =
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, lbq, CoreUtils.getThreadFactory(name));
return MoreExecutors.listeningDecorator(tpe);
}
/*
* Have shutdown actually means shutdown. Tasks that need to complete should use
* futures.
*/
public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name, int poolSize, int stackSize) {
ScheduledThreadPoolExecutor ses = new ScheduledThreadPoolExecutor(poolSize, getThreadFactory(null, name, stackSize, poolSize > 1, null));
ses.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
ses.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
return ses;
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
final int threads) {
return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), null);
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
final int coreThreads,
final int threads) {
return getListeningExecutorService(name, coreThreads, threads, new LinkedTransferQueue<Runnable>(), null);
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
final int threads,
Queue<String> coreList) {
return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), coreList);
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
int threadsTemp,
final BlockingQueue<Runnable> queue,
final Queue<String> coreList) {
if (coreList != null && !coreList.isEmpty()) {
threadsTemp = coreList.size();
}
final int threads = threadsTemp;
if (threads < 1) {
throw new IllegalArgumentException("Must specify > 0 threads");
}
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
return MoreExecutors.listeningDecorator(
new ThreadPoolExecutor(threads, threads,
0L, TimeUnit.MILLISECONDS,
queue,
getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList)));
}
public static ListeningExecutorService getListeningExecutorService(
final String name,
int coreThreadsTemp,
int threadsTemp,
final BlockingQueue<Runnable> queue,
final Queue<String> coreList) {
if (coreThreadsTemp < 0) {
throw new IllegalArgumentException("Must specify >= 0 core threads");
}
if (coreThreadsTemp > threadsTemp) {
throw new IllegalArgumentException("Core threads must be <= threads");
}
if (coreList != null && !coreList.isEmpty()) {
threadsTemp = coreList.size();
if (coreThreadsTemp > threadsTemp) {
coreThreadsTemp = threadsTemp;
}
}
final int coreThreads = coreThreadsTemp;
final int threads = threadsTemp;
if (threads < 1) {
throw new IllegalArgumentException("Must specify > 0 threads");
}
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
return MoreExecutors.listeningDecorator(
new ThreadPoolExecutor(coreThreads, threads,
1L, TimeUnit.MINUTES,
queue,
getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList)));
}
/**
* Create a bounded thread pool executor
* @param maxPoolSize: the maximum number of threads to allow in the pool.
* @param keepAliveTime: when the number of threads is greater than the core, this is the maximum
* time that excess idle threads will wait for new tasks before terminating.
* @param unit: the time unit for the keepAliveTime argument.
* @param threadFactory: the factory to use when the executor creates a new thread.
*/
public static ThreadPoolExecutor getBoundedThreadPoolExecutor(int maxPoolSize, long keepAliveTime, TimeUnit unit, ThreadFactory tFactory) {
return new ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, unit,
new LinkedBlockingQueue<Runnable>(), tFactory);
}
public static ThreadFactory getThreadFactory(String name) {
return getThreadFactory(name, SMALL_STACK_SIZE);
}
public static ThreadFactory getThreadFactory(String groupName, String name) {
return getThreadFactory(groupName, name, SMALL_STACK_SIZE, true, null);
}
public static ThreadFactory getThreadFactory(String name, int stackSize) {
return getThreadFactory(null, name, stackSize, true, null);
}
/**
* Creates a thread factory that creates threads within a thread group if
* the group name is given. The threads created will catch any unhandled
* exceptions and log them to the HOST logger.
*
* @param groupName
* @param name
* @param stackSize
* @return
*/
public static ThreadFactory getThreadFactory(
final String groupName,
final String name,
final int stackSize,
final boolean incrementThreadNames,
final Queue<String> coreList) {
ThreadGroup group = null;
if (groupName != null) {
group = new ThreadGroup(Thread.currentThread().getThreadGroup(), groupName);
}
final ThreadGroup finalGroup = group;
return new ThreadFactory() {
private final AtomicLong m_createdThreadCount = new AtomicLong(0);
private final ThreadGroup m_group = finalGroup;
@Override
public synchronized Thread newThread(final Runnable r) {
final String threadName = name +
(incrementThreadNames ? " - " + m_createdThreadCount.getAndIncrement() : "");
String coreTemp = null;
if (coreList != null && !coreList.isEmpty()) {
coreTemp = coreList.poll();
}
final String core = coreTemp;
Runnable runnable = new Runnable() {
@Override
public void run() {
if (core != null) {
PosixJNAAffinity.INSTANCE.setAffinity(core);
}
try {
r.run();
} catch (Throwable t) {
hostLog.error("Exception thrown in thread " + threadName, t);
}
}
};
Thread t = new Thread(m_group, runnable, threadName, stackSize);
t.setDaemon(true);
return t;
}
};
}
/**
* Return the local hostname, if it's resolvable. If not,
* return the IPv4 address on the first interface we find, if it exists.
* If not, returns whatever address exists on the first interface.
* @return the String representation of some valid host or IP address,
* if we can find one; the empty string otherwise
*/
public static String getHostnameOrAddress() {
try {
final InetAddress addr = InetAddress.getLocalHost();
return addr.getHostName();
} catch (UnknownHostException e) {
try {
// XXX-izzy Won't we randomly pull localhost here sometimes?
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces == null) {
return "";
}
NetworkInterface intf = interfaces.nextElement();
Enumeration<InetAddress> addresses = intf.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address instanceof Inet4Address) {
return address.getHostAddress();
}
}
addresses = intf.getInetAddresses();
if (addresses.hasMoreElements())
{
return addresses.nextElement().getHostAddress();
}
return "";
} catch (SocketException e1) {
return "";
}
}
}
/**
* Return the local IP address, if it's resolvable. If not,
* return the IPv4 address on the first interface we find, if it exists.
* If not, returns whatever address exists on the first interface.
* @return the String representation of some valid host or IP address,
* if we can find one; the empty string otherwise
*/
public static InetAddress getLocalAddress() {
try {
final InetAddress addr = InetAddress.getLocalHost();
return addr;
} catch (UnknownHostException e) {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces == null) {
return null;
}
NetworkInterface intf = interfaces.nextElement();
Enumeration<InetAddress> addresses = intf.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address instanceof Inet4Address) {
return address;
}
}
addresses = intf.getInetAddresses();
if (addresses.hasMoreElements()) {
return addresses.nextElement();
}
return null;
} catch (SocketException e1) {
return null;
}
}
}
public static long getHSIdFromHostAndSite(int host, int site) {
long HSId = site;
HSId = (HSId << 32) + host;
return HSId;
}
public static int getHostIdFromHSId(long HSId) {
return (int) (HSId & 0xffffffff);
}
public static String hsIdToString(long hsId) {
return Integer.toString((int)hsId) + ":" + Integer.toString((int)(hsId >> 32));
}
public static String hsIdCollectionToString(Collection<Long> ids) {
List<String> idstrings = new ArrayList<String>();
for (Long id : ids) {
idstrings.add(hsIdToString(id));
}
// Easy hack, sort hsIds lexically.
Collections.sort(idstrings);
StringBuilder sb = new StringBuilder();
boolean first = false;
for (String id : idstrings) {
if (!first) {
first = true;
} else {
sb.append(", ");
}
sb.append(id);
}
return sb.toString();
}
public static int getSiteIdFromHSId(long siteId) {
return (int)(siteId>>32);
}
public static <K,V> ImmutableMap<K, ImmutableList<V>> unmodifiableMapCopy(Map<K, List<V>> m) {
ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder();
for (Map.Entry<K, List<V>> e : m.entrySet()) {
builder.put(e.getKey(), ImmutableList.<V>builder().addAll(e.getValue()).build());
}
return builder.build();
}
public static byte[] urlToBytes(String url) {
if (url == null) {
return null;
}
try {
// get the URL/path for the deployment and prep an InputStream
InputStream input = null;
try {
URL inputURL = new URL(url);
input = inputURL.openStream();
} catch (MalformedURLException ex) {
// Invalid URL. Try as a file.
try {
input = new FileInputStream(url);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
} catch (IOException ioex) {
throw new RuntimeException(ioex);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte readBytes[] = new byte[1024 * 8];
while (true) {
int read = input.read(readBytes);
if (read == -1) {
break;
}
baos.write(readBytes, 0, read);
}
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String throwableToString(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.flush();
return sw.toString();
}
public static String hsIdKeyMapToString(Map<Long, ?> m) {
StringBuilder sb = new StringBuilder();
sb.append('{');
boolean first = true;
for (Map.Entry<Long, ?> entry : m.entrySet()) {
if (!first) sb.append(", ");
first = false;
sb.append(CoreUtils.hsIdToString(entry.getKey()));
sb.append(entry.getValue());
}
sb.append('}');
return sb.toString();
}
public static String hsIdEntriesToString(Collection<Map.Entry<Long, Long>> entries) {
StringBuilder sb = new StringBuilder();
sb.append('{');
boolean first = true;
for (Map.Entry<Long, Long> entry : entries) {
if (!first) sb.append(", ");
first = false;
sb.append(CoreUtils.hsIdToString(entry.getKey())).append(" -> ");
sb.append(CoreUtils.hsIdToString(entry.getValue()));
}
sb.append('}');
return sb.toString();
}
public static int availableProcessors() {
return Math.max(1, Runtime.getRuntime().availableProcessors());
}
}
|
package org.voltdb.utils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.hadoop_voltpatches.util.PureJavaCrc32;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.mindrot.BCrypt;
import org.voltcore.logging.Level;
import org.voltcore.logging.VoltLogger;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.VoltZK;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.CatalogType;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.ColumnRef;
import org.voltdb.catalog.ConnectorProperty;
import org.voltdb.catalog.Constraint;
import org.voltdb.catalog.ConstraintRef;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Deployment;
import org.voltdb.catalog.Group;
import org.voltdb.catalog.GroupRef;
import org.voltdb.catalog.Index;
import org.voltdb.catalog.PlanFragment;
import org.voltdb.catalog.Procedure;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.catalog.Statement;
import org.voltdb.catalog.Systemsettings;
import org.voltdb.catalog.Table;
import org.voltdb.compiler.ClusterConfig;
import org.voltdb.compiler.deploymentfile.AdminModeType;
import org.voltdb.compiler.deploymentfile.ClusterType;
import org.voltdb.compiler.deploymentfile.CommandLogType;
import org.voltdb.compiler.deploymentfile.CommandLogType.Frequency;
import org.voltdb.compiler.deploymentfile.DeploymentType;
import org.voltdb.compiler.deploymentfile.ExportConfigurationType;
import org.voltdb.compiler.deploymentfile.ExportOnServerType;
import org.voltdb.compiler.deploymentfile.ExportType;
import org.voltdb.compiler.deploymentfile.HeartbeatType;
import org.voltdb.compiler.deploymentfile.HttpdType;
import org.voltdb.compiler.deploymentfile.PartitionDetectionType;
import org.voltdb.compiler.deploymentfile.PathEntry;
import org.voltdb.compiler.deploymentfile.PathsType;
import org.voltdb.compiler.deploymentfile.PropertyType;
import org.voltdb.compiler.deploymentfile.SecurityType;
import org.voltdb.compiler.deploymentfile.ServerExportEnum;
import org.voltdb.compiler.deploymentfile.SnapshotType;
import org.voltdb.compiler.deploymentfile.SystemSettingsType;
import org.voltdb.compiler.deploymentfile.SystemSettingsType.Temptables;
import org.voltdb.compiler.deploymentfile.UsersType;
import org.voltdb.compiler.deploymentfile.UsersType.User;
import org.voltdb.compilereport.IndexAnnotation;
import org.voltdb.compilereport.ProcedureAnnotation;
import org.voltdb.compilereport.StatementAnnotation;
import org.voltdb.compilereport.TableAnnotation;
import org.voltdb.export.processors.GuestProcessor;
import org.voltdb.export.processors.RawProcessor;
import org.voltdb.exportclient.ExportToFileClient;
import org.voltdb.plannodes.AbstractPlanNode;
import org.voltdb.types.ConstraintType;
import org.voltdb.types.IndexType;
import org.xml.sax.SAXException;
import com.google.common.base.Charsets;
import static org.voltdb.compiler.deploymentfile.ServerExportEnum.JDBC;
public abstract class CatalogUtil {
private static final VoltLogger hostLog = new VoltLogger("HOST");
// The minimum version of catalog that's compatible with this version of Volt
public static final int[] minCompatibleVersion = {3, 2};
public static final String CATALOG_FILENAME = "catalog.txt";
public static final String CATALOG_BUILDINFO_FILENAME = "buildinfo.txt";
/**
* Load a catalog from the jar bytes.
*
* @param catalogBytes
* @param log
* @return The serialized string of the catalog content.
* @throws Exception
* If the catalog cannot be loaded because it's incompatible, or
* if there is no version information in the catalog.
*/
public static String loadCatalogFromJar(byte[] catalogBytes, VoltLogger log) throws IOException {
assert(catalogBytes != null);
String serializedCatalog = null;
String voltVersionString = null;
InMemoryJarfile jarfile = new InMemoryJarfile(catalogBytes);
byte[] serializedCatalogBytes = jarfile.get(CATALOG_FILENAME);
if (null == serializedCatalogBytes) {
throw new IOException("Database catalog not found - please build your application using the current version of VoltDB.");
}
serializedCatalog = new String(serializedCatalogBytes, "UTF-8");
// Get Volt version string
byte[] buildInfoBytes = jarfile.get(CATALOG_BUILDINFO_FILENAME);
if (buildInfoBytes == null) {
throw new IOException("Catalog build information not found - please build your application using the current version of VoltDB.");
}
String buildInfo = new String(buildInfoBytes, "UTF-8");
String[] buildInfoLines = buildInfo.split("\n");
if (buildInfoLines.length != 5) {
throw new IOException("Catalog built with an old version of VoltDB - please build your application using the current version of VoltDB.");
}
voltVersionString = buildInfoLines[0].trim();
// Check if it's compatible
if (!isCatalogCompatible(voltVersionString)) {
throw new IOException("Catalog compiled with " + voltVersionString + " is not compatible with the current version of VoltDB (" +
VoltDB.instance().getVersionString() + ") - " + " please build your application using the current version of VoltDB.");
}
return serializedCatalog;
}
/**
* Serialize a file into bytes. Used to serialize catalog and deployment
* file for UpdateApplicationCatalog on the client.
*
* @param path
* @return a byte array of the file
* @throws IOException
* If there are errors reading the file
*/
public static byte[] toBytes(File path) throws IOException {
FileInputStream fin = new FileInputStream(path);
byte[] buffer = new byte[(int) fin.getChannel().size()];
try {
if (fin.read(buffer) == -1) {
throw new IOException("File " + path.getAbsolutePath() + " is empty");
}
} finally {
fin.close();
}
return buffer;
}
/**
* Get a unique id for a plan fragment by munging the indices of it's parents
* and grandparents in the catalog.
*
* @param frag Catalog fragment to identify
* @return unique id for fragment
*/
public static long getUniqueIdForFragment(PlanFragment frag) {
long retval = 0;
CatalogType parent = frag.getParent();
retval = ((long) parent.getParent().getRelativeIndex()) << 32;
retval += ((long) parent.getRelativeIndex()) << 16;
retval += frag.getRelativeIndex();
return retval;
}
/**
*
* @param catalogTable
* @return An empty table with the same schema as a given catalog table.
*/
public static VoltTable getVoltTable(Table catalogTable) {
List<Column> catalogColumns = CatalogUtil.getSortedCatalogItems(catalogTable.getColumns(), "index");
VoltTable.ColumnInfo[] columns = new VoltTable.ColumnInfo[catalogColumns.size()];
int i = 0;
for (Column catCol : catalogColumns) {
columns[i++] = new VoltTable.ColumnInfo(catCol.getTypeName(), VoltType.get((byte)catCol.getType()));
}
return new VoltTable(columns);
}
/**
* Given a set of catalog items, return a sorted list of them, sorted by
* the value of a specified field. The field is specified by name. If the
* field doesn't exist, trip an assertion. This is primarily used to sort
* a table's columns or a procedure's parameters.
*
* @param <T> The type of item to sort.
* @param items The set of catalog items.
* @param sortFieldName The name of the field to sort on.
* @return A list of catalog items, sorted on the specified field.
*/
public static <T extends CatalogType> List<T> getSortedCatalogItems(CatalogMap<T> items, String sortFieldName) {
assert(items != null);
assert(sortFieldName != null);
// build a treemap based on the field value
TreeMap<Object, T> map = new TreeMap<Object, T>();
boolean hasField = false;
for (T item : items) {
// check the first time through for the field
if (hasField == false)
hasField = item.getFields().contains(sortFieldName);
assert(hasField == true);
map.put(item.getField(sortFieldName), item);
}
// create a sorted list from the map
ArrayList<T> retval = new ArrayList<T>();
for (T item : map.values()) {
retval.add(item);
}
return retval;
}
/**
* For a given Table catalog object, return the PrimaryKey Index catalog object
* @param catalogTable
* @return The index representing the primary key.
* @throws Exception if the table does not define a primary key
*/
public static Index getPrimaryKeyIndex(Table catalogTable) throws Exception {
// We first need to find the pkey constraint
Constraint catalog_constraint = null;
for (Constraint c : catalogTable.getConstraints()) {
if (c.getType() == ConstraintType.PRIMARY_KEY.getValue()) {
catalog_constraint = c;
break;
}
}
if (catalog_constraint == null) {
throw new Exception("ERROR: Table '" + catalogTable.getTypeName() + "' does not have a PRIMARY KEY constraint");
}
// And then grab the index that it is using
return (catalog_constraint.getIndex());
}
/**
* Return all the of the primary key columns for a particular table
* If the table does not have a primary key, then the returned list will be empty
* @param catalogTable
* @return An ordered list of the primary key columns
*/
public static Collection<Column> getPrimaryKeyColumns(Table catalogTable) {
Collection<Column> columns = new ArrayList<Column>();
Index catalog_idx = null;
try {
catalog_idx = CatalogUtil.getPrimaryKeyIndex(catalogTable);
} catch (Exception ex) {
// IGNORE
return (columns);
}
assert(catalog_idx != null);
for (ColumnRef catalog_col_ref : getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
columns.add(catalog_col_ref.getColumn());
}
return (columns);
}
/**
* Convert a Table catalog object into the proper SQL DDL, including all indexes,
* constraints, and foreign key references.
* @param catalog_tbl
* @return SQL Schema text representing the table.
*/
public static String toSchema(Table catalog_tbl) {
assert(!catalog_tbl.getColumns().isEmpty());
final String spacer = " ";
Set<Index> skip_indexes = new HashSet<Index>();
Set<Constraint> skip_constraints = new HashSet<Constraint>();
String ret = "CREATE TABLE " + catalog_tbl.getTypeName() + " (";
// Columns
String add = "\n";
for (Column catalog_col : CatalogUtil.getSortedCatalogItems(catalog_tbl.getColumns(), "index")) {
VoltType col_type = VoltType.get((byte)catalog_col.getType());
// this next assert would be great if we dealt with default values well
//assert(! ((catalog_col.getDefaultvalue() == null) && (catalog_col.getNullable() == false) ) );
ret += add + spacer + catalog_col.getTypeName() + " " +
col_type.toSQLString() +
(col_type == VoltType.STRING && catalog_col.getSize() > 0 ? "(" + catalog_col.getSize() + ")" : "");
// Default value
String defaultvalue = catalog_col.getDefaultvalue();
//VoltType defaulttype = VoltType.get((byte)catalog_col.getDefaulttype());
boolean nullable = catalog_col.getNullable();
// TODO: Shouldn't have to check whether the string contains "null"
if (defaultvalue != null && defaultvalue.toLowerCase().equals("null") && nullable) {
defaultvalue = null;
}
else { // XXX: if (defaulttype != VoltType.VOLTFUNCTION) {
// TODO: Escape strings properly
defaultvalue = "'" + defaultvalue + "'";
}
ret += " DEFAULT " + (defaultvalue != null ? defaultvalue : "NULL") +
(!nullable ? " NOT NULL" : "");
// Single-column constraints
for (ConstraintRef catalog_const_ref : catalog_col.getConstraints()) {
Constraint catalog_const = catalog_const_ref.getConstraint();
ConstraintType const_type = ConstraintType.get(catalog_const.getType());
// Check if there is another column in our table with the same constraint
// If there is, then we need to add it to the end of the table definition
boolean found = false;
for (Column catalog_other_col : catalog_tbl.getColumns()) {
if (catalog_other_col.equals(catalog_col)) continue;
if (catalog_other_col.getConstraints().getIgnoreCase(catalog_const.getTypeName()) != null) {
found = true;
break;
}
}
if (!found) {
switch (const_type) {
case FOREIGN_KEY: {
Table catalog_fkey_tbl = catalog_const.getForeignkeytable();
Column catalog_fkey_col = null;
for (ColumnRef ref : catalog_const.getForeignkeycols()) {
catalog_fkey_col = ref.getColumn();
break; // Nasty hack to get first item
}
assert(catalog_fkey_col != null);
ret += " REFERENCES " + catalog_fkey_tbl.getTypeName() + " (" + catalog_fkey_col.getTypeName() + ")";
skip_constraints.add(catalog_const);
break;
}
default:
// Nothing for now
}
}
}
add = ",\n";
}
// Constraints
for (Constraint catalog_const : catalog_tbl.getConstraints()) {
if (skip_constraints.contains(catalog_const)) continue;
ConstraintType const_type = ConstraintType.get(catalog_const.getType());
// Primary Keys / Unique Constraints
if (const_type == ConstraintType.PRIMARY_KEY || const_type == ConstraintType.UNIQUE) {
Index catalog_idx = catalog_const.getIndex();
String idx_suffix = IndexType.getSQLSuffix(catalog_idx.getType());
ret += add + spacer +
(!idx_suffix.isEmpty() ? "CONSTRAINT " + catalog_const.getTypeName() + " " : "") +
(const_type == ConstraintType.PRIMARY_KEY ? "PRIMARY KEY" : "UNIQUE") + " (";
String col_add = "";
for (ColumnRef catalog_colref : CatalogUtil.getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
ret += col_add + catalog_colref.getColumn().getTypeName();
col_add = ", ";
} // FOR
ret += ")";
skip_indexes.add(catalog_idx);
// Foreign Key
} else if (const_type == ConstraintType.FOREIGN_KEY) {
Table catalog_fkey_tbl = catalog_const.getForeignkeytable();
String col_add = "";
String our_columns = "";
String fkey_columns = "";
for (ColumnRef catalog_colref : catalog_const.getForeignkeycols()) {
// The name of the ColumnRef is the column in our base table
Column our_column = catalog_tbl.getColumns().getIgnoreCase(catalog_colref.getTypeName());
assert(our_column != null);
our_columns += col_add + our_column.getTypeName();
Column fkey_column = catalog_colref.getColumn();
assert(fkey_column != null);
fkey_columns += col_add + fkey_column.getTypeName();
col_add = ", ";
}
ret += add + spacer + "CONSTRAINT " + catalog_const.getTypeName() + " " +
"FOREIGN KEY (" + our_columns + ") " +
"REFERENCES " + catalog_fkey_tbl.getTypeName() + " (" + fkey_columns + ")";
}
skip_constraints.add(catalog_const);
}
ret += "\n);\n";
// All other Indexes
for (Index catalog_idx : catalog_tbl.getIndexes()) {
if (skip_indexes.contains(catalog_idx)) continue;
ret += "CREATE INDEX " + catalog_idx.getTypeName() +
" ON " + catalog_tbl.getTypeName() + " (";
add = "";
for (ColumnRef catalog_colref : CatalogUtil.getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
ret += add + catalog_colref.getColumn().getTypeName();
add = ", ";
}
ret += ");\n";
}
return ret;
}
/**
* Return true if a table is a streamed / export table
* This function is duplicated in CatalogUtil.h
* @param database
* @param table
* @return true if a table is export or false otherwise
*/
public static boolean isTableExportOnly(org.voltdb.catalog.Database database,
org.voltdb.catalog.Table table)
{
// no export, no export only tables
if (database.getConnectors().size() == 0) {
return false;
}
// there is one well-known-named connector
org.voltdb.catalog.Connector connector = database.getConnectors().get("0");
// iterate the connector tableinfo list looking for tableIndex
// tableInfo has a reference to a table - can compare the reference
// to the desired table by looking at the relative index. ick.
for (org.voltdb.catalog.ConnectorTableInfo tableInfo : connector.getTableinfo()) {
if (tableInfo.getTable().getRelativeIndex() == table.getRelativeIndex()) {
return tableInfo.getAppendonly();
}
}
return false;
}
/**
* Return true if a table is the source table for a materialized view.
*/
public static boolean isTableMaterializeViewSource(org.voltdb.catalog.Database database,
org.voltdb.catalog.Table table)
{
CatalogMap<Table> tables = database.getTables();
for (Table t : tables) {
Table matsrc = t.getMaterializer();
if ((matsrc != null) && (matsrc.getRelativeIndex() == table.getRelativeIndex())) {
return true;
}
}
return false;
}
/**
* Check if a catalog compiled with the given version of VoltDB is
* compatible with the current version of VoltDB.
*
* The rule is that the catalog must be compiled with a version of VoltDB
* that's within the range [minCompatibleVersion, currentVersion],
* inclusive.
*
* @param catalogVersionStr
* The version string of the VoltDB that compiled the catalog.
* @return true if it's compatible, false otherwise.
*/
public static boolean isCatalogCompatible(String catalogVersionStr)
{
if (catalogVersionStr == null || catalogVersionStr.isEmpty()) {
return false;
}
int[] catalogVersion = MiscUtils.parseVersionString(catalogVersionStr);
int[] currentVersion = MiscUtils.parseVersionString(VoltDB.instance().getVersionString());
if (catalogVersion == null) {
throw new IllegalArgumentException("Invalid version string " + catalogVersionStr);
}
int maxCmpResult = MiscUtils.compareVersions(catalogVersion, currentVersion);
int minCmpResult = MiscUtils.compareVersions(catalogVersion, minCompatibleVersion);
if (minCmpResult == -1 || maxCmpResult == 1) {
return false;
}
return true;
}
public static long compileDeploymentAndGetCRC(Catalog catalog, String deploymentURL, boolean crashOnFailedValidation) {
DeploymentType deployment = CatalogUtil.parseDeployment(deploymentURL);
if (deployment == null) {
return -1;
}
return compileDeploymentAndGetCRC(catalog, deployment, crashOnFailedValidation);
}
public static long compileDeploymentStringAndGetCRC(Catalog catalog, String deploymentString, boolean crashOnFailedValidation) {
DeploymentType deployment = CatalogUtil.parseDeploymentFromString(deploymentString);
if (deployment == null) {
return -1;
}
return compileDeploymentAndGetCRC(catalog, deployment, crashOnFailedValidation);
}
/**
* Parse the deployment.xml file and add its data into the catalog.
* @param catalog Catalog to be updated.
* @param deployment Parsed representation of the deployment.xml file.
* @param crashOnFailedValidation
* @param printLog Whether or not to print the cluster configuration.
* @return CRC of the deployment contents (>0) or -1 on failure.
*/
public static long compileDeploymentAndGetCRC(Catalog catalog,
DeploymentType deployment,
boolean crashOnFailedValidation)
{
if (!validateDeployment(catalog, deployment)) {
return -1;
}
// add our hacky Deployment to the catalog
catalog.getClusters().get("cluster").getDeployment().add("deployment");
// set the cluster info
setClusterInfo(catalog, deployment);
//Set the snapshot schedule
setSnapshotInfo( catalog, deployment.getSnapshot());
//Set enable security
setSecurityEnabled(catalog, deployment.getSecurity());
//set path and path overrides
// NOTE: this must be called *AFTER* setClusterInfo and setSnapshotInfo
// because path locations for snapshots and partition detection don't
// exist in the catalog until after those portions of the deployment
// file are handled.
setPathsInfo(catalog, deployment.getPaths(), crashOnFailedValidation);
// set the users info
setUsersInfo(catalog, deployment.getUsers());
// set the HTTPD info
setHTTPDInfo(catalog, deployment.getHttpd());
setExportInfo( catalog, deployment.getExport());
setCommandLogInfo( catalog, deployment.getCommandlog());
return getDeploymentCRC(deployment);
}
/*
* Command log element is created in setPathsInfo
*/
private static void setCommandLogInfo(Catalog catalog, CommandLogType commandlog) {
int fsyncInterval = 200;
int maxTxnsBeforeFsync = Integer.MAX_VALUE;
boolean enabled = false;
boolean sync = false;
int logSizeMb = 1024;
org.voltdb.catalog.CommandLog config = catalog.getClusters().get("cluster").getLogconfig().get("log");
if (commandlog != null) {
logSizeMb = commandlog.getLogsize();
sync = commandlog.isSynchronous();
enabled = commandlog.isEnabled();
Frequency freq = commandlog.getFrequency();
if (freq != null) {
long maxTxnsBeforeFsyncTemp = freq.getTransactions();
if (maxTxnsBeforeFsyncTemp < 1 || maxTxnsBeforeFsyncTemp > Integer.MAX_VALUE) {
throw new RuntimeException("Invalid command log max txns before fsync (" + maxTxnsBeforeFsync
+ ") specified. Supplied value must be between 1 and (2^31 - 1) txns");
}
maxTxnsBeforeFsync = (int)maxTxnsBeforeFsyncTemp;
fsyncInterval = freq.getTime();
if (fsyncInterval < 1 | fsyncInterval > 5000) {
throw new RuntimeException("Invalid command log fsync interval(" + fsyncInterval
+ ") specified. Supplied value must be between 1 and 5000 milliseconds");
}
}
}
config.setEnabled(enabled);
config.setSynchronous(sync);
config.setFsyncinterval(fsyncInterval);
config.setMaxtxns(maxTxnsBeforeFsync);
config.setLogsize(logSizeMb);
}
public static long getDeploymentCRC(String deploymentURL) {
DeploymentType deployment = parseDeployment(deploymentURL);
// wasn't a valid xml deployment file
if (deployment == null) {
hostLog.error("Not a valid XML deployment file at URL: " + deploymentURL);
return -1;
}
return getDeploymentCRC(deployment);
}
/**
* This code is not really tenable, and should be replaced with some
* XML normalization code, but for now it should work and be pretty
* tolerant of XML documents with different formatting for the same
* values.
* @return A positive CRC for the deployment contents
*/
static long getDeploymentCRC(DeploymentType deployment) {
StringBuilder sb = new StringBuilder(1024);
sb.append(" CLUSTER ");
ClusterType ct = deployment.getCluster();
sb.append(ct.getHostcount()).append(",");
sb.append(ct.getKfactor()).append(",");
sb.append(ct.getSitesperhost()).append(",");
sb.append(" PARTITIONDETECTION ");
PartitionDetectionType pdt = deployment.getPartitionDetection();
if (pdt != null) {
sb.append(pdt.isEnabled()).append(",");
PartitionDetectionType.Snapshot st = pdt.getSnapshot();
if (st != null) {
sb.append(st.getPrefix()).append(",");
}
}
sb.append(" SECURITY ");
SecurityType st = deployment.getSecurity();
if (st != null) {
sb.append(st.isEnabled());
}
sb.append(" ADMINMODE ");
AdminModeType amt = deployment.getAdminMode();
if (amt != null)
{
sb.append(amt.getPort()).append(",");
sb.append(amt.isAdminstartup()).append("\n");
}
sb.append(" HEARTBEATCONFIG ");
HeartbeatType hbt = deployment.getHeartbeat();
if (hbt != null)
{
sb.append(hbt.getTimeout()).append("\n");
}
sb.append(" USERS ");
UsersType ut = deployment.getUsers();
if (ut != null) {
List<User> users = ut.getUser();
for (User u : users) {
sb.append(" USER ");
sb.append(u.getName()).append(",");
sb.append(Arrays.toString(mergeUserRoles(u).toArray()));
sb.append(",").append(u.getPassword()).append(",");
sb.append(u.isPlaintext()).append(",");
}
}
sb.append("\n");
sb.append(" HTTPD ");
HttpdType ht = deployment.getHttpd();
if (ht != null) {
HttpdType.Jsonapi jt = ht.getJsonapi();
if (jt != null) {
sb.append(jt.isEnabled()).append(",");
}
sb.append(ht.isEnabled());
sb.append(ht.getPort());
}
sb.append(" SYSTEMSETTINGS ");
SystemSettingsType sst = deployment.getSystemsettings();
if (sst != null)
{
sb.append(" TEMPTABLES ");
Temptables ttt = sst.getTemptables();
if (ttt != null)
{
sb.append(ttt.getMaxsize()).append("\n");
}
}
sb.append(" EXPORT ");
ExportType export = deployment.getExport();
if( export != null) {
sb.append(" ENABLE ").append(export.isEnabled());
// mimic what is done when the catalog is built, which
// ignores anything else within the export XML stanza
// when enabled is false
ExportOnServerType onServer = export.getOnserver();
if (onServer != null && export.isEnabled()) {
sb.append(" ONSERVER ");
ServerExportEnum exportTo = onServer.getExportto();
if (exportTo != null) {
sb.append( "EXPORTTO ").append(exportTo.name());
}
if (exportTo.name().equalsIgnoreCase("CUSTOM")) {
sb.append(" EXPORTCONNECTORCLASS ").append(onServer.getExportconnectorclass());
}
ExportConfigurationType config = onServer.getConfiguration();
if (config != null) {
List<PropertyType> props = config.getProperty();
if( props != null && !props.isEmpty()) {
sb.append(" CONFIGURATION");
int propCnt = 0;
for( PropertyType prop: props) {
if( propCnt++ > 0) {
sb.append(",");
}
sb.append(" ").append(prop.getName());
sb.append(": ").append(prop.getValue());
}
}
}
}
sb.append("\n");
}
byte[] data = null;
try {
data = sb.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
hostLog.error("CRCing deployment file to determine" +
" compatibility and determined deployment file is"+
" not valid UTF-8. File must be UTF-8 encoded.");
data = new byte[]{0x0}; // should generate a CRC mismatch.
}
PureJavaCrc32 crc = new PureJavaCrc32();
crc.update(data);
long retval = crc.getValue();
return Math.abs(retval);
}
/**
* Parses the deployment XML file.
* @param deploymentURL Path to the deployment.xml file.
* @return a reference to the root <deployment> element.
*/
public static DeploymentType parseDeployment(String deploymentURL) {
// get the URL/path for the deployment and prep an InputStream
InputStream deployIS = null;
try {
URL deployURL = new URL(deploymentURL);
deployIS = deployURL.openStream();
} catch (MalformedURLException ex) {
// Invalid URL. Try as a file.
try {
deployIS = new FileInputStream(deploymentURL);
} catch (FileNotFoundException e) {
deployIS = null;
}
} catch (IOException ioex) {
deployIS = null;
}
// make sure the file exists
if (deployIS == null) {
hostLog.error("Could not locate deployment info at given URL: " + deploymentURL);
return null;
} else {
hostLog.info("URL of deployment info: " + deploymentURL);
}
return getDeployment(deployIS);
}
/**
* Parses the deployment XML string.
* @param deploymentString The deployment file content.
* @return a reference to the root <deployment> element.
*/
public static DeploymentType parseDeploymentFromString(String deploymentString) {
ByteArrayInputStream byteIS;
try {
byteIS = new ByteArrayInputStream(deploymentString.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
hostLog.warn("Unable to read deployment string: " + e.getMessage());
return null;
}
// get deployment info from xml file
return getDeployment(byteIS);
}
/**
* Get a reference to the root <deployment> element from the deployment.xml file.
* @param deployIS
* @return Returns a reference to the root <deployment> element.
*/
@SuppressWarnings("unchecked")
public static DeploymentType getDeployment(InputStream deployIS) {
try {
JAXBContext jc = JAXBContext.newInstance("org.voltdb.compiler.deploymentfile");
// This schema shot the sheriff.
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(VoltDB.class.getResource("compiler/DeploymentFileSchema.xsd"));
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema(schema);
JAXBElement<DeploymentType> result =
(JAXBElement<DeploymentType>) unmarshaller.unmarshal(deployIS);
DeploymentType deployment = result.getValue();
return deployment;
} catch (JAXBException e) {
// Convert some linked exceptions to more friendly errors.
if (e.getLinkedException() instanceof java.io.FileNotFoundException) {
hostLog.error(e.getLinkedException().getMessage());
return null;
} else if (e.getLinkedException() instanceof org.xml.sax.SAXParseException) {
hostLog.error("Error schema validating deployment.xml file. " + e.getLinkedException().getMessage());
return null;
} else {
throw new RuntimeException(e);
}
} catch (SAXException e) {
hostLog.error("Error schema validating deployment.xml file. " + e.getMessage());
return null;
}
}
/**
* Validate the contents of the deployment.xml file. This is for things like making sure users aren't being added to
* non-existent groups, not for validating XML syntax.
* @param catalog Catalog to be validated against.
* @param deployment Reference to root <deployment> element of deployment file to be validated.
* @return Returns true if the deployment file is valid.
*/
private static boolean validateDeployment(Catalog catalog, DeploymentType deployment) {
if (deployment.getUsers() == null) {
return true;
}
Cluster cluster = catalog.getClusters().get("cluster");
Database database = cluster.getDatabases().get("database");
Set<String> validGroups = new HashSet<String>();
for (Group group : database.getGroups()) {
validGroups.add(group.getTypeName());
}
for (UsersType.User user : deployment.getUsers().getUser()) {
if (user.getGroups() == null && user.getRoles() == null)
continue;
for (String group : mergeUserRoles(user)) {
if (!validGroups.contains(group)) {
hostLog.error("Cannot assign user \"" + user.getName() + "\" to non-existent group \"" + group +
"\"");
return false;
}
}
}
return true;
}
/**
* Set cluster info in the catalog.
* @param leader The leader hostname
* @param catalog The catalog to be updated.
* @param printLog Whether or not to print cluster configuration.
*/
private static void setClusterInfo(Catalog catalog, DeploymentType deployment) {
ClusterType cluster = deployment.getCluster();
int hostCount = cluster.getHostcount();
int sitesPerHost = cluster.getSitesperhost();
int kFactor = cluster.getKfactor();
ClusterConfig config = new ClusterConfig(hostCount, sitesPerHost, kFactor);
if (!config.validate()) {
hostLog.error(config.getErrorMsg());
} else {
Cluster catCluster = catalog.getClusters().get("cluster");
// copy the deployment info that is currently not recorded anywhere else
Deployment catDeploy = catCluster.getDeployment().get("deployment");
catDeploy.setHostcount(hostCount);
catDeploy.setSitesperhost(sitesPerHost);
catDeploy.setKfactor(kFactor);
// copy partition detection configuration from xml to catalog
String defaultPPDPrefix = "partition_detection";
if (deployment.getPartitionDetection() != null) {
if (deployment.getPartitionDetection().isEnabled()) {
catCluster.setNetworkpartition(true);
CatalogMap<SnapshotSchedule> faultsnapshots = catCluster.getFaultsnapshots();
SnapshotSchedule sched = faultsnapshots.add("CLUSTER_PARTITION");
if (deployment.getPartitionDetection().getSnapshot() != null) {
sched.setPrefix(deployment.getPartitionDetection().getSnapshot().getPrefix());
}
else {
sched.setPrefix(defaultPPDPrefix);
}
}
else {
catCluster.setNetworkpartition(false);
}
}
else {
// Default partition detection on for IV2
if (VoltDB.instance().isIV2Enabled()) {
catCluster.setNetworkpartition(true);
CatalogMap<SnapshotSchedule> faultsnapshots = catCluster.getFaultsnapshots();
SnapshotSchedule sched = faultsnapshots.add("CLUSTER_PARTITION");
sched.setPrefix(defaultPPDPrefix);
}
else {
catCluster.setNetworkpartition(false);
}
}
// copy admin mode configuration from xml to catalog
if (deployment.getAdminMode() != null)
{
catCluster.setAdminport(deployment.getAdminMode().getPort());
catCluster.setAdminstartup(deployment.getAdminMode().isAdminstartup());
}
else
{
// encode the default values
catCluster.setAdminport(VoltDB.DEFAULT_ADMIN_PORT);
catCluster.setAdminstartup(false);
}
setSystemSettings(deployment, catDeploy);
if (deployment.getHeartbeat() != null)
{
catCluster.setHeartbeattimeout(deployment.getHeartbeat().getTimeout());
}
else
{
// default to 10 seconds
catCluster.setHeartbeattimeout(10);
}
}
}
private static void setSystemSettings(DeploymentType deployment,
Deployment catDeployment)
{
// Create catalog Systemsettings
Systemsettings syssettings =
catDeployment.getSystemsettings().add("systemsettings");
int maxtemptablesize = 100;
int snapshotpriority = 6;
if (deployment.getSystemsettings() != null)
{
Temptables temptables = deployment.getSystemsettings().getTemptables();
if (temptables != null)
{
maxtemptablesize = temptables.getMaxsize();
}
SystemSettingsType.Snapshot snapshot = deployment.getSystemsettings().getSnapshot();
if (snapshot != null) {
snapshotpriority = snapshot.getPriority();
}
}
syssettings.setMaxtemptablesize(maxtemptablesize);
syssettings.setSnapshotpriority(snapshotpriority);
}
private static void validateDirectory(String type, File path, boolean crashOnFailedValidation) {
String error = null;
do {
if (!path.exists()) {
error = "Specified " + type + " \"" + path + "\" does not exist"; break;
}
if (!path.isDirectory()) {
error = "Specified " + type + " \"" + path + "\" is not a directory"; break;
}
if (!path.canRead()) {
error = "Specified " + type + " \"" + path + "\" is not readable"; break;
}
if (!path.canWrite()) {
error = "Specified " + type + " \"" + path + "\" is not writable"; break;
}
if (!path.canExecute()) {
error = "Specified " + type + " \"" + path + "\" is not executable"; break;
}
} while(false);
if (error != null) {
if (crashOnFailedValidation) {
VoltDB.crashLocalVoltDB(error, false, null);
} else {
hostLog.warn(error);
}
}
}
/**
* Set deployment time settings for export
* @param catalog The catalog to be updated.
* @param exportsType A reference to the <exports> element of the deployment.xml file.
*/
private static void setExportInfo(Catalog catalog, ExportType exportType) {
if (exportType == null) {
return;
}
boolean adminstate = exportType.isEnabled();
String connector = RawProcessor.class.getName();
if (exportType.getOnserver() != null) {
connector = GuestProcessor.class.getName();
}
Database db = catalog.getClusters().get("cluster").getDatabases().get("database");
org.voltdb.catalog.Connector catconn = db.getConnectors().get("0");
if (catconn == null) {
if (adminstate) {
hostLog.info("Export configuration enabled in deployment file however no export " +
"tables are present in the project file. Export disabled.");
}
return;
}
catconn.setLoaderclass(connector);
catconn.setEnabled(adminstate);
ExportOnServerType exportOnServer = exportType.getOnserver();
if (exportOnServer != null) {
String exportClientClassName = null;
switch( exportOnServer.getExportto()) {
case FILE: exportClientClassName = ExportToFileClient.class.getName(); break;
case JDBC: exportClientClassName = "org.voltdb.exportclient.JDBCExportClient"; break;
//Validate that we can load the class.
case CUSTOM:
try {
CatalogUtil.class.getClassLoader().loadClass(exportOnServer.getExportconnectorclass());
exportClientClassName = exportOnServer.getExportconnectorclass();
} catch (ClassNotFoundException ex) {
hostLog.error(
"Custom Export failed to configure, failed to load " +
" export plugin class: " + exportOnServer.getExportconnectorclass() +
" Disabling export.");
exportType.setEnabled(false);
return;
}
break;
}
// this is OK as the deployment file XML schema does not allow for
// export configuration property names that begin with underscores
if (exportClientClassName != null && exportClientClassName.length() > 0) {
ConnectorProperty prop = catconn.getConfig().add(GuestProcessor.EXPORT_TO_TYPE);
prop.setName(GuestProcessor.EXPORT_TO_TYPE);
prop.setValue(exportClientClassName);
}
ExportConfigurationType exportConfiguration = exportOnServer.getConfiguration();
if (exportConfiguration != null) {
List<PropertyType> configProperties = exportConfiguration.getProperty();
if (configProperties != null && ! configProperties.isEmpty()) {
for( PropertyType configProp: configProperties) {
ConnectorProperty prop = catconn.getConfig().add(configProp.getName());
prop.setName(configProp.getName());
prop.setValue(configProp.getValue());
}
}
}
}
if (!adminstate) {
hostLog.info("Export configuration is present and is " +
"configured to be disabled. Export will be disabled.");
}
}
/**
* Set the security setting in the catalog from the deployment file
* @param catalog the catalog to be updated
* @param securityEnabled security element of the deployment xml
*/
private static void setSecurityEnabled( Catalog catalog, SecurityType securityEnabled) {
Cluster cluster = catalog.getClusters().get("cluster");
boolean enabled = false;
if (securityEnabled != null) {
enabled = securityEnabled.isEnabled();
}
cluster.setSecurityenabled(enabled);
}
/**
* Set the auto-snapshot settings in the catalog from the deployment file
* @param catalog The catalog to be updated.
* @param snapshot A reference to the <snapshot> element of the deployment.xml file.
*/
private static void setSnapshotInfo(Catalog catalog, SnapshotType snapshotSettings) {
Database db = catalog.getClusters().get("cluster").getDatabases().get("database");
SnapshotSchedule schedule = db.getSnapshotschedule().add("default");
if (snapshotSettings != null)
{
schedule.setEnabled(snapshotSettings.isEnabled());
String frequency = snapshotSettings.getFrequency();
if (!frequency.endsWith("s") &&
!frequency.endsWith("m") &&
!frequency.endsWith("h")) {
hostLog.error(
"Snapshot frequency " + frequency +
" needs to end with time unit specified" +
" that is one of [s, m, h] (seconds, minutes, hours)" +
" Defaulting snapshot frequency to 10m.");
frequency = "10m";
}
int frequencyInt = 0;
String frequencySubstring = frequency.substring(0, frequency.length() - 1);
try {
frequencyInt = Integer.parseInt(frequencySubstring);
} catch (Exception e) {
hostLog.error("Frequency " + frequencySubstring +
" is not an integer. Defaulting frequency to 10m.");
frequency = "10m";
frequencyInt = 10;
}
String prefix = snapshotSettings.getPrefix();
if (prefix == null || prefix.isEmpty()) {
hostLog.error("Snapshot prefix " + prefix +
" is not a valid prefix. Using prefix of 'SNAPSHOTNONCE' ");
prefix = "SNAPSHOTNONCE";
}
if (prefix.contains("-") || prefix.contains(",")) {
String oldprefix = prefix;
prefix = prefix.replaceAll("-", "_");
prefix = prefix.replaceAll(",", "_");
hostLog.error("Snapshot prefix " + oldprefix + " cannot include , or -." +
" Using the prefix: " + prefix + " instead.");
}
int retain = snapshotSettings.getRetain();
if (retain < 1) {
hostLog.error("Snapshot retain value " + retain +
" is not a valid value. Must be 1 or greater." +
" Defaulting snapshot retain to 1.");
retain = 1;
}
schedule.setFrequencyunit(
frequency.substring(frequency.length() - 1, frequency.length()));
schedule.setFrequencyvalue(frequencyInt);
schedule.setPrefix(prefix);
schedule.setRetain(retain);
}
else
{
schedule.setEnabled(false);
}
}
private static File getFeaturePath(PathsType paths, PathEntry pathEntry,
File voltDbRoot,
String pathDescription, String defaultPath)
{
File featurePath;
if (paths == null || pathEntry == null) {
featurePath = new VoltFile(voltDbRoot, defaultPath);
} else {
featurePath = new VoltFile(pathEntry.getPath());
if (!featurePath.isAbsolute())
{
featurePath = new VoltFile(voltDbRoot, pathEntry.getPath());
}
}
if (!featurePath.exists()) {
hostLog.info("Creating " + pathDescription + " directory: " +
featurePath.getAbsolutePath());
if (!featurePath.mkdirs()) {
hostLog.fatal("Failed to create " + pathDescription + " directory \"" +
featurePath + "\"");
}
}
return featurePath;
}
/**
* Set voltroot path, and set the path overrides for export overflow, partition, etc.
* @param catalog The catalog to be updated.
* @param paths A reference to the <paths> element of the deployment.xml file.
* @param printLog Whether or not to print paths info.
*/
private static void setPathsInfo(Catalog catalog, PathsType paths, boolean crashOnFailedValidation) {
File voltDbRoot;
final Cluster cluster = catalog.getClusters().get("cluster");
// Handles default voltdbroot (and completely missing "paths" element).
voltDbRoot = getVoltDbRoot(paths);
validateDirectory("volt root", voltDbRoot, crashOnFailedValidation);
PathEntry path_entry = null;
if (paths != null)
{
path_entry = paths.getSnapshots();
}
File snapshotPath =
getFeaturePath(paths, path_entry, voltDbRoot,
"snapshot", "snapshots");
validateDirectory("snapshot path", snapshotPath, crashOnFailedValidation);
path_entry = null;
if (paths != null)
{
path_entry = paths.getExportoverflow();
}
File exportOverflowPath =
getFeaturePath(paths, path_entry, voltDbRoot, "export overflow",
"export_overflow");
validateDirectory("export overflow", exportOverflowPath, crashOnFailedValidation);
// only use these directories in the enterprise version
File commandLogPath = null;
File commandLogSnapshotPath = null;
path_entry = null;
if (paths != null)
{
path_entry = paths.getCommandlog();
}
if (VoltDB.instance().getConfig().m_isEnterprise) {
commandLogPath =
getFeaturePath(paths, path_entry, voltDbRoot, "command log", "command_log");
validateDirectory("command log", commandLogPath, crashOnFailedValidation);
}
else {
// dumb defaults if you ask for logging in community version
commandLogPath = new VoltFile(voltDbRoot, "command_log");
}
path_entry = null;
if (paths != null)
{
path_entry = paths.getCommandlogsnapshot();
}
if (VoltDB.instance().getConfig().m_isEnterprise) {
commandLogSnapshotPath =
getFeaturePath(paths, path_entry, voltDbRoot, "command log snapshot", "command_log_snapshot");
validateDirectory("command log snapshot", commandLogSnapshotPath, crashOnFailedValidation);
}
else {
// dumb defaults if you ask for logging in community version
commandLogSnapshotPath = new VoltFile(voltDbRoot, "command_log_snapshot");;
}
//Set the volt root in the catalog
catalog.getClusters().get("cluster").setVoltroot(voltDbRoot.getPath());
//Set the auto-snapshot schedule path if there are auto-snapshots
SnapshotSchedule schedule = cluster.getDatabases().
get("database").getSnapshotschedule().get("default");
if (schedule != null) {
schedule.setPath(snapshotPath.getPath());
}
//Update the path in the schedule for ppd
schedule = cluster.getFaultsnapshots().get("CLUSTER_PARTITION");
if (schedule != null) {
schedule.setPath(snapshotPath.getPath());
}
//Also set the export overflow directory
cluster.setExportoverflow(exportOverflowPath.getPath());
//Set the command log paths, also creates the command log entry in the catalog
final org.voltdb.catalog.CommandLog commandLogConfig = cluster.getLogconfig().add("log");
commandLogConfig.setInternalsnapshotpath(commandLogSnapshotPath.getPath());
commandLogConfig.setLogpath(commandLogPath.getPath());
}
/**
* Get a File object representing voltdbroot. Create directory if missing.
* Use paths if non-null to get override default location.
*
* @param paths override paths or null
* @return File object for voltdbroot
*/
public static File getVoltDbRoot(PathsType paths) {
File voltDbRoot;
if (paths == null || paths.getVoltdbroot() == null || paths.getVoltdbroot().getPath() == null) {
voltDbRoot = new VoltFile("voltdbroot");
if (!voltDbRoot.exists()) {
hostLog.info("Creating voltdbroot directory: " + voltDbRoot.getAbsolutePath());
if (!voltDbRoot.mkdir()) {
hostLog.fatal("Failed to create voltdbroot directory \"" + voltDbRoot.getAbsolutePath() + "\"");
}
}
} else {
voltDbRoot = new VoltFile(paths.getVoltdbroot().getPath());
}
return voltDbRoot;
}
/**
* Set user info in the catalog.
* @param catalog The catalog to be updated.
* @param users A reference to the <users> element of the deployment.xml file.
*/
private static void setUsersInfo(Catalog catalog, UsersType users) {
if (users == null) {
return;
}
// TODO: The database name is not available in deployment.xml (it is defined in project.xml). However, it must
// always be named "database", so I've temporarily hardcoded it here until a more robust solution is available.
Database db = catalog.getClusters().get("cluster").getDatabases().get("database");
SecureRandom sr = new SecureRandom();
for (UsersType.User user : users.getUser()) {
String sha1hex = user.getPassword();
if (user.isPlaintext()) {
sha1hex = extractPassword(user.getPassword());
}
org.voltdb.catalog.User catUser = db.getUsers().add(user.getName());
String hashedPW =
BCrypt.hashpw(
sha1hex,
BCrypt.gensalt(BCrypt.GENSALT_DEFAULT_LOG2_ROUNDS,sr));
catUser.setShadowpassword(hashedPW);
// process the @groups and @roles comma separated list
for (final String role : mergeUserRoles(user)) {
final GroupRef groupRef = catUser.getGroups().add(role);
final Group catalogGroup = db.getGroups().get(role);
if (catalogGroup != null) {
groupRef.setGroup(catalogGroup);
}
}
}
}
/**
* Takes the list of roles specified in the groups, and roles user
* attributes and merges the into one set that contains no duplicates
* @param user an instance of {@link UsersType.User}
* @return a {@link Set} of role name
*/
public static Set<String> mergeUserRoles(final UsersType.User user) {
Set<String> roles = new TreeSet<String>();
if (user == null) return roles;
if (user.getGroups() != null && !user.getGroups().trim().isEmpty()) {
String [] grouplist = user.getGroups().trim().split(",");
for (String group: grouplist) {
if( group == null || group.trim().isEmpty()) continue;
roles.add(group.trim());
}
}
if (user.getRoles() != null && !user.getRoles().trim().isEmpty()) {
String [] rolelist = user.getRoles().trim().split(",");
for (String role: rolelist) {
if( role == null || role.trim().isEmpty()) continue;
roles.add(role.trim());
}
}
return roles;
}
private static void setHTTPDInfo(Catalog catalog, HttpdType httpd) {
// defaults
int httpdPort = -1;
boolean jsonEnabled = false;
Cluster cluster = catalog.getClusters().get("cluster");
// if the httpd info is available, use it
if (httpd != null && httpd.isEnabled()) {
httpdPort = httpd.getPort();
HttpdType.Jsonapi jsonapi = httpd.getJsonapi();
if (jsonapi != null)
jsonEnabled = jsonapi.isEnabled();
}
// set the catalog info
cluster.setHttpdportno(httpdPort);
cluster.setJsonapi(jsonEnabled);
}
/** Read a hashed password from password.
* SHA-1 hash it once to match what we will get from the wire protocol
* and then hex encode it
* */
private static String extractPassword(String password) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (final NoSuchAlgorithmException e) {
hostLog.l7dlog(Level.FATAL, LogKeys.compiler_VoltCompiler_NoSuchAlgorithm.name(), e);
System.exit(-1);
}
final byte passwordHash[] = md.digest(password.getBytes(Charsets.UTF_8));
return Encoder.hexEncode(passwordHash);
}
public static void
uploadCatalogToZK(ZooKeeper zk, int catalogVersion, long txnId, long uniqueId, byte[] catalogHash, byte catalogBytes[])
throws KeeperException, InterruptedException {
ByteBuffer versionAndBytes = ByteBuffer.allocate(catalogBytes.length + 20 + 20);
versionAndBytes.putInt(catalogVersion);
versionAndBytes.putLong(txnId);
versionAndBytes.putLong(uniqueId);
versionAndBytes.put(catalogHash);
versionAndBytes.put(catalogBytes);
zk.create(VoltZK.catalogbytes,
versionAndBytes.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
public static void
setCatalogToZK(ZooKeeper zk, int catalogVersion, long txnId, long uniqueId, byte[] catalogHash, byte catalogBytes[])
throws KeeperException, InterruptedException {
ByteBuffer versionAndBytes = ByteBuffer.allocate(catalogBytes.length + 20 + 20);
versionAndBytes.putInt(catalogVersion);
versionAndBytes.putLong(txnId);
versionAndBytes.putLong(uniqueId);
versionAndBytes.put(catalogHash);
versionAndBytes.put(catalogBytes);
zk.setData(VoltZK.catalogbytes,
versionAndBytes.array(), -1);
}
public static class CatalogAndIds {
public final long txnId;
public final long uniqueId;
public final int version;
public final byte hash[];
public final byte bytes[];
public CatalogAndIds(long txnId, long uniqueId, int catalogVersion, byte[] catalogHash, byte[] catalogBytes) {
this.txnId = txnId;
this.uniqueId = uniqueId;
this.version = catalogVersion;
this.hash = catalogHash;
this.bytes = catalogBytes;
}
}
public static CatalogAndIds getCatalogFromZK(ZooKeeper zk) throws KeeperException, InterruptedException {
ByteBuffer versionAndBytes =
ByteBuffer.wrap(zk.getData(VoltZK.catalogbytes, false, null));
int version = versionAndBytes.getInt();
long catalogTxnId = versionAndBytes.getLong();
long catalogUniqueId = versionAndBytes.getLong();
byte[] catalogHash = new byte[20]; // sha-1 hash size
versionAndBytes.get(catalogHash);
byte[] catalogBytes = new byte[versionAndBytes.remaining()];
versionAndBytes.get(catalogBytes);
versionAndBytes = null;
return new CatalogAndIds(catalogTxnId, catalogUniqueId, version, catalogHash, catalogBytes);
}
/**
* Given plan graphs and a SQL stmt, compute a bi-directonal usage map between
* schema (indexes, table & views) and SQL/Procedures.
* Use "annotation" objects to store this extra information in the catalog
* during compilation and catalog report generation.
*/
public static void updateUsageAnnotations(Database db,
Statement stmt,
AbstractPlanNode topPlan,
AbstractPlanNode bottomPlan)
{
SortedSet<String> tablesRead = new TreeSet<String>();
SortedSet<String> tablesUpdated = new TreeSet<String>();
SortedSet<String> indexes = new TreeSet<String>();
if (topPlan != null) {
topPlan.getTablesAndIndexes(tablesRead, tablesUpdated, indexes);
}
if (bottomPlan != null) {
bottomPlan.getTablesAndIndexes(tablesRead, tablesUpdated, indexes);
}
// make useage only in either read or updated, not both
tablesRead.removeAll(tablesUpdated);
for (Table table : db.getTables()) {
for (String indexName : indexes) {
Index index = table.getIndexes().get(indexName);
if (index != null) {
updateIndexUsageAnnotation(index, stmt);
}
}
if (tablesRead.contains(table.getTypeName())) {
updateTableUsageAnnotation(table, stmt, true);
tablesRead.remove(table.getTypeName());
}
if (tablesUpdated.contains(table.getTypeName())) {
updateTableUsageAnnotation(table, stmt, false);
tablesUpdated.remove(table.getTypeName());
}
}
assert(tablesRead.size() == 0);
assert(tablesUpdated.size() == 0);
}
private static void updateIndexUsageAnnotation(Index index, Statement stmt) {
Procedure proc = (Procedure) stmt.getParent();
// skip CRUD generated procs
if (proc.getDefaultproc()) {
return;
}
IndexAnnotation ia = (IndexAnnotation) index.getAnnotation();
if (ia == null) {
ia = new IndexAnnotation();
index.setAnnotation(ia);
}
ia.statementsThatUseThis.add(stmt);
ia.proceduresThatUseThis.add(proc);
ProcedureAnnotation pa = (ProcedureAnnotation) proc.getAnnotation();
if (pa == null) {
pa = new ProcedureAnnotation();
proc.setAnnotation(pa);
}
pa.indexesUsed.add(index);
StatementAnnotation sa = (StatementAnnotation) stmt.getAnnotation();
if (sa == null) {
sa = new StatementAnnotation();
stmt.setAnnotation(sa);
}
sa.indexesUsed.add(index);
}
private static void updateTableUsageAnnotation(Table table, Statement stmt, boolean read) {
Procedure proc = (Procedure) stmt.getParent();
// skip CRUD generated procs
if (proc.getDefaultproc()) {
return;
}
TableAnnotation ta = (TableAnnotation) table.getAnnotation();
if (ta == null) {
ta = new TableAnnotation();
table.setAnnotation(ta);
}
if (read) {
ta.statementsThatReadThis.add(stmt);
ta.proceduresThatReadThis.add(proc);
}
else {
ta.statementsThatUpdateThis.add(stmt);
ta.proceduresThatUpdateThis.add(proc);
}
ProcedureAnnotation pa = (ProcedureAnnotation) proc.getAnnotation();
if (pa == null) {
pa = new ProcedureAnnotation();
proc.setAnnotation(pa);
}
if (read) {
pa.tablesRead.add(table);
}
else {
pa.tablesUpdated.add(table);
}
StatementAnnotation sa = (StatementAnnotation) stmt.getAnnotation();
if (sa == null) {
sa = new StatementAnnotation();
stmt.setAnnotation(sa);
}
if (read) {
sa.tablesRead.add(table);
}
else {
sa.tablesUpdated.add(table);
}
}
}
|
package eg.ui;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
//--Eadgyth--/
import eg.Constants;
/**
* The window that shows info about Eadgyth
*/
public class InfoWin {
private final static String INFO
= "<html>"
+ "Version since 1.0.6 for testing<br>"
+ "Malte Bussiek<br>"
+ "https://eadgyth.github.io/Programming-Editor"
+ "</html>";
private final JFrame frame = new JFrame();
private final JPanel okButton = new JPanel(new FlowLayout());
private final JPanel text = new JPanel(new GridLayout(2, 1));
private final JPanel combine = new JPanel(new BorderLayout());
private final JButton okBt = new JButton("OK");
private final JLabel titleLb = new JLabel("Eadgyth Programming-Editor");
private final JLabel infoLb = new JLabel(INFO);
public InfoWin() {
titleLb.setFont(Constants.SANSSERIF_BOLD_11);
infoLb.setFont(Constants.SANSSERIF_PLAIN_9);
okBt.setFocusPainted(false);
okBt.addActionListener(e -> frame.setVisible(false));
okButton.add(okBt);
text.setBackground(Color.white);
text.setBorder(eg.Constants.EMPTY_BORDER_5);
text.add(titleLb);
text.add(infoLb);
combine.setBorder(Constants.EMPTY_BORDER_5);
combine.add(text, BorderLayout.CENTER);
combine.add(okButton, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setIconImage(IconFiles.EADGYTH_ICON_16.getImage());
frame.setLocation(650, 100);
frame.setTitle("About");
frame.setContentPane(combine);
frame.setResizable(false);
frame.setSize(eg.utils.ScreenParams.scaledDimension(300, 150));
frame.setVisible(true);
}
}
|
package il.org.hasadna.opentrain;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.StrictMode;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public final class MainActivity extends Activity {
private static final String LOGTAG = MainActivity.class.getName();
private static final String LEADERBOARD_URL = "https://location.services.mozilla.com/leaders";
private ScannerServiceInterface mConnectionRemote;
private ServiceConnection mConnection;
private ServiceBroadcastReceiver mReceiver;
private int mGpsFixes;
private class ServiceBroadcastReceiver extends BroadcastReceiver {
private boolean mReceiverIsRegistered;
public void register() {
if (!mReceiverIsRegistered) {
registerReceiver(this, new IntentFilter(ScannerService.MESSAGE_TOPIC));
mReceiverIsRegistered = true;
}
}
public void unregister() {
if (mReceiverIsRegistered) {
unregisterReceiver(this);
mReceiverIsRegistered = false;
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ScannerService.MESSAGE_TOPIC)) {
Log.e(LOGTAG, "Received an unknown intent");
return;
}
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
if (subject.equals("Notification")) {
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
Log.d(LOGTAG, "Received a notification intent and showing: " + text);
return;
} else if (subject.equals("Reporter")) {
updateUI();
Log.d(LOGTAG, "Received a reporter intent...");
return;
} else if (subject.equals("Scanner")) {
mGpsFixes = intent.getIntExtra("fixes", 0);
updateUI();
Log.d(LOGTAG, "Received a scanner intent...");
return;
} else if (intent.getBooleanExtra("TrainIndication", false)) {
updateUI();
Log.d(LOGTAG, "Received train indication...");
return;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
enableStrictMode();
setContentView(R.layout.activity_main);
//Updater.checkForUpdates(this);
Log.d(LOGTAG, "onCreate");
}
private void checkGps() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(R.string.app_name)
.setMessage(R.string.gps_alert_msg)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
}
private boolean isGoogleApiKeyValid() {
String apiKey = PackageUtils.getMetaDataString(this, "com.google.android.maps.v2.API_KEY");
if ("FAKE_GOOGLE_API_KEY".equals(apiKey)) {
Log.w(LOGTAG, "Fake Google API Key found.");
return false;
}
return true;
}
@Override
protected void onStart() {
super.onStart();
// Reason for commenting out checkGps() :
// We are currently working under the assumption that we don't need GPS accuracy
// and it's better to use Location API and save battery
//checkGps();
mReceiver = new ServiceBroadcastReceiver();
mReceiver.register();
mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder binder) {
mConnectionRemote = ScannerServiceInterface.Stub.asInterface(binder);
Log.d(LOGTAG, "Service connected");
updateUI();
}
@Override
public void onServiceDisconnected(ComponentName className) {
mConnectionRemote = null;
Log.d(LOGTAG, "Service disconnected", new Exception());
}
};
Intent intent = new Intent(this, ScannerService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
Log.d(LOGTAG, "onStart");
}
@Override
protected void onStop() {
super.onStop();
try {
unbindService(mConnection);
mConnection = null;
mConnectionRemote = null;
} catch (Exception ex) {
//Service was already unbound.
}
mReceiver.unregister();
mReceiver = null;
Log.d(LOGTAG, "onStop");
}
protected void updateUI() {
// TODO time this to make sure we're not blocking too long on mConnectionRemote
// if we care, we can bundle this into one call -- or use android to remember
// the state before the rotation.
if (mConnectionRemote == null) {
return;
}
Log.d(LOGTAG, "Updating UI");
boolean scanning = false;
try {
scanning = mConnectionRemote.isScanning();
} catch (RemoteException e) {
Log.e(LOGTAG, "", e);
}
Button scanningBtn = (Button) findViewById(R.id.toggle_scanning);
TextView status = (TextView) findViewById(R.id.status_text);
if (scanning) {
status.setText(R.string.status_on);
scanningBtn.setBackgroundResource(R.drawable.red_button);
} else {
status.setText(R.string.status_off);
scanningBtn.setBackgroundResource(R.drawable.green_button);
}
int locationsScanned = 0;
int APs = 0;
long lastUploadTime = 0;
long reportsSent = 0;
long lastTrainIndicationTime = 0; // TODO: should have time when we were last on train
try {
locationsScanned = mConnectionRemote.getLocationCount();
APs = mConnectionRemote.getAPCount();
lastUploadTime = mConnectionRemote.getLastUploadTime();
reportsSent = mConnectionRemote.getReportsSent();
lastTrainIndicationTime = mConnectionRemote.getLastTrainIndicationTime();
} catch (RemoteException e) {
Log.e(LOGTAG, "", e);
}
String lastUploadTimeString = (lastUploadTime > 0) ? DateTimeUtils
.formatTimeForLocale(lastUploadTime) : "-";
String lastTrainIndicationTimeString = (lastTrainIndicationTime > 0) ? DateTimeUtils
.formatTimeForLocale(lastTrainIndicationTime) : "-";
formatTextView(R.id.gps_satellites, R.string.gps_satellites, mGpsFixes);
formatTextView(R.id.wifi_access_points, R.string.wifi_access_points, APs);
formatTextView(R.id.locations_scanned, R.string.locations_scanned, locationsScanned);
formatTextView(R.id.last_upload_time, R.string.last_upload_time, lastUploadTimeString);
formatTextView(R.id.reports_sent, R.string.reports_sent, reportsSent);
formatTextView(R.id.last_train, R.string.last_train, lastTrainIndicationTimeString);
}
public void onClick_ToggleScanning(View v) throws RemoteException {
if (mConnectionRemote == null) {
return;
}
boolean scanning = mConnectionRemote.isScanning();
Log.d(LOGTAG, "Connection remote return: isScanning() = " + scanning);
Button scanningBtn = (Button) v;
TextView status = (TextView) findViewById(R.id.status_text);
if (scanning) {
unbindService(mConnection);
mConnectionRemote.stopScanning();
status.setText(R.string.status_on);
scanningBtn.setBackgroundResource(R.drawable.red_button);
} else {
Intent intent = new Intent(this, ScannerService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
mConnectionRemote.startScanning();
status.setText(R.string.status_off);
scanningBtn.setBackgroundResource(R.drawable.green_button);
}
}
public void onClick_ViewLeaderboard(View v) {
Intent openLeaderboard = new Intent(Intent.ACTION_VIEW, Uri.parse(LEADERBOARD_URL));
startActivity(openLeaderboard);
}
/*public void onClick_ViewMap(View v) throws RemoteException {
// We are starting Wi-Fi scanning because we want the the APs for our
// geolocation request whose results we want to display on the map.
if (mConnectionRemote != null) {
mConnectionRemote.startScanning();
}
Log.d(LOGTAG, "onClick_ViewMap");
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
}*/
@TargetApi(9)
private void enableStrictMode() {
if (VERSION.SDK_INT < 9) {
return;
}
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.permitDiskReads()
.permitDiskWrites()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog().build());
}
private void formatTextView(int textViewId, int stringId, Object... args) {
TextView textView = (TextView) findViewById(textViewId);
String str = getResources().getString(stringId);
Log.d("hebrew","str = " + str + " args = " + args);
str = String.format(str, args);
textView.setText(str);
}
}
|
package inpro.apps.util;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class RecoCommandLineParser extends CommonCommandLineParser {
public static final int REGULAR_RECO = 0;
public static final int FORCED_ALIGNER_RECO = 1;
public static final int FAKE_RECO = 2;
public static final int GRAMMAR_RECO = 3;
public static final int SLM_RECO = 4;
public static final int DEFAULT_DELTIFIER = -1;
public static final int INCREMENTAL = 0;
public static final int NON_INCREMENTAL = 1;
public static final int SMOOTHED_INCREMENTAL = 2;
public static final int FIXEDLAG_INCREMENTAL = 3;
public RecoCommandLineParser(String... args) {
super(args);
}
public RecoCommandLineParser() {
super(new String[0]);
}
int recoMode;
public int rtpPort;
int incrementalMode;
int incrementalModifier;
String referenceText;
/* stores location of a grammar or SLM */
URL languageModelURL;
/**
* @return the languageModelURL
*/
public URL getLanguageModelURL() {
return languageModelURL;
}
boolean dataThrottle;
protected boolean ignoreErrors;
@Override
void printUsage() {
System.err.println("simple sphinx recognizer for the inpro project");
System.err.println("usage: java inpro.apps.SimpleReco");
System.err.println("general options:");
System.err.println(" -h this screen");
System.err.println(" -c <URL> sphinx configuration file to use (reasonable default)");
System.err.println(" -v more verbose output (speed and memory tracker)");
System.err.println(" -f force operation, i.e. try to ignore all errors");
System.err.println("input selection:");
System.err.println(" -M read data from microphone");
System.err.println(" -R <port> read data from RTP");
System.err.println(" -F <fileURL> read data from sound file with given URL");
// System.err.println("dialogue system options:");
// System.err.println(" -D configname use the named dialogue manager (see documentation)");
System.err.println("output selection:");
System.err.println(" -O output dialogue system responses");
System.err.println(" -T send incremental hypotheses to TEDview");
System.err.println(" -L incremental output using LabelWriter");
System.err.println("incrementality options:");
System.err.println(" by default, incremental results are generated at every frame");
System.err.println(" -N no incremental output");
System.err.println(" -Is <n> apply smoothing factor");
System.err.println(" -If <n> apply fixed lag");
System.err.println(" -In no result smoothing/lagging, DEFAULT");
System.err.println(" -C show current incremental ASR hypothesis");
System.err.println("special recognition modes:");
System.err.println(" -fa <text> do forced alignment with the given reference text");
System.err.println(" -tg <file> do fake recognition from the given reference textgrid");
System.err.println(" -gr <URL> recognize using the given JSGF grammar");
System.err.println(" -lm <URL> recognize using the given language model");
System.err.println(" (-fa, -tg, -gr, and -lm are exclusive)");
System.err.println(" -rt when reading from file, run no faster than real-time (includes VAD)");
}
/**
* check validity of the configuration
* additionally warns if configuration makes no sense
* @return true for valid combinations of configuration options
*/
@Override
boolean checkConfiguration() {
boolean success = false;
// check for necessary requirements
if (inputMode == UNSPECIFIED_INPUT) {
printUsage();
System.err.println("Must specify one of -M, -R, or -F");
} else if ((recoMode == FAKE_RECO) && (inputMode != FILE_INPUT)) {
printUsage();
System.err.println("You can only combine faked recognition with file input. Sorry.");
} else {
success = true;
}
// test for nonsense option combinations
if (dataThrottle && (inputMode != FILE_INPUT))
System.err.println("Warning: only throttling speed for file input; your microphone's not faster anyway.");
return success;
}
@Override
void parse(String[] args) throws IllegalArgumentException {
recoMode = REGULAR_RECO;
incrementalMode = DEFAULT_DELTIFIER;
for (int i = 0; i < args.length; i++) {
try {
if (args[i].equals("-h")) {
printUsage();
System.exit(0);
return;
}
else if (args[i].equals("-c")) {
i++;
configURL = getURLForPath(args[i]);
}
else if (args[i].equals("-v")) {
verbose = true;
}
else if (args[i].equals("-f")) {
ignoreErrors = true;
}
else if (args[i].equals("-fa")) {
i++;
recoMode = FORCED_ALIGNER_RECO;
referenceText = args[i];
}
else if (args[i].equals("-tg")) {
i++;
recoMode = FAKE_RECO;
referenceText = args[i];
}
else if (args[i].equals("-M")) {
inputMode = MICROPHONE_INPUT;
}
else if (args[i].equals("-R")) {
inputMode = RTP_INPUT;
i++;
rtpPort = Integer.parseInt(args[i]);
}
else if (args[i].equals("-F")) {
inputMode = FILE_INPUT;
i++;
audioURL = getURLForPath(args[i]);
}
else if (args[i].equals("-T")) {
outputMode |= TED_OUTPUT;
}
else if (args[i].equals("-L")) {
outputMode |= LABEL_OUTPUT;
}
else if (args[i].equals("-C")) {
outputMode |= CURRHYP_OUTPUT;
}
else if (args[i].equals("-O")) {
outputMode |= DISPATCHER_OBJECT_OUTPUT;
}
else if (args[i].equals("-N")) {
incrementalMode = NON_INCREMENTAL;
}
else if (args[i].equals("-In")) {
incrementalMode = INCREMENTAL;
}
else if (args[i].equals("-Is")) {
incrementalMode = SMOOTHED_INCREMENTAL;
i++;
incrementalModifier = Integer.parseInt(args[i]);
}
else if (args[i].equals("-If")) {
incrementalMode = FIXEDLAG_INCREMENTAL;
i++;
incrementalModifier = Integer.parseInt(args[i]);
}
else if (args[i].equals("-lm")) {
recoMode = SLM_RECO;
i++;
languageModelURL = getURLForPath(args[i]);
}
else if (args[i].equals("-gr")) {
recoMode = GRAMMAR_RECO;
i++;
languageModelURL = getURLForPath(args[i]);
}
else if (args[i].equals("-rt")) {
dataThrottle = true;
}
else {
throw new IllegalArgumentException(args[i]);
}
} catch (Exception e) {
printUsage();
if (i < args.length) {
System.err.println("Illegal argument: " + args[i]);
} else {
System.err.println("Something was wrong with the program arguments.");
}
System.exit(1);
}
}
}
public String getReference() {
return referenceText;
}
public boolean isRecoMode(int mode) {
return recoMode == mode;
}
public boolean isIncremental() {
return !(incrementalMode == NON_INCREMENTAL);
}
public boolean ignoreErrors() {
return ignoreErrors;
}
public int getIncrementalMode() {
return incrementalMode;
}
public int getIncrementalModifier() {
return incrementalModifier;
}
public boolean playAtRealtime() {
return dataThrottle;
}
private URL getURLForPath(String path)
{
URL result;
//first try to read the given string as an URL
try
{
result = new URL(path);
return result;
}
catch(MalformedURLException e)
{
System.err.println(path + " is no URL - I'll try to use it as path.");
}
/*if it wasn't a string try to read it as file path
*the catching part should be useless since there will be a file not found exception
*/
try {
result = new File(path).toURI().toURL();
return result;
} catch (MalformedURLException e) {
System.err.println("The Argument " + path + " was also no path.");
}
System.exit(1);
return null;
}
}
|
package net.sf.picard.sam;
import net.sf.picard.cmdline.Option;
import net.sf.picard.cmdline.StandardOptionDefinitions;
import net.sf.picard.cmdline.Usage;
import net.sf.picard.metrics.MetricsFile;
import net.sf.picard.util.Histogram;
import net.sf.picard.util.Log;
import net.sf.picard.PicardException;
import net.sf.picard.io.IoUtil;
import net.sf.samtools.*;
import net.sf.samtools.util.SortingCollection;
import net.sf.samtools.util.SortingLongCollection;
import java.io.*;
import java.util.*;
/**
* A better duplication marking algorithm that handles all cases including clipped
* and gapped alignments.
*
* @author Tim Fennell
*/
public class MarkDuplicates extends AbstractDuplicateFindingAlgorithm {
private final Log log = Log.getInstance(MarkDuplicates.class);
/**
* If more than this many sequences in SAM file, don't spill to disk because there will not
* be enough file handles.
*/
@Usage public final String USAGE =
"Examines aligned records in the supplied SAM or BAM file to locate duplicate molecules. " +
"All records are then written to the output file with the duplicate records flagged.";
@Option(shortName= StandardOptionDefinitions.INPUT_SHORT_NAME, doc="The input SAM or BAM file to analyze. Must be coordinate sorted.")
public File INPUT;
@Option(shortName=StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc="The output file to right marked records to")
public File OUTPUT;
@Option(shortName="M", doc="File to write duplication metrics to")
public File METRICS_FILE;
@Option(doc="If true do not write duplicates to the output file instead of writing them with appropriate flags set.")
public boolean REMOVE_DUPLICATES = false;
@Option(doc="If true, assume that the input file is coordinate sorted, even if the header says otherwise.",
shortName=StandardOptionDefinitions.ASSUME_SORTED_SHORT_NAME)
public boolean ASSUME_SORTED = false;
@Option(doc="This option is obsolete. ReadEnds will always be spilled to disk.", shortName="MAX_SEQS")
public int MAX_SEQUENCES_FOR_DISK_READ_ENDS_MAP = 50000;
@Option(doc="Maximum number of file handles to keep open when spilling read ends to disk. " + "" +
"Set this number a little lower than the per-process maximum number of file that may be open. " +
"This number can be found by executing the 'ulimit -n' command on a Unix system.", shortName = "MAX_FILE_HANDLES")
public int MAX_FILE_HANDLES_FOR_READ_ENDS_MAP = 8000;
private SortingCollection<ReadEnds> pairSort;
private SortingCollection<ReadEnds> fragSort;
private SortingLongCollection duplicateIndexes;
private int numDuplicateIndices = 0;
final private Map<String,Short> libraryIds = new HashMap<String,Short>();
private short nextLibraryId = 1;
// Variables used for optical duplicate detection and tracking
private final Histogram<Short> opticalDupesByLibraryId = new Histogram<Short>();
/** Stock main method. */
public static void main(final String[] args) {
System.exit(new MarkDuplicates().instanceMain(args));
}
/**
* Main work method. Reads the BAM file once and collects sorted information about
* the 5' ends of both ends of each read (or just one end in the case of pairs).
* Then makes a pass through those determining duplicates before re-reading the
* input file and writing it out with duplication flags set correctly.
*/
protected int doWork() {
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsWritable(OUTPUT);
IoUtil.assertFileIsWritable(METRICS_FILE);
reportMemoryStats("Start of doWork");
log.info("Reading input file and constructing read end information.");
buildSortedReadEndLists();
reportMemoryStats("After buildSortedReadEndLists");
generateDuplicateIndexes();
reportMemoryStats("After generateDuplicateIndexes");
log.info("Marking " + this.numDuplicateIndices + " records as duplicates.");
log.info("Found " + ((long) this.opticalDupesByLibraryId.getSumOfValues()) + " optical duplicate clusters.");
final Map<String,DuplicationMetrics> metricsByLibrary = new HashMap<String,DuplicationMetrics>();
final SAMFileReader in = new SAMFileReader(INPUT);
final SAMFileHeader header = in.getFileHeader();
final SAMFileHeader outputHeader = header.clone();
outputHeader.setSortOrder(SAMFileHeader.SortOrder.coordinate);
final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(outputHeader,
true,
OUTPUT);
// Now copy over the file while marking all the necessary indexes as duplicates
long recordInFileIndex = 0;
long nextDuplicateIndex = (this.duplicateIndexes.hasNext() ? this.duplicateIndexes.next(): -1);
if(header != null) {
for(final SAMReadGroupRecord readGroup : header.getReadGroups()) {
final String library = readGroup.getLibrary();
DuplicationMetrics metrics = metricsByLibrary.get(library);
if (metrics == null) {
metrics = new DuplicationMetrics();
metrics.LIBRARY = library;
metricsByLibrary.put(library, metrics);
}
}
}
for (final SAMRecord rec : in) {
final String library = getLibraryName(header, rec);
DuplicationMetrics metrics = metricsByLibrary.get(library);
if (metrics == null) {
metrics = new DuplicationMetrics();
metrics.LIBRARY = library;
metricsByLibrary.put(library, metrics);
}
// First bring the simple metrics up to date
if (rec.getReadUnmappedFlag()) {
++metrics.UNMAPPED_READS;
}
else if (!rec.getReadPairedFlag() || rec.getMateUnmappedFlag()) {
++metrics.UNPAIRED_READS_EXAMINED;
}
else {
++metrics.READ_PAIRS_EXAMINED; // will need to be divided by 2 at the end
}
if (recordInFileIndex++ == nextDuplicateIndex) {
rec.setDuplicateReadFlag(true);
// Update the duplication metrics
if (!rec.getReadPairedFlag() || rec.getMateUnmappedFlag()) {
++metrics.UNPAIRED_READ_DUPLICATES;
}
else {
++metrics.READ_PAIR_DUPLICATES;// will need to be divided by 2 at the end
}
// Now try and figure out the next duplicate index
if (this.duplicateIndexes.hasNext()) {
nextDuplicateIndex = this.duplicateIndexes.next();
} else {
// Only happens once we've marked all the duplicates
nextDuplicateIndex = -1;
}
}
else {
rec.setDuplicateReadFlag(false);
}
if (this.REMOVE_DUPLICATES && rec.getDuplicateReadFlag()) {
// do nothing
}
else {
out.addAlignment(rec);
}
}
reportMemoryStats("Before output close");
out.close();
reportMemoryStats("After output close");
// Write out the metrics
final MetricsFile<DuplicationMetrics,Double> file = getMetricsFile();
for (final Map.Entry<String,DuplicationMetrics> entry : metricsByLibrary.entrySet()) {
final String libraryName = entry.getKey();
final DuplicationMetrics metrics = entry.getValue();
metrics.READ_PAIRS_EXAMINED = metrics.READ_PAIRS_EXAMINED / 2;
metrics.READ_PAIR_DUPLICATES = metrics.READ_PAIR_DUPLICATES / 2;
// Add the optical dupes to the metrics
Short libraryId = this.libraryIds.get(libraryName);
if (libraryId != null) {
Histogram<Short>.Bin bin = this.opticalDupesByLibraryId.get(libraryId);
if (bin != null) {
metrics.READ_PAIR_OPTICAL_DUPLICATES = (long) bin.getValue();
}
}
metrics.calculateDerivedMetrics();
file.addMetric(metrics);
}
if (metricsByLibrary.size() == 1) {
file.setHistogram(metricsByLibrary.values().iterator().next().calculateRoiHistogram());
}
file.write(METRICS_FILE);
return 0;
}
private void reportMemoryStats(final String stage) {
System.gc();
final Runtime runtime = Runtime.getRuntime();
log.info(stage + " freeMemory: " + runtime.freeMemory() + "; totalMemory: " + runtime.totalMemory() +
"; maxMemory: " + runtime.maxMemory());
}
/**
* Goes through all the records in a file and generates a set of ReadEnds objects that
* hold the necessary information (reference sequence, 5' read coordinate) to do
* duplication, caching to disk as necssary to sort them.
*/
private void buildSortedReadEndLists() {
final int maxInMemory = (int) ((Runtime.getRuntime().maxMemory() * 0.25) / ReadEnds.SIZE_OF);
log.info("Will retain up to " + maxInMemory + " data points before spilling to disk.");
this.pairSort = SortingCollection.newInstance(ReadEnds.class,
new ReadEndsCodec(),
new ReadEndsComparator(),
maxInMemory);
this.fragSort = SortingCollection.newInstance(ReadEnds.class,
new ReadEndsCodec(),
new ReadEndsComparator(),
maxInMemory);
final SAMFileReader sam = new SAMFileReader(INPUT);
final SAMFileHeader header = sam.getFileHeader();
if (header.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
if (ASSUME_SORTED) {
log.info("Assuming input is coordinate sorted.");
} else {
throw new PicardException(INPUT + " is not coordinate sorted.");
}
}
final ReadEndsMap tmp = new DiskReadEndsMap(MAX_FILE_HANDLES_FOR_READ_ENDS_MAP);
long index = 0;
for (final SAMRecord rec : sam) {
if (rec.getReadUnmappedFlag()) {
if (rec.getReferenceIndex() == -1) {
// When we hit the unmapped reads with no coordinate, no reason to continue.
break;
}
// If this read is unmapped but sorted with the mapped reads, just skip it.
}
else {
final ReadEnds fragmentEnd = buildReadEnds(header, index, rec);
this.fragSort.add(fragmentEnd);
if (rec.getReadPairedFlag() && !rec.getMateUnmappedFlag()) {
final String key = rec.getAttribute(ReservedTagConstants.READ_GROUP_ID) + ":" + rec.getReadName();
ReadEnds pairedEnds = tmp.remove(rec.getReferenceIndex(), key);
// See if we've already seen the first end or not
if (pairedEnds == null) {
pairedEnds = buildReadEnds(header, index, rec);
tmp.put(pairedEnds.read2Sequence, key, pairedEnds);
}
else {
final int sequence = fragmentEnd.read1Sequence;
final int coordinate = fragmentEnd.read1Coordinate;
// If the second read is actually later, just add the second read data, else flip the reads
if (sequence > pairedEnds.read1Sequence ||
(sequence == pairedEnds.read1Sequence && coordinate >= pairedEnds.read1Coordinate)) {
pairedEnds.read2Sequence = sequence;
pairedEnds.read2Coordinate = coordinate;
pairedEnds.read2IndexInFile = index;
pairedEnds.orientation = getOrientationByte(pairedEnds.orientation == ReadEnds.R,
rec.getReadNegativeStrandFlag());
}
else {
pairedEnds.read2Sequence = pairedEnds.read1Sequence;
pairedEnds.read2Coordinate = pairedEnds.read1Coordinate;
pairedEnds.read2IndexInFile = pairedEnds.read1IndexInFile;
pairedEnds.read1Sequence = sequence;
pairedEnds.read1Coordinate = coordinate;
pairedEnds.read1IndexInFile = index;
pairedEnds.orientation = getOrientationByte(rec.getReadNegativeStrandFlag(),
pairedEnds.orientation == ReadEnds.R);
}
pairedEnds.score += getScore(rec);
this.pairSort.add(pairedEnds);
}
}
}
// Print out some stats every 1m reads
if (++index % 1000000 == 0) {
log.info("Read " + index + " records. Tracking " + tmp.size() + " as yet unmatched pairs. " +
tmp.sizeInRam() + " records in RAM. Last sequence index: " + rec.getReferenceIndex());
}
}
log.info("Read " + index + " records. " + tmp.size() + " pairs never matched.");
sam.close();
// Tell these collections to free up memory if possible.
this.pairSort.doneAdding();
this.fragSort.doneAdding();
}
/** Builds a read ends object that represents a single read. */
private ReadEnds buildReadEnds(final SAMFileHeader header, final long index, final SAMRecord rec) {
final ReadEnds ends = new ReadEnds();
ends.read1Sequence = rec.getReferenceIndex();
ends.read1Coordinate = rec.getReadNegativeStrandFlag() ? rec.getUnclippedEnd() : rec.getUnclippedStart();
ends.orientation = rec.getReadNegativeStrandFlag() ? ReadEnds.R : ReadEnds.F;
ends.read1IndexInFile = index;
ends.score = getScore(rec);
// Doing this lets the ends object know that it's part of a pair
if (rec.getReadPairedFlag() && !rec.getMateUnmappedFlag()) {
ends.read2Sequence = rec.getMateReferenceIndex();
}
// Fill in the library ID
ends.libraryId = getLibraryId(header, rec);
// Fill in the location information for optical duplicates
if (addLocationInformation(rec.getReadName(), ends)) {
// calculate the RG number (nth in list)
ends.readGroup = 0;
final String rg = (String) rec.getAttribute("RG");
final List<SAMReadGroupRecord> readGroups = header.getReadGroups();
if (rg != null && readGroups != null) {
for (SAMReadGroupRecord readGroup : readGroups) {
if (readGroup.getReadGroupId().equals(rg)) break;
else ends.readGroup++;
}
}
}
return ends;
}
/** Get the library ID for the given SAM record. */
private short getLibraryId(final SAMFileHeader header, final SAMRecord rec) {
final String library = getLibraryName(header, rec);
Short libraryId = this.libraryIds.get(library);
if (libraryId == null) {
libraryId = this.nextLibraryId++;
this.libraryIds.put(library, libraryId);
}
return libraryId;
}
/**
* Gets the library name from the header for the record. If the RG tag is not present on
* the record, or the library isn't denoted on the read group, a constant string is
* returned.
*/
private String getLibraryName(final SAMFileHeader header, final SAMRecord rec) {
final String readGroupId = (String) rec.getAttribute("RG");
if (readGroupId != null) {
final SAMReadGroupRecord rg = header.getReadGroup(readGroupId);
if (rg != null) {
return rg.getLibrary();
}
}
return "Unknown Library";
}
/**
* Returns a single byte that encodes the orientation of the two reads in a pair.
*/
private byte getOrientationByte(final boolean read1NegativeStrand, final boolean read2NegativeStrand) {
if (read1NegativeStrand) {
if (read2NegativeStrand) return ReadEnds.RR;
else return ReadEnds.RF;
}
else {
if (read2NegativeStrand) return ReadEnds.FR;
else return ReadEnds.FF;
}
}
/** Calculates a score for the read which is the sum of scores over Q20. */
private short getScore(final SAMRecord rec) {
short score = 0;
for (final byte b : rec.getBaseQualities()) {
if (b >= 15) score += b;
}
return score;
}
/**
* Goes through the accumulated ReadEnds objects and determines which of them are
* to be marked as duplicates.
*
* @return an array with an ordered list of indexes into the source file
*/
private void generateDuplicateIndexes() {
final int maxInMemory = (int) ((Runtime.getRuntime().maxMemory() * 0.25) / SortingLongCollection.SIZEOF);
log.info("Will retain up to " + maxInMemory + " duplicate indices before spilling to disk.");
this.duplicateIndexes = new SortingLongCollection(maxInMemory, TMP_DIR);
ReadEnds firstOfNextChunk = null;
final List<ReadEnds> nextChunk = new ArrayList<ReadEnds>(200);
// First just do the pairs
log.info("Traversing read pair information and detecting duplicates.");
for (final ReadEnds next : this.pairSort) {
if (firstOfNextChunk == null) {
firstOfNextChunk = next;
nextChunk.add(firstOfNextChunk);
}
else if (areComparableForDuplicates(firstOfNextChunk, next, true)) {
nextChunk.add(next);
}
else {
if (nextChunk.size() > 1) {
markDuplicatePairs(nextChunk);
}
nextChunk.clear();
nextChunk.add(next);
firstOfNextChunk = next;
}
}
markDuplicatePairs(nextChunk);
this.pairSort = null;
// Now deal with the fragments
log.info("Traversing fragment information and detecting duplicates.");
boolean containsPairs = false;
boolean containsFrags = false;
for (final ReadEnds next : this.fragSort) {
if (firstOfNextChunk != null && areComparableForDuplicates(firstOfNextChunk, next, false)) {
nextChunk.add(next);
containsPairs = containsPairs || next.isPaired();
containsFrags = containsFrags || !next.isPaired();
}
else {
if (nextChunk.size() > 1 && containsFrags) {
markDuplicateFragments(nextChunk, containsPairs);
}
nextChunk.clear();
nextChunk.add(next);
firstOfNextChunk = next;
containsPairs = next.isPaired();
containsFrags = !next.isPaired();
}
}
markDuplicateFragments(nextChunk, containsPairs);
this.fragSort = null;
log.info("Sorting list of duplicate records.");
this.duplicateIndexes.doneAddingStartIteration();
}
private boolean areComparableForDuplicates(final ReadEnds lhs, final ReadEnds rhs, final boolean compareRead2) {
boolean retval = lhs.libraryId == rhs.libraryId &&
lhs.read1Sequence == rhs.read1Sequence &&
lhs.read1Coordinate == rhs.read1Coordinate &&
lhs.orientation == rhs.orientation;
if (retval && compareRead2) {
retval = lhs.read2Sequence == rhs.read2Sequence &&
lhs.read2Coordinate == rhs.read2Coordinate;
}
return retval;
}
private void addIndexAsDuplicate(final long bamIndex) {
this.duplicateIndexes.add(bamIndex);
++this.numDuplicateIndices;
}
/**
* Takes a list of ReadEnds objects and removes from it all objects that should
* not be marked as duplicates.
*
* @param list
*/
private void markDuplicatePairs(final List<ReadEnds> list) {
short maxScore = 0;
ReadEnds best = null;
for (final ReadEnds end : list) {
if (end.score > maxScore || best == null) {
maxScore = end.score;
best = end;
}
}
for (final ReadEnds end : list) {
if (end != best) {
addIndexAsDuplicate(end.read1IndexInFile);
addIndexAsDuplicate(end.read2IndexInFile);
}
}
trackOpticalDuplicates(list);
}
/**
* Looks through the set of reads and identifies how many of the duplicates are
* in fact optical duplicates, and stores the data in the instance level histogram.
*/
private void trackOpticalDuplicates(final List<ReadEnds> list) {
final boolean[] opticalDuplicateFlags = findOpticalDuplicates(list, OPTICAL_DUPLICATE_PIXEL_DISTANCE);
int opticalDuplicates = 0;
for (boolean b: opticalDuplicateFlags) if (b) ++opticalDuplicates;
if (opticalDuplicates > 0) {
this.opticalDupesByLibraryId.increment(list.get(0).libraryId, opticalDuplicates);
}
}
/**
* Takes a list of ReadEnds objects and removes from it all objects that should
* not be marked as duplicates.
*
* @param list
*/
private void markDuplicateFragments(final List<ReadEnds> list, final boolean containsPairs) {
if (containsPairs) {
for (final ReadEnds end : list) {
if (!end.isPaired()) addIndexAsDuplicate(end.read1IndexInFile);
}
}
else {
short maxScore = 0;
ReadEnds best = null;
for (final ReadEnds end : list) {
if (end.score > maxScore || best == null) {
maxScore = end.score;
best = end;
}
}
for (final ReadEnds end : list) {
if (end != best) {
addIndexAsDuplicate(end.read1IndexInFile);
}
}
}
}
/** Comparator for ReadEnds that orders by read1 position then pair orientation then read2 position. */
static class ReadEndsComparator implements Comparator<ReadEnds> {
public int compare(final ReadEnds lhs, final ReadEnds rhs) {
int retval = lhs.libraryId - rhs.libraryId;
if (retval == 0) retval = lhs.read1Sequence - rhs.read1Sequence;
if (retval == 0) retval = lhs.read1Coordinate - rhs.read1Coordinate;
if (retval == 0) retval = lhs.orientation - rhs.orientation;
if (retval == 0) retval = lhs.read2Sequence - rhs.read2Sequence;
if (retval == 0) retval = lhs.read2Coordinate - rhs.read2Coordinate;
if (retval == 0) retval = (int) (lhs.read1IndexInFile - rhs.read1IndexInFile);
if (retval == 0) retval = (int) (lhs.read2IndexInFile - rhs.read2IndexInFile);
return retval;
}
}
}
|
package org.concord.otrunk.view;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import org.concord.applesupport.AppleApplicationAdapter;
import org.concord.applesupport.AppleApplicationUtil;
import org.concord.framework.otrunk.OTChangeEvent;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTID;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.framework.otrunk.OTrunk;
import org.concord.framework.otrunk.view.OTExternalAppService;
import org.concord.framework.otrunk.view.OTFrameManager;
import org.concord.framework.otrunk.view.OTJComponentServiceFactory;
import org.concord.framework.otrunk.view.OTUserListService;
import org.concord.framework.otrunk.view.OTViewContainer;
import org.concord.framework.otrunk.view.OTViewContainerChangeEvent;
import org.concord.framework.otrunk.view.OTViewContainerListener;
import org.concord.framework.otrunk.view.OTViewContext;
import org.concord.framework.otrunk.view.OTViewFactory;
import org.concord.framework.text.UserMessageHandler;
import org.concord.framework.util.SimpleTreeNode;
import org.concord.otrunk.OTMLToXHTMLConverter;
import org.concord.otrunk.OTSystem;
import org.concord.otrunk.OTrunkImpl;
import org.concord.otrunk.OTrunkServiceEntry;
import org.concord.otrunk.datamodel.OTDataObject;
import org.concord.otrunk.overlay.OTOverlayGroup;
import org.concord.otrunk.user.OTUserObject;
import org.concord.otrunk.xml.ExporterJDOM;
import org.concord.otrunk.xml.XMLDatabase;
import org.concord.otrunk.xml.XMLDatabaseChangeEvent;
import org.concord.otrunk.xml.XMLDatabaseChangeListener;
import org.concord.swing.CustomDialog;
import org.concord.swing.MemoryMonitorPanel;
import org.concord.swing.MostRecentFileDialog;
import org.concord.swing.StreamRecord;
import org.concord.swing.StreamRecordView;
import org.concord.swing.util.Util;
import org.concord.view.SimpleTreeModel;
import org.concord.view.SwingUserMessageHandler;
/**
* OTViewer Class name and description
*
* Date created: Dec 14, 2004
*
* @author scott
* <p>
*
*/
public class OTViewer extends JFrame
implements TreeSelectionListener, OTViewContainerListener, AppleApplicationAdapter
{
/**
* first version of this class
*/
private static final long serialVersionUID = 1L;
public final static String TITLE_PROP = "otrunk.view.frame_title";
public final static String HIDE_TREE_PROP = "otrunk.view.hide_tree";
public final static String SHOW_CONSOLE_PROP = "otrunk.view.show_console";
public final static String DEMO_ONLY_PROP = "otrunk.view.demo";
public final static String HTTP_PUT = "PUT";
public final static String HTTP_POST = "POST";
private static OTrunkImpl otrunk;
private static OTViewFactory otViewFactory;
protected int userMode = OTConfig.NO_USER_MODE;
URL currentURL = null;
String baseFrameTitle;
final static String DEFAULT_BASE_FRAME_TITLE = "OTrunk Viewer";
OTViewContainerPanel bodyPanel;
OTFrameManagerImpl frameManager;
JTree folderTreeArea;
SimpleTreeModel folderTreeModel;
JTree dataTreeArea;
SimpleTreeModel dataTreeModel;
JSplitPane splitPane;
JFrame consoleFrame;
// Temp, to close the window
AbstractAction exitAction;
AbstractAction saveAsAction;
JMenuBar menuBar;
XMLDatabase xmlDB;
OTUserSession userSession;
File currentAuthoredFile = null;
Hashtable otContainers = new Hashtable();
String startupMessage = "";
boolean justStarted = false;
boolean showTree = false;
URL remoteURL;
private AbstractAction saveUserDataAsAction;
private AbstractAction saveUserDataAction;
private AbstractAction debugAction;
private AbstractAction showConsoleAction;
private AbstractAction newUserDataAction;
private AbstractAction loadUserDataAction;
private AbstractAction loadAction;
private AbstractAction reloadWindowAction;
private AbstractAction saveAction;
private AbstractAction saveRemoteAsAction;
private AbstractAction exportImageAction;
private AbstractAction exportHiResImageAction;
private AbstractAction exportToHtmlAction;
private JDialog commDialog;
/**
* This is true if the user was asked about saving user data after they
* initiated a close of the current view.
*/
private boolean askedAboutSavingUserData = false;
/**
* This is true if the user was asked about saving the user data, and said
* yes
*/
private boolean needToSaveUserData = false;
private boolean useScrollPane;
private OTChangeListener systemChangeListener;
private OTSystem userSystem;
private ArrayList services = new ArrayList();
private JPanel statusPanel;
/**
* This is true if the SailOTViewer created this OTViewer
*/
private boolean launchedBySailOTViewer = false;
public static void setOTViewFactory(OTViewFactory factory)
{
otViewFactory = factory;
}
public OTViewer()
{
super();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println("Error setting native LAF: " + e);
}
this.showTree = true;
AppleApplicationUtil.registerWithMacOSX(this);
baseFrameTitle = DEFAULT_BASE_FRAME_TITLE;
try {
// this overrides the default base frame title
String title = System.getProperty(TITLE_PROP, null);
if (title != null) {
baseFrameTitle = title;
}
} catch (Throwable t) {
// do nothing, just use the default title
}
setTitle(baseFrameTitle);
// If "otrunk.view.demo" is true, closing frame will just dispose
// the frame, not exit.
if (!Boolean.getBoolean(DEMO_ONLY_PROP)){
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
exitAction.actionPerformed(null);
}
});
}
consoleFrame = new JFrame("Console");
StreamRecord record = new StreamRecord(50000);
StreamRecordView view = new StreamRecordView(record);
consoleFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
System.setOut((PrintStream) view.addOutputStream(System.out, "Console"));
System.setErr((PrintStream) view.addOutputStream(System.err, System.out));
consoleFrame.getContentPane().add(view);
consoleFrame.setSize(800, 600);
if (OTConfig.getBooleanProp(SHOW_CONSOLE_PROP, false)) {
consoleFrame.setVisible(true);
}
commDialog = new JDialog(this, true);
// for debugging
// add a breakpoint below, run in debugging mode, and then hit Meta-B
// the object you're currently focused on will be passed in here and you
// can
// start exploring the data structures, etc.
KeyboardFocusManager focusManager =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
KeyEventDispatcher deleteDispatcher = new KeyEventDispatcher(){
public boolean dispatchKeyEvent(KeyEvent e)
{
if ((e.getID() == java.awt.event.KeyEvent.KEY_RELEASED)
&& ((e.getModifiersEx() & java.awt.event.InputEvent.META_DOWN_MASK) != 0)
&& (e.getKeyCode() == java.awt.event.KeyEvent.VK_B)) {
Object o = e.getSource();
System.out.println(o.toString());
return true;
}
return false;
}
};
focusManager.addKeyEventDispatcher(deleteDispatcher);
// If the mouse click is a right click event and alt is pressed
// or on a Mac the ctrl and option keys are down
// then this code will print out the toString method of the
// object which the mouse is over to the console.
AWTEventListener awtEventListener = new AWTEventListener(){
public void eventDispatched(AWTEvent event)
{
if(!(event instanceof MouseEvent)){
return;
}
MouseEvent mEvent = (MouseEvent) event;
if (mEvent.getID() == MouseEvent.MOUSE_CLICKED
&& (mEvent.getModifiersEx() & MouseEvent.ALT_DOWN_MASK) != 0) {
System.out.println(event.getSource().toString());
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener,
AWTEvent.MOUSE_EVENT_MASK);
}
/**
* this needs to be called before initialized.
*
* @param serviceInterface
* @param service
*/
public void addService(Class serviceInterface, Object service)
{
OTrunkServiceEntry entry = new OTrunkServiceEntry(service, serviceInterface);
services.add(entry);
}
public void setUserMode(int mode)
{
userMode = mode;
}
public int getUserMode()
{
return userMode;
}
public void updateTreePane()
{
Dimension minimumSize = new Dimension(100, 50);
folderTreeArea = new JTree(folderTreeModel);
// we are just disabling this however if we want to
// use this tree for authoring, or for managing student
// created objects this will need to be some form of option
folderTreeArea.setEditable(false);
folderTreeArea.addTreeSelectionListener(this);
JComponent leftComponent = null;
JScrollPane folderTreeScrollPane = new JScrollPane(folderTreeArea);
if (System.getProperty(OTConfig.DEBUG_PROP, "").equals("true")) {
// ViewFactory.getComponent(root);
dataTreeArea = new JTree(dataTreeModel);
dataTreeArea.setEditable(false);
dataTreeArea.addTreeSelectionListener(this);
JScrollPane dataTreeScrollPane = new JScrollPane(dataTreeArea);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Folders", folderTreeScrollPane);
tabbedPane.add("Resources", dataTreeScrollPane);
// Provide minimum sizes for the two components in the split pane
folderTreeScrollPane.setMinimumSize(minimumSize);
dataTreeScrollPane.setMinimumSize(minimumSize);
tabbedPane.setMinimumSize(minimumSize);
leftComponent = tabbedPane;
} else {
leftComponent = folderTreeScrollPane;
}
if (splitPane == null) {
splitPane =
new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftComponent, bodyPanel);
} else {
splitPane.setLeftComponent(leftComponent);
}
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
}
public void initArgs(String[] args)
{
URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args);
if (authorOTMLURL == null) {
authorOTMLURL = OTViewer.class.getResource("no-arguments-page.otml");
}
if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) {
currentAuthoredFile = new File(authorOTMLURL.getPath());
}
String urlStr = authorOTMLURL.toString();
initWithWizard(urlStr);
}
/**
* @param args
* @return
*/
public String getURL(String[] args)
{
URL authorOTMLURL = OTViewerHelper.getURLFromArgs(args);
if ("file".equalsIgnoreCase(authorOTMLURL.getProtocol())) {
try {
URI authorOTMLURI = new URI(authorOTMLURL.toString());
currentAuthoredFile = new File(authorOTMLURI);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return authorOTMLURL.toString();
}
public void init(String url)
{
updateRemoteURL(url);
createActions();
updateMenuBar();
setJMenuBar(menuBar);
frameManager = new OTFrameManagerImpl();
bodyPanel = new OTViewContainerPanel(frameManager);
bodyPanel.addViewContainerListener(this);
if (showTree) {
dataTreeModel = new SimpleTreeModel();
folderTreeModel = new SimpleTreeModel();
updateTreePane();
getContentPane().add(splitPane);
} else {
getContentPane().add(bodyPanel);
}
if (OTConfig.isShowStatus()) {
statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 3, 1));
final JLabel saveStateLabel = new JLabel("File saved");
statusPanel.add(saveStateLabel);
statusPanel.add(Box.createHorizontalStrut(20));
statusPanel.add(new MemoryMonitorPanel());
statusPanel.add(Box.createHorizontalStrut(5));
getContentPane().add(statusPanel, BorderLayout.SOUTH);
// It takes a while for xmlDM to be initialized...
Thread waitForDB = new Thread() {
public void run()
{
while (xmlDB == null) {
try {
sleep(1000);
} catch (Exception e) {
}
}
xmlDB.addXMLDatabaseChangeListener(new XMLDatabaseChangeListener() {
public void stateChanged(XMLDatabaseChangeEvent e)
{
if (xmlDB.isDirty()) {
saveStateLabel.setText("Unsaved changes");
} else {
saveStateLabel.setText("File saved");
}
statusPanel.repaint();
}
});
}
};
waitForDB.start();
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if (screenSize.width < 1000 || screenSize.height < 700) {
setVisible(true);
int state = getExtendedState();
// Set the maximized bits
state |= Frame.MAXIMIZED_BOTH;
// Maximize the frame
setExtendedState(state);
} else {
int cornerX = 50;
int cornerY = 50;
int sizeX = 800;
int sizeY = 500;
// OTViewService viewService = otViewFactory.
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY);
setVisible(true);
}
}
});
if (url == null) {
return;
}
try {
initializeURL(new URL(url));
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e) {
// FIXME: this should popup a dialog
System.err.println("Can't load url");
e.printStackTrace();
return;
}
}
public void initializeURL(URL url)
throws Exception
{
loadURL(url);
OTMainFrame mainFrame = (OTMainFrame) otrunk.getService(OTMainFrame.class);
if (OTConfig.getBooleanProp(HIDE_TREE_PROP, false)
|| !mainFrame.getShowLeftPanel()) {
splitPane.getLeftComponent().setVisible(false);
}
useScrollPane = true;
if (mainFrame.getFrame() != null) {
if (mainFrame.getFrame().isResourceSet("width")
&& mainFrame.getFrame().isResourceSet("height")) {
int cornerX = mainFrame.getFrame().getPositionX();
int cornerY = mainFrame.getFrame().getPositionY();
int sizeX = mainFrame.getFrame().getWidth();
int sizeY = mainFrame.getFrame().getHeight();
// See if title is set for main frame (only if name is
// still default, so that jnlp prop will still
// overrides this)
if (baseFrameTitle == DEFAULT_BASE_FRAME_TITLE &&
mainFrame.getFrame().isResourceSet("title")){
System.out.println("change");
baseFrameTitle = mainFrame.getFrame().getTitle();
setTitle(baseFrameTitle);
}
setBounds(cornerX, cornerY, cornerX + sizeX, cornerY + sizeY);
repaint();
}
useScrollPane = mainFrame.getFrame().getUseScrollPane();
}
bodyPanel.setUseScrollPane(useScrollPane);
setupBodyPanel();
}
public void initWithWizard(String url)
{
justStarted = true;
init(url);
if (userMode == OTConfig.SINGLE_USER_MODE) {
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
instructionPanel();
}
});
}
}
public void loadUserDataFile(File file)
{
try {
OTMLUserSession xmlUserSession = new OTMLUserSession(file, null);
loadUserSession(xmlUserSession);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method just sets the viewers userSession without loading it.
* This is useful if a user needs to select the data they want to use
* when the load method is called. Currently this is used by the "wizard" in
* the ot viewer.
*
* @param userSession
*/
public void setUserSession(OTUserSession userSession)
{
this.userSession = userSession;
userSession.setOTrunk(otrunk);
}
/**
* This method loads in a user session, and reloads the window.
*
* @param userSession
* @throws Exception
*/
public void loadUserSession(OTUserSession userSession)
throws Exception
{
this.userSession = userSession;
otrunk.registerUserSession(userSession);
reloadWindow();
}
public void updateOverlayGroupListeners()
{
OTObjectList overlays = userSystem.getOverlays();
for(int i=0; i<overlays.size(); i++){
OTObject item = overlays.get(i);
if(item instanceof OTOverlayGroup){
((OTOverlayGroup) item).addOTChangeListener(systemChangeListener);
}
}
}
public void reloadOverlays()
{
try {
otrunk.reloadOverlays(userSession);
updateOverlayGroupListeners();
reloadWindow();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void loadFile(File file)
{
currentAuthoredFile = file;
try {
initializeURL(currentAuthoredFile.toURL());
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadURL(URL url)
throws Exception
{
XMLDatabase systemDB = null;
try {
// try loading in the system object if there is one
String systemOtmlUrlStr =
OTConfig.getStringProp(OTConfig.SYSTEM_OTML_PROP);
if(systemOtmlUrlStr != null){
URL systemOtmlUrl = new URL(systemOtmlUrlStr);
systemDB = new XMLDatabase(systemOtmlUrl, System.out);
// don't track the resource info on the system db.
systemDB.loadObjects();
}
} catch (Exception e){
e.printStackTrace();
systemDB = null;
}
try {
xmlDB = new XMLDatabase(url, System.out);
// Only track the resource info when there isn't a user. Currently
// all classroom uses
// of OTViewer has NO_USER_MODE turned off, so using this setting
// safe to test
// the resource tracking without affecting real users.
if (userMode == OTConfig.NO_USER_MODE) {
xmlDB.setTrackResourceInfo(true);
}
xmlDB.loadObjects();
} catch (org.jdom.input.JDOMParseException e) {
String xmlWarningTitle = "XML Decoding error";
String xmlWarningMessage =
"There appears to a problem parsing the XML of this document. \n"
+ "Please show this error message to one of the workshop leaders. \n\n"
+ e.getMessage();
JOptionPane.showMessageDialog(null, xmlWarningMessage, xmlWarningTitle,
JOptionPane.ERROR_MESSAGE);
throw e;
}
addService(UserMessageHandler.class, new SwingUserMessageHandler(this));
otrunk = new OTrunkImpl(systemDB, xmlDB, services);
OTViewFactory myViewFactory =
(OTViewFactory) otrunk.getService(OTViewFactory.class);
if (myViewFactory != null) {
otViewFactory = myViewFactory;
}
OTViewContext factoryContext = otViewFactory.getViewContext();
factoryContext.addViewService(OTrunk.class, otrunk);
factoryContext.addViewService(OTFrameManager.class, frameManager);
factoryContext.addViewService(OTJComponentServiceFactory.class,
new OTJComponentServiceFactoryImpl());
factoryContext.addViewService(OTExternalAppService.class,
new OTExternalAppServiceImpl());
factoryContext.addViewService(OTUserListService.class, new OTUserListService() {
public Vector getUserList() {
return otrunk.getUsers();
}
});
currentURL = url;
}
// This method was refactored out of loadURL
private void setupBodyPanel()
throws Exception
{
bodyPanel.setTopLevelContainer(true);
bodyPanel.setOTViewFactory(otViewFactory);
// set the current mode from the viewservice to the main bodyPanel
// bodyPanel.setViewMode(otViewFactory.getDefaultMode());
// set the viewFactory of the frame manager
frameManager.setViewFactory(otViewFactory);
xmlDB.setDirty(false);
reloadWindow();
}
public OTObject getAuthoredRoot()
throws Exception
{
String rootLocalId =
OTConfig.getStringProp(OTConfig.ROOT_OBJECT_PROP);
if(rootLocalId != null){
OTID rootID = xmlDB.getOTIDFromLocalID(rootLocalId);
return otrunk.getOTObject(rootID);
}
return otrunk.getRoot();
}
public OTObject getRoot()
throws Exception
{
switch (userMode) {
case OTConfig.NO_USER_MODE:
return getAuthoredRoot();
case OTConfig.SINGLE_USER_MODE:
if (userSession == null) {
return null;
}
OTObject otRoot = getAuthoredRoot();
return otrunk.getUserRuntimeObject(otRoot, getCurrentUser());
}
return null;
}
public void reloadWindow()
throws Exception
{
OTObject root = getRoot();
boolean overrideShowTree = false;
if (userMode == OTConfig.SINGLE_USER_MODE) {
if (root == null) {
// FIXME This is an error
// the newAnonUserData should have been called before this
// method is
// called
// no user file has been started yet
overrideShowTree = true;
} else {
OTObject realRoot = otrunk.getRealRoot();
if (realRoot instanceof OTSystem) {
OTSystem localUserSystem =
(OTSystem) otrunk.getUserRuntimeObject(realRoot, getCurrentUser());
// FIXME there should be a better way than this because we
// have to handle
// multiple users.
if (localUserSystem != userSystem) {
userSystem = localUserSystem;
systemChangeListener = new OTChangeListener() {
public void stateChanged(OTChangeEvent e)
{
if ("overlays".equals(e.getProperty())) {
reloadOverlays();
}
}
};
updateOverlayGroupListeners();
userSystem.addOTChangeListener(systemChangeListener);
}
}
}
}
if (showTree && !overrideShowTree) {
OTDataObject rootDataObject = xmlDB.getRoot();
dataTreeModel.setRoot(new OTDataObjectNode("root", rootDataObject, otrunk));
folderTreeModel.setRoot(new OTFolderNode(root));
}
bodyPanel.setCurrentObject(root);
if (showTree && !overrideShowTree) {
folderTreeModel.fireTreeStructureChanged(new TreePath(
(SimpleTreeNode) folderTreeModel.getRoot()));
dataTreeModel.fireTreeStructureChanged(new TreePath(
(SimpleTreeNode) dataTreeModel.getRoot()));
}
Frame frame = (Frame) SwingUtilities.getRoot(this);
switch (userMode) {
case OTConfig.NO_USER_MODE:
if (remoteURL != null) {
frame.setTitle(baseFrameTitle + ": " + remoteURL.toString());
} else {
frame.setTitle(baseFrameTitle + ": " + currentURL.toString());
}
break;
case OTConfig.SINGLE_USER_MODE:
String userSessionLabel = null;
if (userSession != null) {
userSessionLabel = userSession.getLabel();
}
if(userSessionLabel != null){
frame.setTitle(baseFrameTitle + ": " + userSessionLabel);
} else {
frame.setTitle(baseFrameTitle);
}
break;
}
if(userSession == null){
saveUserDataAction.setEnabled(false);
saveUserDataAsAction.setEnabled(false);
} else {
saveUserDataAction.setEnabled(userSession.allowSave());
saveUserDataAsAction.setEnabled(userSession.allowSaveAs());
}
}
public void reload()
throws Exception
{
initializeURL(currentURL);
}
public OTUserSession getUserSession()
{
return userSession;
}
public OTUserObject getCurrentUser()
{
if(userSession == null){
return null;
}
return userSession.getUserObject();
}
public static void main(String[] args)
{
System.setProperty("apple.laf.useScreenMenuBar", "true");
OTViewer viewer = new OTViewer();
if (OTConfig.getBooleanProp(OTConfig.SINGLE_USER_PROP, false)) {
viewer.setUserMode(OTConfig.SINGLE_USER_MODE);
} else if (OTConfig.getBooleanProp(OTConfig.NO_USER_PROP, false)) {
viewer.setUserMode(OTConfig.NO_USER_MODE);
}
viewer.initArgs(args);
}
class ExitAction extends AbstractAction
{
/**
* nothing to serialize here.
*/
private static final long serialVersionUID = 1L;
public ExitAction()
{
super("Exit");
}
public void actionPerformed(ActionEvent e)
{
// If this suceeds then the VM will exit so
// the window will get disposed
exit();
}
}
/*
* (non-Javadoc)
*
* @see org.concord.otrunk.view.OTViewContainerListener#currentObjectChanged(org.concord.framework.otrunk.view.OTViewContainer)
*/
public void currentObjectChanged(OTViewContainerChangeEvent evt)
{
final OTViewContainer myContainer = (OTViewContainer) evt.getSource();
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
OTObject currentObject = myContainer.getCurrentObject();
if (folderTreeArea != null) {
OTFolderNode node =
(OTFolderNode) folderTreeArea.getLastSelectedPathComponent();
if (node == null)
return;
if (node.getPfObject() != currentObject) {
folderTreeArea.setSelectionPath(null);
}
}
}
});
}
/*
* (non-Javadoc)
*
* @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
*/
public void valueChanged(TreeSelectionEvent event)
{
if (event.getSource() == folderTreeArea) {
OTFolderNode node =
(OTFolderNode) folderTreeArea.getLastSelectedPathComponent();
if (node == null)
return;
OTObject pfObject = node.getPfObject();
bodyPanel.setCurrentObject(pfObject);
if (splitPane.getRightComponent() != bodyPanel) {
splitPane.setRightComponent(bodyPanel);
}
} else if (event.getSource() == dataTreeArea) {
SimpleTreeNode node =
(SimpleTreeNode) dataTreeArea.getLastSelectedPathComponent();
Object resourceValue = null;
if (node != null) {
resourceValue = node.getObject();
if (resourceValue == null) {
resourceValue = "null resource value";
}
} else {
resourceValue = "no selected data object";
}
JComponent nodeView = null;
if (resourceValue instanceof OTDataObject) {
nodeView = new OTDataObjectView((OTDataObject) resourceValue);
} else {
nodeView = new JTextArea(resourceValue.toString());
}
JScrollPane scrollPane = new JScrollPane(nodeView);
splitPane.setRightComponent(scrollPane);
}
}
private void updateRemoteURL(String defaultURL)
{
String remote = System.getProperty(OTConfig.REMOTE_URL_PROP, null);
try {
if (remote == null) {
if (defaultURL != null && defaultURL.startsWith("http:")) {
remoteURL = new URL(defaultURL);
}
} else {
remoteURL = new URL(remote);
}
} catch (Exception e) {
remoteURL = null;
System.err.println("Remote URL is invalid.");
e.printStackTrace();
}
}
public void createActions()
{
newUserDataAction = new AbstractAction("New") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
createNewUser();
}
};
loadUserDataAction = new AbstractAction("Open...") {
/**
* nothing to serialize here. Just the parent class.
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
openUserData(true);
}
};
exportToHtmlAction = new AbstractAction("Export to html...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0)
{
File fileToSave = getReportFile();
OTMLToXHTMLConverter otxc =
new OTMLToXHTMLConverter(otViewFactory, bodyPanel.getViewContainer());
otxc.setXHTMLParams(fileToSave, 800, 600);
(new Thread(otxc)).start();
}
};
// Isn't it enabled by default?
exportToHtmlAction.setEnabled(true);
saveUserDataAction = new AbstractAction("Save") {
/**
* Nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
userSession.save();
// the save operation might change the label used by the session
setTitle(baseFrameTitle + ": " + userSession.getLabel());
}
};
saveUserDataAsAction = new AbstractAction("Save As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if(userSession instanceof OTMLUserSession){
((OTMLUserSession)userSession).setDialogParent(SwingUtilities.getRoot(OTViewer.this));
}
userSession.saveAs();
}
};
loadAction = new AbstractAction("Open Authored Content...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd =
new MostRecentFileDialog("org.concord.otviewer.openotml");
mrfd.setFilenameFilter("otml");
int retval = mrfd.showOpenDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
}
if (file != null && file.exists()) {
System.out.println("load file name: " + file);
// if they open an authored file then they are overriding
// the remoteURL,
// at least for now. This makes the title bar update
// correctly, and
// fixes a lockup that happens when they have opened a local
// file and then
// try to save it again.
remoteURL = null;
loadFile(file);
exportToHtmlAction.setEnabled(true);
}
}
};
loadAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O,
java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
saveAction = new AbstractAction("Save Authored Content...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
if (OTConfig.isRemoteSaveData() && remoteURL != null) {
try {
if (OTConfig.isRestEnabled()) {
try {
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_PUT);
setTitle(remoteURL.toString());
} catch (Exception e) {
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST);
setTitle(remoteURL.toString());
}
} else {
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST);
setTitle(remoteURL.toString());
}
} catch (Exception e) {
JOptionPane.showMessageDialog(
(Frame) SwingUtilities.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} else {
if (currentAuthoredFile == null) {
saveAsAction.actionPerformed(arg0);
return;
}
if (checkForReplace(currentAuthoredFile)) {
try {
ExporterJDOM.export(currentAuthoredFile, xmlDB.getRoot(),
xmlDB);
xmlDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
} // end if (remoteUrl == null)
}
};
saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
saveAsAction = new AbstractAction("Save Authored Content As...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd =
new MostRecentFileDialog("org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("otml");
if (currentAuthoredFile != null) {
mrfd.setCurrentDirectory(currentAuthoredFile.getParentFile());
mrfd.setSelectedFile(currentAuthoredFile);
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".otml")) {
file = new File(file.getAbsolutePath() + ".otml");
}
if (checkForReplace(file)) {
try {
ExporterJDOM.export(file, xmlDB.getRoot(), xmlDB);
currentAuthoredFile = file;
currentURL = file.toURL();
xmlDB.setDirty(false);
} catch (Exception e) {
e.printStackTrace();
}
}
frame.setTitle(fileName);
remoteURL = null;
updateMenuBar();
}
}
};
saveRemoteAsAction = new AbstractAction("Save Remotely As...") {
/**
* nothing to serizile here
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent arg0)
{
// Pop up a dialog asking for a URL
// Post the otml to the url
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.setLayout(new BorderLayout());
JLabel prompt =
new JLabel("Please enter the URL to which you would like to save:");
prompt.setBorder(new EmptyBorder(0, 0, 10, 0));
JTextField textField = new JTextField();
if (remoteURL == null) {
textField.setText("http:
} else {
textField.setText(remoteURL.toString());
}
JPanel checkboxPanel = new JPanel();
JCheckBox restCheckbox = new JCheckBox("REST Enabled?");
restCheckbox.setSelected(OTConfig.isRestEnabled());
checkboxPanel.setBorder(new EmptyBorder(5, 5, 0, 0));
checkboxPanel.add(restCheckbox);
panel.add(prompt, BorderLayout.NORTH);
panel.add(textField, BorderLayout.CENTER);
panel.add(checkboxPanel, BorderLayout.SOUTH);
int returnVal =
CustomDialog.showOKCancelDialog(
(Frame) SwingUtilities.getRoot(OTViewer.this), // parent
panel, // custom content
"Save URL", // title
false, // resizeable
true // modal
);
if (returnVal == 0) {
try {
remoteURL = new URL(textField.getText());
// WARNING this will cause a security exception if we
// are running in a applet or jnlp which
// has a security sandbox.
System.setProperty(OTConfig.REST_ENABLED_PROP,
Boolean.toString(restCheckbox.isSelected()));
otrunk.remoteSaveData(xmlDB, remoteURL, OTViewer.HTTP_POST);
setTitle(remoteURL.toString());
updateMenuBar();
} catch (Exception e) {
System.err.println("Bad URL. Not saving.");
JOptionPane.showMessageDialog(
(Frame) SwingUtilities.getRoot(OTViewer.this),
"There was an error saving. Check your URL and try again.",
"Error Saving", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
} else {
// CANCELLED
}
}
};
exportImageAction = new AbstractAction("Export Image...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
// this introduces a dependency on concord Swing project
// instead there needs to be a way to added these actions
// through
// the xml
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp);
}
};
exportHiResImageAction = new AbstractAction("Export Hi Res Image...") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Component currentComp = bodyPanel.getCurrentComponent();
Util.makeScreenShot(currentComp, 2, 2);
}
};
debugAction = new AbstractAction("Debug Mode") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (((JCheckBoxMenuItem) source).isSelected()) {
System.setProperty(OTConfig.DEBUG_PROP, "true");
} else {
System.setProperty(OTConfig.DEBUG_PROP, "false");
}
try {
reloadWindow();
} catch (Exception exp) {
exp.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
updateMenuBar();
}
});
exportToHtmlAction.setEnabled(true);
}
};
showConsoleAction = new AbstractAction("Show Console") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
if (consoleFrame != null) {
consoleFrame.setVisible(true);
}
}
};
reloadWindowAction = new AbstractAction("Reload window") {
/**
* nothing to serialize here
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
try {
reload();
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
reloadWindowAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R,
java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
exitAction = new ExitAction();
}
/**
* @return Returns the menuBar.
*/
public JMenuBar updateMenuBar()
{
JMenu fileMenu = null;
if (menuBar == null) {
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
} else {
fileMenu = menuBar.getMenu(0);
fileMenu.removeAll();
}
if (OTConfig.isAuthorMode()) {
userMode = OTConfig.NO_USER_MODE;
}
if (userMode == OTConfig.SINGLE_USER_MODE) {
fileMenu.setEnabled(!justStarted);
// we add new and load ("open") menu items only if this is NOT launched
// by sail or if otrunk.view.destructive_menu is set to true
if (!isLaunchedBySailOTViewer() || (OTConfig.isShowDestructiveMenuItems())){
fileMenu.add(newUserDataAction);
fileMenu.add(loadUserDataAction);
}
fileMenu.add(saveUserDataAction);
fileMenu.add(saveUserDataAsAction);
}
if (OTConfig.isDebug()) {
if (userMode == OTConfig.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME, "Save Authored Content As...");
saveRemoteAsAction.putValue(Action.NAME,
"Save Authored Content Remotely As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
saveRemoteAsAction.putValue(Action.NAME, "Save Remotely As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
fileMenu.add(saveRemoteAsAction);
}
if (OTConfig.isAuthorMode() && !OTConfig.isDebug()) {
if (userMode == OTConfig.SINGLE_USER_MODE) {
loadAction.putValue(Action.NAME, "Open Authored Content...");
saveAction.putValue(Action.NAME, "Save Authored Content");
saveAsAction.putValue(Action.NAME, "Save Authored Content As...");
} else {
loadAction.putValue(Action.NAME, "Open...");
saveAction.putValue(Action.NAME, "Save");
saveAsAction.putValue(Action.NAME, "Save As...");
}
fileMenu.add(loadAction);
fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
}
if (OTConfig.getBooleanProp("otrunk.view.export_image", false)) {
fileMenu.add(exportImageAction);
fileMenu.add(exportHiResImageAction);
}
fileMenu.add(exportToHtmlAction);
fileMenu.add(showConsoleAction);
if (OTConfig.isAuthorMode() || OTConfig.isDebug()) {
fileMenu.add(reloadWindowAction);
}
JCheckBoxMenuItem debugItem = new JCheckBoxMenuItem(debugAction);
debugItem.setSelected(OTConfig.isDebug());
fileMenu.add(debugItem);
fileMenu.add(exitAction);
return menuBar;
}
boolean checkForReplace(File file)
{
if (file == null){
return false;
}
if (!file.exists()) {
return true; // File doesn't exist, so go ahead and save
}
if (currentAuthoredFile != null && file.compareTo(currentAuthoredFile) == 0){
return true; // we're already authoring this file, so no need to
// prompt
}
final Object[] options = { "Yes", "No" };
return javax.swing.JOptionPane.showOptionDialog(null, "The file '"
+ file.getName() + "' already exists. " + "Replace existing file?",
"Warning", javax.swing.JOptionPane.YES_NO_OPTION,
javax.swing.JOptionPane.WARNING_MESSAGE, null, options, options[1]) == javax.swing.JOptionPane.YES_OPTION;
}
/**
* FIXME This method name is confusing. The method first checks for unsaved
* changes, and if there are unsaved changes it asks the user if they want to
* "don't save", "cancel" or "save"
*
* @return
*/
public boolean checkForUnsavedUserData()
{
if(userSession == null){
return true;
}
if(userSession.hasUnsavedChanges()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
askedAboutSavingUserData = true;
int chosenOption =
JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[2]);
switch (chosenOption) {
case 0:
System.err.println("Not saving work");
break;
case 1:
System.err.println("Canceling close");
return false;
case 2:
System.err.println("Set needToSaveUserData true");
needToSaveUserData = true;
break;
}
}
return true;
}
/**
* Checks if the user has unsaved authored data. If they do then it prompts
* them to confirm what they are doing. If they cancel then it returns
* false.
*
* @return
*/
public boolean checkForUnsavedAuthorData()
{
if (xmlDB != null) {
if (xmlDB.isDirty()) {
// show dialog message telling them they haven't
// saved their work
// FIXME
String options[] = { "Don't Save", "Cancel", "Save" };
int chosenOption =
JOptionPane.showOptionDialog(this, "Save Changes?", "Save Changes?",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[2]);
switch (chosenOption) {
case 0:
System.err.println("Not saving authored data");
break;
case 1:
System.err.println("Canceling close");
return false;
case 2:
System.err.println("Saving authored data");
saveAction.actionPerformed(null);
break;
}
}
}
return true;
}
/**
* This does not check for unsaved user data
*
*/
public void newAnonUserData()
{
newUserData(OTViewerHelper.ANON_SINGLE_USER_NAME);
}
public void newUserData(String userName)
{
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
if(userSession == null) {
throw new IllegalStateException("a OTUserSession must be supplied before newUserData can be called");
}
try {
userSession.newLayer();
OTUserObject userObject = userSession.getUserObject();
if(userName != null){
userObject.setName(userName);
}
// This will request the label from the userSession
reloadWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean exit()
{
try {
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return false;
}
if (OTConfig.isAuthorMode() && !checkForUnsavedAuthorData()) {
// the user canceled the operation
return false;
}
// FIXME there is a problem with this logic. If the user saved data
// just before closing
// checkForUnsavedUserData will not see any unsaved data. But if
// some view creates
// data in the viewClosed method then that data will not get saved
// here.
// I think the key to solving this is to separate the
// automatic/logging data from the
// user visible data. And then make a rule that saving data in the
// viewClosed method
// is not allowed.
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
if (otrunk != null)
otrunk.close();
} catch (Exception exp) {
exp.printStackTrace();
// exit anyhow
}
System.exit(0);
return true;
}
protected void conditionalSaveUserData()
{
if (!askedAboutSavingUserData) {
checkForUnsavedUserData();
}
if (needToSaveUserData) {
saveUserDataAction.actionPerformed(null);
} else {
System.err.println("Not saving work before closing.");
}
// Reset these back to false, so if the user is switching to a new
// user or loading a new file we are in a clean state, for that file or
// user
askedAboutSavingUserData = false;
needToSaveUserData = false;
}
public File getReportFile()
{
Frame frame = (Frame) SwingUtilities.getRoot(OTViewer.this);
MostRecentFileDialog mrfd =
new MostRecentFileDialog("org.concord.otviewer.saveotml");
mrfd.setFilenameFilter("html");
if (userSession instanceof OTMLUserSession){
OTMLUserSession otmlUserSession = (OTMLUserSession) userSession;
if(otmlUserSession.currentUserFile != null){
mrfd.setCurrentDirectory(otmlUserSession.currentUserFile.getParentFile());
}
}
int retval = mrfd.showSaveDialog(frame);
File file = null;
if (retval == MostRecentFileDialog.APPROVE_OPTION) {
file = mrfd.getSelectedFile();
String fileName = file.getPath();
if (!fileName.toLowerCase().endsWith(".html")) {
file = new File(file.getAbsolutePath() + ".html");
}
return file;
}
return null;
}
public void createNewUser()
{
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// This ensures viewClosed is called
bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
// call some new method for creating a new un-saved user state
// this should set the currentUserFile to null, so the save check
// prompts
// for a file name
newAnonUserData();
exportToHtmlAction.setEnabled(true);
}
public void openUserData(boolean saveCurrentData)
{
if(saveCurrentData){
if (!checkForUnsavedUserData()) {
// the user canceled the operation
return;
}
// FIXME Calling the method below would insure the view is closed, and
// that any data that is
// is modified in that view closed operation will get saved, however if
// the user
// cancels the open dialog then we would be left in an unknown
// state. The current view would be closed which they would want to see
// again.
// bodyPanel.setCurrentObject(null);
conditionalSaveUserData();
}
if(userSession == null){
throw new IllegalStateException("can't open user data without a userSession");
}
boolean success = userSession.open();
try {
reloadWindow();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(success){
exportToHtmlAction.setEnabled(true);
}
}
public void instructionPanel()
{
commDialog.setResizable(false);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.insets = new Insets(5,10,5,10);
JLabel lNew = new JLabel("Click the \"New\" button to create a new portfolio:");
JLabel lOpen = new JLabel("Click the \"Open\" button to open a saved portfolio:");
JButton bNew = new JButton("New");
JButton bOpen = new JButton("Open");
c.gridx = 0;
c.gridy = 0;
panel.add(lNew, c);
c.gridx = 1;
panel.add(bNew, c);
c.gridx = 0;
c.gridy = 1;
panel.add(lOpen, c);
c.gridx = 1;
panel.add(bOpen, c);
bNew.setOpaque(false);
bOpen.setOpaque(false);
setUserSession(new OTMLUserSession());
bNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
newAnonUserData();
exportToHtmlAction.setEnabled(true);
}
});
bOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
commDialog.setVisible(false);
openUserData(false);
}
});
commDialog.getContentPane().add(panel);
commDialog.setBounds(200, 200, 450, 200);
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
commDialog.setVisible(true);
justStarted = false;
updateMenuBar();
}
});
}
public OTViewContainerPanel getViewContainerPanel()
{
return this.bodyPanel;
}
public void setExitAction(AbstractAction exitAction)
{
this.exitAction = exitAction;
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#about()
*/
public void about()
{
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#preferences()
*/
public void preferences()
{
// TODO Auto-generated method stub
}
public void setLaunchedBySailOTViewer(boolean launchedBySailOTViewer){
this.launchedBySailOTViewer = launchedBySailOTViewer;
}
public boolean isLaunchedBySailOTViewer(){
return launchedBySailOTViewer;
}
/*
* (non-Javadoc)
*
* @see org.concord.applesupport.AppleApplicationAdapter#quit()
*/
public void quit()
{
exitAction.actionPerformed(null);
}
public OTrunk getOTrunk()
{
return otrunk;
}
} // @jve:decl-index=0:visual-constraint="10,10"
class HtmlFileFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept(File f)
{
if (f == null)
return false;
if (f.isDirectory())
return true;
return (f.getName().toLowerCase().endsWith(".html"));
}
public String getDescription()
{
return "HTML files";
}
} // @jve:decl-index=0:visual-constraint="10,10"
|
package org.jivesoftware.util;
import org.jivesoftware.messenger.container.Container;
import org.jivesoftware.messenger.container.ServiceLookup;
import org.jivesoftware.messenger.container.ServiceLookupFactory;
import org.jivesoftware.messenger.muc.MultiUserChatServer;
import org.jivesoftware.messenger.auth.AuthToken;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.UserManager;
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.messenger.user.RosterManager;
import org.jivesoftware.messenger.XMPPServer;
import org.jivesoftware.messenger.PrivateStore;
import org.jivesoftware.messenger.PresenceManager;
import org.jivesoftware.messenger.SessionManager;
import org.jivesoftware.messenger.XMPPServerInfo;
import java.util.LinkedHashMap;
import java.util.Map;
import java.net.URLEncoder;
/**
* A utility bean for Messenger admin console pages.
*/
public class WebManager extends WebBean {
private Map breadcrumbMap = new LinkedHashMap();
private String title = "";
private String sidebar = "";
private int start = 0;
private int range = 15;
public WebManager() {
}
/**
* Returns the auth token redirects to the login page if an auth token is not found.
*/
public AuthToken getAuthToken() {
AuthToken authToken = (AuthToken)session.getAttribute("jive.admin.authToken");
if (authToken == null) {
showLogin();
}
return authToken;
}
/**
* Returns <tt>true</tt> if the Messenger container is in setup mode, <tt>false</tt> otherwise.
*/
public boolean isSetupMode() {
return getContainer().isSetupMode();
}
/**
* Returns an instnace of the ServiceLookup.
*/
public ServiceLookup getServiceLookup() {
try {
return ServiceLookupFactory.getLookup();
}
catch (UnauthorizedException ex) {
return null;
}
}
/**
* Returns the server's container.
*/
public Container getContainer() {
return (Container)getServiceLookup().lookup(Container.class);
}
/**
* Returns the XMPP server object -- can get many config items from here.
*/
public XMPPServer getXMPPServer() {
final XMPPServer xmppServer = (XMPPServer)getServiceLookup().lookup(XMPPServer.class);
if (xmppServer == null) {
// Show that the server is down
showServerDown();
return null;
}
return xmppServer;
}
public UserManager getUserManager() {
return (UserManager)getServiceLookup().lookup(UserManager.class);
}
public RosterManager getRosterManager() {
return (RosterManager)getServiceLookup().lookup(RosterManager.class);
}
public PrivateStore getPrivateStore() {
return (PrivateStore)getServiceLookup().lookup(PrivateStore.class);
}
public PresenceManager getPresenceManager() {
return (PresenceManager)getServiceLookup().lookup(PresenceManager.class);
}
public SessionManager getSessionManager() {
return (SessionManager)getServiceLookup().lookup(SessionManager.class);
}
public MultiUserChatServer getMultiUserChatServer() {
return (MultiUserChatServer)getServiceLookup().lookup(MultiUserChatServer.class);
}
public XMPPServerInfo getServerInfo() {
return getXMPPServer().getServerInfo();
}
/**
* Returns the page user or <tt>null</tt> if one is not found.
*/
public User getUser() {
User pageUser = null;
try {
pageUser = getUserManager().getUser(getAuthToken().getUsername());
}
catch (UserNotFoundException ignored) {}
return pageUser;
}
/**
* Returns <tt>true</tt> if the server is in embedded mode, <tt>false</tt> otherwise.
*/
public boolean isEmbedded() {
try {
ClassUtils.forName("org.jivesoftware.messenger.starter.ServerStarter");
return true;
}
catch (Exception ignored) {
return false;
}
}
/**
* Restarts the container then sleeps for 3 seconds.
*/
public void restart(Container container) {
try {
container.restart();
}
catch (Exception e) {
Log.error(e);
}
sleep();
}
/**
* Stops the container then sleeps for 3 seconds.
*/
public void stop(Container container) {
try {
container.stop();
}
catch (Exception e) {
Log.error(e);
}
sleep();
}
public WebManager getManager() {
return this;
}
public void validateService() {
if (getPresenceManager() == null ||
getXMPPServer() == null) {
showServerDown();
}
}
public String getErrorPage() {
return "error-serverdown.jsp";
}
public boolean isServerRunning() {
if (getPresenceManager() == null ||
getXMPPServer() == null) {
return false;
}
return true;
}
public void addBreadCrumb(String name, String url) {
breadcrumbMap.put(name, url);
}
public Map getBreadCrumbs() {
return breadcrumbMap;
}
public void setSidebar(String sidebar) {
this.sidebar = sidebar;
}
public String getSidebar() {
return sidebar;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public int getBreadcrumbSize() {
return getBreadCrumbs().size();
}
public void setStart(int start) {
this.start = start;
}
public int getStart() {
return start;
}
public void setRange(int range) {
this.range = range;
}
public int getRange() {
return range;
}
public int getCurrentPage() {
return (start / range) + 1;
}
private void sleep() {
// Sleep for a minute:
try {
Thread.sleep(3000L);
}
catch (Exception ignored) {
}
}
private void showLogin() {
try {
response.sendRedirect(getRedirectURL(null));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
protected void showServerDown() {
try {
response.sendRedirect("error-serverdown.jsp");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private String getRedirectURL(String optionalParams) {
StringBuffer buf = new StringBuffer();
try {
StringBuffer rURL = request.getRequestURL();
int pos = rURL.lastIndexOf("/");
if ((pos+1) <= rURL.length()) {
buf.append(rURL.substring(pos+1, rURL.length()));
}
String qs = request.getQueryString();
if (qs != null) {
buf.append("?").append(qs);
}
}
catch (Exception e) {
Log.error(e);
}
try {
String url= "login.jsp?url=" + URLEncoder.encode(buf.toString(), "ISO-8859-1")
+ (optionalParams != null ? "&"+optionalParams : "");
return url;
}
catch (Exception e) {
Log.error(e);
return null;
}
}
}
|
package com.example.w0143446.pictureviewer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class ImageFragment extends Fragment {
// The image we are to display
String image = null;
TextView tvNote;
ImageView ivImage;
public ImageFragment() {
// Required empty public constructor
}
//take arguments in instance
public static ImageFragment newInstance(int index) {
ImageFragment f = new ImageFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//tvNote = (TextView) getView().findViewById(R.id.tvNote);
System.out.println("onCreateView called");
return inflater.inflate(R.layout.fragment_image, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("onActivityCreated called");
tvNote = (TextView) getView().findViewById(R.id.tvNote); //throws cannot cast LinearLayout to TextView exception
ivImage = (ImageView) getView().findViewById(R.id.image);
}
public void setText(String text) {
tvNote.setText(text);
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
}
|
package duro.runtime;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
public class DictionaryProcess extends Process implements Iterable<Object> {
private static final long serialVersionUID = 1L;
private Hashtable<Object, Object> protos = new Hashtable<Object, Object>();
@Override
public void replay(List<Instruction> commands) {
// Does is make sense to have this method here?
}
@Override
public void resume(List<Instruction> playedInstructions) {
// Does is make sense to have this method here?
}
private Hashtable<Object, Object> properties = new Hashtable<Object, Object>();
@Override
public CallFrameInfo getInstructions(Object key) {
CallFrameInfo callFrameInfo = (CallFrameInfo)properties.get(key);
if(callFrameInfo != null)
return callFrameInfo;
for(Object proto: protos.values()) {
callFrameInfo = ((Process)proto).getInstructions(key);
if(callFrameInfo != null)
return callFrameInfo;
}
return null;
}
public void defineProto(Object key, Object value) {
properties.put(key, value);
protos.put(key, value);
}
@Override
public void define(Object key, Object value) {
properties.put(key, value);
protos.remove(key);
}
@Override
public Object lookup(Object key) {
return properties.get(key);
}
@Override
public Iterator<Object> iterator() {
return properties.keySet().iterator();
}
@Override
public String toString() {
return properties.toString();
}
}
|
package org.knowm.xchange.binance;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.knowm.xchange.BaseExchange;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.binance.dto.marketdata.BinancePrice;
import org.knowm.xchange.binance.dto.meta.exchangeinfo.BinanceExchangeInfo;
import org.knowm.xchange.binance.dto.meta.exchangeinfo.Filter;
import org.knowm.xchange.binance.dto.meta.exchangeinfo.Symbol;
import org.knowm.xchange.binance.service.BinanceAccountService;
import org.knowm.xchange.binance.service.BinanceMarketDataService;
import org.knowm.xchange.binance.service.BinanceTradeService;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.meta.CurrencyMetaData;
import org.knowm.xchange.dto.meta.CurrencyPairMetaData;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.utils.AuthUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import si.mazi.rescu.RestProxyFactory;
import si.mazi.rescu.SynchronizedValueFactory;
public class BinanceExchange extends BaseExchange {
private static final Logger LOG = LoggerFactory.getLogger(BinanceExchange.class);
private static final int DEFAULT_PRECISION = 8;
private BinanceExchangeInfo exchangeInfo;
private Long deltaServerTimeExpire;
private Long deltaServerTime;
@Override
protected void initServices() {
this.marketDataService = new BinanceMarketDataService(this);
this.tradeService = new BinanceTradeService(this);
this.accountService = new BinanceAccountService(this);
}
@Override
public SynchronizedValueFactory<Long> getNonceFactory() {
throw new UnsupportedOperationException("Binance uses timestamp/recvwindow rather than a nonce");
}
@Override
public ExchangeSpecification getDefaultExchangeSpecification() {
ExchangeSpecification spec = new ExchangeSpecification(this.getClass().getCanonicalName());
spec.setSslUri("https://api.binance.com");
spec.setHost("www.binance.com");
spec.setPort(80);
spec.setExchangeName("Binance");
spec.setExchangeDescription("Binance Exchange.");
AuthUtils.setApiAndSecretKey(spec, "binance");
return spec;
}
public BinanceExchangeInfo getExchangeInfo() {
return exchangeInfo;
}
@Override
public void remoteInit() {
try {
// populate currency pair keys only, exchange does not provide any other metadata for download
Map<CurrencyPair, CurrencyPairMetaData> currencyPairs = exchangeMetaData.getCurrencyPairs();
Map<Currency, CurrencyMetaData> currencies = exchangeMetaData.getCurrencies();
BinanceMarketDataService marketDataService =
(BinanceMarketDataService) this.marketDataService;
exchangeInfo = marketDataService.getExchangeInfo();
Symbol[] symbols = exchangeInfo.getSymbols();
for (BinancePrice price : marketDataService.tickerAllPrices()) {
CurrencyPair pair = price.getCurrencyPair();
for (Symbol symbol : symbols) {
if (symbol
.getSymbol()
.equals(pair.base.getCurrencyCode() + pair.counter.getCurrencyCode())) {
int basePrecision = Integer.parseInt(symbol.getBaseAssetPrecision());
int counterPrecision = Integer.parseInt(symbol.getQuotePrecision());
int pairPrecision = 8;
int amountPrecision = 8;
BigDecimal minQty = null;
BigDecimal maxQty = null;
Filter[] filters = symbol.getFilters();
for (Filter filter : filters) {
if (filter.getFilterType().equals("PRICE_FILTER")) {
pairPrecision = Math.min(pairPrecision, numberOfDecimals(filter.getTickSize()));
} else if (filter.getFilterType().equals("LOT_SIZE")) {
amountPrecision = Math.min(amountPrecision, numberOfDecimals(filter.getMinQty()));
minQty = new BigDecimal(filter.getMinQty()).stripTrailingZeros();
maxQty = new BigDecimal(filter.getMaxQty()).stripTrailingZeros();
}
}
currencyPairs.put(
price.getCurrencyPair(),
new CurrencyPairMetaData(
new BigDecimal("0.1"), // Trading fee at Binance is 0.1 %
minQty, // Min amount
maxQty, // Max amount
pairPrecision, // precision
null /* TODO get fee tiers, although this is not necessary now
because their API returns current fee directly */));
currencies.put(
pair.base,
new CurrencyMetaData(
basePrecision,
currencies.containsKey(pair.base)
? currencies.get(pair.base).getWithdrawalFee()
: null));
currencies.put(
pair.counter,
new CurrencyMetaData(
counterPrecision,
currencies.containsKey(pair.counter)
? currencies.get(pair.counter).getWithdrawalFee()
: null));
}
}
}
} catch (Exception e) {
throw new ExchangeException("Failed to initialize: " + e.getMessage(), e);
}
}
private int numberOfDecimals(String value) {
return new BigDecimal(value).stripTrailingZeros().scale();
}
public void clearDeltaServerTime() {
deltaServerTime = null;
}
public long deltaServerTime() throws IOException {
if (deltaServerTime == null || deltaServerTimeExpire <= System.currentTimeMillis()) {
// Do a little warm up
Binance binance =
RestProxyFactory.createProxy(Binance.class, getExchangeSpecification().getSslUri());
Date serverTime = new Date(binance.time().getServerTime().getTime());
// Assume that we are closer to the server time when we get the repose
Date systemTime = new Date(System.currentTimeMillis());
// Expire every 10min
deltaServerTimeExpire = systemTime.getTime() + TimeUnit.MINUTES.toMillis(10);
deltaServerTime = serverTime.getTime() - systemTime.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
LOG.trace(
"deltaServerTime: {} - {} => {}",
df.format(serverTime),
df.format(systemTime),
deltaServerTime);
}
return deltaServerTime;
}
}
|
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Integer;
import java.util.*;
import java.util.regex.Pattern;
// Don't Change >>>
public class TopTitleStatistics extends Configured implements Tool {
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new TopTitleStatistics(), args);
System.exit(res);
}
@Override
public int run(String[] args) throws Exception {
Configuration conf = this.getConf();
FileSystem fs = FileSystem.get(conf);
Path tmpPath = new Path("/mp2/tmp");
fs.delete(tmpPath, true);
Job jobA = Job.getInstance(conf, "Title Count");
jobA.setOutputKeyClass(Text.class);
jobA.setOutputValueClass(IntWritable.class);
jobA.setMapperClass(TitleCountMap.class);
jobA.setReducerClass(TitleCountReduce.class);
FileInputFormat.setInputPaths(jobA, new Path(args[0]));
FileOutputFormat.setOutputPath(jobA, tmpPath);
jobA.setJarByClass(TopTitleStatistics.class);
jobA.waitForCompletion(true);
Job jobB = Job.getInstance(conf, "Top Titles Statistics");
jobB.setOutputKeyClass(Text.class);
jobB.setOutputValueClass(IntWritable.class);
jobB.setMapOutputKeyClass(NullWritable.class);
jobB.setMapOutputValueClass(TextArrayWritable.class);
jobB.setMapperClass(TopTitlesStatMap.class);
jobB.setReducerClass(TopTitlesStatReduce.class);
jobB.setNumReduceTasks(1);
FileInputFormat.setInputPaths(jobB, tmpPath);
FileOutputFormat.setOutputPath(jobB, new Path(args[1]));
jobB.setInputFormatClass(KeyValueTextInputFormat.class);
jobB.setOutputFormatClass(TextOutputFormat.class);
jobB.setJarByClass(TopTitleStatistics.class);
return jobB.waitForCompletion(true) ? 0 : 1;
}
public static String readHDFSFile(String path, Configuration conf) throws IOException{
Path pt=new Path(path);
FileSystem fs = FileSystem.get(pt.toUri(), conf);
FSDataInputStream file = fs.open(pt);
BufferedReader buffIn=new BufferedReader(new InputStreamReader(file));
StringBuilder everything = new StringBuilder();
String line;
while( (line = buffIn.readLine()) != null) {
everything.append(line);
everything.append("\n");
}
return everything.toString();
}
public static class TextArrayWritable extends ArrayWritable {
public TextArrayWritable() {
super(Text.class);
}
public TextArrayWritable(String[] strings) {
super(Text.class);
Text[] texts = new Text[strings.length];
for (int i = 0; i < strings.length; i++) {
texts[i] = new Text(strings[i]);
}
set(texts);
}
}
// <<< Don't Change
public static class TitleCountMap extends Mapper<Object, Text, Text, IntWritable> {
HashSet<String> stopWords;
String delimiters;
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
String stopWordsPath = conf.get("stopwords");
String delimitersPath = conf.get("delimiters");
this.stopWords = new HashSet<>(Arrays.asList(readHDFSFile(stopWordsPath, conf).split("\n")));
this.delimiters = getRegexDelimiters(readHDFSFile(delimitersPath, conf));
}
private String getRegexDelimiters(String value){
StringBuilder regexp = new StringBuilder("");
regexp.append("[");
for (int i = 0; i < value.length(); i++) {
regexp.append(Pattern.quote(
Character.toString(value.charAt(i))
));
}
regexp.append("]");
return regexp.toString();
}
@Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString().toLowerCase().trim();
String[] result = line.split(this.delimiters);
for(String s : result) {
if (s == null || stopWords.contains(s) || s.length() == 0)
continue;
context.write(new Text(s), new IntWritable(1));
}
}
}
public static class TitleCountReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int total = 0;
for (IntWritable val : values)
total += val.get();
context.write(key, new IntWritable(total));
}
}
public static class TopTitlesStatMap extends Mapper<Text, Text, NullWritable, TextArrayWritable> {
Integer N;
TreeSet<Pair<Integer, String>> countToWordMap = new TreeSet<>();
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
this.N = conf.getInt("N", 10);
}
@Override
public void map(Text key, Text value, Context context) throws IOException, InterruptedException {
Integer count = Integer.parseInt(value.toString());
String word = key.toString();
countToWordMap.add(new Pair<>(count, word));
if (countToWordMap.size() > 10) {
countToWordMap.remove(countToWordMap.first());
}
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
for (Pair<Integer, String> item : countToWordMap) {
String[] strings = {item.second, item.first.toString()};
TextArrayWritable val = new TextArrayWritable(strings);
context.write(NullWritable.get(), val);
}
}
}
public static class TopTitlesStatReduce extends Reducer<NullWritable, TextArrayWritable, Text, IntWritable> {
Integer N;
TreeSet<Pair<Integer, String>> countToWordMap = new TreeSet<>();
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
this.N = conf.getInt("N", 10);
}
@Override
public void reduce(NullWritable key, Iterable<TextArrayWritable> values, Context context) throws IOException, InterruptedException {
Integer sum = 0, mean, max = 0, min = 0, var = 0;
for (TextArrayWritable val : values) {
Text[] pair = (Text[]) val.toArray();
String word = pair[0].toString();
Integer count = Integer.parseInt(pair[1].toString());
countToWordMap.add(new Pair<>(count, word));
if (countToWordMap.size() > N) {
countToWordMap.remove(countToWordMap.first());
}
}
int count = countToWordMap.size();
for (Pair<Integer, String> item : countToWordMap) {
Integer v = item.first;
sum += v;
max = (null == max || v > max) ? v : max;
min = (null == min || v < min) ? v : min;
}
mean = sum / count;
// variance
for (Pair<Integer, String> item : countToWordMap) {
Integer v = item.first;
Integer varItem = v - mean;
var = var + varItem * varItem;
}
var = var / count;
context.write(new Text("Mean"), new IntWritable(mean));
context.write(new Text("Sum"), new IntWritable(sum));
context.write(new Text("Min"), new IntWritable(min));
context.write(new Text("Max"), new IntWritable(max));
context.write(new Text("Var"), new IntWritable(var));
}
}
}
// >>> Don't Change
class Pair<A extends Comparable<? super A>,
B extends Comparable<? super B>>
implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A extends Comparable<? super A>,
B extends Comparable<? super B>>
Pair<A, B> of(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int compareTo(Pair<A, B> o) {
int cmp = o == null ? 1 : (this.first).compareTo(o.first);
return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
}
@Override
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair<?, ?>) obj).first)
&& equal(second, ((Pair<?, ?>) obj).second);
}
private boolean equal(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
// <<< Don't Change
|
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Integer;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TreeSet;
// Don't Change >>>
public class TopTitleStatistics extends Configured implements Tool {
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new TopTitleStatistics(), args);
System.exit(res);
}
@Override
public int run(String[] args) throws Exception {
Configuration conf = this.getConf();
FileSystem fs = FileSystem.get(conf);
Path tmpPath = new Path("/mp2/tmp");
fs.delete(tmpPath, true);
Job jobA = Job.getInstance(conf, "Title Count");
jobA.setOutputKeyClass(Text.class);
jobA.setOutputValueClass(IntWritable.class);
jobA.setMapperClass(TitleCountMap.class);
jobA.setReducerClass(TitleCountReduce.class);
FileInputFormat.setInputPaths(jobA, new Path(args[0]));
FileOutputFormat.setOutputPath(jobA, tmpPath);
jobA.setJarByClass(TopTitleStatistics.class);
jobA.waitForCompletion(true);
Job jobB = Job.getInstance(conf, "Top Titles Statistics");
jobB.setOutputKeyClass(Text.class);
jobB.setOutputValueClass(IntWritable.class);
jobB.setMapOutputKeyClass(NullWritable.class);
jobB.setMapOutputValueClass(TextArrayWritable.class);
jobB.setMapperClass(TopTitlesStatMap.class);
jobB.setReducerClass(TopTitlesStatReduce.class);
jobB.setNumReduceTasks(1);
FileInputFormat.setInputPaths(jobB, tmpPath);
FileOutputFormat.setOutputPath(jobB, new Path(args[1]));
jobB.setInputFormatClass(KeyValueTextInputFormat.class);
jobB.setOutputFormatClass(TextOutputFormat.class);
jobB.setJarByClass(TopTitleStatistics.class);
return jobB.waitForCompletion(true) ? 0 : 1;
}
public static String readHDFSFile(String path, Configuration conf) throws IOException{
Path pt=new Path(path);
FileSystem fs = FileSystem.get(pt.toUri(), conf);
FSDataInputStream file = fs.open(pt);
BufferedReader buffIn=new BufferedReader(new InputStreamReader(file));
StringBuilder everything = new StringBuilder();
String line;
while( (line = buffIn.readLine()) != null) {
everything.append(line);
everything.append("\n");
}
return everything.toString();
}
public static class TextArrayWritable extends ArrayWritable {
public TextArrayWritable() {
super(Text.class);
}
public TextArrayWritable(String[] strings) {
super(Text.class);
Text[] texts = new Text[strings.length];
for (int i = 0; i < strings.length; i++) {
texts[i] = new Text(strings[i]);
}
set(texts);
}
}
// <<< Don't Change
public static class TitleCountMap extends Mapper<Object, Text, Text, IntWritable> {
List<String> stopWords;
String delimiters;
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
String stopWordsPath = conf.get("stopwords");
String delimitersPath = conf.get("delimiters");
this.stopWords = Arrays.asList(readHDFSFile(stopWordsPath, conf).split("\n"));
this.delimiters = readHDFSFile(delimitersPath, conf);
}
@Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line, delimiters);
while (tokenizer.hasMoreTokens()) {
String nextToken = tokenizer.nextToken().trim().toLowerCase();
if (!stopWords.contains(nextToken)) {
context.write(new Text(nextToken), new IntWritable(1));
}
}
}
}
public static class TitleCountReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
context.write(key, new IntWritable(sum));
}
}
public static class TopTitlesStatMap extends Mapper<Text, Text, NullWritable, TextArrayWritable> {
Integer N;
private TreeSet<Pair<Integer, String>> countToWordMap = new TreeSet<Pair<Integer, String>>();
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
this.N = conf.getInt("N", 10);
}
@Override
public void map(Text key, Text value, Context context) throws IOException, InterruptedException {
Integer count = Integer.parseInt(value.toString());
String word = key.toString();
countToWordMap.add(new Pair<Integer, String>(count, word));
if (countToWordMap.size() > N) {
countToWordMap.remove(countToWordMap.first());
}
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
for (Pair<Integer, String> item : countToWordMap) {
String[] strings = {item.second, item.first.toString()};
TextArrayWritable val = new TextArrayWritable(strings);
context.write(NullWritable.get(), val);
}
}
}
public static class TopTitlesStatReduce extends Reducer<NullWritable, TextArrayWritable, Text, IntWritable> {
Integer N;
private TreeSet<Pair<Integer, String>> countToWordMap = new TreeSet<Pair<Integer, String>>();
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
this.N = conf.getInt("N", 10);
}
@Override
public void reduce(NullWritable key, Iterable<TextArrayWritable> values, Context context) throws IOException, InterruptedException {
Integer sum = 0, mean, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE, var;
for (TextArrayWritable val: values) {
Text[] pair= (Text[]) val.toArray();
String word = pair[0].toString();
Integer count = Integer.parseInt(pair[1].toString());
countToWordMap.add(new Pair<Integer, String>(count, word));
if (countToWordMap.size() > N) {
countToWordMap.remove(countToWordMap.first());
}
}
List<Integer> countList = new ArrayList<Integer>();
for (Pair<Integer, String> item: countToWordMap) {
Text word = new Text(item.second);
Integer count = new Integer(item.first);
if (count > max)
max = count;
if (count < min)
min = count;
sum += count;
countList.add(count);
}
mean = sum / N;
for (Integer count : countList) {
var += Math.pow(count - mean, 2);
}
var /= N;
context.write(new Text("Mean"), new IntWritable(mean));
context.write(new Text("Sum"), new IntWritable(sum));
context.write(new Text("Min"), new IntWritable(min));
context.write(new Text("Max"), new IntWritable(max));
context.write(new Text("Var"), new IntWritable(var));
}
}
}
// >>> Don't Change
class Pair<A extends Comparable<? super A>,
B extends Comparable<? super B>>
implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A extends Comparable<? super A>,
B extends Comparable<? super B>>
Pair<A, B> of(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int compareTo(Pair<A, B> o) {
int cmp = o == null ? 1 : (this.first).compareTo(o.first);
return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
}
@Override
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair<?, ?>) obj).first)
&& equal(second, ((Pair<?, ?>) obj).second);
}
private boolean equal(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
// <<< Don't Change
|
package com.jme3.app;
import com.jme3.app.state.AbstractAppState;
import com.jme3.app.state.AppStateManager;
import com.jme3.font.BitmapFont;
import com.jme3.font.BitmapText;
import com.jme3.renderer.RenderManager;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial.CullHint;
/**
* Displays stats in SimpleApplication's GUI node or
* using the node and font parameters provided.
*
* @author Paul Speed
*/
public class StatsAppState extends AbstractAppState {
private Application app;
protected StatsView statsView;
protected boolean showSettings = true;
private boolean showFps = true;
private boolean showStats = true;
protected Node guiNode;
protected float secondCounter = 0.0f;
protected int frameCounter = 0;
protected BitmapText fpsText;
protected BitmapFont guiFont;
public StatsAppState() {
}
public StatsAppState( Node guiNode, BitmapFont guiFont ) {
this.guiNode = guiNode;
this.guiFont = guiFont;
}
public BitmapText getFpsText() {
return fpsText;
}
public float getSecondCounter() {
return secondCounter;
}
public void toggleStats() {
setDisplayFps( !showFps );
setDisplayStatView( !showStats );
}
public void setDisplayFps(boolean show) {
showFps = show;
if (fpsText != null) {
fpsText.setCullHint(show ? CullHint.Never : CullHint.Always);
}
}
public void setDisplayStatView(boolean show) {
showStats = show;
if (statsView != null ) {
statsView.setEnabled(show);
statsView.setCullHint(show ? CullHint.Never : CullHint.Always);
}
}
@Override
public void initialize(AppStateManager stateManager, Application app) {
super.initialize(stateManager, app);
this.app = app;
if (app instanceof SimpleApplication) {
SimpleApplication simpleApp = (SimpleApplication)app;
if (guiNode == null)
guiNode = simpleApp.guiNode;
if (guiFont == null )
guiFont = simpleApp.guiFont;
}
if (guiNode == null) {
throw new RuntimeException( "No guiNode specific and cannot be automatically determined." );
}
if (guiFont == null) {
guiFont = app.getAssetManager().loadFont("Interface/Fonts/Default.fnt");
}
loadFpsText();
loadStatsView();
}
/**
* Attaches FPS statistics to guiNode and displays it on the screen.
*
*/
public void loadFpsText() {
fpsText = new BitmapText(guiFont, false);
fpsText.setLocalTranslation(0, fpsText.getLineHeight(), 0);
fpsText.setText("Frames per second");
fpsText.setCullHint(showFps ? CullHint.Never : CullHint.Always);
guiNode.attachChild(fpsText);
}
/**
* Attaches Statistics View to guiNode and displays it on the screen
* above FPS statistics line.
*
*/
public void loadStatsView() {
statsView = new StatsView("Statistics View",
app.getAssetManager(),
app.getRenderer().getStatistics());
// move it up so it appears above fps text
statsView.setLocalTranslation(0, fpsText.getLineHeight(), 0);
statsView.setEnabled(showStats);
statsView.setCullHint(showStats ? CullHint.Never : CullHint.Always);
guiNode.attachChild(statsView);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (enabled) {
fpsText.setCullHint(showFps ? CullHint.Never : CullHint.Always);
statsView.setEnabled(showStats);
statsView.setCullHint(showStats ? CullHint.Never : CullHint.Always);
} else {
fpsText.setCullHint(CullHint.Always);
statsView.setEnabled(false);
statsView.setCullHint(CullHint.Always);
}
}
@Override
public void update(float tpf) {
if (showFps) {
secondCounter += app.getTimer().getTimePerFrame();
frameCounter ++;
if (secondCounter >= 1.0f) {
int fps = (int) (frameCounter / secondCounter);
fpsText.setText("Frames per second: " + fps);
secondCounter = 0.0f;
frameCounter = 0;
}
}
}
@Override
public void cleanup() {
super.cleanup();
guiNode.detachChild(statsView);
guiNode.detachChild(fpsText);
}
}
|
package scheduling.three;
import graph.Graph;
import graph.VertexColoring;
import java.util.BitSet;
import java.util.LinkedList;
import java.util.Queue;
class ComponentSwapper {
private Graph graph;
private VertexColoring coloring;
/**
* Store colors as object field to avoid passing
* huge amount of arguments to private methods.
*/
private int colorBig, colorSmall, colorOther;
ComponentSwapper(VertexColoring coloring) {
this.coloring = coloring;
this.graph = coloring.getGraph();
}
/**
* Try to swap pairs of components X', Y' of induced graph G(X, Y)
* where X has colorBig and Y has colorSmall as long as it is not
* possible or desired amount of vertices has been moved to Y.
*
* @param colorBig color of bigger color class
* @param colorSmall color of smaller color class
* @param verticesToMove desired change of the coloring width
* @return how much the width was decreased
*/
int swap(int colorBig, int colorSmall, int verticesToMove, LinkedList<Integer> compensator) {
this.colorBig = colorBig;
this.colorSmall = colorSmall;
BitSet checked = new BitSet(graph.getVertices());
int currentColor, verticesMoved, verticesMovedTogether = 0;
for (int i = 0; i < graph.getVertices() && 0 < verticesToMove; i++) {
if (!checked.get(i) && 0 < verticesToMove) {
checked.set(i);
currentColor = coloring.get(i);
if (currentColor == colorBig || currentColor == colorSmall) {
verticesMoved = swapWithCompensating(i, checked, compensator, verticesToMove);
verticesMovedTogether += verticesMoved;
verticesToMove -= verticesMoved;
}
}
}
return verticesMovedTogether;
}
/**
* Swap color classes of component of induced graph that
* contains vertex of currentIndex.
* If difference in sizes of color classes is too big
* compensate it by moving vertices from compensator to smaller class.
*
* @param currentIndex of starting point of finding color classes
* @param checked BitSet of vertices not in use
* @param compensator list of vertices that can be used to compensate
* @param verticesToMove desired maximum difference of size of color classes
* @return how many vertices were moved
*/
private int swapWithCompensating(int currentIndex, BitSet checked,
LinkedList<Integer> compensator, int verticesToMove) {
LinkedList<Integer> bigComponent = new LinkedList<>(), smallComponent = new LinkedList<>();
findComponents(currentIndex, bigComponent, smallComponent, checked);
int sizeDifference = bigComponent.size() - smallComponent.size(), verticesMoved = 0;
if (0 < sizeDifference && sizeDifference <= verticesToMove + compensator.size()) {
int toCompensate = sizeDifference - verticesToMove;
toCompensate = 0 < toCompensate ? toCompensate : 0;
verticesMoved = sizeDifference - toCompensate;
changeColor(bigComponent, colorSmall);
changeColor(smallComponent, colorBig);
changeColor(compensator, colorBig, toCompensate);
}
return verticesMoved;
}
/**
* Try to swap components between color classes
* so that the sizes of all color classes will remain the same.
* Use vertices from compensator to compensate difference
* in sizes of color classes.
*
* @param colorBig color of bigger color class
* @param colorSmall color of smaller color class
* @param compensator list of vertices used to compensate
*/
void swapWithoutDecreasing(int colorBig, int colorSmall, LinkedList<Integer> compensator) {
this.colorBig = colorBig;
this.colorSmall = colorSmall;
BitSet checked = new BitSet(graph.getVertices());
int currentColor;
for (int i = 0; i < graph.getVertices(); i++) {
if (!checked.get(i)) {
currentColor = coloring.get(i);
if (currentColor == colorBig || currentColor == colorSmall) {
if (swapAndRestore(i, checked, compensator)) {
return;
}
}
}
}
}
/**
* Swap color classes of component of induced graph that
* contains vertex of currentIndex and restore sizes of color
* classes by moving vertices from compensator to smaller color class.
*
* @param currentIndex of starting point of finding color classes
* @param checked BitSet of vertices not in use
* @param compensator list of vertices that can be used to compensate
* @return true if swapping took place
*/
private boolean swapAndRestore(int currentIndex, BitSet checked, LinkedList<Integer> compensator) {
LinkedList<Integer> bigComponent = new LinkedList<>(), smallComponent = new LinkedList<>();
findComponents(currentIndex, bigComponent, smallComponent, checked);
int sizeDifference = bigComponent.size() - smallComponent.size();
if (0 < sizeDifference && sizeDifference <= compensator.size()) {
changeColor(bigComponent, colorSmall);
changeColor(smallComponent, colorBig);
changeColor(compensator, colorBig, sizeDifference);
return true;
}
return false;
}
/**
* Try to swap components between color classes
* and move vertices in number of difference in sizes
* of those components from compensator to the third
* color class.
*
* @param colorBig color of bigger color class
* @param colorSmall color of smaller color class
* @param colorOther color of the third color class
* @param compensator list of vertices used to compensate
* @param verticesToMove desired change of the coloring width
* @return how much the width was decreased
*/
int swapAndMoveUntilDecreased(int colorBig, int colorSmall, int colorOther,
LinkedList<Integer> compensator, int verticesToMove) {
this.colorBig = colorBig;
this.colorSmall = colorSmall;
this.colorOther = colorOther;
//TODO otherCompensator for compensating common neighbours
BitSet checked = new BitSet(graph.getVertices());
BooleanArray compensatorArray = vertexListToArray(compensator);
LinkedList<Integer> bigComponent = new LinkedList<>(), smallComponent = new LinkedList<>();
int currentColor, verticesMovedTotal = 0, verticesMoved;
for (int i = 0; i < graph.getVertices() && 0 < verticesToMove; i++) {
if (!checked.get(i)) {
checked.set(i);
currentColor = coloring.get(i);
if (currentColor == colorBig || currentColor == colorSmall) {
findComponents(i, bigComponent, smallComponent, checked);
verticesMoved = useComponentsToDecrease(bigComponent, smallComponent,
compensatorArray, verticesToMove);
verticesMovedTotal += verticesMoved;
verticesToMove -= verticesMoved;
bigComponent.clear();
smallComponent.clear();
}
}
}
return verticesMovedTotal;
}
private int useComponentsToDecrease(LinkedList<Integer> bigComponent,
LinkedList<Integer> smallComponent,
BooleanArray compensator, int verticesToMove) {
//TODO arguments
LinkedList<Integer> small3Big = getFrom3To(smallComponent, colorBig);
int decreasedBy = swapAndMoveToOther(bigComponent, smallComponent,
small3Big, compensator, verticesToMove);
if (0 < decreasedBy) {
return decreasedBy;
}
decreasedBy = moveSoleNeighbours(small3Big, compensator, verticesToMove);
if (0 < decreasedBy) {
return decreasedBy;
}
/*
* Now we know that all vertices in bigComponent
* have exactly 2 neighbours in smallComponent.
*/
if (moveCommonNeighbours(small3Big)) {
return ++decreasedBy;
}
//TODO another vertex from other3Big
return reduceToPathsAndSwap();
}
private int swapAndMoveToOther(LinkedList<Integer> bigComponent,
LinkedList<Integer> smallComponent,
LinkedList<Integer> toRemoveFromCompensator,
BooleanArray compensator, int verticesToMove) {
//TODO
int sizeDifference = bigComponent.size() - smallComponent.size();
if (0 < sizeDifference && sizeDifference <= verticesToMove &&
sizeDifference <= compensator.getCount()) {
if (sizeDifference <= compensator.getCount() - toRemoveFromCompensator.size()) {
/*
* Remove newly forbidden vertices
* from compensator.
*/
for (Integer i : toRemoveFromCompensator) {
compensator.set(i, false);
}
/*
* Compensate swap that will take place
* in a moment using updated compensator.
*/
changeColor(compensator, colorOther, sizeDifference);
/*
* Update compensator with vertices newly
* added to small color class.
*/
for (Integer i : getFrom3To(bigComponent, colorSmall)) {
compensator.set(i);
}
changeColor(bigComponent, colorSmall);
changeColor(smallComponent, colorBig);
return sizeDifference;
}
}
return 0;
}
private int moveSoleNeighbours(LinkedList<Integer> small3Big,
BooleanArray compensator, int verticesToMove) {
int verticesMoved = 0;
for (Integer vertex : small3Big) {
if (0 < verticesToMove) {
for (Integer neighbour: graph.getNeighbours(vertex)) {
if(X3Y.getNeighboursInY(neighbour, colorSmall, coloring) == 1) {
coloring.set(vertex, colorOther);
coloring.set(neighbour, colorSmall);
compensator.set(vertex, false);
verticesMoved++;
verticesToMove
break;
}
}
}
else {
break;
}
}
return verticesMoved;
}
private boolean moveCommonNeighbours(LinkedList<Integer> small3Big) {
//TODO
LinkedList<Integer> potentialWithCommonNeigh = new LinkedList<>(small3Big);
int[] withCommonNeigh;
LinkedList<Integer> commonNeigh;
int x, y, tmp;
int w = X3Y.findOneInX3Y(colorOther, colorBig, coloring);
if (w == X3Y.NO_VERTEX) {
return false;
}
while (!potentialWithCommonNeigh.isEmpty()) {
withCommonNeigh = findSmall3BigWithCommonNeigh(potentialWithCommonNeigh);
if (withCommonNeigh == null) {
break;
}
x = withCommonNeigh[0];
y = withCommonNeigh[1];
commonNeigh = getCommonNeigh(x, y);
if (commonNeigh.size() == 3) {
tmp = x;
x = X3Y.findOneInX3Y(colorOther, colorBig, coloring);
coloring.set(tmp, colorOther);
coloring.set(x, colorSmall);
//TODO changes in components structure and compensator
//TODO changing common neigh and list of potential vertices
}
if (moveCommonAndSpare(x, y, w, commonNeigh, small3Big)) {
return true;
}
}
return false;
}
private int[] findSmall3BigWithCommonNeigh(LinkedList<Integer> small3Big) {
int vertex;
while (!small3Big.isEmpty()) {
vertex = small3Big.poll();
for (Integer neighbour : graph.getNeighbours(vertex)) {
for (Integer otherVertex : graph.getNeighbours(neighbour)) {
if (X3Y.has3NeighboursInY(otherVertex, colorBig, coloring) &&
coloring.get(otherVertex) == colorSmall &&
otherVertex != vertex) {
return new int[]{vertex ,otherVertex};
}
}
}
}
return null;
}
private boolean moveCommonAndSpare(int x, int y, int w, LinkedList<Integer> commonNeigh,
LinkedList<Integer> small3Big) {
for (Integer neighbour : commonNeigh) {
if (!graph.hasEdge(neighbour, w)) {
coloring.set(neighbour, colorSmall);
coloring.set(w, colorSmall);
coloring.set(x, colorOther);
coloring.set(y, colorOther);
return true;
}
}
if (2 < small3Big.size()) {
for (Integer z : small3Big) {
if (z != x && z != y) {
coloring.set(commonNeigh.poll(), colorOther);
coloring.set(w, colorSmall);
coloring.set(z, colorOther);
return true;
}
}
}
return false;
}
private int reduceToPathsAndSwap() {
//TODO
return 0;
}
/**
* Find components within induced graph of
* two given color starting from vertex with
* current index.
*
* @param current index to start with
* @param bigComponent container of indexes to fill
* @param smallComponent container of indexes to fill
*/
private void findComponents(int current, LinkedList<Integer> bigComponent,
LinkedList<Integer> smallComponent, BitSet checked) {
Queue<Integer> queue = new LinkedList<>();
int currentColor, otherColor;
queue.add(current);
while (!queue.isEmpty()) {
current = queue.poll();
currentColor = coloring.get(current);
if (currentColor == colorBig) {
otherColor = colorSmall;
bigComponent.add(current);
} else {
otherColor = colorBig;
smallComponent.add(current);
}
for (Integer neighbour : graph.getNeighbours(current)) {
if (coloring.get(neighbour) == otherColor && !checked.get(neighbour)) {
queue.add(neighbour);
}
checked.set(neighbour);
}
}
}
private void markComponentsAsChecked(int current, BitSet checked) {
Queue<Integer> queue = new LinkedList<>();
queue.add(current);
while (!queue.isEmpty()) {
current = queue.poll();
for (Integer neighbour : graph.getNeighbours(current)) {
if (coloring.get(neighbour) == colorOther && !checked.get(neighbour)) {
queue.add(neighbour);
}
checked.set(neighbour);
}
}
}
private LinkedList<Integer> findPathInReduced(int current, BitSet checked) {
//TODO
Queue<Integer> queue = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
int currentColor, otherColor, neighbourInSmall3Big;
boolean notInPath;
queue.add(current);
while (!queue.isEmpty()) {
current = queue.poll();
currentColor = coloring.get(current);
notInPath = false;
if (currentColor == colorBig) {
otherColor = colorSmall;
neighbourInSmall3Big = 0;
for (Integer neighbour : graph.getNeighbours(current)) {
if (coloring.get(neighbour) == colorOther &&
X3Y.has3NeighboursInY(neighbour, currentColor, coloring)) {
if (0 < neighbourInSmall3Big++) {
notInPath = true;
break;
}
}
}
} else {
otherColor = colorBig;
if (X3Y.has3NeighboursInY(current, otherColor, coloring)) {
notInPath = true;
}
}
if (notInPath) {
continue;
}
path.add(current);
for (Integer neighbour : graph.getNeighbours(current)) {
if (coloring.get(neighbour) == otherColor && !checked.get(neighbour)) {
queue.add(neighbour);
}
checked.set(neighbour);
}
}
return path;
}
/**
* Change n vertices from vertices list to
* given color and remove them from list.
*
* @param vertices list of available vertices
* @param color that vertices will now have
* @param n number of vertices to be changed
* @return number of vertices changed
*/
int changeColor(LinkedList<Integer> vertices, int color, int n) {
int changed = 0;
for (int i = 0; 0 < vertices.size() && changed < n; i++) {
coloring.set(vertices.poll(), color);
changed++;
}
return changed;
}
private void changeColor(LinkedList<Integer> vertices, int color) {
changeColor(vertices, color, vertices.size());
}
/**
* Change n vertices that have 1 assigned in the bit set
* to a given color.
*
* @param vertices bit set with 1 for all available vertices
* @param color that vertices will now have
* @param n number of vertices to change color
*/
private void changeColor(BitSet vertices, int color, int n) {
for (int i = 0; i < vertices.size() && 0 < n; i++) {
if (vertices.get(i)) {
coloring.set(i, color);
n
}
}
}
/**
* Set all the bits representing vertices in list to 1.
*
* @param list of vertices to put in BitSet
* @return BooleanArray representing list
*/
private BooleanArray vertexListToArray(LinkedList<Integer> list) {
BooleanArray booleanArray = new BooleanArray(graph.getVertices());
for (Integer i : list) {
booleanArray.set(i);
}
return booleanArray;
}
private LinkedList<Integer> getFrom3To(LinkedList<Integer> fromComponent, int toColor) {
LinkedList<Integer> big3Small = new LinkedList<>();
for (Integer i : fromComponent) {
if (X3Y.has3NeighboursInY(i, toColor, coloring)) {
big3Small.add(i);
}
}
return big3Small;
}
private LinkedList<Integer> getCommonNeigh(int x, int y) {
LinkedList<Integer> xNeigh = graph.getNeighbours(x), commonNeigh = new LinkedList<>();
for (Integer neighbour : graph.getNeighbours(y)) {
if (xNeigh.contains(neighbour)) {
commonNeigh.add(neighbour);
}
}
return commonNeigh;
}
}
|
package se.z_app.zmote.gui;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.ImageView;
/**
* First screen loaded with the current STB logo and loading animation
* @author Francisco Valladares
*
*/
public class SplashActivity extends Activity {
private final int SPLASH_DISPLAY_LENGTH = 1000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Bootstrap(this.getApplicationContext(), (WifiManager) getSystemService(WIFI_SERVICE));
setContentView(R.layout.activity_splash);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_splash, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
ImageView iView = (ImageView) findViewById(R.id.opLogo);
iView.setImageResource(R.drawable.tele2);
new Handler().postDelayed(new Runnable() {
public void run() {
//Finish the splash activity so it can't be returned to.
SplashActivity.this.finish();
// Create an Intent that will start the main activity.
Intent mainIntent = new Intent(SplashActivity.this,
SelectSTBActivity.class);
SplashActivity.this.startActivity(mainIntent);
}
}, SPLASH_DISPLAY_LENGTH);
}
}
|
package semanticMarkup.ling.learn;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import semanticMarkup.core.Treatment;
import semanticMarkup.know.IGlossary;
import semanticMarkup.know.lib.WordNetPOSKnowledgeBase;
import semanticMarkup.ling.Token;
import semanticMarkup.ling.learn.auxiliary.GetNounsAfterPtnReturnValue;
import semanticMarkup.ling.learn.auxiliary.KnownTagCollection;
import semanticMarkup.ling.learn.auxiliary.POSInfo;
import semanticMarkup.ling.learn.auxiliary.SentenceLeadLengthComparator;
import semanticMarkup.ling.learn.auxiliary.StringAndInt;
import semanticMarkup.ling.learn.dataholder.DataHolder;
import semanticMarkup.ling.learn.dataholder.ModifierTableValue;
import semanticMarkup.ling.learn.dataholder.SentenceStructure;
import semanticMarkup.ling.learn.dataholder.WordPOSKey;
import semanticMarkup.ling.learn.dataholder.WordPOSValue;
import semanticMarkup.ling.learn.knowledge.Constant;
import semanticMarkup.ling.learn.knowledge.Initiation;
import semanticMarkup.ling.learn.knowledge.MarkupByPOS;
import semanticMarkup.ling.learn.knowledge.UnknownWordBootstrapping;
import semanticMarkup.ling.learn.utility.LearnerUtility;
import semanticMarkup.ling.learn.utility.StringUtility;
import semanticMarkup.ling.transform.ITokenizer;
public class Learner {
private static final Set<String> NONS = null;
private Configuration myConfiguration;
private ITokenizer myTokenizer;
// Data holder
private DataHolder myDataHolder;
// Learner utility
private LearnerUtility myLearnerUtility;
// Class variables
private int NUM_LEAD_WORDS; // Number of leading words
// leading three words of sentences
private Set<String> checkedWordSet;
private String defaultGeneralTag;
// modules
Initiation initiationModule;
UnknownWordBootstrapping unknownWordBootstrappingModule;
MarkupByPOS markupByPOS;
Map<String, Boolean> checkedModifiers;
public Learner(Configuration configuration, ITokenizer tokenizer,
LearnerUtility learnerUtility) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("Learner");
this.myConfiguration = configuration;
this.myTokenizer = tokenizer;
// Utilities
this.myLearnerUtility = learnerUtility;
// Data holder
this.myDataHolder = new DataHolder(myConfiguration,
myLearnerUtility.getWordFormUtility());
// Class variables
NUM_LEAD_WORDS = this.myConfiguration.getNumLeadWords(); // Set the
// number of
// leading
// words be
checkedWordSet = new HashSet<String>();
this.defaultGeneralTag = "general";
myLogger.info("Created Learner");
myLogger.info("\tLearning Mode: " + myConfiguration.getLearningMode());
myLogger.info("\tMax Tag Lengthr: " + myConfiguration.getMaxTagLength());
myLogger.info("\n");
initiationModule = new Initiation(this.myLearnerUtility,
this.NUM_LEAD_WORDS);
unknownWordBootstrappingModule = new UnknownWordBootstrapping(
this.myLearnerUtility);
markupByPOS = new MarkupByPOS(this.myLearnerUtility);
this.checkedModifiers = new HashMap<String, Boolean>();
}
public DataHolder Learn(List<Treatment> treatments, IGlossary glossary,
String markupMode) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("Learn");
myLogger.trace("Enter Learn");
myLogger.trace(String.format("Learning Mode: %s",
this.myConfiguration.getLearningMode()));
// this.populateSentence(treatments);
// this.populateUnknownWordsTable(this.myDataHolder.allWords);
this.initiationModule.loadTreatments(treatments);
this.initiationModule.run(myDataHolder);
/*
* Map<String, String> mygetHeuristicNounHolder() =
* myDataHolder.getgetHeuristicNounHolder()();
* myHeuristicNounTable.put("word1", "type1");
*
* List<Sentence> mygetSentenceHolder() =
* myDataHolder.getgetSentenceHolder()(); mygetSentenceHolder().add(new
* Sentence("source1", "sentence1", "originalSentence", "lead1",
* "status1", "tag1", "modifier1", "type1"));
*/
// List<String> fileNameList = fileLoader.getFileNameList();
// List<Integer> typeList = fileLoader.getTypeList();
// List<String> textList = fileLoader.getTextList();
// process treatments
// this.populateSentences(treatments);
// pre load words
this.addHeuristicsNouns();
this.addPredefinedWords();
this.posBySuffix();
this.resetCounts(myDataHolder);
this.markupByPattern();
this.markupIgnore();
// learning rules with high certainty
// At the every beginning, only those sentence whose first word is a p,
// could have a tag of "start", see populateSentece - getFirstNWords
// section -Dongye
myLogger.info("Learning rules with high certainty:");
this.discover("start");
// bootstrapping rules
myLogger.info("Bootstrapping rules:");
this.discover("normal");
// myDataHolder.write2File("");here!!!
myLogger.info("Additional bootstrappings:");
this.additionalBootstrapping();
myLogger.info("Unknownword bootstrappings:");
// this.unknownWordBootstrapping();
this.unknownWordBootstrappingModule.run(myDataHolder);
myLogger.info("Adjectives Verification:");
this.adjectivesVerification(myDataHolder);
this.separateModifierTag(myDataHolder);
this.resolveNMB(myDataHolder);
this.setAndOr(myDataHolder);
if (StringUtils.equals(this.myConfiguration.getLearningMode(), "adj")) {
// print STDOUT
// "::::::::::::::::::::::::Bootstrapping on adjective subjects: \n";
// adjectivesubjectbootstrapping()
} else {
int v = 0;
do {
v = 0;
this.handleAndOr(myDataHolder);
} while (v > 0);
}
this.resetAndOrTags(myDataHolder);
this.getLearnerUtility().tagAllSentences(myDataHolder, "singletag",
"sentence");
this.markupByPOS.run(myDataHolder);
this.phraseClause(myDataHolder);
this.ditto(myDataHolder);
this.pronounCharacterSubject(myDataHolder);
this.finalizeIgnored(myDataHolder);
this.remainNullTag(myDataHolder);
if (StringUtils.equals(this.myConfiguration.getLearningMode(), "adj")) {
// this.commonSubstructure(myDataHolder);
}
myDataHolder.write2File("");
myLogger.info("Learning done!");
// myLogger.info(myDataHolder.toString());
// myLogger.info(myDataHolder.getSentenceHolder().toString());
// myLogger.info(this.myDataHolder.getHeuristicNounHolder().toString());
// myLogger.info(myDataHolder.getSentenceHolder().get(0).toString());
return myDataHolder;
}
public void addGlossary(IGlossary glossary) {
if (glossary != null) {
String category = "struture";
Set<String> pWords = glossary.getWords(category);
Set<String> categories = new HashSet<String>();
categories.add(category);
Set<String> bWords = glossary.getWordsNotInCategories(categories);
this.getDataHolder().addWords2WordPOSHolder(pWords, "p");
this.getDataHolder().addWords2WordPOSHolder(bWords, "b");
}
}
private void addPredefinedWords() {
this.addStopWords();
this.addCharacters();
this.addNumbers();
this.addClusterStrings();
this.addProperNouns();
}
/**
*
* @return
*/
public DataHolder getDataHolder() {
return this.myDataHolder;
}
public void addHeuristicsNouns() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.addHeuristicsNouns");
myLogger.trace("Enter addHeuristicsNouns");
Set<String> nouns = this.learnHeuristicsNouns();
myLogger.debug("Nouns learned from heuristics:");
myLogger.debug("\t" + nouns.toString());
myLogger.debug("Total: " + nouns.size());
List<Set<String>> results = this.characterHeuristics();
Set<String> rnouns = results.get(0);
Set<String> descriptors = results.get(1);
addDescriptors(descriptors);
addNouns(rnouns);
// this.myDataHolder.printHolder(DataHolder.SINGULAR_PLURAL);
myLogger.debug("Total: " + nouns.size());
Iterator<String> iter = nouns.iterator();
myLogger.info("Learn singular-plural pair");
while (iter.hasNext()) {
String e = iter.next();
myLogger.trace("Check Word: " + e);
if ((e.matches("^.*\\w.*$"))
&& (!StringUtility.isMatchedWords(e, "NUM|"
+ Constant.NUMBER + "|" + Constant.CLUSTERSTRING
+ "|" + Constant.CHARACTER + "|"
+ Constant.PROPERNOUN))) {
myLogger.trace("Pass");
// same word may have two different pos tags
String[] nounArray = e.split("\\|");
for (int i = 0; i < nounArray.length; i++) {
String nounAndPOS = nounArray[i];
Pattern p = Pattern.compile("(\\w+)\\[([spn])\\]");
Matcher m = p.matcher(nounAndPOS);
if (m.lookingAt()) {
String word = m.group(1);
String pos = m.group(2);
this.myDataHolder.updateDataHolder(word, pos, "*",
"wordpos", 0);
if (pos.equals("p")) {
String plural = word;
String singular = this.myLearnerUtility
.getWordFormUtility().getSingular(plural);
if (singular != null) {
if (!singular.equals("")) {
this.myDataHolder.addSingularPluralPair(
singular, plural);
}
}
}
if (pos.equals("s")) {
String singular = word;
List<String> pluralList = this.myLearnerUtility
.getWordFormUtility().getPlural(singular);
Iterator<String> pluralIter = pluralList.iterator();
while (pluralIter.hasNext()) {
String plural = pluralIter.next();
if (plural != null) {
if (!plural.equals("")) {
this.myDataHolder
.addSingularPluralPair(
singular, plural);
}
}
}
}
}
}
}
}
myLogger.trace("Quite addHeuristicsNouns");
}
/**
*
* @param descriptors
*/
public void addDescriptors(Set<String> descriptors) {
Iterator<String> iter = descriptors.iterator();
while (iter.hasNext()) {
String descriptor = iter.next();
if (!StringUtility.isMatchedWords(descriptor, Constant.FORBIDDEN)) {
this.myDataHolder.updateDataHolder(descriptor, "b", "",
"wordpos", 1);
}
}
}
/**
*
* @param rnouns
*/
public void addNouns(Set<String> rnouns) {
Iterator<String> iter = rnouns.iterator();
while (iter.hasNext()) {
String noun = iter.next();
if (!StringUtility.isMatchedWords(noun, Constant.FORBIDDEN)) {
this.myDataHolder.updateDataHolder(noun, "n", "", "wordpos", 1);
}
}
}
/**
*
* @return nouns learned by heuristics
*/
public Set<String> learnHeuristicsNouns() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.addHeuristicsNouns.learnHeuristicsNouns");
// Set of words
Set<String> words = new HashSet<String>();
// Set of nouns
Set<String> nouns = new HashSet<String>();
List<String> sentences = new LinkedList<String>();
for (int i = 0; i < this.myDataHolder.getSentenceHolder().size(); i++) {
String originalSentence = this.myDataHolder.getSentenceHolder()
.get(i).getOriginalSentence();
myLogger.trace("Original Sentence: " + originalSentence);
sentences.add(StringUtility.strip(originalSentence));
}
// Now we have original sentences in sentences
// Method addWords
for (int i = 0; i < sentences.size(); i++) {
String sentence = sentences.get(i);
sentence = sentence.toLowerCase();
String noun = this.getPresentAbsentNouns(sentence);
if (!noun.equals("")) {
nouns.add(noun);
}
// add words
List<String> tokens = this.myLearnerUtility.tokenizeText(sentence,
"all");
for (String token : tokens) {
if (StringUtility.isWord(token)) {
words.add(token);
myLogger.trace("Add a word into words: " + token);
}
}
}
// solve the problem: septa and septum are both s
Iterator<String> nounsIterator = nouns.iterator();
while (nounsIterator.hasNext()) {
String oldNoun = nounsIterator.next();
String newNoun = this.getHeuristicsNounsHelper(oldNoun, nouns);
if (!newNoun.equals(oldNoun)) {
nouns.remove(oldNoun);
nouns.add(newNoun);
}
}
// sort all words
Map<String, Set<String>> wordMap = new HashMap<String, Set<String>>();
Iterator<String> wordsIterator = words.iterator();
while (wordsIterator.hasNext()) {
String word = wordsIterator.next();
String root = myLearnerUtility.getWordFormUtility().getRoot(word);
if (wordMap.containsKey(root)) {
Set<String> wordList = wordMap.get(root);
wordList.add(word);
// List<String> wordList2 = wordMap.get(root);
// System.out.println(wordList2);
} else {
Set<String> wordList = new HashSet<String>();
wordList.add(word);
wordMap.put(root, wordList);
}
}
// print out the wordMap
myLogger.trace("WordMap:");
Iterator<Map.Entry<String, Set<String>>> wordMapIter = wordMap
.entrySet().iterator();
while (wordMapIter.hasNext()) {
Map.Entry<String, Set<String>> e = wordMapIter.next();
myLogger.trace(e.toString());
}
// find nouns
myLogger.info("Learn singular-plural pair");
Iterator<Map.Entry<String, Set<String>>> iter = wordMap.entrySet()
.iterator();
while (iter.hasNext()) {
Map.Entry<String, Set<String>> e = iter.next();
Set<String> wordSet = e.getValue();
Iterator<String> wordIterator = wordSet.iterator();
while (wordIterator.hasNext()) {
String word = wordIterator.next();
// getnouns
if (word.matches("^.*" + Constant.NENDINGS)) {
nouns.add(word + "[s]");
if (wordSet.contains(word + "s")) {
nouns.add(word + "s" + "[p]");
this.myDataHolder.addSingularPluralPair(word, word
+ "s");
}
if (wordSet.contains(word + "es")) {
nouns.add(word + "es" + "[p]");
this.myDataHolder.addSingularPluralPair(word, word
+ "es");
}
}
}
}
// Iterator<LinkedList> wordMapIterator = wordMap.i
Iterator<Map.Entry<String, Set<String>>> wordMapIterator = wordMap
.entrySet().iterator();
while (wordMapIterator.hasNext()) {
Map.Entry<String, Set<String>> wordMapEntry = wordMapIterator
.next();
Set<String> wordSet = wordMapEntry.getValue();
// check if there is a word with Vending
boolean hasVending = false;
// for (int i1 = 0; i1 < wordList.size(); i1++) {
Iterator<String> wordIterator = wordSet.iterator();
while (wordIterator.hasNext()) {
String tempWord = wordIterator.next();
if (tempWord.matches("^.*" + Constant.VENDINGS)) {
hasVending = true;
break;
}
}
// at least two words without verb endings
if ((!hasVending) && (wordSet.size() > 1)) {
List<String> wordList = new LinkedList<String>(wordSet);
for (int i = 0; i < wordList.size(); i++) {
for (int j = i + 1; j < wordList.size(); j++) {
String word1 = wordList.get(i);
String word2 = wordList.get(j);
List<String> pair = myLearnerUtility
.getWordFormUtility().getSingularPluralPair(
word1, word2);
if (pair.size() == 2) {
String singular = pair.get(0);
String plural = pair.get(1);
nouns.add(singular + "[s]");
nouns.add(plural + "[p]");
this.myDataHolder.addSingularPluralPair(singular,
plural);
}
}
}
}
}
// print out nouns
myLogger.debug("Nouns: " + nouns);
return nouns;
}
// #solve the problem: septa and septum are both s
// septum - Singular
// septa -Plural
// septa[s] => septa[p]
public String getHeuristicsNounsHelper(String oldNoun, Set<String> words) {
String newNoun = oldNoun;
if (oldNoun.matches("^.*a\\[s\\]$")) {
String noun = oldNoun.replaceAll("\\[s\\]", "");
if (words.contains(noun)) {
newNoun = noun + "[p]";
}
}
return newNoun;
}
/**
* any word preceeding "present"/"absent" would be a n
*
* @param text
* the content to learn from
* @return nouns learned
*/
public String getPresentAbsentNouns(String text) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.addHeuristicsNouns.learnHeuristicsNouns.getPresentAbsentNouns");
String pachecked = "and|or|to";
// if (text.matches("(\\w+?)\\s+(present|absent)")) {
// System.out.println(text);
Matcher matcher = Pattern.compile("^.*?(\\w+?)\\s+(present|absent).*$")
.matcher(text);
if (matcher.lookingAt()) {
String word = matcher.group(1);
if ((!word.matches("\\b(" + pachecked + ")\\b"))
&& (!word.matches("\\b(" + Constant.STOP + ")\\b"))
&& (!word
.matches("\\b(always|often|seldom|sometimes|[a-z]+ly)\\b"))) {
myLogger.trace("present/absent " + word);
if (((word.matches("^.*" + Constant.PENDINGS))
|| (word.matches("^.*[^s]s$")) || (word
.matches("teeth")))
&& (!word.matches(Constant.SENDINGS))) {
return word + "[p]";
} else {
return word + "[s]";
}
}
}
return "";
}
/**
* Discover nouns and descriptors according to a set of rules
*
* @return a linked list, whose first element is a set of nouns, and second
* element is a set of descriptors
*/
public List<Set<String>> characterHeuristics() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.addHeuristicsNouns.characterHeuristics");
Set<String> taxonNames = new HashSet<String>();
Set<String> nouns = new HashSet<String>();
Set<String> anouns = new HashSet<String>();
Set<String> pnouns = new HashSet<String>();
Set<String> descriptors = new HashSet<String>();
Map<String, Boolean> descriptorMap = new HashMap<String, Boolean>();
int sent_num = this.myDataHolder.getSentenceHolder().size();
for (int i = 0; i < sent_num; i++) {
// taxon rule
SentenceStructure sent = this.myDataHolder.getSentenceHolder().get(
i);
String source = sent.getSource();
String sentence = sent.getSentence();
String originalSentence = sent.getOriginalSentence();
myLogger.trace("Source: " + source);
myLogger.trace("Sentence: " + sentence);
myLogger.trace("Original Sentence: " + originalSentence);
originalSentence = StringUtility.trimString(originalSentence);
// noun rule 0: taxon names
taxonNames = this.getTaxonNameNouns(originalSentence);
// $sentence =~ s#<\s*/?\s*i\s*>##g;
// $originalsent =~ s#<\s*/?\s*i\s*>##g;
sentence = sentence.replaceAll("<\\s*/?\\s*i\\s*>", "");
originalSentence = originalSentence.replaceAll("<\\s*/?\\s*i\\s*>",
"");
// Update getSentenceHolder()
this.myDataHolder.getSentenceHolder().get(i).setSentence(sentence);
// noun rule 0.5: Meckle#s cartilage
Set<String> nouns0 = this
.getNounsMecklesCartilage(originalSentence);
nouns.addAll(nouns0);
sentence = sentence.replaceAll("
// Update getSentenceHolder()
this.myDataHolder.getSentenceHolder().get(i).setSentence(sentence);
// noun rule 2: end of sentence nouns
// (a|an|the|some|any|this|that|those|these) noun$
Set<String> nouns2 = this.getNounsRule2(originalSentence);
nouns.addAll(nouns2);
// noun rule 3: proper nouns and acronyms
String copy = originalSentence;
Set<String> nouns_temp = this.getNounsRule3Helper(copy);
Iterator<String> iter = nouns_temp.iterator();
while (iter.hasNext()) {
String token = iter.next();
if (token.matches("^.*[A-Z].+$")
&& (!token.matches("^.*-\\w+ed$"))) {
if (token.matches("^[A-Z0-9]+$")) {
token = token.toLowerCase();
anouns.add(token);
} else {
token = token.toLowerCase();
pnouns.add(token);
}
nouns.add(token);
}
}
// noun rule 1: sources with 1 _ are character statements, 2 _ are
// descriptions
Set<String> nouns1 = getNounsRule1(source, originalSentence,
descriptorMap);
nouns.addAll(nouns1);
// noun rule 4: non-stop/prep followed by a number: epibranchial 4
// descriptor heuristics
Set<String> nouns4 = this.getNounsRule4(originalSentence);
nouns.addAll(nouns4);
// remove puncts for descriptor rules
originalSentence = StringUtility.removePunctuation(
originalSentence, "-");
// System.out.println("oSent:");
// System.out.println(originalSentence);
// Descriptor rule 1: single term descriptions are descriptors
descriptors.addAll(this.getDescriptorsRule1(source,
originalSentence, nouns));
// Descriptor rule 2: (is|are) red: isDescriptor
descriptors.addAll(this.getDescriptorsRule2(originalSentence,
descriptorMap));
}
nouns = this.filterOutDescriptors(nouns, descriptors);
anouns = this.filterOutDescriptors(anouns, descriptors);
pnouns = this.filterOutDescriptors(pnouns, descriptors);
this.getDataHolder().add2HeuristicNounTable(nouns, "organ");
this.getDataHolder().add2HeuristicNounTable(anouns, "acronyms");
this.getDataHolder().add2HeuristicNounTable(pnouns, "propernouns");
this.getDataHolder().add2HeuristicNounTable(taxonNames, "taxonnames");
nouns.addAll(anouns);
nouns.addAll(pnouns);
nouns.addAll(taxonNames);
List<Set<String>> results = new LinkedList<Set<String>>();
results.add(nouns);
results.add(descriptors);
return results;
}
/**
* filter out descriptors from nouns, and return remaining nouns
*
* @param rNouns
* set of nouns
* @param rDescriptors
* set of descriptors
* @return set of nouns that are not descriptors
*/
public Set<String> filterOutDescriptors(Set<String> rNouns,
Set<String> rDescriptors) {
Set<String> filtedNouns = new HashSet<String>();
Iterator<String> iter = rNouns.iterator();
while (iter.hasNext()) {
String noun = iter.next();
noun = noun.toLowerCase();
Pattern p = Pattern.compile("\\b(" + Constant.PREPOSITION + "|"
+ Constant.STOP + ")\\b", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(noun);
if ((!m.lookingAt()) && (!rDescriptors.contains(noun))) {
filtedNouns.add(noun);
}
}
return filtedNouns;
}
/**
* Nouns rule 0: get <i></i> enclosed taxon names
*
* @param oSent
* @return
*/
public Set<String> getTaxonNameNouns(String oSent) {
Set<String> taxonNames = new HashSet<String>();
String regex = "(.*?)<\\s*i\\s*>\\s*([^<]*)\\s*<\\s*\\/\\s*i\\s*>(.*)";
String copy = oSent;
while (true) {
Matcher matcher = Pattern.compile(regex).matcher(copy);
if (matcher.lookingAt()) {
String taxonName = matcher.group(2);
if (taxonName.length() > 0) {
taxonNames.add(taxonName);
String[] taxonNameArray = taxonName.split("\\s+");
for (int i = 0; i < taxonNameArray.length; i++) {
taxonNames.add(taxonNameArray[i]);
}
copy = matcher.group(3);
} else {
break;
}
} else {
break;
}
}
return taxonNames;
}
/**
* Nouns rule 0.5: Meckle#s cartilage
*
* @param oSent
* @return
*/
public Set<String> getNounsMecklesCartilage(String oSent) {
Set<String> nouns = new HashSet<String>();
String regex = "^.*\\b(\\w+
Matcher m = Pattern.compile(regex).matcher(oSent);
if (m.lookingAt()) {
String noun = "";
noun = m.group(1);
noun = noun.toLowerCase();
nouns.add(noun);
noun = noun.replaceAll("
nouns.add(noun);
noun = noun.replaceAll("s$", "");
nouns.add(noun);
}
return nouns;
}
/**
*
* @param source
* @param originalSentence
* @param descriptorMap
* @return
*/
public Set<String> getNounsRule1(String source, String originalSentence,
Map<String, Boolean> descriptorMap) {
Set<String> nouns = new HashSet<String>();
if ((!(source.matches("^.*\\.xml_\\S+_.*$")))
&& (!(originalSentence.matches("^.*\\s.*$")))) {
if (!this.isDescriptor(originalSentence, descriptorMap)) {
originalSentence = originalSentence.toLowerCase();
nouns.add(originalSentence);
}
}
return nouns;
}
/**
*
* @param oSent
* @return
*/
public Set<String> getNounsRule2(String oSent) {
String copy = oSent;
String regex = "(.*?)\\b(a|an|the|some|any|this|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth) +(\\w+)\\s*($|\\(|\\[|\\{|\\b"
+ Constant.PREPOSITION + "\\b)(.*)";
Set<String> nouns = new HashSet<String>();
while (true) {
if (copy == null) {
break;
}
Matcher m = Pattern.compile(regex).matcher(copy);
if (m.lookingAt()) {
String t = m.group(3);
String prep = m.group(4);
copy = m.group(5);
if (prep.matches("^.*\\w.*$")
&& t.matches("^.*\\b(length|width|presence|\\w+tion)\\b.*$")) {
continue;
}
t = t.toLowerCase();
nouns.add(t);
} else {
break;
}
}
return nouns;
}
/**
*
* @param sentence
* @return
*/
public Set<String> getNounsRule3Helper(String sentence) {
Set<String> nouns = new HashSet<String>();
String[] segs = sentence.split("[()\\[\\]\\{\\}]");
for (int i1 = 0; i1 < segs.length; i1++) {
String seg = segs[i1];
seg = StringUtility.removePunctuation(seg, "-");
String[] tokens = seg.split("\\s+");
// #ignore the first word in character statements--this is normally
// capitalized
for (int j = 1; j < tokens.length; j++) {
String token = tokens[j];
if (token.matches("^.*[A-Z].+$")
&& (!token.matches("^.*-\\w+ed$"))) {
nouns.add(token);
}
}
}
return nouns;
}
/**
* noun rule 4: non-stop/prep followed by a number: epibranchial 4
* descriptor heuristics
*
* @param oSent
* @return a set of nouns
*/
public Set<String> getNounsRule4(String oSent) {
Set<String> nouns = new HashSet<String>();
String copy = oSent;
String regex = "(.*?)\\s(\\w+)\\s+\\d+(.*)";
while (true) {
if (copy == null) {
break;
}
Matcher m = Pattern.compile(regex).matcher(copy);
if (m.lookingAt()) {
String t = m.group(2);
copy = m.group(3);
String regex2 = "\\b(" + Constant.PREPOSITION + "|"
+ Constant.STOP + ")\\b";
if (!t.matches(regex2)) {
t = t.toLowerCase();
nouns.add(t);
}
} else {
break;
}
}
return nouns;
}
/**
*
* @param source
* @param sentence
* @param nouns
* @return
*/
public Set<String> getDescriptorsRule1(String source, String sentence,
Set<String> nouns) {
Set<String> descriptors = new HashSet<String>();
// single word
if (source.matches("^.*\\.xml_\\S+_.*$")
&& (!sentence.matches("^.*\\s.*$"))) {
Iterator<String> iter = nouns.iterator();
boolean isExist = false;
while (iter.hasNext()) {
String noun = iter.next();
if (noun.equals(sentence)) {
isExist = true;
break;
}
}
if (isExist == false) {
sentence = sentence.toLowerCase();
descriptors.add(sentence);
}
}
return descriptors;
}
/**
* (is|are) red: isDescriptor
*
* @param oSent
* @return
*/
public Set<String> getDescriptorsRule2(String sentence,
Map<String, Boolean> descriptorMap) {
Set<String> descriptors = new HashSet<String>();
String[] tokens = sentence.split("\\s+");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
token = token.toLowerCase();
if (isDescriptor(token, descriptorMap)) {
token = token.toLowerCase();
descriptors.add(token);
}
}
return descriptors;
}
/**
* Check if the term is a descriptor
*
* @param term
* @param descriptorMap
* descriptors have already learned
* @return a boolean value indicating whether the term is a descriptor. This
* result will be stored in the descriptorMap for future use
*/
public boolean isDescriptor(String term, Map<String, Boolean> descriptorMap) {
if (descriptorMap.containsKey(term)) {
if (descriptorMap.get(term).booleanValue()) {
return true;
} else {
return false;
}
} else {
for (int i = 0; i < this.myDataHolder.getSentenceHolder().size(); i++) {
String originalSentence = this.myDataHolder.getSentenceHolder()
.get(i).getOriginalSentence();
if (isMatched(originalSentence, term, descriptorMap)) {
return true;
}
}
term = term.toLowerCase();
descriptorMap.put(term, false);
return false;
}
}
/**
* Check if the term matches the sentence
*
* @param sentence
* @param term
* @param descriptorMap
* @return a boolean value indicating whether the term matches the sentence
*/
public boolean isMatched(String sentence, String term,
Map<String, Boolean> descriptorMap) {
if (sentence.matches("^.*" + " (is|are|was|were|be|being) " + term
+ ".*$")) {
term = term.toLowerCase();
descriptorMap.put(term, true);
return true;
} else {
return false;
}
}
public void addStopWords() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.addStopWords");
myLogger.trace("Add stop words");
List<String> stops = new ArrayList<String>();
stops.addAll(Arrays.asList(Constant.STOP.split("\\|")));
stops.addAll(Arrays.asList(new String[] { "NUM", "(", "[", "{", ")",
"]", "}", "d+" }));
myLogger.trace("Stop Words: " + stops);
for (int i = 0; i < stops.size(); i++) {
String word = stops.get(i);
if (word.matches("\\b(" + Constant.FORBIDDEN + ")\\b")) {
continue;
}
this.myDataHolder.updateDataHolder(word, "b", "*", "wordpos", 0);
myLogger.trace(String.format(
"(\"%s\", \"b\", \"*\", \"wordpos\", 0) added\n", word));
// this.getWordPOSHolder().put(new WordPOSKey(word, "b"), new
// WordPOSValue("*", 0, 0, null, null));
// System.out.println("Add Stop Word: " + word+"\n");
}
myLogger.trace("Quite\n");
}
public void addCharacters() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.addCharacters");
myLogger.trace("Add characters");
List<String> chars = new ArrayList<String>();
chars.addAll(Arrays.asList(Constant.CHARACTER.split("\\|")));
// System.out.println(chars);
// System.out.println(Constant.CHARACTER);
for (int i = 0; i < chars.size(); i++) {
String word = chars.get(i);
// String reg="\\b("+Constant.FORBIDDEN+")\\b";
// boolean f = word.matches(reg);
if (word.matches("\\b(" + Constant.FORBIDDEN + ")\\b")) {
continue;
}
this.myDataHolder.updateDataHolder(word, "b", "*", "wordpos", 0);
// this.getWordPOSHolder().put(new WordPOSKey(word, "b"), new
// WordPOSValue("", 0, 0, null, null));
// System.out.println("addCharacter word: " + word);
}
}
public void addNumbers() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.addNumbers");
myLogger.trace("Add numbers");
List<String> nums = new ArrayList<String>();
nums.addAll(Arrays.asList(Constant.NUMBER.split("\\|")));
// System.out.println(nums);
// System.out.println(Constant.NUMBER);
for (int i = 0; i < nums.size(); i++) {
String word = nums.get(i);
// String reg="\\b("+Constant.FORBIDDEN+")\\b";
// boolean f = word.matches(reg);
if (word.matches("\\b(" + Constant.FORBIDDEN + ")\\b")) {
continue;
}
this.myDataHolder.updateDataHolder(word, "b", "*", "wordpos", 0);
// this.getWordPOSHolder().put(new WordPOSKey(word, "b"), new
// WordPOSValue("*", 0, 0, null, null));
// System.out.println("add Number: " + word);
}
this.myDataHolder.updateDataHolder("NUM", "b", "*", "wordpos", 0);
// this.getWordPOSHolder().put(new WordPOSKey("NUM", "b"), new
// WordPOSValue("*",0, 0, null, null));
}
public void addClusterStrings() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.addClusterstrings");
myLogger.trace("Add clusterstrings");
List<String> cltstrs = new ArrayList<String>();
cltstrs.addAll(Arrays.asList(Constant.CLUSTERSTRING.split("\\|")));
// System.out.println(cltstrs);
// System.out.println(Constant.CLUSTERSTRING);
for (int i = 0; i < cltstrs.size(); i++) {
String word = cltstrs.get(i);
if (word.matches("\\b(" + Constant.FORBIDDEN + ")\\b")) {
continue;
}
this.myDataHolder.updateDataHolder(word, "b", "*", "wordpos", 0);
// this.getWordPOSHolder().put(new WordPOSKey(word, "b"), new
// WordPOSValue("*", 1, 1, null, null));
// System.out.println("addClusterString: " + word);
}
}
public void addProperNouns() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.addProperNouns");
myLogger.trace("Add proper nouns");
List<String> ppnouns = new ArrayList<String>();
ppnouns.addAll(Arrays.asList(Constant.PROPERNOUN.split("\\|")));
for (int i = 0; i < ppnouns.size(); i++) {
String word = ppnouns.get(i);
if (word.matches("\\b(" + Constant.FORBIDDEN + ")\\b")) {
continue;
}
this.myDataHolder.updateDataHolder(word, "b", "*", "wordpos", 0);
// this.getWordPOSHolder().put(new WordPOSKey(word, "z"), new
// WordPOSValue("*", 0, 0, null, null));
// System.out.println("Add ProperNoun: " + word);
}
}
// suffix: -fid(adj), -form (adj), -ish(adj), -less(adj), -like (adj)),
// -merous(adj), -most(adj), -shaped(adj), -ous(adj)
// -ly (adv), -er (advj), -est (advj),
// foreach unknownword in unknownwords table
// seperate root and suffix
// if root is a word in WN or in unknownwords table
// make the unknowword a "b" boundary
/**
* for each unknownword in unknownwords table seperate root and suffix if
* root is a word in WN or in unknownwords table make the unknowword a "b"
* boundary
*
* suffix: -fid(adj), -form (adj), -ish(adj), -less(adj), -like (adj)),
* -merous(adj), -most(adj), -shaped(adj), -ous(adj)
*/
public void posBySuffix() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.posBySuffix");
myLogger.trace("Enter posBySuffix");
Iterator<Map.Entry<String, String>> iterator = this.myDataHolder
.getUnknownWordHolder().entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> unknownWordEntry = iterator.next();
String unknownWord = unknownWordEntry.getKey();
String unknownWordTag = unknownWordEntry.getValue();
if (unknownWordTag.equals("unknown")) {
// boolean flag1 =
posBySuffixCase1Helper(unknownWord);
// boolean flag2 =
posBySuffixCase2Helper(unknownWord);
}
}
myLogger.trace("Quite posBySuffix");
}
/**
*
* @param dh
* DataHolder handle to update the dataholder and return the
* updated dataholder
* @return Number of records that have been changed
*/
public int resetCounts(DataHolder dh) {
int count = 0;
Iterator<Entry<WordPOSKey, WordPOSValue>> iter = dh
.getWordPOSHolderIterator();
while (iter.hasNext()) {
Entry<WordPOSKey, WordPOSValue> wordPOSObject = iter.next();
wordPOSObject.getValue().setCertiantyU(0);
wordPOSObject.getValue().setCertiantyL(0);
count++;
}
return count;
}
public boolean posBySuffixCase1Helper(String unknownWord) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.posBySuffix");
String pattern1 = "^[a-z_]+(" + Constant.SUFFIX + ")$";
myLogger.debug("Pattern1: " + pattern1);
if (unknownWord.matches(pattern1)) {
Matcher matcher = Pattern
.compile("(.*?)(" + Constant.SUFFIX + ")$").matcher(
unknownWord);
if ((unknownWord.matches("^[a-zA-Z0-9_-]+$")) && matcher.matches()) {
myLogger.debug("posBySuffix - check word: " + unknownWord);
String base = matcher.group(1);
String suffix = matcher.group(2);
if (this.containSuffix(unknownWord, base, suffix)) {
myLogger.debug("Pass\n");
this.myDataHolder.updateDataHolder(unknownWord, "b", "*",
"wordpos", 0);
myLogger.debug("posBySuffix - set word: " + unknownWord);
return true;
} else {
myLogger.debug("Not Pass\n");
}
}
}
return false;
}
public boolean posBySuffixCase2Helper(String unknownWord) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.posBySuffix");
String pattern2 = "^[._.][a-z]+"; // , _nerved
myLogger.debug("Pattern2: " + pattern2);
if (unknownWord.matches(pattern2)) {
this.myDataHolder.getWordPOSHolder().put(
new WordPOSKey(unknownWord, "b"),
new WordPOSValue("*", 0, 0, null, null));
myLogger.debug("posbysuffix set " + unknownWord
+ " a boundary word\n");
return true;
}
return false;
}
/**
* return false or true depending on if the word contains the suffix as the
* suffix
*
* @param word
* @param base
* @param suffix
* @return
*/
public boolean containSuffix(String word, String base, String suffix) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.posBySuffix.containSuffix");
myLogger.trace("Enter containSuffix");
boolean flag = false; // return value
boolean wordInWN = false; // if this word is in WordNet
boolean baseInWN = false;
WordNetPOSKnowledgeBase myWN = this.myLearnerUtility
.getWordNetPOSKnowledgeBase();
// check base
if (base.length() == 0) {
myLogger.trace("case 0");
return true;
}
base.replaceAll("_", ""); // cup_shaped
if (myWN.contains(word)) {
myLogger.trace("case 1.1");
wordInWN = true; // word is in WordNet
} else {
myLogger.trace("case 1.2");
wordInWN = false;
}
if (myWN.contains(base)) {
myLogger.trace("case 2.1");
baseInWN = true;
} else {
myLogger.trace("case 2.2");
baseInWN = false;
}
// if WN pos is adv, return 1: e.g. ly, or if $base is in
// unknownwords table
if (suffix.equals("ly")) {
myLogger.trace("case 3.1");
if (wordInWN) {
if (myWN.isAdverb(word)) {
return true;
}
}
// if the word is in unknown word set, return true
if (this.myDataHolder.getUnknownWordHolder().containsKey(base)) {
return true;
}
}
// if WN recognize superlative, comparative adjs, return 1: e.g. er, est
else if (suffix.equals("er") || suffix.equals("est")) {
myLogger.trace("case 3.2");
if (wordInWN) {
boolean case1 = !myWN.isAdjective(word);
boolean case2 = myWN.isAdjective(base);
if (case1 && case2) {
return true;
} else {
return false;
}
}
}
// if $base is in WN or unknownwords table, or if $word has sole pos
// adj in WN, return 1: e.g. scalelike
else {
myLogger.trace("case 3.3");
if (myWN.isSoleAdjective(word)) {
return true;
}
if (baseInWN) {
return true;
}
if (this.myDataHolder.getUnknownWordHolder().containsKey(base)) {
return true;
}
}
return flag;
}
public void markupByPattern() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.markupByPattern");
myLogger.trace("Enter markupByPattern");
int size = this.myDataHolder.getSentenceHolder().size();
for (int i = 0; i < size; i++) {
boolean flag = markupByPatternHelper(this.myDataHolder
.getSentenceHolder().get(i));
if (flag) {
myLogger.debug("Updated Sentence
}
}
myLogger.trace("Quite markupByPattern");
}
public boolean markupByPatternHelper(SentenceStructure sentence) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("markupByPattern");
// case 1
if (sentence.getOriginalSentence().matches("^x=.*")) {
myLogger.trace("Case 1");
sentence.setTag("chromosome");
sentence.setModifier("");
return true;
}
// case 2
else if (sentence.getOriginalSentence().matches("^2n=.*")) {
myLogger.trace("Case 2");
sentence.setTag("chromosome");
sentence.setModifier("");
return true;
}
// case 3
else if (sentence.getOriginalSentence().matches("^x .*")) {
myLogger.trace("Case 3");
sentence.setTag("chromosome");
sentence.setModifier("");
return true;
}
// case 4
else if (sentence.getOriginalSentence().matches("^2n .*")) {
myLogger.trace("Case 4");
sentence.setTag("chromosome");
sentence.setModifier("");
return true;
}
// case 5
else if (sentence.getOriginalSentence().matches("^2 n.*")) {
myLogger.trace("Case 5");
sentence.setTag("chromosome");
sentence.setModifier("");
return true;
}
// case 6
else if (sentence.getOriginalSentence().matches("^fl.*")) {
myLogger.trace("Case 6");
sentence.setTag("flowerTime");
sentence.setModifier("");
return true;
}
// case 7
else if (sentence.getOriginalSentence().matches("^fr.*")) {
myLogger.trace("Case 7");
sentence.setTag("fruitTime");
sentence.setModifier("");
return true;
}
return false;
}
// private String IGNOREPTN ="(IGNOREPTN)"; //disabled
public void markupIgnore() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.markupIgnore");
myLogger.trace("Enter markupIgnore");
for (int i = 0; i < this.myDataHolder.getSentenceHolder().size(); i++) {
boolean flag = markupIgnoreHelper(this.myDataHolder
.getSentenceHolder().get(i));
if (flag) {
myLogger.debug("Updated Sentence
}
}
myLogger.trace("Quite markupIgnore");
}
public boolean markupIgnoreHelper(SentenceStructure sentence) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("markupIgnore");
String thisOriginalSentence = sentence.getOriginalSentence();
String pattern = "(^|^ )" + Constant.IGNOREPTN + ".*$";
if (thisOriginalSentence.matches(pattern)) {
sentence.setTag("ignore");
sentence.setModifier("");
myLogger.trace("Set Tag to \"ignore\", Modifier to \"\"");
return true;
}
return false;
}
/**
*
* @param status
* "start" or "normal"
* @return
*/
public int discover(String status) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.discover");
myLogger.trace("Enter Discover - Status: " + status);
int newDisc = 0;
// this.myDataHolder.printHolder(DataHolder.SENTENCE);
for (int i = 0; i < this.myDataHolder.getSentenceHolder().size(); i++) {
SentenceStructure sentEntry = this.myDataHolder.getSentenceHolder()
.get(i);
// sentid
String thisSentence = sentEntry.getSentence();
String thisLead = sentEntry.getLead();
String thisTag = sentEntry.getTag();
String thisStatus = sentEntry.getStatus();
// if (!(thisTag == null || !thisTag.equals("ignore")
// myLogger.debug("Tag: "+thisTag);
if ((!StringUtils.equals(thisTag, "ignore") || (thisTag == null))
&& thisStatus.equals(status)) {
myLogger.debug("Sentence
myLogger.debug("Lead: " + thisLead);
myLogger.debug("Tag: " + thisTag);
myLogger.debug("Sentence: " + thisSentence);
// tag is not null
if (isMarked(this.myDataHolder.getSentenceHolder().get(i))) {
myLogger.debug("Not Pass");
continue;
}
// tag is null
else {
myLogger.debug("Pass");
}
String[] startWords = thisLead.split("\\s+");
myLogger.debug("startWords: " + startWords.toString());
String pattern = buildPattern(startWords);
if (pattern != null) {
myLogger.debug("Build pattern [" + pattern
+ "] from starting words [" + thisLead + "]");
// IDs of untagged sentences that match the pattern
Set<Integer> matched = matchPattern(pattern, status, false);
int round = 0;
int numNew = 0;
do {
numNew = ruleBasedLearn(matched);
newDisc = newDisc + numNew;
myLogger.trace("Round: " + round);
round++;
} while (numNew > 0);
} else {
myLogger.debug("Build no pattern from starting words ["
+ thisLead + "]");
}
}
}
myLogger.trace("Return " + newDisc);
myLogger.trace("Quite discover");
return newDisc;
}
/**
* A helper of method discover(). Check if the tag of the i-th sentence is
* NOT null
*
* @param sentence
* the sentence to check
* @return if the tag of the i-th sentence is NOT null, returns true;
* otherwise returns false
*/
public boolean isMarked(SentenceStructure sentence) {
String thisTag = sentence.getTag();
if (thisTag != null) {
return true;
} else {
return false;
}
}
/**
* build a pattern based on existing checked word set, and the start words
*
* @param startWords
* @return a pattern. If no pattern is generated, return null
*/
public String buildPattern(String[] startWords) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.discover.buildPattern");
myLogger.trace("Enter buildPattern");
myLogger.trace("Start Words: " + startWords);
Set<String> newWords = new HashSet<String>();
String temp = "";
String prefix = "\\w+\\s";
String pattern = "";
Set<String> checkedWords = this.checkedWordSet;
myLogger.trace("checkedWords: " + checkedWords);
for (int i = 0; i < startWords.length; i++) {
String word = startWords[i];
// This is not very sure, need to make sure - Dongye
if ((!word.matches("[\\p{Punct}0-9]"))
&& (!checkedWords.contains(word))) {
temp = temp + word + "|";
newWords.add(word);
}
}
myLogger.trace("temp: " + temp);
// no new words
if (temp.length() == 0) {
myLogger.trace("No new words");
myLogger.trace("Return null");
myLogger.trace("Quite buildPattern");
myLogger.trace("\n");
return null;
} else {
// remove the last char, which is a '|'
temp = temp.substring(0, temp.length() - 1);
}
temp = "\\b(?:" + temp + ")\\b";
pattern = "^" + temp + "|";
for (int j = 0; j < this.NUM_LEAD_WORDS - 1; j++) {
temp = prefix + temp;
pattern = pattern + "^" + temp + "|";
}
myLogger.trace("Pattern: " + pattern);
pattern = pattern.substring(0, pattern.length() - 1);
pattern = "(?:" + pattern + ").*$";
checkedWords.addAll(newWords);
this.checkedWordSet = checkedWords;
myLogger.trace("Return Pattern: " + pattern);
myLogger.trace("Quite buildPattern");
myLogger.trace("\n");
return pattern;
}
/**
* Find the IDs of the sentences that matches the pattern
*
* @param pattern
* @param status
* @param hasTag
* @return a set of sentence IDs of the sentences that matches the pattern
*/
public Set<Integer> matchPattern(String pattern, String status,
boolean hasTag) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.discover.matchPattern");
myLogger.trace("Enter matchPattern");
myLogger.trace("Pattern: " + pattern);
myLogger.trace("Status: " + status);
myLogger.trace("HasTag: " + hasTag);
Set<Integer> matchedIDs = new HashSet<Integer>();
for (int i = 0; i < this.myDataHolder.getSentenceHolder().size(); i++) {
SentenceStructure sent = this.myDataHolder.getSentenceHolder().get(
i);
String thisSentence = sent.getSentence();
String thisStatus = sent.getStatus();
String thisTag = sent.getTag();
boolean a = hasTag;
boolean b = (thisTag == null);
if ((a ^ b) && (StringUtils.equals(status, thisStatus))) {
Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(thisSentence);
if (m.lookingAt()) {
myLogger.debug("Push Sentence
myLogger.debug("Sentence: " + thisSentence);
myLogger.debug("Status: " + thisStatus);
myLogger.debug("Tag: " + thisTag);
myLogger.debug("\n");
matchedIDs.add(i);
}
}
}
myLogger.trace("Return IDs: " + matchedIDs);
myLogger.trace("Quite matchPattern");
myLogger.trace("\n");
return matchedIDs;
}
/**
* return a positive number if anything new is learnt from @source sentences
* by applying rules and clues to grow %NOUNS and %BDRY and to confirm tags
* create and maintain decision tables
*
* @param matched
* @return
*/
public int ruleBasedLearn(Set<Integer> matched) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.discover.ruleBasedLearn");
myLogger.trace("Enter ruleBasedLearn");
myLogger.trace("Matched IDs: " + matched);
int sign = 0;
Iterator<Integer> iter = matched.iterator();
while (iter.hasNext()) {
int sentID = iter.next().intValue();
SentenceStructure sentence = this.myDataHolder.getSentenceHolder()
.get(sentID);
if (!isMarked(sentence)) {
StringAndInt tagAndNew = null;
String tag = null;
int numNew = 0;
tagAndNew = doIt(sentID);
tag = tagAndNew.getString();
numNew = tagAndNew.getInt();
this.tagSentence(sentID, tag);
sign = sign + numNew;
}
}
myLogger.trace("Return: " + sign);
myLogger.trace("Quit ruleBaseLearn");
myLogger.trace("\n");
return sign;
}
/**
* update wordpos table (on certainty) when a sentence is tagged for the
* first time. Note: 1) this update should not be done when a pos is looked
* up, because we may lookup a pos for the same example multiple times. 2)
* if the tag need to be adjusted (not by doit function), also need to
* adjust certainty counts.
*
* @param sentID
* the ID of the sentence
* @return a pair of (tag, sign)
*/
public StringAndInt doIt(int sentID) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.discover.ruleBasedLearn.doIt");
myLogger.trace("Enter doIt");
myLogger.trace("sentence ID: " + sentID);
SentenceStructure sentEntry = this.myDataHolder.getSentenceHolder()
.get(sentID);
String thisSentence = sentEntry.getSentence();
String thisLead = sentEntry.getLead();
StringAndInt returnValue = this.doItCaseHandle(thisSentence, thisLead);
myLogger.trace("Return Tag: " + returnValue.getString() + ", sign: "
+ returnValue.getInt());
myLogger.trace("Quit doIt");
myLogger.trace("\n");
return returnValue;
}
/**
*
* @param thisSentence
* @param thisLead
* @return
*/
public StringAndInt doItCaseHandle(String thisSentence, String thisLead) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.discover.ruleBasedLearn.doIt.doItCaseHandle");
myLogger.trace("Enter doItCaseHandle");
myLogger.trace("Sentence: " + thisSentence);
myLogger.trace("Lead: " + thisLead);
if (thisSentence == null || thisLead == null) {
return null;
}
int sign = 0;
String tag = "";
List<String> words = Arrays.asList(thisLead.split("\\s+"));
String ptn = this.getPOSptn(words);
myLogger.trace("ptn: " + ptn);
Pattern p2 = Pattern.compile("ps");
Matcher m2 = p2.matcher(ptn);
Pattern p3 = Pattern.compile("p(\\?)");
Matcher m3 = p3.matcher(ptn);
Pattern p4 = Pattern.compile("[psn](b)");
Matcher m4 = p4.matcher(ptn);
Pattern p5 = Pattern.compile("([psn][psn]+)");
Matcher m5 = p5.matcher(ptn);
Pattern p6A = Pattern.compile("b[?b]([psn])$");
Matcher m6A = p6A.matcher(ptn);
Pattern p6B = Pattern.compile("[?b]b([psn])$");
Matcher m6B = p6B.matcher(ptn);
boolean case6A = m6A.find();
boolean case6B = m6B.find();
Pattern p7 = Pattern.compile("^s(\\?)$");
Matcher m7 = p7.matcher(ptn);
Pattern p10 = Pattern.compile("^\\?(b)");
Matcher m10 = p10.matcher(ptn);
// Case 1: single word case
if (ptn.matches("^[pns]$")) {
myLogger.trace("Case 1");
tag = words.get(0);
sign = sign
+ this.myDataHolder.updateDataHolder(tag, ptn, "-",
"wordpos", 1);
myLogger.debug("Directly markup with tag: " + tag + "\n");
}
// Case 2: "ps"
else if (m2.find()) {
myLogger.trace("Case 2");
myLogger.debug("Found [ps] pattern\n");
int start = m2.start();
int end = m2.end();
String pWord = words.get(start);
String sWord = words.get(end - 1);
List<String> tempWords = StringUtility.stringArraySplice(words, 0,
start + 1);
tag = StringUtility.joinList(" ", tempWords);
myLogger.debug("\tdetermine the tag: " + tag);
int returnedSign = 0;
returnedSign = this.myDataHolder.updateDataHolder(pWord, "p", "-",
"wordpos", 1);
sign += returnedSign;
myLogger.trace(String.format(
"updateDataHolder(%s, p, -, wordpos, 1), returned: %d",
pWord, returnedSign));
returnedSign = this.myDataHolder.updateDataHolderNN(0,
tempWords.size(), tempWords);
sign += returnedSign;
myLogger.trace(String.format(
"updateDataHolderNN(0, %d, %s), returned: %d",
tempWords.size(), tempWords.toString(), returnedSign));
returnedSign = this.myDataHolder.updateDataHolder(sWord, "b", "",
"wordpos", 1);
sign += returnedSign;
myLogger.trace(String.format(
"updateDataHolder(%s, b, , wordpos, 1), returned: %d",
sWord, returnedSign));
}
// Case 3: "p(\\?)"
else if (m3.find()) {
myLogger.trace("Case 3");
myLogger.debug("Found [p?] pattern");
// int start = m3.start(1);
int end = m3.end(1);
String secondMatchedWord = words.get(end - 1);
// case 3.1
if (StringUtils.equals(this.myLearnerUtility.getWordFormUtility()
.getNumber(secondMatchedWord), "p")) {
myLogger.trace("Case 3.1");
tag = secondMatchedWord;
sign = sign
+ this.myDataHolder.updateDataHolder(tag, "p", "-",
"wordpos", 1);
this.myDataHolder
.add2Holder(
DataHolder.ISA,
Arrays.asList(new String[] { tag,
words.get(end - 2) }));
myLogger.debug("\t:[p p] pattern: determine the tag: " + tag);
}
// case 3.2
else {
myLogger.trace("Case 3.2");
List<String> wordsCopy = new ArrayList<String>(words);
// $i is just end-1
List<String> tempWords = StringUtility.stringArraySplice(words,
0, end - 1);
tag = StringUtility.joinList(" ", tempWords);
myLogger.debug("\t:determine the tag: " + tag);
myLogger.debug("\t:updates on POSs");
int temp = 0;
temp = this.myDataHolder.updateDataHolder(
wordsCopy.get(end - 1), "b", "", "wordpos", 1);
sign += temp;
myLogger.debug("\t:updateDataHolder1 returns " + temp);
temp = this.myDataHolder.updateDataHolder(
wordsCopy.get(end - 2), "p", "-", "wordpos", 1);
sign += temp;
myLogger.debug("\t:updateDataHolder2 returns " + temp);
temp = this.myDataHolder.updateDataHolderNN(0,
tempWords.size(), tempWords);
sign += temp;
myLogger.debug("\t:updateDataHolder returns " + temp);
}
}
// case 4: "[psn](b)"
else if (m4.find()) {
myLogger.trace("Case 4");
Pattern p41 = Pattern.compile("^sbp");
Matcher m41 = p41.matcher(ptn);
if (m41.find()) {
myLogger.trace("\tCase 4.1");
myLogger.debug("Found [sbp] pattern");
List<String> wordsCopy = new ArrayList<String>(words);
tag = StringUtility.joinList(" ",
StringUtility.stringArraySplice(wordsCopy, 0, 3));
myLogger.trace("\t:determine the tag: " + tag);
} else {
myLogger.trace("\tCase 4.2");
myLogger.debug("Found [[psn](b)] pattern");
int index = m4.start(1);
// get tag, which is the words prior to the b word (exclusive)
List<String> wordsTemp = StringUtility.stringArraySplice(words,
0, index);
tag = StringUtility.joinList(" ", wordsTemp);
myLogger.trace("Tag: " + tag);
// update the b word
sign += this.myDataHolder.updateDataHolder(words.get(index),
"b", "", "wordpos", 1);
myLogger.trace(String.format(
"updateDataHolder (%s, b, , wordpos, 1)",
words.get(index)));
sign += this.myDataHolder.updateDataHolder(
words.get(index - 1), ptn.substring(index - 1, index),
"-", "wordpos", 1);
myLogger.trace(String.format(
"updateDataHolder (%s, %s, -, wordpos, 1)",
words.get(index - 1), ptn.substring(index - 1, index)));
sign += this.myDataHolder.updateDataHolderNN(0,
wordsTemp.size(), wordsTemp);
myLogger.trace(String.format("updateDataHolderNN (0, %d, %s)",
wordsTemp.size(), wordsTemp.toString()));
myLogger.debug("\t:determine the tag: " + tag);
myLogger.debug("\t:updates on POSs");
}
}
// case 5: "pp"
else if (m5.find()) {
myLogger.debug("Case 5: Found [[psn][psn]+] pattern");
int start = m5.start(1);
int end = m5.end(1);
List<String> copyWords = new ArrayList<String>();
copyWords.addAll(words);
GetNounsAfterPtnReturnValue returnedValue = this.getNounsAfterPtn(
thisSentence, end);
List<String> moreNoun = new LinkedList<String>();
List<String> morePtn = new LinkedList<String>();
String bWord = "";
moreNoun.addAll(returnedValue.getNouns());
morePtn.addAll(returnedValue.getNounPtn());
bWord = returnedValue.getBoundaryWord();
List<POSInfo> t;
if (StringUtility.createMatcher(ptn, "pp").find()) {
myLogger.trace("Case 5.1");
String morePtnStr = StringUtility.joinList("", morePtn);
Pattern p511 = Pattern.compile("/^p*(s)");
Matcher m511 = p511.matcher(morePtnStr);
Pattern p512 = Pattern.compile("^(p+)");
Matcher m512 = p512.matcher(morePtnStr);
if (m511.find()) {
myLogger.trace("Case 5.1.1");
// find last p word, and reset it to "b"
int sAfterPIndex = m511.start(1);
int lastPIndex = sAfterPIndex - 1;
String sWord = moreNoun.get(sAfterPIndex);
String lastPWord = lastPIndex >= 0 ? moreNoun
.get(lastPIndex) : "";
bWord = lastPWord;
if (StringUtils.equals(lastPWord, "")) {
tag = words.get(ptn.lastIndexOf("p"));
} else {
tag = lastPWord;
}
sign += this.getDataHolder().updateDataHolder(sWord, "b",
"", "wordpos", 1);
} else if (m512.find()) {
myLogger.trace("Case 5.1.2");
tag = moreNoun.get(m512.end(1) - 1);
} else {
myLogger.trace("Case 5.1.3");
int lastPIndex = ptn.lastIndexOf("p");
tag = words.get(lastPIndex);
}
t = this.getDataHolder().checkPOSInfo(tag);
} else {
myLogger.trace("Case 5.2");
List<String> tempWords = new LinkedList<String>();
tempWords
.addAll(StringUtility.stringArraySplice(words, 0, end));
tag = StringUtility.joinList(" ", tempWords);
if (moreNoun.size() > 0) {
tag = tag + " " + StringUtility.joinList(" ", moreNoun);
}
t = this.getDataHolder().checkPOSInfo(
tag.substring(tag.lastIndexOf(" ") + 1, tag.length()));
}
if (t.size() > 0) {
String pos = t.get(0).getPOS();
// String role = t.get(0).getRole();
// int certiantyU = t.get(0).getCertaintyU();
// int certiantyL = t.get(0).getCertaintyL();
if (StringUtility.createMatcher(pos, "[psn]").find()) {
// case 5.x
myLogger.debug("Case 5.x: relax this condition");
List<String> tWords = new LinkedList<String>();
tWords.addAll(Arrays.asList(thisSentence.split(" ")));
sign += this.getDataHolder().updateDataHolder(bWord, "b",
"", "wordpos", 1);
ptn = ptn.substring(start, end);
String tempPtn = ptn + StringUtility.joinList("", morePtn);
for (int k = start; k < tempPtn.length(); k++) {
if (k != tempPtn.length() - 1) {
sign += this.getDataHolder().updateDataHolder(
tWords.get(k), tempPtn.substring(k, k + 1),
"_", "wordpos", 1);
} else {
sign += this.getDataHolder().updateDataHolder(
tWords.get(k), tempPtn.substring(k, k + 1),
"-", "wordpos", 1);
}
}
if (tWords.size() > 1) {
sign += this.getDataHolder().updateDataHolderNN(0,
tempPtn.length(), tWords);
}
}
}
myLogger.debug("\t:determine the tag: " + tag);
}
// case 6: "b[?b]([psn])$" or "[?b]b([psn])$"
else if (case6A || case6B) {
myLogger.debug("Case 6: Found [b?[psn]$] or [[?b]b([psn])$] pattern");
int end = -1;
// the index of noun
if (case6A) {
end = m6A.end(1) - 1;
} else {
end = m6B.end(1) - 1;
}
GetNounsAfterPtnReturnValue tempReturnValue = this
.getNounsAfterPtn(thisSentence, end + 1);
// List<String> moreNouns = tempReturnValue.getNouns();
List<String> morePtn = tempReturnValue.getNounPtn();
String bWord = tempReturnValue.getBoundaryWord();
List<String> sentenceHeadWords = this.getLearnerUtility()
.tokenizeText(thisSentence, "firstseg");
end += morePtn.size();
List<String> tempWords = StringUtility.stringArraySplice(
sentenceHeadWords, 0, end + 1);
tag = StringUtility.joinList(" ", tempWords);
myLogger.debug("\t:updates on POSs");
if (StringUtility.createMatcher(bWord, "\\w").find()) {
sign += this.getDataHolder().updateDataHolder(bWord, "b", "",
"wordpos", 1);
}
String allPtn = "" + ptn;
allPtn = allPtn + StringUtility.joinList("", morePtn);
// from the index of noun
for (int i = 2; i < allPtn.length(); i++) {
// case 6.1: last ptn
if (i != allPtn.length() - 1) {
myLogger.trace("Case 6.1");
sign += this.getDataHolder().updateDataHolder(
sentenceHeadWords.get(i),
allPtn.substring(i, i + 1), "_", "wordpos", 1);
}
// case 6.2: not last ptn
else {
myLogger.trace("Case 6.2");
sign += this.getDataHolder().updateDataHolder(
sentenceHeadWords.get(i),
allPtn.substring(i, i + 1), "-", "wordpos", 1);
}
}
myLogger.debug("\t:determine the tag: " + tag);
}
// case 7: "^s(\\?)$"
else if (m7.find()) {
myLogger.trace("Case 7");
String singularWord = words.get(0);
String questionedWord = words.get(1);
String wnPOS = this.myLearnerUtility.getWordFormUtility().checkWN(
questionedWord, "pos");
if (StringUtility.createMatcher(wnPOS, "p").find()) {
myLogger.trace("Case 7.1");
tag = singularWord + " " + questionedWord;
myLogger.debug("\t:determine the tag: " + tag);
myLogger.debug("\t:updates on POSs");
String questionedPOS = this.getLearnerUtility()
.getWordFormUtility().getNumber(singularWord);
sign += this.getDataHolder().updateDataHolder(questionedWord,
questionedPOS, "-", "wordpos", 1);
} else {
myLogger.trace("Case 7.2");
tag = words.get(0);
myLogger.debug("\t:determine the tag: " + tag);
myLogger.debug("\t:updates on POSs");
sign += this.getDataHolder().updateDataHolder(questionedWord,
"b", "", "wordpos", 1);
sign += this.getDataHolder().updateDataHolder(singularWord,
"s", "-", "wordpos", 1);
}
}
// case 8: "^bs$"
else if (StringUtility.createMatcher(ptn, "^bs$").find()) {
myLogger.trace("Case 8");
tag = StringUtility.joinList(" ", words);
sign += this.getDataHolder().updateDataHolder(words.get(0), "b",
"", "wordpos", 1);
sign += this.getDataHolder().updateDataHolder(words.get(1), "s",
"-", "wordpos", 1);
}
// case 9: ^bp$
else if (StringUtility.createMatcher(ptn, "^bp$").find()) {
myLogger.trace("Case 9");
tag = StringUtility.joinList(" ", words);
sign += this.getDataHolder().updateDataHolder(words.get(0), "b",
"", "wordpos", 1);
sign += this.getDataHolder().updateDataHolder(words.get(1), "p",
"-", "wordpos", 1);
}
// case 10: "^\\?(b)"
else if (m10.find()) {
myLogger.trace("Case 10");
myLogger.trace("Found [?(b)] pattern");
int index = m10.start(1);
sign += this.myDataHolder.updateDataHolder(words.get(index), "b",
"", "wordpos", 1);
myLogger.trace(String.format(
"updateDataHolder (%s, b, , wordpos, 1)", words.get(index)));
List<String> wordsTemp = StringUtility.stringArraySplice(words, 0,
index);
tag = StringUtility.joinList(" ", wordsTemp);
String word = words.get(index - 1); // the "?" word
myLogger.trace("Tag: " + tag);
myLogger.trace("Word: " + word);
if (!isFollowedByNoun(thisSentence, thisLead)) {
myLogger.trace("Case 10.1");
String wnP1 = this.myLearnerUtility.getWordFormUtility()
.checkWN(word, "pos");
myLogger.trace("wnP1: " + wnP1);
String wnP2 = "";
if (!StringUtility.createMatcher(wnP1, "\\w").find()) {
wnP2 = this.myLearnerUtility.getWordFormUtility()
.getNumber(word);
}
myLogger.trace("wnP2: " + wnP2);
if (StringUtility.createMatcher(wnP1, "[ar]").find()) {
wnP1 = "";
}
if ((StringUtility.createMatcher(wnP1, "[psn]").find())
|| (StringUtility.createMatcher(wnP2, "[ps]").find())) {
myLogger.trace("Case 10.1.1");
myLogger.debug("\t:determine the tag: " + tag);
myLogger.debug("\t:updates on POSs");
sign += this.myDataHolder.updateDataHolder(word, "n", "-",
"wordpos", 1);
myLogger.trace(String.format(
"updateDataHolder(%s, n, -, wordpos, 1)", word));
sign += this.myDataHolder.updateDataHolderNN(0,
wordsTemp.size() - 1, wordsTemp);
myLogger.trace(String.format(
"updateDataHolderNN(%d, %d, %s)", 0,
wordsTemp.size() - 1, wordsTemp));
} else {
myLogger.trace("Case 10.1.2");
myLogger.debug("\t:" + tag
+ " is adv/adj or modifier. skip.");
tag = "";
}
} else {
myLogger.trace("Case 10.2");
myLogger.debug(String.format(
"\t:%s is adv/adj or modifier. skip.", tag));
tag = "";
}
} else {
myLogger.trace("\tCase 0");
myLogger.trace(String.format("Pattern [%s] is not processed", ptn));
}
StringAndInt returnValue = new StringAndInt(tag, sign);
myLogger.trace("Return: " + returnValue.toString());
return returnValue;
}
public int doItCase7Helper(String regex, String ptn) {
Matcher m = StringUtility.createMatcher(ptn, regex);
if (m.find()) {
int start = m.start();
return start + 1;
} else {
return -1;
}
}
public GetNounsAfterPtnReturnValue getNounsAfterPtn(String sentence,
int startWordIndex) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.getNounsAfterPattern");
myLogger.trace(String
.format("enter (%s, %d)", sentence, startWordIndex));
String bWord = "";
List<String> nouns = new ArrayList<String>();
List<String> nounPtn = new ArrayList<String>();
List<String> tempWords = new ArrayList<String>();
tempWords.addAll(this.getLearnerUtility().tokenizeText(sentence,
"firstseg"));
List<String> words = StringUtility.stringArraySplice(tempWords,
startWordIndex, tempWords.size());
myLogger.trace("words: " + words);
String ptn = this.getPOSptn(words);
myLogger.trace("ptn: " + ptn);
if (ptn != null) {
Matcher m1 = StringUtility.createMatcher(ptn, "^([psn]+)");
Matcher m2 = StringUtility.createMatcher(ptn, "^(\\?+)");
boolean case1 = false;
boolean case2 = false;
int end = -1;
if (m1.find()) {
case1 = true;
end = m1.end(1);
}
if (m2.find()) {
case2 = true;
end = m2.end(1);
}
if (case1 || case2) {
myLogger.trace("end: " + end);
if (end < words.size()) {
bWord = words.get(end);
}
List<String> nWords = new ArrayList<String>();
nWords.addAll(StringUtility.stringArraySplice(words, 0, end));
for (int i = 0; i < nWords.size(); i++) {
String p = ptn.substring(i, i + 1);
p = StringUtils.equals(p, "?") ? this.getLearnerUtility()
.getWordFormUtility().checkWN(nWords.get(i), "pos")
: p;
if (StringUtility.createMatcher(p, "^[psn]+$").find()) {
nouns.add(nWords.get(i));
nounPtn.add(p);
} else {
bWord = nWords.get(i);
break;
}
}
}
}
GetNounsAfterPtnReturnValue returnValue = new GetNounsAfterPtnReturnValue(
nouns, nounPtn, bWord);
myLogger.trace("return " + returnValue);
return (returnValue);
}
/**
* Check if a lead is followed by a noun without any proposition in between
* in the sentence
*
* @param thisSentence
* the sentence
* @param thisLead
* the lead
* @return true if lead is followed by a N without any proposition in
* between
*/
public boolean isFollowedByNoun(String sentence, String lead) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.discover.ruleBasedLearn.doIt.isFollowedByNoun");
myLogger.trace(String.format("(%s, %s)", sentence, lead));
// null case
if (sentence == null || lead == null) {
myLogger.trace("Return false");
return false;
}
if (StringUtils.equals(sentence, "")) {
myLogger.trace("Return false");
return false;
}
// remove lead from sentence
sentence = sentence.replaceFirst("^" + lead, "");
myLogger.trace("Sentence after remove lead: " + sentence);
// List<String> nouns = this.myDataHolder.getWordByPOS("ps");
Set<String> POSTags = new HashSet<String>();
POSTags.add("p");
POSTags.add("s");
Set<String> nouns = this.myDataHolder
.getWordsFromWordPOSByPOSs(POSTags);
if (nouns.size() == 0) {
myLogger.trace("Return false");
return false;
}
// String pattern1 = StringUtility.joinList("|", nouns);
String pattern1 = StringUtils.join(nouns, "|");
pattern1 = "(.*?)\\b(" + pattern1 + ")" + "\\b";
myLogger.trace("Pattern: " + pattern1);
Pattern p1 = Pattern.compile(pattern1);
Matcher m1 = p1.matcher(sentence);
String inBetweenPart = "";
if (m1.find()) {
inBetweenPart = m1.group(1);
String pattern2 = "\\b(" + Constant.PREPOSITION + ")\\b";
Pattern p2 = Pattern.compile(pattern2);
Matcher m2 = p2.matcher(inBetweenPart);
if (!m2.find()) {
myLogger.trace("Return true");
return true;
}
}
myLogger.trace("Return false");
return false;
}
/**
* The length of the ptn must be the same as the number of words in words.
* If certainty is < 50%, replace POS with ?.
*
* @param words
* @return
*/
public String getPOSptn(List<String> words) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.discover.ruleBasedLearn.doIt.getPOSptn");
myLogger.trace("Enter getPOSptn");
myLogger.trace("Words: " + words.toString());
String ptn = "";
String POS = "";
double certainty;
for (int i = 0; i < words.size(); i++) {
String word = words.get(i);
myLogger.trace("\tCheck word: " + word);
List<POSInfo> POSInfoList = this.myDataHolder.checkPOSInfo(word);
if (POSInfoList.size() >= 0) {
if (POSInfoList.size() == 0) {
myLogger.trace("\t\tThe word is not in WordPOS holder");
POS = "?";
} else {
POSInfo p = POSInfoList.get(0);
POS = p.getPOS();
if (p.getCertaintyU() == 0) {
certainty = 1.0;
} else {
double certaintyU = (double) p.getCertaintyU();
double certaintyL = (double) p.getCertaintyL();
certainty = certaintyU / certaintyL;
}
myLogger.trace(String.format("\t\tCertaintyU: %d",
p.getCertaintyU()));
myLogger.trace(String.format("\t\tCertaintyL: %d",
p.getCertaintyL()));
myLogger.trace(String
.format("\t\tCertainty: %f", certainty));
if ((!StringUtils.equals(POS, "?")) && (certainty <= 0.5)) {
myLogger.info("\t\tThis POS has a certainty less than 0.5. It is ignored.");
POS = "?";
}
}
ptn = ptn + POS;
myLogger.trace("\t\tAdd pos: " + POS);
} else {
myLogger.error("Error: checkPOSInfo gave invalid return value");
}
}
myLogger.trace("Return ptn: " + ptn);
myLogger.trace("Quite getPOSptn");
return ptn;
}
public void additionalBootstrapping() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.additionalBootStrapping");
myLogger.trace("[additionalBootStrapping]Start");
// this.myDataHolder.printHolder(DataHolder.SENTENCE);
int flag = 0;
do {
myLogger.trace(String.format("Enter one do-while loop iteration"));
flag = 0;
// warmup markup
int cmReturn = wrapupMarkup();
myLogger.trace(String
.format("wrapupMarkup() returned %d", cmReturn));
flag += cmReturn;
// one lead word markup
Set<String> tags = myDataHolder.getCurrentTags();
myLogger.trace(tags.toString());
int omReturn = oneLeadWordMarkup(tags);
myLogger.trace(String.format("oneLeadWordMarkup() returned %d",
omReturn));
flag += omReturn;
// doit markup
int dmReturn = this.doItMarkup();
myLogger.trace(String.format("doItMarkup() returned %d", dmReturn));
flag += dmReturn;
myLogger.trace(String.format("Quite this iteration with flag = %d",
flag));
} while (flag > 0);
myLogger.trace("[additionalBootStrapping]End");
}
/**
* In the sentence collections, search for such sentence, whose lead is
* among the tags passed in, and add the lead into word POS collections as a
* noun
*
* @param tags
* a set of all tags in the tagged sentences in the sentence
* collection
* @return the numbet of updates made
*/
public int oneLeadWordMarkup(Set<String> tags) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.additionalBootStrapping.oneLeadWordMarkup");
// String tags = StringUtility.joinList("|", tags);
int sign = 0;
myLogger.trace(String.format("Enter (%s)", tags));
Iterator<SentenceStructure> iter = this.myDataHolder
.getSentenceHolder().iterator();
while (iter.hasNext()) {
SentenceStructure sentence = iter.next();
int ID = sentence.getID();
String tag = sentence.getTag();
String lead = sentence.getLead();
if ((tag == null)
&& (!(StringUtility.createMatcher(lead, ".* .*").find()))) {
if (tags.contains(lead)) {
this.tagSentence(ID, lead);
myLogger.trace(String.format(
"updateDataHolder(%s, n, -, wordpos, 1)", lead));
sign += myDataHolder.updateDataHolder(lead, "n", "-",
"wordpos", 1);
}
}
}
myLogger.trace("Return: " + sign);
return 0;
}
/**
* for the remaining of sentences that do not have a tag yet, look for lead
* word co-ocurrance, use the most freq. co-occured phrases as tags e.g.
* plication induplicate (n times) and plication reduplicate (m times) =>
* plication is the tag and a noun e.g. stigmatic scar basal (n times) and
* stigmatic scar apical (m times) => stigmatic scar is the tag and scar is
* a noun. what about externally like A; externally like B, functionally
* staminate florets, functionally staminate xyz?
*
* @return
*/
public int wrapupMarkup() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.additionalBootStrapping.wrapupMarkup");
myLogger.trace("Enter");
int sign = 0;
Set<Integer> checkedIDs = new HashSet<Integer>();
List<SentenceStructure> sentenceList = new LinkedList<SentenceStructure>();
for (int id1 = 0; id1 < this.myDataHolder.getSentenceHolder().size(); id1++) {
SentenceStructure sentence = this.myDataHolder.getSentenceHolder()
.get(id1);
String tag = sentence.getTag();
String lead = sentence.getLead();
if ((tag == null)
&& (StringUtility.createMatcher(lead, ".* .*").find())) {
sentenceList.add(sentence);
}
}
SentenceLeadLengthComparator myComparator = new SentenceLeadLengthComparator(
false);
Collections.sort(sentenceList, myComparator);
Iterator<SentenceStructure> iter1 = sentenceList.iterator();
while (iter1.hasNext()) {
SentenceStructure sentence = iter1.next();
int ID1 = sentence.getID();
String lead = sentence.getLead();
// if this sentence has been checked, pass
if (checkedIDs.contains(ID1)) {
continue;
}
List<String> words = new ArrayList<String>();
words.addAll(Arrays.asList(lead.split("\\s+")));
List<String> sharedHead = new ArrayList<String>();
sharedHead.addAll(words.subList(0, words.size() - 1));
String match = StringUtility.joinList(" ", sharedHead);
Set<SentenceStructure> sentenceSet = new HashSet<SentenceStructure>();
for (int index = 0; index < this.myDataHolder.getSentenceHolder()
.size(); index++) {
SentenceStructure thisSentence = this.myDataHolder
.getSentenceHolder().get(index);
String thisLead = thisSentence.getLead();
String tag = thisSentence.getTag();
String pTemp = "^" + match + " [\\S]+$";
myLogger.trace(thisLead);
myLogger.trace(pTemp);
// if ((tag==null) && StringUtility.isMatchedNullSafe(pTemp,
// thisLead)) {
if ((tag == null)
&& StringUtility.isMatchedNullSafe(thisLead, pTemp)) {
if (!StringUtils.equals(thisLead, lead)) {
sentenceSet.add(thisSentence);
}
}
}
if (sentenceSet.size() > 1) {
String ptn = this.getPOSptn(sharedHead);
String wnPOS = this.myLearnerUtility.getWordFormUtility()
.checkWN(sharedHead.get(sharedHead.size() - 1), "pos");
myLogger.trace("ptn: " + ptn);
myLogger.trace("wnPOS: " + wnPOS);
if ((StringUtility.createMatcher(ptn, "[nsp]$").find())
|| ((StringUtility.createMatcher(ptn, "\\?$").find()) && (StringUtility
.createMatcher(wnPOS, "n").find()))) {
Iterator<SentenceStructure> iter2 = sentenceSet.iterator();
while (iter2.hasNext()) {
SentenceStructure thisSentence = iter2.next();
int ID = thisSentence.getID();
String thisLead = thisSentence.getLead();
List<String> words2 = new ArrayList<String>();
words2.addAll(Arrays.asList(thisLead.split("\\s+")));
// case 1
boolean case1 = false;
boolean case2 = false;
case1 = words2.size() > sharedHead.size();
if (case1) {
List<String> checkWord = new ArrayList<String>();
checkWord.add(words2.get(sharedHead.size()));
case2 = StringUtility.createMatcher(
this.getPOSptn(checkWord), "[psn]").find();
}
if (case1 && case2) {
myLogger.trace("Case 1");
String nb = words2.size() >= sharedHead.size() + 2 ? words2
.get(sharedHead.size() + 1) : "";
words2 = StringUtility.stringArraySplice(words2, 0,
sharedHead.size() + 1);
String nmatch = StringUtility.joinList(" ", words2);
this.tagSentence(ID, nmatch);
myLogger.trace(String.format("tag (%d, %s)", ID,
nmatch));
this.tagSentence(ID1, match);
myLogger.trace(String.format("tag (%d, %s)", ID1,
match));
String updatedWord = words2.get(words2.size() - 1);
int update1 = this.myDataHolder.updateDataHolder(
updatedWord, "n", "-", "wordpos", 1);
sign += update1;
myLogger.trace(String.format("update (%s)",
updatedWord));
if (!StringUtils.equals(nb, "")) {
int update2 = this.myDataHolder
.updateDataHolder(nb, "b", "",
"wordpos", 1);
sign += update2;
myLogger.trace(String.format("update (%s)", nb));
}
updatedWord = words.get(words.size() - 1);
int update3 = this.myDataHolder.updateDataHolder(
words.get(words.size() - 1), "b", "",
"wordpos", 1);
sign += update3;
myLogger.trace(String.format("update (%s)",
updatedWord));
}
// case 2
else {
myLogger.trace("Case 2");
String b = words2.size() >= sharedHead.size() + 1 ? words2
.get(sharedHead.size()) : "";
this.tagSentence(ID, match);
this.tagSentence(ID1, match);
// if (sharedHead.get(sharedHead.size() -
// 1).equals("tissue")) {
// System.out.println();
int update1 = this.myDataHolder.updateDataHolder(
sharedHead.get(sharedHead.size() - 1), "n",
"-", "wordpos", 1);
sign += update1;
if (!StringUtils.equals(b, "")) {
int update2 = this.myDataHolder
.updateDataHolder(b, "b", "",
"wordpos", 1);
sign += update2;
}
int update3 = this.myDataHolder.updateDataHolder(
words.get(words.size() - 1), "b", "",
"wordpos", 1);
sign += update3;
}
checkedIDs.add(ID);
}
} else {
Iterator<SentenceStructure> iter2 = sentenceSet.iterator();
while (iter2.hasNext()) {
SentenceStructure thisSentence = iter2.next();
int ID = thisSentence.getID();
checkedIDs.add(ID);
}
}
} else {
checkedIDs.add(ID1);
}
}
myLogger.trace("Return " + sign);
return sign;
}
/**
* check if the lead has the head in the beginning of it
*
* @param head
* @param lead
* @return true if it has, false if it does not have
*/
public boolean hasHead(List<String> head, List<String> lead) {
// null case
if (head == null || lead == null) {
return false;
}
int headSize = head.size();
int leadSize = lead.size();
if (headSize > leadSize) {
return false;
}
for (int i = 0; i < headSize; i++) {
if (!StringUtils.equals(head.get(i), lead.get(i))) {
return false;
}
}
return true;
}
/**
* skip and/or cases skip leads with $stop words
*
* @return number of updates
*/
public int doItMarkup() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger
.getLogger("learn.additionalBootStrapping.doItMarkup");
myLogger.trace("Enter");
int sign = 0;
// for (int i=0;i<myDataHolder.getSentenceHolder().size();i++) {
Iterator<SentenceStructure> iter = this.myDataHolder
.getSentenceHolder().iterator();
while (iter.hasNext()) {
SentenceStructure sentenceObject = iter.next();
String tag = sentenceObject.getTag();
if (doItMarkupHelper(tag)) {
int ID = sentenceObject.getID();
String lead = sentenceObject.getLead();
String sentence = sentenceObject.getSentence();
// case 1
if (doItMarkupCase1Helper(sentence)) {
myLogger.trace(String.format("sent #%d: case 1", ID));
continue;
}
// case 2
if (doItMarkupCase2Helper(lead)) {
myLogger.trace(String.format("sent #%d: case 2", ID));
continue;
}
StringAndInt tagAndSign = doIt(ID);
String doItTag = tagAndSign.getString();
int doItSign = tagAndSign.getInt();
sign = doItSign;
// case 3
if (StringUtility.createMatcher(doItTag, "\\w").find()) {
myLogger.trace(String.format("sent #%d: case 3", ID));
this.tagSentence(ID, doItTag);
}
}
}
myLogger.trace("Return: " + sign);
return sign;
}
public boolean doItMarkupHelper(String tag) {
boolean flag = false;
flag = (tag == null) || (StringUtils.equals(tag, ""))
|| (StringUtils.equals(tag, "unknown"));
return flag;
}
public boolean doItMarkupCase1Helper(String sentence) {
boolean flag = false;
flag = StringUtility.createMatcher(sentence,
"^.{0,40} (nor|or|and|\\/)").find();
return flag;
}
public boolean doItMarkupCase2Helper(String lead) {
boolean flag = false;
flag = StringUtility.createMatcher(lead,
"\\b(" + Constant.STOP + ")\\b").find();
return flag;
}
public void unknownWordBootstrapping() {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.unknownWordBootstrapping");
myLogger.trace("[unknownWordBootstrapping]Start");
unknownWordBootstrappingPreprocessing();
unknownWordBootstrappingMain();
unknownWordBootstrappingPostprocessing();
myLogger.trace("[unknownWordBootstrapping]End");
}
public void unknownWordBootstrappingPreprocessing() {
this.myLearnerUtility.tagAllSentences(this.myDataHolder, "singletag",
"sentence");
}
public void unknownWordBootstrappingMain() {
String plMiddle = "(ee)";
int newInt = 0;
do {
// this.unknownWordBootstrappingGetUnknownWord(plMiddle);
} while (newInt > 0);
}
public void unknownWordBootstrappingPostprocessing() {
// pistillate_zone
// get all nouns from wordPOS holder
Set<String> POSTags = new HashSet<String>();
POSTags.add("p");
POSTags.add("s");
Set<String> nouns = this.getDataHolder().getWordsFromWordPOSByPOSs(
POSTags);
// get boudaries
Set<String> boundaries = new HashSet<String>();
Set<String> words = this.getDataHolder().getWordsFromUnknownWord(
"^.*_.*$", true, "^unknown$", true);
Iterator<String> wordIter = words.iterator();
String pattern = "_(" + StringUtils.join(nouns, "|") + ")$";
while (wordIter.hasNext()) {
String word = wordIter.next();
Pattern p1 = Pattern.compile("^[a-zA-Z0-9_-]+$");
Matcher m1 = p1.matcher(word);
Pattern p2 = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m2 = p2.matcher(word);
if (m1.matches() && (!m2.matches())) {
if (!StringUtility.createMatcher(word,
"\\b(" + Constant.FORBIDDEN + ")\\b").find()) {
boundaries.add(word);
}
this.getDataHolder().updateDataHolder(word, "b", "", "wordpos",
1);
}
}
// if the boundaries is not empty
if (boundaries.size() > 0) {
Iterator<SentenceStructure> iter = this.getDataHolder()
.getSentenceHolderIterator();
while (iter.hasNext()) {
SentenceStructure sentenceItem = iter.next();
String tag = sentenceItem.getTag();
String sentence = sentenceItem.getSentence();
int sentenceID = sentenceItem.getID();
if ((!(StringUtils.equals(tag, "ignore")) || (tag == null))
&& (StringUtility.createMatcher(sentence, "(^| )("
+ StringUtils.join(boundaries, "|") + ") ")
.find())) {
KnownTagCollection tags = new KnownTagCollection(null,
null, null, boundaries, null, null);
sentence = this.myLearnerUtility.annotateSentence(sentence,
tags, this.myDataHolder.getBMSWords());
SentenceStructure updatedSentence = this.getDataHolder()
.getSentence(sentenceID);
updatedSentence.setSentence(sentence);
}
}
}
}
/**
* Utilities
*
* @return
*/
public Set<String> getCheckedWordSet() {
return this.checkedWordSet;
}
public void setCheckedWordSet(Set<String> wordSet) {
this.checkedWordSet = wordSet;
}
public boolean tagSentence(int sentenceID, String tag) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.tagSentence");
myLogger.trace(String.format("Enter (%d, %s)", sentenceID, tag));
// case 1
if (!StringUtility.createMatcher(tag, "\\w+").find()) {
myLogger.trace("\t:tag is not a word. Return");
return false;
} else {
// case 2
if (StringUtility.createMatcher(tag, "^(" + Constant.STOP + ")\\b")
.find()) {
myLogger.trace(String
.format("\t:tag %s starts with a stop word, ignore tagging requrest",
tag));
return false;
} else {
// case 3
int maxLength = this.myConfiguration.getMaxTagLength();
if (tag.length() > maxLength) {
maxLength = this.myConfiguration.getMaxTagLength();
tag = tag.substring(0, maxLength);
myLogger.debug(String.format("\ttag: %s longer than %d)",
tag, maxLength));
} else {
;
}
SentenceStructure sentence = myDataHolder
.getSentence(sentenceID);
sentence.setTag(tag);
myLogger.debug(String.format(
"\t:mark up sentence #%d with tag %s", sentenceID, tag));
return true;
}
}
}
/**
* correct markups that used an adj as an s, e.g lateral, adult, juvenile
*/
public void adjectivesVerification(DataHolder dataholderHandler) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.adjectivesVerification");
String pattern = "^<N>([a-z]+)</N> ([^N,;.]+ <N>[a-z]+</N>)";
Iterator<SentenceStructure> iter = dataholderHandler
.getSentenceHolderIterator();
while (iter.hasNext()) {
SentenceStructure sentenceItem = iter.next();
String sentence = sentenceItem.getSentence();
// System.out.println(sentence);
Set<Integer> ids = new HashSet<Integer>();
ids.add(133);
ids.add(163);
ids.add(236);
ids.add(269);
if (ids.contains(sentenceItem.getID())) {
System.out.println();
}
if (sentence != null) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(sentence);
if (m.find()) {
String part1 = m.group(1);
String part2 = m.group(2);
myLogger.trace(String.format("Sentence %s\n"
+ "\tSentence: %s\n" + "\tPart1: %s\n"
+ "\tPart2: %s", sentenceItem.getID(),
sentenceItem.getSentence(), part1, part2));
boolean condition1 = this.isSentenceTag(dataholderHandler,
part2);
boolean condition2 = StringUtils.equals(this
.getLearnerUtility().getWordFormUtility()
.getNumber(part1), "p");
if (condition1 && condition2) {
String wrongWord = part1;
myLogger.trace("\tWrong: " + wrongWord);
// if (StringUtility.isMatchedNullSafe(wrongWord,
if (StringUtility.isMatchedNullSafe(wrongWord, "\\w")) {
this.noun2Modifier(dataholderHandler, wrongWord);
Set<String> words = dataholderHandler
.getWordsFromUnknownWord(null, false,
String.format("^%s$", wrongWord),
true);
for (String word : words) {
this.noun2Modifier(dataholderHandler, word);
}
}
}
}
}
}
}
/**
* Check if a word is (part of) the tag of any sentence
*
* @param dataholderHandler
* DataHolder handler
* @param raw
* word to check
* @return true if it is, false otherwise
*/
public boolean isSentenceTag(DataHolder dataholderHandler, String raw) {
boolean result = false;
result = dataholderHandler.isExistSentence(false,
String.format("^%s.*$", raw));
return result;
}
/**
* change the POS tag of a word from noun to modifier
*
* @param dataholderHandler
* dataholder handler
*
* @param word
* the word to change
* @return true if any updates has been made, false otherwise
*/
public boolean noun2Modifier(DataHolder dataholderHandler, String word) {
boolean isUpdated = false;
ArrayList<String> deletedPOSs = new ArrayList<String>();
deletedPOSs.add("s");
deletedPOSs.add("p");
deletedPOSs.add("n");
for (String POS : deletedPOSs) {
dataholderHandler.deleteWordPOS(true, word, true, POS);
}
dataholderHandler.updateDataHolder(word, "m", "", "modifiers", 1);
String oldPattern = String.format("(^%s$|^.* %s$)", word, word);
dataholderHandler.updateSentenceTag(oldPattern, null);
return isUpdated;
}
public void separateModifierTag(DataHolder dataholderHandler) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.separateModifierTag");
List<SentenceStructure> sentences = dataholderHandler
.getSentencesByTagPattern("^.* .*$");
for (SentenceStructure sentenceItem : sentences) {
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
String tag = sentenceItem.getTag();
myLogger.trace("ID: " + sentenceID);
myLogger.trace("Sentence: " + sentence);
myLogger.trace("Tag: " + tag);
// case 1
String tagBackup = "" + tag;
// if (StringUtility.isMatchedNullSafe("\\w+", tagBackup)) {
if (StringUtility.isMatchedNullSafe(tagBackup, "\\w+")) {
myLogger.trace("Case 1");
if (!StringUtility.isMatchedNullSafe(tagBackup,
String.format("\\b(%s)\\b", Constant.STOP))) {
List<String> words = new LinkedList<String>();
words.addAll(Arrays.asList(tagBackup.split("\\s+")));
tag = words.get(words.size() - 1);
String modifier = "";
if (words.size() > 1) {
modifier = StringUtils.join(
StringUtility.stringArraySplice(words, 0,
words.size() - 1), " ");
}
if (sentenceID == 22) {
System.out.println();
}
if (StringUtility.isMatchedNullSafe(tag, "\\w")) {
// case 1.1
myLogger.trace("Case 1.1");
dataholderHandler.tagSentenceWithMT(sentenceID,
sentence, modifier, tag, "separatemodifiertag");
} else {
// case 1.2
myLogger.trace("Case 1.2");
myLogger.trace(sentenceID);
dataholderHandler.tagSentenceWithMT(sentenceID,
sentence, null, tag, "separatemodifiertag");
}
}
}
// case 2
else {
// treat them case by case
// case 2: in some species, abaxially with =>NULL
myLogger.trace("Case 2");
if ((StringUtility.isMatchedNullSafe(tagBackup, "^in"))
&& (StringUtility.isMatchedNullSafe(tagBackup,
"\\b(with|without)\\b"))) {
myLogger.trace("Case 2.1");
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
"", null, "separtemodifiertag");
} else {
myLogger.trace("Case 2.2");
String tagWithStopWordsReplaced = "" + tagBackup;
if (tagWithStopWordsReplaced != null) {
Pattern p = Pattern.compile("@ ([^@]+)$");
Matcher m = p.matcher(tagWithStopWordsReplaced);
if (m.find()) {
String tg = m.group(1);
ArrayList<String> tagWords = new ArrayList<String>();
tagWords.addAll(Arrays.asList(tg.split("\\s+")));
tag = tagWords.get(tagWords.size() - 1);
String modifier = "";
if (tagWords.size() > 1) {
modifier = StringUtils.join(StringUtility
.stringArraySplice(tagWords, 0,
tagWords.size()), " ");
}
if (StringUtility.isMatchedNullSafe(tag, "\\w")) {
myLogger.trace("Case 2.2.1");
dataholderHandler.tagSentenceWithMT(sentenceID,
sentence, modifier, tag,
"separatemodifiertag");
} else {
myLogger.trace("Case 2.2.2");
dataholderHandler.tagSentenceWithMT(sentenceID,
sentence, "", null,
"separatemodifiertag");
}
}
}
}
}
}
}
public void resolveNMB(DataHolder dataholderHandler) {
Set<String> tags = dataholderHandler.getSentenceTags();
Iterator<Entry<WordPOSKey, WordPOSValue>> wordPOSIter = dataholderHandler
.getWordPOSHolderIterator();
// get words
Set<String> words = new HashSet<String>();
while (wordPOSIter.hasNext()) {
Entry<WordPOSKey, WordPOSValue> wordPOSEntry = wordPOSIter.next();
if (StringUtils.equals(wordPOSEntry.getKey().getPOS(), "b")) {
String word = wordPOSEntry.getKey().getWord();
boolean case1 = dataholderHandler.getWordPOSHolder()
.containsKey(new WordPOSKey(word, "s"));
boolean case2 = tags.contains(word);
if (case1 || case2) {
words.add(word);
}
}
}
// update wordPOS holder and / or sentence holder
Iterator<String> wordIter = words.iterator();
while (wordIter.hasNext()) {
String word = wordIter.next();
if (dataholderHandler.getModifierHolder().containsKey(word)) {
// remove N role
dataholderHandler.getWordPOSHolder().remove(
new WordPOSKey(word, "s"));
// reset sentence tags
Iterator<SentenceStructure> sentenceIter = dataholderHandler
.getSentenceHolderIterator();
while (sentenceIter.hasNext()) {
SentenceStructure sentenceItem = sentenceIter.next();
String tag = sentenceItem.getSentence();
boolean case1 = StringUtils.equals(tag, word);
boolean case2 = StringUtility.isMatchedNullSafe(tag, " "
+ word);
if (case1 || case2) {
sentenceItem.setModifier("");
sentenceItem.setTag(null);
}
}
dataholderHandler.getBMSWords().add(word);
}
}
// retag clauses with <N><M><B> tags
Iterator<SentenceStructure> sentenceIter = dataholderHandler
.getSentenceHolderIterator();
while (sentenceIter.hasNext()) {
SentenceStructure sentenceItem = sentenceIter.next();
String sentence = sentenceItem.getSentence();
sentence = sentence.replaceAll("<[ON]><M><B>", "<M><B>");
sentence = sentence.replaceAll("</B></M></[ON]>", "</B></M>");
sentenceItem.setSentence(sentence);
}
}
public void setAndOr(DataHolder dataholderHandler) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.separateModifierTag");
myLogger.debug("Tag and/or sentences andor");
String ptn1 = "^(?:[mbq,]{0,10}[onp]+(?:,|(?=&)))+&(?:[mbq,]{0,10}[onp]+)"; // n,n,n&n
String ptn2 = "^(?:[mbq,]{0,10}(?:,|(?=&)))+&(?:[mbq,]{0,10})[onp]+"; // m,m,&mn
Iterator<SentenceStructure> sentenceIter = dataholderHandler
.getSentenceHolderIterator();
while (sentenceIter.hasNext()) {
SentenceStructure sentenceItem = sentenceIter.next();
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
String lead = sentenceItem.getLead();
if (isIsAndOrSentence(sentenceID, sentence, lead, ptn1, ptn2)) {
sentenceItem.setTag("andor");
}
}
}
public boolean isIsAndOrSentence(int sentenceID, String sentence,
String lead, String ptn1, String ptn2) {
Set<String> token = new HashSet<String>();
token.addAll(Arrays.asList("and or nor".split(" ")));
token.add("\\");
token.add("and / or");
int limit = 80;
List<String> words = new ArrayList<String>();
words.addAll(Arrays.asList(sentence.split(" ")));
String sentencePtn = this.getLearnerUtility().getSentencePtn(
myDataHolder, token, limit, words);
if (sentencePtn == null) {
return false;
}
boolean result = isIsAndOrSentenceHelper(words, sentencePtn, ptn1, ptn2);
return result;
}
public boolean isIsAndOrSentenceHelper(List<String> words,
String sentencePtn, String ptn1, String ptn2) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.isIsAndOrSentence");
sentencePtn = sentencePtn.toLowerCase();
// ignore the distinction between type modifiers and modifiers
sentencePtn = sentencePtn.replaceAll("t", "m");
Pattern p1 = Pattern.compile(ptn1);
Matcher m1 = p1.matcher(sentencePtn);
Pattern p2 = Pattern.compile(ptn2);
Matcher m2 = p2.matcher(sentencePtn);
int end = -1;
boolean case1 = false;
boolean case2 = false;
if (m1.find()) {
end = m1.end();
case1 = true;
}
if (m2.find()) {
end = m2.end();
case2 = true;
}
if (case1 || case2) {
String matchedWords = StringUtils.join(words.subList(0, end), " ");
String regex = String.format("\\b(%s)\\b", Constant.PREPOSITION);
if (StringUtility.isMatchedNullSafe(matchedWords, regex)) {
myLogger.trace("Case 1");
return false;
}
myLogger.trace("Case 2");
return true;
}
myLogger.trace("Case 3");
return false;
}
public void handleAndOr(DataHolder dataholderHandler) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.handleAndOr");
myLogger.info("to match pattern " + Constant.ANDORPTN);
List<SentenceStructure> sentenceItems = dataholderHandler
.getSentencesByTagPattern("^andor$");
int sign = 0;
for (SentenceStructure sentenceItem : sentenceItems) {
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
// myLogger.trace(Constant.SEGANDORPTN);
// myLogger.trace(Constant.ANDORPTN);
int result = this.andOrTag(dataholderHandler, sentenceID, sentence,
Constant.SEGANDORPTN, Constant.ANDORPTN);
sign = sign + result;
}
}
public int andOrTag(DataHolder dataholderHandler, int sentenceID,
String sentence, String sPattern, String wPattern) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.andOrTag");
myLogger.trace("Enter");
int sign = 0;
List<String> mPatterns = new ArrayList<String>();
List<String> sPatterns = new ArrayList<String>();
List<String> mSegments = new ArrayList<String>();
List<String> sSegments = new ArrayList<String>();
Set<String> token = new HashSet<String>();
token.addAll(Arrays.asList("and or nor".split(" ")));
token.add("\\");
token.add("and / or");
String strToken = "(" + StringUtils.join(token, " ") + ")";
int limit = 80;
List<String> words = new ArrayList<String>();
words.addAll(Arrays.asList(sentence.split(" ")));
String pattern = this.getLearnerUtility().getSentencePtn(
dataholderHandler, token, limit, words);
pattern = pattern.replaceAll("t", "m");
myLogger.info(String.format("Andor pattern %s for %s", pattern,
words.toString()));
if (pattern == null) {
return -1;
}
// Matcher m1 = StringUtility.createMatcher(pattern, wPattern);
Matcher m2 = StringUtility.createMatcher(pattern, "^b+&b+[,:;.]");
if (sentenceID == 163) {
System.out.println();
}
List<List<String>> res = this.andOrTagCase1Helper(pattern, wPattern,
words, token);
if (res != null) {
mPatterns = res.get(0);
mSegments = res.get(1);
sPatterns = res.get(2);
sSegments = res.get(3);
List<String> tagAndModifier1 = res.get(4);
List<String> tagAndModifier2 = res.get(5);
List<String> update1 = res.get(6);
List<String> update2 = res.get(7);
if (tagAndModifier1.size() > 0) {
String modifier = tagAndModifier1.get(0);
String tag = tagAndModifier1.get(1);
dataholderHandler.tagSentenceWithMT(sentenceID, sentence, "",
tag, "andor[n&n]");
myLogger.trace("tagSentenceWithMT(" + sentenceID + ", "
+ sentence + ", , " + tag + ", andor[n&n]");
} else {
myLogger.debug(String.format(
"Andor can not determine a tag or modifier for %d: %s",
sentenceID, sentence));
}
if (tagAndModifier2.size() > 0) {
String modifier = tagAndModifier2.get(0);
String tag = tagAndModifier2.get(1);
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag, "andor[m&mn]");
myLogger.trace("tagSentenceWithMT(" + sentenceID + ", "
+ sentence + ", " + modifier + ", " + tag
+ ", andor[m&mn]");
} else {
myLogger.debug(String.format(
"Andor can not determine a tag or modifier for %d: %s",
sentenceID, sentence));
}
if (update1.size() > 0) {
String newBoundaryWord = update1.get(0);
sign = sign
+ dataholderHandler.updateDataHolder(newBoundaryWord,
"b", "", "wordpos", 1);
}
if (update2.size() > 0) {
for (String tempWord : update2) {
sign = sign
+ dataholderHandler.updateDataHolder(tempWord, "p",
"-", "wordpos", 1);
}
}
}
else if (m2.find()) {
myLogger.trace("Case 2");
dataholderHandler.tagSentenceWithMT(sentenceID, sentence, "",
"ditto", "andor");
} else {
myLogger.trace("Case 3");
myLogger.trace("[andortag]Andor can not determine a tag or modifier for "
+ sentenceID + ": " + sentence);
}
myLogger.trace("Return " + sign + "\n");
return sign;
}
public List<List<String>> andOrTagCase1Helper(String pattern,
String wPattern, List<String> words, Set<String> token) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.andOrTag");
List<String> mPatterns = new ArrayList<String>();
List<String> sPatterns = new ArrayList<String>();
List<String> mSegments = new ArrayList<String>();
List<String> sSegments = new ArrayList<String>();
List<String> update1 = new ArrayList<String>();
List<String> update2 = new ArrayList<String>();
List<String> tagAndModifier1 = new ArrayList<String>();
List<String> tagAndModifier2 = new ArrayList<String>();
String strToken = "(" + StringUtils.join(token, " ") + ")";
Matcher m1 = StringUtility.createMatcher(pattern, wPattern);
if (m1.find()) {
myLogger.trace("Case 1");
if (pattern.equals("n&qqnbq")) {
// System.out.println();
}
int start1 = m1.start(1);
int end1 = m1.end(1);
int start2 = m1.start(2);
int end2 = m1.end(2);
int start3 = m1.start(3);
int end3 = m1.end(3);
int start4 = m1.start(4);
int end4 = m1.end(4);
int start5 = m1.start(5);
int end5 = m1.end(5);
// System.out.println(pattern);
// System.out.println(start1);
// System.out.println();
String earlyGroupsPattern = start1 == -1 ? "" : pattern.substring(
0, start1);
String[] patterns = earlyGroupsPattern.split("s*<B>,<\\/B>\\s*");
String earlyGroupsWords = start1 == -1 ? "" : StringUtils.join(
words.subList(0, start1), " ");
String[] segments = earlyGroupsWords.split("\\s*<B>,<\\/B>s*");
String secondLastModifierPattern = m1.group(1);
String secondLastModifierWords = secondLastModifierPattern == null ? ""
: StringUtils.join(words.subList(start1, end1), " ");
String sencondLastStructurePattern = m1.group(2);
String secondLastStructureWords = sencondLastStructurePattern == null ? ""
: StringUtils.join(words.subList(start2, end2), " ");
String lastModifierPattern = m1.group(3);
String lastModifierWords = lastModifierPattern == null ? ""
: StringUtils.join(words.subList(start3, end3), " ");
String lastStructurePattern = m1.group(4);
String lastStructureWords = lastStructurePattern == null ? ""
: StringUtils.join(words.subList(start4, end4), " ");
String endSegmentPattern = m1.group(5);
String endSegmentWords = endSegmentPattern == null ? ""
: StringUtils.join(words.subList(start5, end5), " ");
int bIndex = start5;
// matching pattern with original text
if (!(patterns.length == 1 && StringUtils.equals(patterns[0], ""))) {
for (int i = 0; i < patterns.length; i++) {
Pattern p = Pattern.compile("sPattern");
Matcher m10 = p.matcher(patterns[i]);
if (m10.find()) {
String g1 = m10.group(1);
mPatterns.add(g1);
String g2 = m10.group(2);
sPatterns.add(g2);
List<String> w = new ArrayList<String>(
Arrays.asList(segments[i].split(" ")));
String m = StringUtils.join(w.subList(0, m10.end(1)),
" ");
if (StringUtility.isMatchedNullSafe(m,
"\\b(although|but|when|if|where)\\b")) {
return null;
}
mSegments.add(m);
sSegments.add(StringUtils.join(
w.subList(m10.end(1), w.size()), " "));
} else {
myLogger.info("wrong segment: " + patterns[i] + "=>"
+ segments[i] + "\n");
return null;
}
}
}
if (secondLastModifierPattern != null)
mPatterns.add(secondLastModifierPattern);
if (!StringUtils.equals(secondLastModifierWords, ""))
mSegments.add(secondLastModifierWords);
if (sencondLastStructurePattern != null)
sPatterns.add(sencondLastStructurePattern);
if (!StringUtils.equals(secondLastStructureWords, ""))
sSegments.add(secondLastStructureWords);
if (lastModifierPattern != null)
mPatterns.add(lastModifierPattern);
if (!StringUtils.equals(lastModifierWords, ""))
mSegments.add(lastModifierWords);
if (lastStructurePattern != null)
sPatterns.add(lastStructurePattern);
if (!StringUtils.equals(lastStructureWords, ""))
sSegments.add(lastStructureWords);
// find the modifier and the tag for sentenceID
// case 1.1
if (this.countStructures(sPatterns) > 1) {
// compound subject involving multiple structures: mn,mn,&mn =>
// use all but bounary as the tag, modifier="";
String tag = StringUtils.join(words.subList(0, bIndex), " ");
String modifier = "";
tag = tag.replaceAll("<\\S+?>", "");
if (tag != null) {
String regex11 = "\\b(" + StringUtils.join(token, "|")
+ ")\\b";
Matcher m11 = StringUtility.createMatcher(tag, regex11);
if (m11.find()) {
String conj = m11.group(1);
tag = tag.replaceAll(",", " " + conj + " ");
tag = tag.replaceAll("\\s+", " ");
tag = tag.replaceAll("(" + conj + " )+", "$1");
tag = tag.replaceAll("^\\s+", "");
tag = tag.replaceAll("\\s+$", "");
// dataholderHandler.tagSentenceWithMT(sentenceID,
// sentence, "", tag, "andor[n&n]");
tagAndModifier1.add("");
tagAndModifier1.add(tag);
}
// else {
// myLogger.debug(String.format("Andor can not determine a tag or modifier for %d: %s",
// sentenceID, sentence));
}
// case 1.2
else if (this.countStructures(sPatterns) == 1) {
// m&mn => connect all modifiers as the modifier, and the n
// as the tag
int i = 0;
for (i = 0; i < sPatterns.size(); i++) {
if (StringUtility.isMatchedNullSafe(sPatterns.get(i),
"\\w")) {
break;
}
}
tag = sSegments.get(i);
tag = tag.replaceAll("<\\S+?>", "");
modifier = StringUtils.join(mSegments, " ");
modifier = modifier.replaceAll("<\\S+?>", "");
tag = StringUtility.trimString(tag);
modifier = StringUtility.trimString(modifier);
String myStop = Constant.STOP;
myStop = myStop.replaceAll(
String.format("\\b%s\\b", token), "");
myStop = myStop.replaceAll("\\s+$", "");
if (StringUtility.isMatchedNullSafe(modifier, "\\b"
+ strToken + "\\b")
&& StringUtility.isEntireMatchedNullSafe(modifier,
"\\b(" + myStop + "|to)\\b")) {
// case 1.2.1
List<String> wordsTemp = new ArrayList<String>();
wordsTemp.addAll(Arrays.asList(tag.split("\\s+")));
modifier = modifier
+ " "
+ StringUtils.join(wordsTemp.subList(0,
wordsTemp.size() - 1), " ");
tag = wordsTemp.get(wordsTemp.size() - 1);
// dataholderHandler.tagSentenceWithMT(sentenceID,
// sentence, modifier, tag, "andor[m&mn]");
tagAndModifier2.add(modifier);
tagAndModifier2.add(tag);
}
// else {
// myLogger.debug(String.format("Andor can not determine a tag or modifier for %d: %s",
// sentenceID, sentence));
}
// case 1.3
else {
myLogger.debug("Andor can not determine a tag or modifier");
}
int q = -1;
if (endSegmentPattern != null) {
Matcher m13 = StringUtility.createMatcher(
endSegmentPattern, "q");
if (m13.find()) {
q = m13.start();
}
}
if (q >= 0) {
String newBoundaryWord = endSegmentWords.split(" ")[q];
if (StringUtility.isMatchedNullSafe(newBoundaryWord, "\\w")) {
update1.add(newBoundaryWord);
// sign = sign +
// dataholderHandler.updateDataHolder(newBoundaryWord,
// "b", "", "wordpos", 1);
}
}
// structure patterns and segments: $nptn =
// "((?:[np],?)*&?[np])"; #grouped #must present, no q allowed
// mark all ps "p"
for (int i = 0; i < sPatterns.size(); i++) {
String sPatternI = sPatterns.get(i);
sPatternI = sPatternI.replaceAll("(.)", "$1 ");
sPatternI = StringUtility.trimString(sPatternI);
String[] ps = sPatternI.split(" ");
String[] ts = sSegments.get(i).split("\\s+");
for (int j = 0; j < ps.length; j++) {
if (StringUtils.equals(ps[j], "p")) {
ts[j] = StringUtility.trimString(ts[j]);
update2.add(ts[j]);
// sign = sign
// + dataholderHandler.updateDataHolder(ts[j],
// "p", "-", "wordpos", 1);
}
}
}
}
List<List<String>> res = new ArrayList<List<String>>();
res.add(mPatterns);
res.add(mSegments);
res.add(sPatterns);
res.add(sSegments);
res.add(tagAndModifier1);
res.add(tagAndModifier2);
res.add(update1);
res.add(update2);
return res;
} else {
return null;
}
}
public int countStructures(List<String> patterns) {
int count = 0;
for (String pattern : patterns) {
if (StringUtility.isMatchedNullSafe(pattern, "\\w")) {
count++;
}
}
return count;
}
public void resetAndOrTags(DataHolder dataholderHandler) {
dataholderHandler.updateSentenceTag("^andor$", null);
}
public void ditto(DataHolder dataholderHandler) {
String nPhrasePattern = "(?:<[A-Z]*[NO]+[A-Z]*>[^<]+?<\\/[A-Z]*[NO]+[A-Z]*>\\s*)+";
String mPhrasePattern = "(?:<[A-Z]*M[A-Z]*>[^<]+?<\\/[A-Z]*M[A-Z]*>\\s*)+";
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
if (sentenceItem.getTag() == null) {
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
this.dittoHelper(dataholderHandler, sentenceID, sentence,
nPhrasePattern, mPhrasePattern);
}
}
}
public int dittoHelper(DataHolder dataholderHandler, int sentenceID,
String sentence, String nPhrasePattern, String mPhrasePattern) {
int res = 0;
String sentenceCopy = "" + sentence;
sentenceCopy = sentenceCopy.replaceAll("></?", "");
String modifier = "";
Matcher m2 = StringUtility.createMatcher(sentenceCopy, "(.*?)"
+ nPhrasePattern);
if (!StringUtility.isMatchedNullSafe(sentence, "<[NO]>")) {
String tag = "ditto";
dataholderHandler.tagSentenceWithMT(sentenceID, sentence, "", tag,
"ditto-no-N");
res = 1;
} else if (m2.find()) {
String head = m2.group(1);
String pattern21 = String
.format("\\b(%s)\\b", Constant.PREPOSITION);
if (StringUtility.isMatchedNullSafe(head, pattern21)) {
String tag = "ditto";
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag, "ditto-proposition");
res = 21;
} else if (StringUtility.isMatchedNullSafe(head, ",<\\/B>\\s*$")) {
String tag = "ditto";
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag, "ditto-,-N");
res = 22;
}
}
return res;
}
public void phraseClause(DataHolder dataholderHandler) {
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
if (sentenceItem.getTag() == null) {
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
List<String> res = this.phraseClauseHelper(sentence);
if (res != null && res.size() == 2) {
String modifier = res.get(0);
String tag = res.get(1);
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag, "phraseclause");
}
}
}
}
public List<String> phraseClauseHelper(String sentence) {
if (sentence == null) {
return null;
}
List<String> res = new ArrayList<String>(2);
String pattern = "^(.*?)((?:<[A-Z]*M[A-Z]*>[^<]*?<\\/[A-Z]*M[A-Z]*>\\s*)*)((?:<[A-Z]*[NO]+[A-Z]*>[^<]*?<\\/[A-Z]*[NO]+[A-Z]*>\\s*)+)<B>[,:\\.;]<\\/B>\\s*$";
String sentenceCopy = "" + sentence;
sentenceCopy = sentenceCopy.replaceAll("></?", "");
Matcher m = StringUtility.createMatcher(sentenceCopy, pattern);
if (m.find()) {
String head = m.group(1);
String modifier = m.group(2);
String tag = m.group(3);
String prepositionPattern = String.format("\\b(%s)\\b",
Constant.PREPOSITION);
if (!StringUtility.isMatchedNullSafe(head, prepositionPattern)
&& !StringUtility.isMatchedNullSafe(head, "<\\/N>")
&& !StringUtility.isMatchedNullSafe(modifier,
prepositionPattern)) {
if (tag != null) {
Matcher m2 = StringUtility.createMatcher(tag,
"(.*?)<N>([^<]+)<\\/N>\\s*$");
if (m2.find()) {
modifier = modifier + m2.group(1);
tag = m2.group(2);
}
tag = tag.replaceAll("<\\S+?>", "");
modifier = modifier.replaceAll("<\\S+?>", "");
tag = tag.replaceAll("(^\\s*|\\s*$)", "");
modifier = modifier.replaceAll("(^\\s*|\\s*$)", "");
res.add(modifier);
res.add(tag);
return res;
}
}
}
return res;
}
public void pronounCharacterSubject(DataHolder dataholderHandler) {
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
int sentenceID = sentenceItem.getID();
String lead = sentenceItem.getLead();
String sentence = sentenceItem.getSentence();
String modifier = sentenceItem.getModifier();
String tag = sentenceItem.getTag();
List<String> mt = pronounCharacterSubjectHelper(lead, sentence,
modifier, tag);
if (mt != null) {
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag,
"pronouncharactersubject[character subject]");
}
}
// preposition cases
String prepositionPattern = String
.format("^(%s)", Constant.PREPOSITION);
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
int sentenceID = sentenceItem.getID();
String lead = sentenceItem.getLead();
String modifier = sentenceItem.getModifier();
String tag = sentenceItem.getTag();
String sentence = sentenceItem.getSentence();
boolean case1 = (StringUtils.equals(tag, "ignore"));
boolean case2 = (tag == null);
boolean case3 = StringUtility.isMatchedNullSafe(tag,
prepositionPattern + " ");
if ((case1 || case2) && case3) {
dataholderHandler.tagSentenceWithMT(sentenceID, sentence, "",
"", "pronouncharactersubject[proposition subject]");
}
}
// pronoun cases
String pronounPattern = String.format("(%s)", Constant.PRONOUN);
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
int sentenceID = sentenceItem.getID();
String lead = sentenceItem.getLead();
String modifier = sentenceItem.getModifier();
String tag = sentenceItem.getTag();
String sentence = sentenceItem.getSentence();
boolean case1 = StringUtility.isMatchedNullSafe(tag,
String.format("(^| )%s( |\\$)", pronounPattern));
boolean case2 = StringUtility.isMatchedNullSafe(modifier,
String.format("(^| )%s( |\\$)", pronounPattern));
if (case1 || case2) {
modifier = modifier.replaceAll("\\b(" + Constant.PRONOUN
+ ")\\b", "");
tag = tag.replaceAll("\\b(" + Constant.PRONOUN + ")\\b", "");
modifier = modifier.replaceAll("\\s+", " ");
tag = tag.replaceAll("\\s+", " ");
if (!StringUtility.isMatchedNullSafe(tag, "\\w")
|| StringUtility.isMatchedNullSafe(tag, "ditto")) {
tag = dataholderHandler.getParentSentenceTag(sentenceID);
}
modifier = modifier.replaceAll("(^\\s*|\\s*$)", "");
tag = tag.replaceAll("(^\\s*|\\s*$)", "");
List<String> mt = dataholderHandler.getMTFromParentTag(tag);
String m = mt.get(0);
tag = mt.get(1);
if (StringUtility.isMatchedNullSafe(m, "\\w")) {
modifier = modifier + m;
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag,
"pronouncharactersubject[pronoun subject]");
}
}
}
// correct to missed N
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
int sentenceID = sentenceItem.getID();
String lead = sentenceItem.getLead();
String modifier = sentenceItem.getModifier();
String tag = sentenceItem.getTag();
String sentence = sentenceItem.getSentence();
List<String> mt = this.pronounCharacterSubjectHelper4(lead,
sentence, modifier, tag);
if (mt != null) {
modifier = mt.get(0);
tag = mt.get(1);
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag,
"pronouncharactersubject[correct to missed N]");
}
}
}
public List<String> pronounCharacterSubjectHelper4(String lead,
String sentence, String modifier, String tag) {
boolean case1 = (StringUtils.equals(tag, "ignore"));
boolean case2 = (tag == null);
boolean case3 = !StringUtility.isMatchedNullSafe(tag, " (and|nor|or) ");
boolean case4 = !StringUtility.isMatchedNullSafe(sentence, "\\[");
boolean case5 = false;
if (sentence != null) {
Pattern p = Pattern.compile("^[^N]*<N>" + tag);
Matcher m = p.matcher(sentence);
if (m.find()) {
case5 = true;
}
}
if ((case1 || case2) && case3 && case4 && case5) {
if (sentence != null) {
sentence = sentence.replaceAll("></?", "");
Pattern p = Pattern
.compile("^(\\S*) ?<N>([^<]+)<\\/N> <[MB]+>(\\S+)<\\/[MB]+> \\S*\\b"
+ tag + "\\b\\S*");
Matcher m2 = p.matcher(sentence);
if (m2.find()) {
modifier = m2.group(1);
tag = m2.group(2);
String g3 = m2.group(3);
if (!StringUtility.isMatchedNullSafe(g3, "\\bof\\b")) {
modifier = modifier.replaceAll("<\\S+?>", "");
tag = tag.replaceAll("<\\S+?>", "");
modifier = modifier.replaceAll("(^\\s*|\\s*$)", "");
tag = tag.replaceAll("(^\\s*|\\s*$)", "");
List<String> mt = new ArrayList<String>();
mt.add(modifier);
mt.add(tag);
return mt;
}
}
}
}
return null;
}
public List<String> pronounCharacterSubjectHelper(String lead,
String sentence, String modifier, String tag) {
String t = "(?:<\\/?[A-Z]+>)?";
boolean b1 = !StringUtils.equals(tag, "ignore");
boolean b2 = (tag == null);
boolean b3 = StringUtility.isMatchedNullSafe(lead, "(^| )("
+ Constant.CHARACTER + ")( |$)");
boolean b4 = StringUtility.isMatchedNullSafe(tag, "(^| )("
+ Constant.CHARACTER + ")( |$)");
if (((b1 || b2) && b3) || b4) {
sentence = sentence.replaceAll("></?", "");
if (sentence != null) {
String pattern1 = String
.format("^.*?%s\\b(%s)\\b%s %s(?:of)%s (.*?)(<[NO]>([^<]*?)<\\/[NO]> ?)+ ",
t, Constant.CHARACTER, t, t, t);
Matcher m1 = StringUtility.createMatcher(sentence, pattern1);
String pattern2 = String
.format("^(.*?)((?:<\\/?[BM]+>\\w+?<\\/?[BM]+>\\s*)*)%s\\b(%s)\\b%s",
t, Constant.CHARACTER, t);
Matcher m2 = StringUtility.createMatcher(sentence, pattern2);
// case 1.1
if (m1.find()) {
tag = m1.group(4);
modifier = sentence.substring(m1.start(2), m1.start(4));
String s2 = m1.group(2);
String s3 = m1.group(3);
if ((!StringUtility.isMatchedNullSafe(s2,
String.format("\\b(%s)\\b", Constant.PREPOSITION)))
&& (!StringUtility.isMatchedNullSafe(s3, String
.format("\\b(%s|\\d)\\b", Constant.STOP)))) {
modifier = modifier.replaceAll("<\\S+?>", "");
modifier = modifier.replaceAll("(^\\s*|\\s*$)", "");
tag = tag.replaceAll("<\\S+?>", "");
tag = tag.replaceAll("(^\\s*|\\s*$)", "");
} else {
modifier = "";
tag = "ditto";
}
}
// case 1.2
else if (m2.find()) {
String text = m2.group(1);
if ((!StringUtility.isMatchedNullSafe(text, "\\b("
+ Constant.STOP + "|\\d+)\\b"))
&& (StringUtility.isMatchedNullSafe(text, "\\w"))
&& (!StringUtility
.isMatchedNullSafe(text, "[,:;.]"))) {
text = text.replaceAll("<\\S+?>", "");
// $text =~ s#(^\s*|\s*$)##g;
// $text =~ s#[[:punct:]]##g;
text = text.replaceAll("(^\\s*|\\s*$)", "");
text = text.replaceAll("\\p{Punct}", "");
String[] textArray = text.split("\\s+");
// List<String> textList = new LinkedList<String>();
// textList.addAll(Arrays.asList(textArray));
if (textArray.length >= 1) {
tag = textArray[textArray.length - 1];
String pattern = "<[NO]>" + tag + "</[NO]>";
if (StringUtility.isMatchedNullSafe(sentence,
pattern)) {
// 1.2.1.1
text = text.replaceAll(tag, "");
modifier = text;
} else {
// 1.2.1.2
modifier = "";
tag = "ditto";
}
}
} else {
// 1.2.2
modifier = "";
tag = "ditto";
}
}
// case 1.3
else if (StringUtility.isMatchedNullSafe(sentence, "\\b("
+ Constant.CHARACTER + ")\\b")) {
modifier = "";
tag = "ditto";
}
}
List<String> mt = new ArrayList<String>(2);
mt.add(modifier);
mt.add(tag);
return mt;
} else {
return null;
}
}
public void finalizeIgnored(DataHolder dataholderHandler) {
List<SentenceStructure> sentences = dataholderHandler
.getSentencesByTagPattern("^ignore$");
for (SentenceStructure sentenceItem : sentences) {
String sentence = sentenceItem.getSentence();
if (sentence != null) {
Matcher m = StringUtility.createMatcher(sentence,
Constant.IGNOREPTN);
if (m.find()) {
String g1 = m.group(1);
if (StringUtility.isMatchedNullSafe(g1, "<N>")) {
int sentenceID = sentenceItem.getID();
SentenceStructure sentenceItemX = dataholderHandler
.getSentence(sentenceID);
sentenceItemX.setTag(null);
}
}
}
}
this.markupByPOS.run(dataholderHandler);
}
// tag remaining sentences whose tag is null
public void remainNullTag(DataHolder dataholderHandler) {
PropertyConfigurator.configure("conf/log4j.properties");
Logger myLogger = Logger.getLogger("learn.remainNullTag");
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
String tag = sentenceItem.getTag();
String source = sentenceItem.getSource();
boolean c1 = (tag == null);
boolean c2 = (StringUtils.equals(tag, ""));
boolean c3 = (StringUtils.equals(tag, "ditto"));
boolean c4 = (StringUtils.equals(tag, "unknown"));
boolean c5 = StringUtility.isMatchedNullSafe(source, "-0$");
if ((c1 || c2 || c3 || c4) && c5) {
sentenceItem.setModifier("");
sentenceItem.setTag(this.defaultGeneralTag);
myLogger.debug(String.format("mark [%d] <general>: %s",
sentenceItem.getID(), sentenceItem.getSentence()));
}
}
String nPhrasePattern = "(?:<[A-Z]*[NO]+[A-Z]*>[^<]+?<\\/[A-Z]*[NO]+[A-Z]*>\\s*)+";
String mPhrasePattern = "(?:<[A-Z]*M[A-Z]*>[^<]+?<\\/[A-Z]*M[A-Z]*>\\s*)+";
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
// String tag = sentenceItem.getTag();
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
String sentenceCopy = "" + sentenceItem.getSentence();
sentenceCopy = sentenceCopy.replaceAll("></?", "");
if (!StringUtility.isMatchedNullSafe(sentenceCopy, "<[NO]>")) {
dataholderHandler.tagSentenceWithMT(sentenceID, sentence, "",
"ditto", "remainnulltag-[R3]");
} else {
if (sentenceCopy != null) {
Matcher m2 = StringUtility.createMatcher(sentenceCopy,
"(.*?)(" + nPhrasePattern + ")");
if (m2.find()) {
String head = m2.group(1);
String tagPhrase = m2.group(2);
tagPhrase = StringUtility.trimString(tagPhrase);
if (StringUtility.isMatchedNullSafe(head, "\\b("
+ Constant.PREPOSITION + ")\\b")) {
dataholderHandler.tagSentenceWithMT(sentenceID,
sentence, "", "ditto",
"remainnulltag-[R3:ditto]");
} else {
String[] words = tagPhrase.split("\\s+");
String tagX = words[words.length - 1];
List<String> wordList = new ArrayList<String>();
wordList.addAll(Arrays.asList(words));
String modifier = StringUtils.join(
wordList.subList(0, wordList.size() - 1),
" ");
if (head != null) {
Matcher m22 = StringUtility.createMatcher(head,
"([^,]+)$");
if (m22.find()) {
modifier = m22.group(1) + " " + modifier;
}
tagX = tagX.replaceAll("<\\S+?>", "");
modifier = modifier.replaceAll("<\\S+?>", "");
tagX = StringUtility.trimString(tagX);
dataholderHandler.tagSentenceWithMT(sentenceID,
sentence, modifier, tagX,
"remainnulltag-[R3:m-t]");
}
}
}
}
}
}
}
// sentences that are tagged with a commons substructure, such as blades,
// margins need to be modified with its parent structure
public void commonSubstructure(DataHolder dataholderHandler) {
Set<String> commonTags = this
.collectCommonStructures(dataholderHandler);
String pattern = StringUtils.join(commonTags, "|");
pattern = "\\\\[?(" + pattern + ")\\\\]?";
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
String tag = sentenceItem.getTag();
boolean c1 = StringUtils.equals(tag, "ignore");
boolean c2 = (tag == null);
boolean c3 = (StringUtility.isMatchedNullSafe(tag, "^" + pattern
+ "$"));
if ((c1 || c2) && c3) {
int sentenceID = sentenceItem.getID();
String modifier = sentenceItem.getModifier();
String sentence = sentenceItem.getSentence();
if (!isModifierContainsStructure(dataholderHandler, modifier)
&& !StringUtility.isMatchedNullSafe(tag, "\\[")) {
// structure, and
// when the tag is not already inferred from parent tag:
// mid/[phyllaries]
String parentStructure = dataholderHandler
.getParentSentenceTag(sentenceID);
String pTag = "" + parentStructure;
parentStructure = parentStructure.replaceAll("([\\[\\]])",
"");
if (!StringUtils.equals(parentStructure, "[parenttag]")
&& !StringUtility.isMatchedNullSafe(modifier,
parentStructure)
&& !StringUtility.isMatchedNullSafe(tag,
parentStructure)) {
// remove any overlapped words btw parentStructure and
// tag
pTag = pTag.replaceAll("\\b" + tag + "\\b", "");
String modifierCopy = "" + modifier;
modifier = StringUtility.trimString(modifier);
pTag = StringUtility.trimString(pTag);
pTag = pTag.replaceAll("\\s+", " ");
if (isTypeModifier(dataholderHandler, modifier)) {
// cauline/base => cauline [leaf] / base
modifier = modifier + " " + pTag;
} else {
// main marginal/spine => [leaf blade] main
// marginal/spine
modifier = pTag + " " + modifier;
}
// tagsentwmt($sentid, $sentence, $modifier, $tag,
// "commonsubstructure");
dataholderHandler.tagSentenceWithMT(sentenceID,
sentence, modifier, tag, "commonsubstructure");
}
}
}
}
}
public boolean isTypeModifier(DataHolder dataholderHandler, String modifier) {
boolean res = false;
String[] words = modifier.split("\\s+");
String word = words[words.length - 1];
if (dataholderHandler.getModifierHolder().containsKey(word)) {
ModifierTableValue modifierItem = dataholderHandler
.getModifierHolder().get(modifier);
if (modifierItem.getIsTypeModifier()) {
res = true;
}
}
return res;
}
public boolean isModifierContainsStructure(DataHolder dataholderHandler,
String modifier) {
boolean res = false;
String[] words = modifier.split("\\s+");
for (String word : words) {
Set<String> POSTags = new HashSet<String>();
POSTags.add("p");
POSTags.add("s");
Set<String> PSWords = dataholderHandler
.getWordsFromWordPOSByPOSs(POSTags);
if (PSWords.contains(word)) {
res = true;
break;
}
}
return res;
}
// find tags with more than one different structure modifiers
public Set<String> collectCommonStructures(DataHolder dataholderHandler) {
Set<String> PSTags = new HashSet<String>(
Arrays.asList("s p".split(" ")));
Set<String> BTags = new HashSet<String>();
BTags.add("b");
Set<String> PSWords = dataholderHandler
.getWordsFromWordPOSByPOSs(PSTags);
Set<String> BWords = dataholderHandler.getWordsFromWordPOSByPOSs(BTags);
Set<String> structures = StringUtility.setSubtraction(PSWords, BWords);
Set<String> commonTags = new HashSet<String>();
return commonTags;
}
/**
* comma used for 'and': seen in TreatiseH, using comma for 'and' as in
* "adductor , diductor scars clearly differentiated ;", which is the same
* as "adductor and diductor scars clearly differentiated ;". ^m*n+,m*n+ or
* m*n+,m*n+;$, or m,mn. Clauses dealt in commaand do not contain "and/or".
* andortag() deals with clauses that do.
*
* @param dataholderHandler
*/
public void CommaAnd(DataHolder dataholderHandler) {
// cover m,mn
// last + =>*
// "(?:<[A-Z]*[NO]+[A-Z]*>[^<]+?<\/[A-Z]*[NO]+[A-Z]*>\\s*)+"
String nPhrasePattern = "(?:<[A-Z]*[NO]+[A-Z]*>[^<]+?<\\/[A-Z]*[NO]+[A-Z]*>\\s*)+";
// add last \\s*
// "(?:<[A-Z]*M[A-Z]*>[^<]+?<\/[A-Z]*M[A-Z]*>\\s*)"
String mPhrasePattern = "(?:<[A-Z]*M[A-Z]*>[^<]+?<\\/[A-Z]*M[A-Z]*>\\s*)";
// "(?:<[A-Z]*B[A-Z]*>[,:\.;<]<\/[A-Z]*B[A-Z]*>)"
String bPattern = "(?:<[A-Z]*B[A-Z]*>[,:.;<]<\\/[A-Z]*B[A-Z]*>)";
String commaPattern = "<B>,</B>";
String phrasePattern = mPhrasePattern + "\\s*" + nPhrasePattern;
String pattern = phrasePattern + "\\s+" + commaPattern + "\\s+(?:"
+ phrasePattern + "| |" + commaPattern + ")+";
String pattern1 = "^(" + pattern + ")";
String pattern2 = "(.*?)(" + pattern + ")\\s*" + bPattern + "\\$";
// changed last * to +
String pattern3 = "^((?:" + mPhrasePattern + "\\s+)+" + commaPattern
+ "\\s+(?:" + mPhrasePattern + "|\\s*|" + commaPattern + ")+"
+ mPhrasePattern + "+\\s*" + nPhrasePattern + ")";
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
String sentenceCopy = "" + sentence;
sentenceCopy = sentenceCopy.replaceAll("></?", "");
Matcher m1 = StringUtility.createMatcher(sentenceCopy, pattern1);
Matcher m2 = StringUtility.createMatcher(sentenceCopy, pattern2);
Matcher m3 = StringUtility.createMatcher(sentenceCopy, pattern3);
// case 1
if (m1.find()) {
String tag = m1.group(1);
tag = tag.replaceAll(",", "and");
tag = tag.replaceAll("</?\\S+?>", "");
tag = StringUtility.trimString(tag);
// case 1.1
if (!StringUtility.isMatchedNullSafe(tag, " and$")) {
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
"", tag, "commaand[CA1]");
}
}
// case 2
else if (m2.find()) {
String g1 = m2.group(1);
String tag = m2.group(2);
if (!StringUtility.isMatchedNullSafe(g1, "\\b("
+ Constant.PREPOSITION + ")\\b")
&& !StringUtility.isMatchedNullSafe(g1, "<N>")) {
tag = tag.replaceAll(",", "and");
tag = tag.replaceAll("</?\\S+?>", "");
tag = StringUtility.trimString(tag);
// case 2.1.1
if (!StringUtility.isMatchedNullSafe(tag, " and$")) {
dataholderHandler.tagSentenceWithMT(sentenceID,
sentence, "", tag, "commaand[CA2]");
}
}
}
// case 3
else if (m3.find()) {
String tag = m3.group(1);
String g1 = m3.group(1);
// case 3.1
if (!StringUtility.isMatchedNullSafe(g1, "\\b("
+ Constant.PREPOSITION + ")\\b")) {
tag = tag.replaceAll(",", "and");
tag = tag.replaceAll("</?\\S+?>", "");
tag = StringUtility.trimString(tag);
// case 3.1.1
if (!StringUtility.isMatchedNullSafe(tag, " and$")) {
String[] tagWords = tag.split("\\s+");
List<String> tagWordsList = new ArrayList<String>(
Arrays.asList(tagWords));
tag = tagWordsList.get(tagWordsList.size() - 1);
String modifier = StringUtils.join(tagWordsList
.subList(0, tagWordsList.size() - 1), " ");
dataholderHandler.tagSentenceWithMT(sentenceID,
sentence, modifier, tag, "commaand[CA3]");
}
}
}
}
}
public void normalizeModifiers(DataHolder dataholderHandler) {
Comparator<SentenceStructure> stringLengthComparator = new Comparator<SentenceStructure>() {
@Override
public int compare(SentenceStructure s1, SentenceStructure s2) {
String m1 = s1.getModifier();
String m2 = s2.getModifier();
if (m1.length() == m2.length()) {
return 0;
} else {
return m1.length() < m2.length() ? -1 : 1;
}
}
};
// Part 1
// non- and/or/to/plus cases
List<SentenceStructure> sentenceList = new ArrayList<SentenceStructure>();
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
String modifier = sentenceItem.getModifier();
boolean c1 = !StringUtils.equals(modifier, "");
boolean c2 = !StringUtility.isMatchedNullSafe(modifier,
" (and|or|nor|plus|to) ");
if (c1 && c2) {
sentenceList.add(sentenceItem);
}
}
Collections.sort(sentenceList, stringLengthComparator);
Collections.reverse(sentenceList);
for (SentenceStructure sentenceItem : sentenceList) {
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
String tag = sentenceItem.getTag();
String modifier = sentenceItem.getModifier();
String mCopy = "" + modifier;
modifier = finalizeModifier(dataholderHandler, modifier, tag, sentence);
modifier = modifier.replaceAll("\\s*\\[.*?\\]\\s*", " ");
modifier = StringUtility.trimString(modifier);
if (!StringUtils.equals(mCopy, modifier)) {
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag, "normalizemodifiers");
}
}
// Part 2
// deal with to: characterA to characterB organ (small to median shells)
List<SentenceStructure> sentenceList2 = new ArrayList<SentenceStructure>();
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
String modifier = sentenceItem.getModifier();
boolean c1 = StringUtility.isMatchedNullSafe(modifier, " to ");
if (c1) {
sentenceList2.add(sentenceItem);
}
}
Collections.sort(sentenceList2, stringLengthComparator);
for (SentenceStructure sentenceItem : sentenceList2) {
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
String tag = sentenceItem.getTag();
String modifier = sentenceItem.getModifier();
String mCopy = "" + modifier;
modifier = modifier.replaceAll(".*? to ", "");
List<String> mWords = new ArrayList<String>(Arrays.asList(modifier
.split("\\s+")));
Collections.reverse(mWords);
String m = "";
int count = dataholderHandler.getSentenceCount(true, m, true, tag);
String modi = "" + m;
for (String word : mWords) {
m = word + " " + m;
m = m.replaceAll("\\s+$", "");
int c = dataholderHandler.getSentenceCount(true, m, true, tag);
if (c > count) {
count = c;
modi = "" + m;
}
}
// tagsentwmt($sentid, $sentence, $modi, $tag,
// "normalizemodifiers");
dataholderHandler.tagSentenceWithMT(sentenceID, sentence, modi,
tag, "normalizemodifiers");
}
// Part 3
// modifier with and/or/plus
List<SentenceStructure> sentenceList3 = new ArrayList<SentenceStructure>();
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
String modifier = sentenceItem.getModifier();
boolean con = !StringUtility.isMatchedNullSafe(modifier,
" (and|or|nor|plus|to) ");
if (con) {
sentenceList3.add(sentenceItem);
}
}
Collections.sort(sentenceList3, stringLengthComparator);
Collections.reverse(sentenceList3);
for (SentenceStructure sentenceItem : sentenceList3) {
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
String tag = sentenceItem.getTag();
String modifier = sentenceItem.getModifier();
String mCopy = "" + modifier;
modifier = this.finalizeCompoundModifier(dataholderHandler,
modifier, tag, sentence);
modifier = modifier.replaceAll("\\s*\\[.*?\\]\\s*", " ");
modifier = StringUtility.trimString(modifier);
if (!StringUtils.equals(mCopy, modifier)) {
// tagsentwmt($sentid, $sentence, $modifier, $tag,
// "normalizemodifiers");
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag, "normalizemodifiers");
}
}
// Part 4
// modifier with and/or/plus
List<SentenceStructure> sentenceList4 = new ArrayList<SentenceStructure>();
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
String modifier = sentenceItem.getModifier();
boolean con = !StringUtility.isMatchedNullSafe(modifier,
"[_ ](and|or|nor|plus|to)[ _]");
if (con) {
sentenceList4.add(sentenceItem);
}
}
Collections.sort(sentenceList4, stringLengthComparator);
Collections.reverse(sentenceList4);
for (SentenceStructure sentenceItem : sentenceList4) {
int sentenceID = sentenceItem.getID();
String sentence = sentenceItem.getSentence();
String tag = sentenceItem.getTag();
String modifier = sentenceItem.getModifier();
String mTag = "" + tag;
tag = this.finalizeCompoundTag(tag, sentence);
tag = tag.replaceAll("\\s*\\[.*?\\]\\s*", " ");
tag = StringUtility.trimString(tag);
if (!StringUtils.equals(mTag, tag)) {
// tagsentwmt($sentid, $sentence, $modifier, $tag,
// "normalizemodifiers");
dataholderHandler.tagSentenceWithMT(sentenceID, sentence,
modifier, tag, "normalizemodifiers");
}
}
}
public String finalizeCompoundModifier(DataHolder dataholderHandler, String modifier, String tag,
String sentence) {
// case 1
if (StringUtility.isMatchedNullSafe(modifier, "\\[")) {
return modifier;
}
modifier = modifier.replaceAll("\\(.*?\\)", " ");
modifier = modifier.replaceAll("\\(.*", "");
modifier = modifier.replaceAll("\\W","");
modifier = modifier.replaceAll("\\s+", " ");
String mCopy = ""+modifier;
String result = "";
String m = "";
String n = "";
List<String> lastPart = new ArrayList(Arrays.asList(modifier.split("\\s+")));
Collections.reverse(lastPart);
int cut = 0;
for (String l : lastPart) {
if (cut == 0 && StringUtility.isMatchedNullSafe(sentence, "<N>"+l)) {
n = l + " " + n;
n = StringUtility.trimString(n);
}
else {
cut = 1;
String tm = StringUtility.isMatchedNullSafe(n, "\\w") ? l + " "
+ n : l;
for (SentenceStructure sentenceItem : dataholderHandler
.getSentenceHolder()) {
if (StringUtils.equals(sentenceItem.getModifier(), tm)
&& StringUtils.equals(sentenceItem.getTag(), tag)) {
m = l + " " + m;
}
}
break;
}
}
m = StringUtility.trimString(m);
n = StringUtility.trimString(n);
modifier = modifier.replaceAll("\\s*"+n, "");
// components
List<String> parts = new ArrayList<String>();
List<String> conj = new ArrayList<String>();
conj.add("");
if (modifier != null) {
Matcher m1 = StringUtility.createMatcher(modifier, "(^.*?) (and|or|nor|plus) (.*)");
while (m1.find()) {
String g1 = m1.group(1);
String g2 = m1.group(2);
String g3 = m1.group(3);
parts.add(g1);
parts.add(g2);
modifier = g3;
m1 = StringUtility.createMatcher(modifier, "(^.*?) (and|or|nor|plus) (.*)");
}
}
parts.add(modifier);
// at least one m in a part
// for (String part : parts) {
for (int i = 0; i < parts.size(); i++) {
String part = parts.get(i);
String[] words = part.split("\\s+");
boolean isFound = false;
String r = "";
for (String word : words) {
if ((this.checkedModifiers.containsKey(word) && this.checkedModifiers.get(word)) || StringUtility.isMatchedNullSafe(sentence, "<N>"+word)) {
isFound = true;
r = r + " " + word;
}
}
r = StringUtility.trimString(r);
result = result + " " + conj.get(i)+ " "+r;
String regex2 = "\\b(" + Constant.CHARACTER + "|" + Constant.STOP
+ "|" + Constant.NUMBER + "|" + Constant.CLUSTERSTRING
+ ")\\b";
if (!StringUtility.isMatchedNullSafe(r, "\\w")
|| StringUtility.isMatchedNullSafe(r, regex2)) {
result = "";
break;
}
}
result = StringUtility.isMatchedNullSafe(result, "\\w") ? result
+ " " + n : m + " " + n;
result = StringUtility.trimString(result);
return result;
}
// [bm]+n+&[bm]+n+
public String finalizeCompoundTag(String tag, String sentence) {
// avoid unmatched ( in regexp
tag = tag.replaceAll("\\(.*?\\)", " ");
tag = tag.replaceAll("\\(.*", "");
tag = tag.replaceAll("\\s+", " ");
String tCopy = "" + tag;
String result = "";
// components
List<String> parts = new ArrayList<String>();
List<String> conj = new ArrayList<String>();
conj.add("");
Matcher m1 = StringUtility.createMatcher(tag, "(^.*?)[_ ](and|or|nor|plus)[_ ](.*)");
while (m1.find()) {
String g1 = m1.group(1);
String g2 = m1.group(2);
String g3 = m1.group(3);
parts.add(g1);
conj.add(g2);
tag = g3;
m1 = StringUtility.createMatcher(tag, "(^.*?)[_ ](and|or|nor|plus)[_ ](.*)");
}
parts.add(tag);
// at least one m in a part
return null;
}
public String finalizeModifier(DataHolder dataholderHandler, String modifier, String tag, String sentence) {
String fModifier = "";
modifier = modifier.replaceAll("\\[.*?\\]", "");
modifier = StringUtility.trimString(modifier);
if (StringUtility.isMatchedNullSafe(modifier, "\\w")) {
List<String> mWords = new ArrayList<String>(Arrays.asList(modifier.split("\\s+")));
Collections.reverse(mWords);
for (String mWord : mWords) {
boolean isModifier = this.isModifier(dataholderHandler, mWord, modifier, tag);
if (isModifier) {
fModifier = mWord + " " + fModifier;
}
else {
break;
}
}
fModifier = fModifier.replaceAll("\\s+", "");
}
return fModifier;
}
public boolean isModifier(DataHolder dataholderHandler, String word, String modifier, String tag) {
if (this.checkedModifiers.containsKey(word)) {
if (this.checkedModifiers.get(word)) {
return true;
} else {
return false;
}
}
// if word is a "s", return 1
Set<String> nouns = new HashSet<String>(Arrays.asList("s p n"
.split(" ")));
List<Entry<WordPOSKey, WordPOSValue>> entries = dataholderHandler
.getWordPOSEntriesByWordPOS(word, nouns);
if (entries.size() > 0) {
this.checkedModifiers.put(word, true);
return true;
}
// if word is a "b", and not a "m", return 0
Set<String> bPOS = new HashSet<String>();
bPOS.add("b");
List<Entry<WordPOSKey, WordPOSValue>> boundaries = dataholderHandler
.getWordPOSEntriesByWordPOS(word, bPOS);
boolean c1 = (boundaries.size() > 0);
boolean c2 = dataholderHandler.getModifierHolder().containsKey(word);
if (c1 && !c2) {
// the word is a boundary word, but not a modifier
this.checkedModifiers.put(word, false);
return false;
}
if (!c1 && c2) {
this.checkedModifiers.put(word, true);
return true;
}
// when word has been used as "b" and "m" or neither "b" nor "m" and is not a "s"
int mCount = this.getMCount(dataholderHandler, word);
String wCopy = ""+word;
if (StringUtility.isMatchedNullSafe(word, "_")) {
wCopy = wCopy.replaceAll("_", " - ");
}
int tCount = 0;
String pattern = "(^| )"+wCopy+" ";
for (SentenceStructure sentenceItem : dataholderHandler.getSentenceHolder()) {
String oSentence = sentenceItem.getOriginalSentence();
if (StringUtility.isMatchedNullSafe(oSentence, pattern)) {
tCount++;
}
}
if (tCount == 0 || tCount > 0.25 * mCount) {
this.checkedModifiers.put(word, false);
return false;
}
else {
this.checkedModifiers.put(word, true);
return true;
}
}
public int getMCount(DataHolder dataholderHandler, String word) {
int count = 0;
String pattern = "(>| )"+word+"(</B></M>)? <N";
for (SentenceStructure sentenceItem : dataholderHandler.getSentenceHolder()) {
String sentence = sentenceItem.getSentence();
if (StringUtility.isMatchedNullSafe(sentence, pattern)) {
count++;
}
}
return count;
}
// some unused variables in perl
// directory of /descriptions folder
private String desDir = "";
// directory of /characters folder
private String chrDir = "";
// prefix for all tables generated by this program
private String prefix = "";
// default general tag
// knowledge base
private String knlgBase = "phenoscape";
private int DECISIONID = 0;
private Map<String, String> numberRecords = new HashMap<String, String>(); // word->(p|s)
private Map<String, String> singularRecords = new HashMap<String, String>();// word->singular
private Map<String, String> POSRecords = new HashMap<String, String>(); // word->POSs
// private Map<String, String> POSRecordsRECORDS = new HashMap<String,
// String>();
private String NEWDESCRIPTION = ""; // record the index of sentences that
// ends a description
private Hashtable<String, String> PLURALS = new Hashtable<String, String>();
private String TAGS = "";
// grouped #may contain q but not the last m, unless it is followed by a p
private String mptn = "((?:[mbq][,&]*)*(?:m|b|q(?=[pon])))";
// grouped #must present, no q allowed
private String nptn = "((?:[nop][,&]*)*[nop])";
// grouped #when following a p, a b could be a q
private String bptn = "([,;:\\\\.]*\\$|,*[bm]|(?<=[pon]),*q)";
private String SEGANDORPTN = "(?:" + mptn + nptn + ")";
private String ANDORPTN = "^(?:" + SEGANDORPTN + "[,&]+)*" + SEGANDORPTN
+ bptn;
// utility method
public LearnerUtility getLearnerUtility() {
return this.myLearnerUtility;
}
public ITokenizer getTokenizer() {
return this.myTokenizer;
}
public Configuration getConfiguration() {
return this.myConfiguration;
}
public static void main(String[] args) {
assertEquals("tagAllSentenceHelper", 1, 12);
}
}
|
package net.jforum.view.forum;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.jforum.Command;
import net.jforum.JForum;
import net.jforum.SessionFacade;
import net.jforum.dao.AttachmentDAO;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.ForumDAO;
import net.jforum.dao.PostDAO;
import net.jforum.dao.TopicDAO;
import net.jforum.dao.UserDAO;
import net.jforum.entities.Attachment;
import net.jforum.entities.Forum;
import net.jforum.entities.Post;
import net.jforum.entities.QuotaLimit;
import net.jforum.entities.Topic;
import net.jforum.entities.User;
import net.jforum.entities.UserSession;
import net.jforum.exceptions.AttachmentException;
import net.jforum.exceptions.AttachmentSizeTooBigException;
import net.jforum.repository.ForumRepository;
import net.jforum.repository.PostRepository;
import net.jforum.repository.RankingRepository;
import net.jforum.repository.SecurityRepository;
import net.jforum.repository.SmiliesRepository;
import net.jforum.repository.TopicRepository;
import net.jforum.security.PermissionControl;
import net.jforum.security.SecurityConstants;
import net.jforum.util.I18n;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import net.jforum.util.preferences.TemplateKeys;
import net.jforum.view.forum.common.AttachmentCommon;
import net.jforum.view.forum.common.ForumCommon;
import net.jforum.view.forum.common.PostCommon;
import net.jforum.view.forum.common.TopicsCommon;
import net.jforum.view.forum.common.ViewCommon;
import org.apache.log4j.Logger;
/**
* @author Rafael Steil
* @version $Id: PostAction.java,v 1.83 2005/07/17 16:16:37 rafaelsteil Exp $
*/
public class PostAction extends Command {
private static final Logger logger = Logger.getLogger(PostAction.class);
public void list() throws Exception {
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
UserDAO um = DataAccessDriver.getInstance().newUserDAO();
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
UserSession us = SessionFacade.getUserSession();
int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
int topicId = this.request.getIntParameter("topic_id");
Topic topic = tm.selectById(topicId);
// The topic exists?
if (topic.getId() == 0) {
this.topicNotFound();
return;
}
// Shall we proceed?
if (!SessionFacade.isLogged()) {
Forum f = ForumRepository.getForum(topic.getForumId());
if (f == null || !ForumRepository.isCategoryAccessible(f.getCategoryId())) {
this.setTemplateName(ViewCommon.contextToLogin());
return;
}
}
else if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
return;
}
int count = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int start = ViewCommon.getStartPage();
PermissionControl pc = SecurityRepository.get(us.getUserId());
boolean canEdit = false;
if (pc.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT)) {
canEdit = true;
}
Map usersMap = new HashMap();
List helperList = PostCommon.topicPosts(pm, um, usersMap, canEdit, us.getUserId(), topic.getId(), start, count);
// Ugly assumption:
// Is moderation pending for the topic?
if (topic.isModerated() && helperList.size() == 0) {
this.notModeratedYet();
return;
}
// Set the topic status as read
tm.updateReadStatus(topic.getId(), us.getUserId(), true);
tm.incrementTotalViews(topic.getId());
if (us.getUserId() != anonymousUser) {
((Map) SessionFacade.getAttribute(ConfigKeys.TOPICS_TRACKING)).put(new Integer(topic.getId()),
new Long(topic.getLastPostTimeInMillis().getTime()));
}
this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(topic.getForumId())));
this.context.put("canDownloadAttachments", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD));
this.context.put("am", new AttachmentCommon(this.request, topic.getForumId()));
this.context.put("karmaVotes", DataAccessDriver.getInstance().newKarmaDAO().getUserVotes(topic.getId(), us.getUserId()));
this.context.put("rssEnabled", SystemGlobals.getBoolValue(ConfigKeys.RSS_ENABLED));
this.context.put("canRemove",
SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_REMOVE));
this.context.put("canEdit", canEdit);
this.setTemplateName(TemplateKeys.POSTS_LIST);
this.context.put("allCategories", ForumCommon.getAllCategoriesAndForums(false));
this.context.put("topic", topic);
this.context.put("rank", new RankingRepository());
this.context.put("posts", helperList);
this.context.put("forum", ForumRepository.getForum(topic.getForumId()));
this.context.put("users", usersMap);
this.context.put("topicId", new Integer(topicId));
this.context.put("anonymousPosts", SecurityRepository.canAccess(SecurityConstants.PERM_ANONYMOUS_POST,
Integer.toString(topic.getForumId())));
this.context.put("watching", tm.isUserSubscribed(topicId, SessionFacade.getUserSession().getUserId()));
this.context.put("pageTitle", SystemGlobals.getValue(ConfigKeys.FORUM_NAME) + " - " + topic.getTitle());
this.context.put("isAdmin", SecurityRepository.canAccess(SecurityConstants.PERM_ADMINISTRATION));
this.context.put("readonly", !SecurityRepository.canAccess(SecurityConstants.PERM_READ_ONLY_FORUMS,
Integer.toString(topic.getForumId())));
this.context.put("replyOnly", !SecurityRepository.canAccess(SecurityConstants.PERM_REPLY_ONLY,
Integer.toString(topic.getForumId())));
this.context.put("isModerator", us.isModerator(topic.getForumId()));
// Topic Status
this.context.put("STATUS_LOCKED", new Integer(Topic.STATUS_LOCKED));
this.context.put("STATUS_UNLOCKED", new Integer(Topic.STATUS_UNLOCKED));
// Pagination
int totalPosts = tm.getTotalPosts(topic.getId());
ViewCommon.contextToPagination(start, totalPosts, count);
}
public void review() throws Exception {
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
UserDAO um = DataAccessDriver.getInstance().newUserDAO();
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
int userId = SessionFacade.getUserSession().getUserId();
int topicId = this.request.getIntParameter("topic_id");
Topic topic = tm.selectById(topicId);
if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
return;
}
int count = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int start = ViewCommon.getStartPage();
Map usersMap = new HashMap();
List helperList = PostCommon.topicPosts(pm, um, usersMap, false, userId, topic.getId(), start, count);
Collections.reverse(helperList);
this.setTemplateName(SystemGlobals.getValue(ConfigKeys.TEMPLATE_DIR) + "/empty.htm");
this.setTemplateName(TemplateKeys.POSTS_REVIEW);
this.context.put("posts", helperList);
this.context.put("users", usersMap);
}
private void topicNotFound() {
this.setTemplateName(TemplateKeys.POSTS_TOPIC_NOT_FOUND);
this.context.put("message", I18n.getMessage("PostShow.TopicNotFound"));
}
private void postNotFound() {
this.setTemplateName(TemplateKeys.POSTS_POST_NOT_FOUND);
this.context.put("message", I18n.getMessage("PostShow.PostNotFound"));
}
private void replyOnly()
{
this.setTemplateName(TemplateKeys.POSTS_REPLY_ONLY);
this.context.put("message", I18n.getMessage("PostShow.replyOnly"));
}
private boolean isReplyOnly(int forumId) throws Exception
{
return !SecurityRepository.canAccess(SecurityConstants.PERM_REPLY_ONLY,
Integer.toString(forumId));
}
public void insert() throws Exception
{
int forumId = this.request.getIntParameter("forum_id");
if (!TopicsCommon.isTopicAccessible(forumId)) {
return;
}
if (!this.anonymousPost(forumId)
|| this.isForumReadonly(forumId, this.request.getParameter("topic_id") != null)) {
return;
}
if (this.request.getParameter("topic_id") != null) {
int topicId = this.request.getIntParameter("topic_id");
Topic t = DataAccessDriver.getInstance().newTopicDAO().selectRaw(topicId);
if (t.getStatus() == Topic.STATUS_LOCKED) {
this.topicLocked();
return;
}
this.context.put("topic", t);
this.context.put("setType", false);
}
else {
if (this.isReplyOnly(forumId)) {
this.replyOnly();
return;
}
this.context.put("setType", true);
}
int userId = SessionFacade.getUserSession().getUserId();
this.setTemplateName(TemplateKeys.POSTS_INSERT);
// Attachments
boolean attachmentsEnabled = SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(forumId));
this.context.put("attachmentsEnabled", attachmentsEnabled);
if (attachmentsEnabled) {
QuotaLimit ql = new AttachmentCommon(this.request, forumId).getQuotaLimit(userId);
this.context.put("maxAttachmentsSize", new Long(ql != null ? ql.getSizeInBytes() : 1));
this.context.put("maxAttachments", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
}
boolean needCaptcha = SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_POSTS);
if (needCaptcha) {
SessionFacade.getUserSession().createNewCaptcha();
}
this.context.put("forum", ForumRepository.getForum(forumId));
this.context.put("action", "insertSave");
this.context.put("start", this.request.getParameter("start"));
this.context.put("isNewPost", true);
this.context.put("needCaptcha", needCaptcha);
this.context.put("htmlAllowed",
SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED, Integer.toString(forumId)));
this.context.put("canCreateStickyOrAnnouncementTopics",
SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS));
User user = DataAccessDriver.getInstance().newUserDAO().selectById(userId);
user.setSignature(PostCommon.processText(user.getSignature()));
user.setSignature(PostCommon.processSmilies(user.getSignature(), SmiliesRepository.getSmilies()));
if (this.request.getParameter("preview") != null) {
user.setNotifyOnMessagesEnabled(this.request.getParameter("notify") != null);
}
this.context.put("user", user);
}
public void edit() throws Exception {
this.edit(false, null);
}
private void edit(boolean preview, Post p) throws Exception {
int userId = SessionFacade.getUserSession().getUserId();
int aId = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
boolean canAccess = false;
if (!preview) {
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
p = pm.selectById(this.request.getIntParameter("post_id"));
// The post exist?
if (p.getId() == 0) {
this.postNotFound();
return;
}
}
boolean isModerator = SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT);
canAccess = (isModerator || p.getUserId() == userId);
if ((userId != aId) && canAccess) {
Topic topic = DataAccessDriver.getInstance().newTopicDAO().selectById(p.getTopicId());
if (!TopicsCommon.isTopicAccessible(topic.getForumId())) {
return;
}
if (topic.getStatus() == Topic.STATUS_LOCKED && !isModerator) {
this.topicLocked();
return;
}
if (preview && this.request.getParameter("topic_type") != null) {
topic.setType(this.request.getIntParameter("topic_type"));
}
if (p.hasAttachments()) {
this.context.put("attachments",
DataAccessDriver.getInstance().newAttachmentDAO().selectAttachments(p.getId()));
}
this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(p.getForumId())));
QuotaLimit ql = new AttachmentCommon(this.request, p.getForumId()).getQuotaLimit(userId);
this.context.put("maxAttachmentsSize", new Long(ql != null ? ql.getSizeInBytes() : 1));
this.context.put("maxAttachments", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
this.context.put("forum", ForumRepository.getForum(p.getForumId()));
this.context.put("action", "editSave");
this.context.put("post", p);
this.context.put("setType", p.getId() == topic.getFirstPostId());
this.context.put("topic", topic);
this.setTemplateName(TemplateKeys.POSTS_EDIT);
this.context.put("start", this.request.getParameter("start"));
this.context.put("htmlAllowed", SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED,
Integer.toString(topic.getForumId())));
this.context.put("canCreateStickyOrAnnouncementTopics",
SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS));
}
else {
this.setTemplateName(TemplateKeys.POSTS_EDIT_CANNOTEDIT);
this.context.put("message", I18n.getMessage("CannotEditPost"));
}
User u = PostCommon.getUserForDisplay(userId);
if (preview) {
u.setNotifyOnMessagesEnabled(this.request.getParameter("notify") != null);
if (u.getId() != p.getUserId()) {
// Probably a moderator is editing the message
this.context.put("previewUser", PostCommon.getUserForDisplay(p.getUserId()));
}
}
this.context.put("user", u);
}
public void quote() throws Exception {
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
Post p = pm.selectById(this.request.getIntParameter("post_id"));
if (!this.anonymousPost(p.getForumId())) {
return;
}
Topic t = DataAccessDriver.getInstance().newTopicDAO().selectRaw(p.getTopicId());
if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
return;
}
if (t.getStatus() == Topic.STATUS_LOCKED) {
this.topicLocked();
return;
}
if (p.getId() == 0) {
this.postNotFound();
return;
}
if (p.isModerationNeeded()) {
this.notModeratedYet();
return;
}
this.context.put("forum", ForumRepository.getForum(p.getForumId()));
this.context.put("action", "insertSave");
this.context.put("post", p);
UserDAO um = DataAccessDriver.getInstance().newUserDAO();
User u = um.selectById(p.getUserId());
Topic topic = DataAccessDriver.getInstance().newTopicDAO().selectById(p.getTopicId());
int userId = SessionFacade.getUserSession().getUserId();
this.context.put("attachmentsEnabled", SecurityRepository.canAccess(
SecurityConstants.PERM_ATTACHMENTS_ENABLED, Integer.toString(topic.getForumId())));
QuotaLimit ql = new AttachmentCommon(this.request, topic.getForumId()).getQuotaLimit(userId);
this.context.put("maxAttachmentsSize", new Long(ql != null ? ql.getSizeInBytes() : 1));
this.context.put("maxAttachments", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
this.context.put("isNewPost", true);
this.context.put("topic", topic);
this.context.put("quote", "true");
this.context.put("quoteUser", u.getUsername());
this.setTemplateName(TemplateKeys.POSTS_QUOTE);
this.context.put("setType", false);
this.context.put("htmlAllowed", SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED,
Integer.toString(topic.getForumId())));
this.context.put("start", this.request.getParameter("start"));
this.context.put("user", DataAccessDriver.getInstance().newUserDAO().selectById(userId));
}
public void editSave() throws Exception {
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
Post p = pm.selectById(this.request.getIntParameter("post_id"));
p = PostCommon.fillPostFromRequest(p, true);
// The user wants to preview the message before posting it?
if (this.request.getParameter("preview") != null) {
this.context.put("preview", true);
Post postPreview = new Post(p);
this.context.put("postPreview", PostCommon.preparePostForDisplay(postPreview));
this.edit(true, p);
}
else {
AttachmentCommon attachments = new AttachmentCommon(this.request, p.getForumId());
try {
attachments.preProcess();
}
catch (AttachmentException e) {
JForum.enableCancelCommit();
p.setText(this.request.getParameter("message"));
this.context.put("errorMessage", e.getMessage());
this.context.put("post", p);
this.edit(false, p);
return;
}
Topic t = tm.selectById(p.getTopicId());
if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
return;
}
if (t.getStatus() == Topic.STATUS_LOCKED
&& !SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT)) {
this.topicLocked();
return;
}
pm.update(p);
// Attachments
attachments.editAttachments(p.getId(), p.getForumId());
attachments.insertAttachments(p.getId());
// Updates the topic title
if (t.getFirstPostId() == p.getId()) {
t.setTitle(p.getSubject());
if (SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS)) {
t.setType(this.request.getIntParameter("topic_type"));
}
tm.update(t);
ForumRepository.reloadForum(t.getForumId());
TopicRepository.clearCache(t.getForumId());
}
if (this.request.getParameter("notify") == null) {
tm.removeSubscription(p.getTopicId(), SessionFacade.getUserSession().getUserId());
}
String path = this.request.getContextPath() + "/posts/list/";
String start = this.request.getParameter("start");
if (start != null && !start.equals("0")) {
path += start + "/";
}
path += p.getTopicId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) + "#" + p.getId();
JForum.setRedirect(path);
if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
PostRepository.update(p.getTopicId(), PostCommon.preparePostForDisplay(p));
}
}
}
public void waitingModeration()
{
this.setTemplateName(TemplateKeys.POSTS_WAITING);
int topicId = this.request.getIntParameter("topic_id");
String path = this.request.getContextPath();
if (topicId == 0) {
path += "/forums/show/" + this.request.getParameter("forum_id");
}
else {
path += "/posts/list/" + topicId;
}
this.context.put("message", I18n.getMessage("PostShow.waitingModeration",
new String[] { path + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) }));
}
private void notModeratedYet()
{
this.setTemplateName(TemplateKeys.POSTS_NOT_MODERATED);
this.context.put("message", I18n.getMessage("PostShow.notModeratedYet"));
}
public void insertSave() throws Exception
{
int forumId = this.request.getIntParameter("forum_id");
boolean firstPost = false;
if (!this.anonymousPost(forumId)) {
SessionFacade.setAttribute(ConfigKeys.REQUEST_DUMP, this.request.dumpRequest());
return;
}
Topic t = new Topic();
t.setId(-1);
t.setForumId(forumId);
if (!TopicsCommon.isTopicAccessible(t.getForumId())
|| this.isForumReadonly(t.getForumId(), this.request.getParameter("topic_id") != null)) {
return;
}
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
ForumDAO fm = DataAccessDriver.getInstance().newForumDAO();
if (this.request.getParameter("topic_id") != null) {
t = tm.selectById(this.request.getIntParameter("topic_id"));
// Cannot insert new messages on locked topics
if (t.getStatus() == Topic.STATUS_LOCKED) {
this.topicLocked();
return;
}
}
else {
if (this.isReplyOnly(forumId)) {
this.replyOnly();
return;
}
}
if (this.request.getParameter("topic_type") != null) {
t.setType(this.request.getIntParameter("topic_type"));
}
UserSession us = SessionFacade.getUserSession();
User u = new User();
u.setId(us.getUserId());
u.setUsername(us.getUsername());
t.setPostedBy(u);
// Set the Post
Post p = PostCommon.fillPostFromRequest();
if (p.getText() == null || p.getText().trim().equals("")) {
this.insert();
return;
}
// Check the elapsed time since the last post from the user
int delay = SystemGlobals.getIntValue(ConfigKeys.POSTS_NEW_DELAY);
if (delay > 0) {
Long lastPostTime = (Long)SessionFacade.getAttribute(ConfigKeys.LAST_POST_TIME);
if (lastPostTime != null) {
if (System.currentTimeMillis() < (lastPostTime.longValue() + delay)) {
this.context.put("post", p);
this.context.put("start", this.request.getParameter("start"));
this.context.put("error", I18n.getMessage("PostForm.tooSoon"));
this.insert();
return;
}
}
}
p.setForumId(this.request.getIntParameter("forum_id"));
if (p.getSubject() == null || p.getSubject() == "") {
p.setSubject(t.getTitle());
}
boolean needCaptcha = SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_POSTS);
if (needCaptcha) {
if (!us.validateCaptchaResponse(this.request.getParameter("captcha_anwser"))) {
this.context.put("post", p);
this.context.put("start", this.request.getParameter("start"));
this.context.put("error", I18n.getMessage("CaptchaResponseFails"));
this.insert();
return;
}
}
boolean preview = (this.request.getParameter("preview") != null);
boolean moderate = false;
if (!preview) {
AttachmentCommon attachments = new AttachmentCommon(this.request, forumId);
try {
attachments.preProcess();
}
catch (AttachmentSizeTooBigException e) {
JForum.enableCancelCommit();
p.setText(this.request.getParameter("message"));
p.setId(0);
this.context.put("errorMessage", e.getMessage());
this.context.put("post", p);
this.insert();
return;
}
// If topic_id is -1, then is the first post
if (t.getId() == -1) {
t.setTime(new Date());
t.setTitle(this.request.getParameter("subject"));
t.setModerated(ForumRepository.getForum(forumId).isModerated());
t.setId(tm.addNew(t));
firstPost = true;
}
// Moderators and admins don't need to have their messages moderated
moderate = (t.isModerated()
&& !SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION)
&& !SecurityRepository.canAccess(SecurityConstants.PERM_ADMINISTRATION));
// Topic watch
if (this.request.getParameter("notify") != null) {
this.watch(tm, t.getId(), u.getId());
}
p.setTopicId(t.getId());
// Save the remaining stuff
p.setModerate(moderate);
int postId = pm.addNew(p);
if (this.request.getParameter("topic_id") == null) {
t.setFirstPostId(postId);
}
tm.update(t);
attachments.insertAttachments(postId);
if (!moderate) {
DataAccessDriver.getInstance().newUserDAO().incrementPosts(p.getUserId());
TopicsCommon.updateBoardStatus(t, postId, firstPost, tm, fm);
TopicsCommon.notifyUsers(t, tm);
String path = this.request.getContextPath() + "/posts/list/";
int start = ViewCommon.getStartPage();
path += this.startPage(t, start) + "/";
path += t.getId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) + "#" + postId;
JForum.setRedirect(path);
int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
if (u.getId() != anonymousUser) {
((Map) SessionFacade.getAttribute(ConfigKeys.TOPICS_TRACKING)).put(new Integer(t.getId()),
new Long(p.getTime().getTime()));
}
if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
SimpleDateFormat df = new SimpleDateFormat(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
p.setFormatedTime(df.format(p.getTime()));
PostRepository.append(p.getTopicId(), PostCommon.preparePostForDisplay(p));
}
}
else {
JForum.setRedirect(this.request.getContextPath() + "/posts/waitingModeration/" + (firstPost ? 0 : t.getId())
+ "/" + t.getForumId()
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
if (delay > 0) {
SessionFacade.setAttribute(ConfigKeys.LAST_POST_TIME, new Long(System.currentTimeMillis()));
}
}
else {
this.context.put("preview", true);
this.context.put("post", p);
this.context.put("start", this.request.getParameter("start"));
Post postPreview = new Post(p);
this.context.put("postPreview", PostCommon.preparePostForDisplay(postPreview));
this.insert();
}
}
private int startPage(Topic t, int currentStart) {
int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int newStart = (t.getTotalReplies() + 1) / postsPerPage * postsPerPage;
if (newStart > currentStart) {
return newStart;
}
return currentStart;
}
public void delete() throws Exception {
if (!SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_REMOVE)) {
this.setTemplateName(TemplateKeys.POSTS_CANNOT_DELETE);
this.context.put("message", I18n.getMessage("CannotRemovePost"));
return;
}
// Post
PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
Post p = pm.selectById(this.request.getIntParameter("post_id"));
TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
Topic t = tm.selectById(p.getTopicId());
if (!TopicsCommon.isTopicAccessible(t.getForumId())) {
return;
}
if (p.getId() == 0) {
this.postNotFound();
return;
}
pm.delete(p);
DataAccessDriver.getInstance().newUserDAO().decrementPosts(p.getUserId());
// Attachments
new AttachmentCommon(this.request, p.getForumId()).deleteAttachments(p.getId(), p.getForumId());
// Topic
tm.decrementTotalReplies(p.getTopicId());
int maxPostId = tm.getMaxPostId(p.getTopicId());
if (maxPostId > -1) {
tm.setLastPostId(p.getTopicId(), maxPostId);
}
int minPostId = tm.getMinPostId(p.getTopicId());
if (minPostId > -1) {
tm.setFirstPostId(p.getTopicId(), minPostId);
}
// Forum
ForumDAO fm = DataAccessDriver.getInstance().newForumDAO();
maxPostId = fm.getMaxPostId(p.getForumId());
if (maxPostId > -1) {
fm.setLastPost(p.getForumId(), maxPostId);
}
// It was the last remaining post in the topic?
int totalPosts = tm.getTotalPosts(p.getTopicId());
if (totalPosts > 0) {
String page = this.request.getParameter("start");
String returnPath = this.request.getContextPath() + "/posts/list/";
if (page != null && !page.equals("") && !page.equals("0")) {
int postsPerPage = SystemGlobals.getIntValue(ConfigKeys.POST_PER_PAGE);
int newPage = Integer.parseInt(page);
if (totalPosts % postsPerPage == 0) {
newPage -= postsPerPage;
}
returnPath += newPage + "/";
}
JForum.setRedirect(returnPath + p.getTopicId() + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
else {
// Ok, all posts were removed. Time to say goodbye
TopicsCommon.deleteTopic(p.getTopicId(), p.getForumId(), false);
JForum.setRedirect(this.request.getContextPath() + "/forums/show/" + p.getForumId()
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
ForumRepository.reloadForum(p.getForumId());
TopicRepository.clearCache(p.getForumId());
PostRepository.clearCache(p.getTopicId());
}
private void watch(TopicDAO tm, int topicId, int userId) throws Exception {
if (!tm.isUserSubscribed(topicId, userId)) {
tm.subscribeUser(topicId, userId);
}
}
public void watch() throws Exception {
int topicId = this.request.getIntParameter("topic_id");
int userId = SessionFacade.getUserSession().getUserId();
this.watch(DataAccessDriver.getInstance().newTopicDAO(), topicId, userId);
this.list();
}
public void unwatch() throws Exception {
if (SessionFacade.isLogged()) {
int topicId = this.request.getIntParameter("topic_id");
int userId = SessionFacade.getUserSession().getUserId();
String start = this.request.getParameter("start");
DataAccessDriver.getInstance().newTopicDAO().removeSubscription(topicId, userId);
String returnPath = this.request.getContextPath() + "/posts/list/";
if (start != null && !start.equals("")) {
returnPath += start + "/";
}
returnPath += topicId + SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION);
this.setTemplateName(TemplateKeys.POSTS_UNWATCH);
this.context.put("message", I18n.getMessage("ForumBase.unwatched", new String[] { returnPath }));
}
else {
this.setTemplateName(ViewCommon.contextToLogin());
}
}
public void downloadAttach() throws Exception
{
if (!SecurityRepository.canAccess(SecurityConstants.PERM_ATTACHMENTS_DOWNLOAD)) {
this.setTemplateName(TemplateKeys.POSTS_CANNOT_DOWNLOAD);
this.context.put("message", I18n.getMessage("Attachments.featureDisabled"));
return;
}
int id = this.request.getIntParameter("attach_id");
AttachmentDAO am = DataAccessDriver.getInstance().newAttachmentDAO();
Attachment a = am.selectAttachmentById(id);
String filename = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
+ "/"
+ a.getInfo().getPhysicalFilename();
if (!new File(filename).exists()) {
this.setTemplateName(TemplateKeys.POSTS_ATTACH_NOTFOUND);
this.context.put("message", I18n.getMessage("Attachments.notFound"));
return;
}
a.getInfo().setDownloadCount(a.getInfo().getDownloadCount() + 1);
am.updateAttachment(a);
FileInputStream fis = new FileInputStream(filename);
OutputStream os = response.getOutputStream();
if(am.isPhysicalDownloadMode(a.getInfo().getExtension().getExtensionGroupId()))
{
this.response.setContentType("application/octet-stream");
}
else
{
this.response.setContentType(a.getInfo().getMimetype());
}
this.response.setHeader("Content-Disposition", "attachment; filename=\"" + a.getInfo().getRealFilename() + "\";");
this.response.setContentLength((int)a.getInfo().getFilesize());
byte[] b = new byte[4096];
int c = 0;
while ((c = fis.read(b)) != -1) {
os.write(b);
}
fis.close();
os.close();
JForum.enableBinaryContent(true);
}
private void topicLocked() {
this.setTemplateName(TemplateKeys.POSTS_TOPIC_LOCKED);
this.context.put("message", I18n.getMessage("PostShow.topicLocked"));
}
public void listSmilies()
{
this.setTemplateName(SystemGlobals.getValue(ConfigKeys.TEMPLATE_DIR) + "/empty.htm");
this.setTemplateName(TemplateKeys.POSTS_LIST_SMILIES);
this.context.put("smilies", SmiliesRepository.getSmilies());
}
private boolean isForumReadonly(int forumId, boolean isReply) throws Exception {
if (!SecurityRepository.canAccess(SecurityConstants.PERM_READ_ONLY_FORUMS, Integer.toString(forumId))) {
if (isReply) {
this.list();
}
else {
JForum.setRedirect(this.request.getContextPath() + "/forums/show/" + forumId
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
return true;
}
return false;
}
private boolean anonymousPost(int forumId) throws Exception {
// Check if anonymous posts are allowed
if (!SessionFacade.isLogged()
&& !SecurityRepository.canAccess(SecurityConstants.PERM_ANONYMOUS_POST, Integer.toString(forumId))) {
this.setTemplateName(ViewCommon.contextToLogin());
return false;
}
return true;
}
}
|
package nl.mpi.arbil.data;
import nl.mpi.arbil.templates.ArbilTemplateManager;
import nl.mpi.arbil.templates.ArbilTemplate;
import nl.mpi.arbil.*;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import org.w3c.dom.Document;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.tree.DefaultMutableTreeNode;
import nl.mpi.arbil.MetadataFile.CmdiUtils;
import nl.mpi.arbil.clarin.CmdiComponentBuilder;
import nl.mpi.arbil.clarin.CmdiComponentLinkReader;
import nl.mpi.arbil.clarin.CmdiProfileReader;
import nl.mpi.arbil.clarin.FieldUpdateRequest;
import nl.mpi.arbil.MetadataFile.ImdiUtils;
import nl.mpi.arbil.MetadataFile.MetadataUtils;
public class ImdiTreeObject implements Comparable {
public MetadataUtils metadataUtils;
public ArbilTemplate nodeTemplate;
// static ImdiIcons imdiIcons = new ImdiIcons();
private static Vector listDiscardedOfAttributes = new Vector(); // a list of all unused imdi attributes, only used for testing
private boolean debugOn = false;
private Hashtable<String, ImdiField[]> fieldHashtable; //// TODO: this should be changed to a vector or contain an array so that duplicate named fields can be stored ////
private ImdiTreeObject[] childArray = new ImdiTreeObject[0];
public boolean imdiDataLoaded;
public int resourceFileServerResponse = -1; // -1 = not set otherwise this will be the http response code
public String hashString;
public String mpiMimeType = null;
public String typeCheckerMessage;
public int matchesInCache;
public int matchesRemote;
public int matchesLocalFileSystem;
public boolean fileNotFound;
public boolean isInfoLink = false;
private boolean needsSaveToDisk;
private String nodeText, lastNodeText = "loading imdi...";
// private boolean nodeTextChanged = false;
private URI nodeUri;
public ImdiField resourceUrlField;
public CmdiComponentLinkReader cmdiComponentLinkReader = null;
public boolean isDirectory;
private ImageIcon icon;
private boolean nodeEnabled;
public boolean hasSchemaError = false;
// merge to one array of domid url imditreeobject
private String[][] childLinks = new String[0][0]; // each element in this array is an array [linkPath, linkId]. When the link is from an imdi the id will be the node id, when from get links or list direcotry id will be null
private Vector/*<Component>*/ containersOfThisNode;
private int isLoadingCount = 0;
final private Object loadingCountLock = new Object();
@Deprecated
public boolean lockedByLoadingThread = false;
// private boolean isFavourite;
public boolean hasArchiveHandle = false;
// public boolean autoLoadChildNodes = false;
//public Vector<String[]> addQueue;
public boolean scrollToRequested = false;
// public Vector<ImdiTreeObject> mergeQueue;
// public boolean jumpToRequested = false; // dubious about this being here but it seems to fit here best
private ImdiTreeObject domParentImdi = null; // the parent imdi containing the dom, only set for imdi child nodes
public String xmlNodeId = null; // only set for imdi child nodes and is the xml node id relating to this imdi tree object
public File thumbnailFile = null;
public final Object domLockObject = new Object();
protected ImdiTreeObject(URI localUri) {
// System.out.println("ImdiTreeObject: " + localUri);
containersOfThisNode = new Vector<Component>();
// addQueue = new Vector<String[]>();
nodeUri = localUri;
if (nodeUri != null) {
metadataUtils = ImdiTreeObject.getMetadataUtils(nodeUri.toString());
}
initNodeVariables();
}
// set the node text only if it is null
public void setNodeText(String localNodeText) {
if (nodeText == null) {
nodeText = localNodeText;
}
}
// TODO: this is not used yet but may be required for unicode paths
private String urlEncodePath(String inputPath) {
// url encode the path elements
String encodedString = null;
try {
for (String inputStringPart : inputPath.split("/")) {
// System.out.println("inputStringPart: " + inputStringPart);
if (encodedString == null) {
encodedString = URLEncoder.encode(inputStringPart, "UTF-8");
} else {
encodedString = encodedString + "/" + URLEncoder.encode(inputStringPart, "UTF-8");
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
return encodedString;
}
static public URI conformStringToUrl(String inputUrlString) {
// System.out.println("conformStringToUrl: " + inputUrlString);
URI returnUrl = null;
try {
// localUrlString = localUrlString.replace("\\", "/");
if (!inputUrlString.toLowerCase().startsWith("http") && !inputUrlString.toLowerCase().startsWith("file:") && !inputUrlString.toLowerCase().startsWith(".")) {
returnUrl = new File(inputUrlString).toURI();
} else {
// apache method
// URI tempURI = new URI(inputUrlString);
// URI returnURI = URIUtils.createURI(tempURI.getScheme(), tempURI.getHost(), tempURI.getPort(), tempURI.getPath(), tempURI.getQuery(), tempURI.getFragment());
// return returnURI;
// end apache method : this requires the uri to be broken into its parts so we might as well do it with the standard classes
// mpi method
// URI returnURI = URIUtil.newURI(inputUrlString);
// end mpi method : this will url encode the # etc. and therefore loose the fragment and other parts
// boolean isUncPath = inputUrlString.toLowerCase().startsWith("file:////");
// if (isUncPath) {
// try {
// returnURI = new URI("file:////" + returnURI.toString().substring("file:/".length()));
// } catch (URISyntaxException urise) {
// GuiHelper.linorgBugCatcher.logError(urise);
// separate the path and protocol
int protocolEndIndex;
if (inputUrlString.startsWith(".")) {
// TODO: this is un tested for ./ paths, but at this stage it appears unlikey to ever be needed
protocolEndIndex = 0;
} else {
protocolEndIndex = inputUrlString.indexOf(":/");
}
// while (inputUrlString.charAt(protocolEndIndex) == '/') {
// protocolEndIndex++;
String protocolComponent = inputUrlString.substring(0, protocolEndIndex);
String remainingComponents = inputUrlString.substring(protocolEndIndex + 1);
String[] pathComponentArray = remainingComponents.split("
String pathComponent = pathComponentArray[0];
String fragmentComponent = null;
if (pathComponentArray.length > 1) {
fragmentComponent = pathComponentArray[1];
}
// note that this must be done as separate parameters not a single string otherwise it will not get url encoded
// TODO: this could require the other url components to be added here
returnUrl = new URI(protocolComponent, pathComponent, fragmentComponent);
// System.out.println("returnUrl: " + returnUrl);
//// int protocolEndIndex = inputUrlString.lastIndexOf("/", "xxxx:".length());
// String pathComponentEncoded = URLEncoder.encode(pathComponent, "UTF-8");
// returnUrl = new URI(protocolComponent + pathComponentEncoded);
// System.out.println("returnUrl: " + returnUrl);
}
// // if the imdi api finds only one / after the file: it will interpret the url as relative and make a bit of a mess of it, so we have to make sure that we have two for the url and one for the root
// if (returnUrl.toString().toLowerCase().startsWith("file:") && !returnUrl.toString().toLowerCase().startsWith("file:///")) {
// // here we assume that this application does not use relative file paths
// returnUrl = new URL("file", "", "//" + returnUrl.getPath());
// System.out.println("conformStringToUrl URI: " + new URI(returnUrl.toString()));
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
// System.out.println("conformStringToUrl out: " + returnUrl.toString());
return normaliseURI(returnUrl);
}
static public URI normaliseURI(URI inputURI) {
// System.out.println("normaliseURI: " + inputURI);
boolean isUncPath = inputURI.toString().toLowerCase().startsWith("file:
URI returnURI = inputURI.normalize();
if (isUncPath) {
try {
// note that this must use the single string parameter to prevent re url encoding
returnURI = new URI("file:////" + returnURI.toString().substring("file:/".length()));
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
return returnURI;
}
// static methods for testing imdi file and object types
static public boolean isImdiNode(Object unknownObj) {
if (unknownObj == null) {
return false;
}
return (unknownObj instanceof ImdiTreeObject);
}
static public boolean isStringLocal(String urlString) {
return (!urlString.startsWith("http"));
}
static public boolean isPathHistoryFile(String urlString) {
// System.out.println("isStringImdiHistoryFile" + urlString);
// System.out.println("isStringImdiHistoryFile" + urlString.replaceAll(".imdi.[0-9]*$", ".imdi"));
return isPathMetadata(urlString.replaceAll("mdi.[0-9]*$", "mdi"));
}
static public boolean isPathMetadata(String urlString) {
return isPathImdi(urlString) || isPathCmdi(urlString); // change made for clarin
}
static public boolean isPathImdi(String urlString) {
return urlString.endsWith(".imdi");
}
static public boolean isPathCmdi(String urlString) {
return urlString.endsWith(".cmdi");
}
static public boolean isStringImdiChild(String urlString) {
return urlString.contains("#.METATRANSCRIPT") || urlString.contains("#.CMD"); // change made for clarin
}
static public MetadataUtils getMetadataUtils(String urlString) {
if (ImdiTreeObject.isPathCmdi(urlString)) {
return new CmdiUtils();
} else if (ImdiTreeObject.isPathImdi(urlString)) {
return new ImdiUtils();
}
return null;
}
// end static methods for testing imdi file and object types
public boolean getNeedsSaveToDisk() {
// when the dom parent node is saved all the sub nodes are also saved so we need to clear this flag
if (needsSaveToDisk && !this.getParentDomNode().needsSaveToDisk) {
needsSaveToDisk = false;
}
return needsSaveToDisk;
}
public boolean hasChangedFields() {
boolean fieldsHaveChanges = false;
for (ImdiField[] currentFieldArray : this.fieldHashtable.values()) {
for (ImdiField currentField : currentFieldArray) {
if (currentField.fieldNeedsSaveToDisk()) {
fieldsHaveChanges = true;
}
}
}
return fieldsHaveChanges;
}
public void setImdiNeedsSaveToDisk(ImdiField originatingField, boolean updateUI) {
if (resourceUrlField != null && resourceUrlField.equals(originatingField)) {
hashString = null;
mpiMimeType = null;
thumbnailFile = null;
typeCheckerMessage = null;
MimeHashQueue.getSingleInstance().addToQueue(this);
}
boolean imdiNeedsSaveToDisk = hasChangedFields();
if (isMetaDataNode() && !isImdiChild()) {
if (imdiNeedsSaveToDisk == false) {
for (ImdiTreeObject childNode : getAllChildren()) {
if (childNode.needsSaveToDisk) {
imdiNeedsSaveToDisk = true;
}
}
}
if (this.needsSaveToDisk != imdiNeedsSaveToDisk) {
if (imdiNeedsSaveToDisk) {
ImdiLoader.getSingleInstance().addNodeNeedingSave(this);
} else {
ImdiLoader.getSingleInstance().removeNodesNeedingSave(this);
}
this.needsSaveToDisk = imdiNeedsSaveToDisk;
}
} else {
this.needsSaveToDisk = imdiNeedsSaveToDisk; // this must be set before setImdiNeedsSaveToDisk is called
this.getParentDomNode().setImdiNeedsSaveToDisk(null, updateUI);
}
if (updateUI) {
this.clearIcon();
}
}
public String getAnyMimeType() {
if (mpiMimeType == null && hasResource()) { // use the format from the imdi file if the type checker failed eg if the file is on the server
ImdiField[] formatField = fieldHashtable.get("Format");
if (formatField != null && formatField.length > 0) {
return formatField[0].getFieldValue();
}
}
return mpiMimeType;
}
public void setMimeType(String[] typeCheckerMessageArray) {
mpiMimeType = typeCheckerMessageArray[0];
typeCheckerMessage = typeCheckerMessageArray[1];
if (!isMetaDataNode() && isLocal() && mpiMimeType != null) {
// add the mime type for loose files
ImdiField mimeTypeField = new ImdiField(fieldHashtable.size(), this, "Format", this.mpiMimeType, 0);
// mimeTypeField.fieldID = "x" + fieldHashtable.size();
addField(mimeTypeField);
}
}
private void initNodeVariables() {
// loop any indichildnodes and init
if (childArray != null) {
for (ImdiTreeObject currentNode : childArray) {
if (currentNode.isImdiChild()) {
currentNode.initNodeVariables();
}
}
}
// if (currentTemplate == null) {
// // this will be overwritten when the imdi file is read, provided that a template is specified in the imdi file
// if (isPathCmdi(nodeUri.getPath())) {
// // this must be loaded with the name space uri
// // currentTemplate = ArbilTemplateManager.getSingleInstance().getCmdiTemplate();
// } else {
// currentTemplate = ArbilTemplateManager.getSingleInstance().getCurrentTemplate();
fieldHashtable = new Hashtable<String, ImdiField[]>();
imdiDataLoaded = false;
hashString = null;
//mpiMimeType = null;
matchesInCache = 0;
matchesRemote = 0;
matchesLocalFileSystem = 0;
fileNotFound = false;
needsSaveToDisk = false;
// nodeText = null;
// urlString = null;
// resourceUrlField = null;
isDirectory = false;
icon = null;
nodeEnabled = true;
// isLoadingCount = true;
if (nodeUri != null) {
if (!isMetaDataNode() && isLocal()) {
File fileObject = getFile();
if (fileObject != null) {
this.nodeText = fileObject.getName();
this.isDirectory = fileObject.isDirectory();
// TODO: check this on a windows box with a network drive and linux with symlinks
// this.isDirectory = !fileObject.isFile();
// System.out.println("isFile" + fileObject.isFile());
// System.out.println("isDirectory" + fileObject.isDirectory());
// System.out.println("getAbsolutePath" + fileObject.getAbsolutePath());
}
}
if (!isMetaDataNode() && nodeText == null) {
nodeText = this.getUrlString();
}
}
}
public void reloadNode() {
System.out.println("reloadNode: " + isLoading());
getParentDomNode().needsSaveToDisk = false; // clear any changes
// if (!this.isImdi()) {
// initNodeVariables();
// //loadChildNodes();
// clearIcon();
// // TODO: this could just remove the decendant nodes and let the user re open them
// TreeHelper.getSingleInstance().updateTreeNodeChildren(this);
//// this.clearIcon();
// } else {
//// if (getParentDomNode().isCorpus()) {
//// getParentDomNode().autoLoadChildNodes = true;
ImdiLoader.getSingleInstance().requestReload(getParentDomNode());
}
synchronized public void loadImdiDom() {
System.out.println("loadImdiDom: " + nodeUri.toString());
if (getParentDomNode() != this) {
getParentDomNode().loadImdiDom();
} else {
synchronized (domLockObject) {
initNodeVariables(); // this might be run too often here but it must be done in the loading thread and it also must be done when the object is created
if (!isMetaDataNode() && !isDirectory() && isLocal()) {
// if it is an not imdi or a loose file but not a direcotry then get the md5sum
MimeHashQueue.getSingleInstance().addToQueue(this);
imdiDataLoaded = true;
}
if (this.isDirectory()) {
getDirectoryLinks();
imdiDataLoaded = true;
// clearIcon();
}
if (isMetaDataNode()) {
Document nodDom = null;
// cacheLocation will be null if useCache = false hence no file has been saved
// String cacheLocation = null;
if (this.isLocal() && !this.getFile().exists() && new File(this.getFile().getAbsolutePath() + ".0").exists()) {
// if the file is missing then try to find a valid history file
copyLastHistoryToCurrent();
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Missing file has been recovered from the last history item.", "Recover History");
}
try {
//System.out.println("tempUrlString: " + tempUrlString);
nodDom = new CmdiComponentBuilder().getDocument(this.getURI());
// only read the fields into imdi tree objects if it is not going to be saved to the cache
// if (!useCache) {
if (nodDom == null) {
File nodeFile = this.getFile();
if (nodeFile != null && nodeFile.exists()) {
nodeText = "Could not load IMDI";
} else {
nodeText = "File not found";
fileNotFound = true;
}
} else {
//set the string name to unknown, it will be updated in the tostring function
nodeText = "unknown";
if (this.isCmdiMetaDataNode()) {
// load the links from the cmdi file
// the links will be hooked to the relevent nodes when the rest of the xml is read
cmdiComponentLinkReader = new CmdiComponentLinkReader();
cmdiComponentLinkReader.readLinks(this.getURI());
} else {
cmdiComponentLinkReader = null;
}
Vector<String[]> childLinksTemp = new Vector<String[]>();
Hashtable<ImdiTreeObject, HashSet<ImdiTreeObject>> parentChildTree = new Hashtable<ImdiTreeObject, HashSet<ImdiTreeObject>>();
Hashtable<String, Integer> siblingNodePathCounter = new Hashtable<String, Integer>();
// load the fields from the imdi file
ImdiSchema.getSingleInstance().iterateChildNodes(this, childLinksTemp, nodDom.getFirstChild(), "", "", parentChildTree, siblingNodePathCounter, 0);
childLinks = childLinksTemp.toArray(new String[][]{});
//ImdiTreeObject[] childArrayTemp = new ImdiTreeObject[childLinks.length];
for (ImdiTreeObject currentNode : parentChildTree.keySet()) {
// System.out.println("setting childArray on: " + currentNode.getUrlString());
// save the old child array
ImdiTreeObject[] oldChildArray = currentNode.childArray;
// set the new child array
currentNode.childArray = parentChildTree.get(currentNode).toArray(new ImdiTreeObject[]{});
// check the old child array and for each that is no longer in the child array make sure they are removed from any containers (tables or trees)
List currentChildList = Arrays.asList(currentNode.childArray);
for (ImdiTreeObject currentOldChild : oldChildArray) {
if (currentChildList.indexOf(currentOldChild) == -1) {
// remove from any containers that its found in
for (Object currentContainer : currentOldChild.getRegisteredContainers()) {
if (currentContainer instanceof ImdiChildCellEditor) {
((ImdiChildCellEditor) currentContainer).stopCellEditing();
}
if (currentContainer instanceof ImdiTableModel) {
((ImdiTableModel) currentContainer).removeImdiObjects(new ImdiTreeObject[]{currentOldChild});
}
if (currentContainer instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode currentTreeNode = (DefaultMutableTreeNode) currentContainer;
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) currentContainer).getParent();
if (parentNode != null) { // TODO this could be reduced as it is also sort of done in clear icon
TreeHelper.getSingleInstance().addToSortQueue(parentNode);
} else {
TreeHelper.getSingleInstance().addToSortQueue(currentTreeNode);
}
}
}
}
}
}
}
// save this to the cache before deleting the dom
// if (useCache) {
// // get the links from the imdi before we dispose of the dom
// getImdiLinks(nodDom);
//// cacheLocation = saveNodeToCache(nodDom);
} catch (Exception mue) {
GuiHelper.linorgBugCatcher.logError(mue);
// System.out.println("Invalid input URL: " + mue);
}
//we are now done with the dom so free the memory
nodDom = null;
// return cacheLocation;
imdiDataLoaded = true;
// clearChildIcons();
}
}
}
}
// private String getField(String fieldName) {
// Document itemDom = this.getNodeDom();
// if (itemDom == null) {
// return null;
// IMDIElement rowValue = api.getIMDIElement(itemDom, fieldName);
// if (rowValue != null) {
// return rowValue.getValue();
// } else {
// return null;
private void getDirectoryLinks() {
File[] dirLinkArray = null;
File nodeFile = this.getFile();
if (nodeFile != null && nodeFile.isDirectory()) {
dirLinkArray = nodeFile.listFiles();
Vector<ImdiTreeObject> childLinksTemp = new Vector<ImdiTreeObject>();
for (int linkCount = 0; linkCount < dirLinkArray.length; linkCount++) {
try {
// System.out.println("nodeFile: " + nodeFile);
// System.out.println("dirLinkArray[linkCount]: " + dirLinkArray[linkCount]);
URI childURI = dirLinkArray[linkCount].toURI();
ImdiTreeObject currentImdi = ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(childURI);
if (TreeHelper.getSingleInstance().showHiddenFilesInTree || !currentImdi.getFile().isHidden()) {
childLinksTemp.add(currentImdi);
}
} catch (Exception ex) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue(dirLinkArray[linkCount] + " could not be loaded in\n" + nodeUri.toString(), "Load Directory");
new LinorgBugCatcher().logError(ex);
}
}
//childLinks = childLinksTemp.toArray(new String[][]{});
childArray = childLinksTemp.toArray(new ImdiTreeObject[]{});
}
}
// private void getImdiLinks(Document nodDom) {
// try {
// if (nodDom != null) {
// OurURL baseURL = new OurURL(nodeUri.toURL());
//// debugOut("getIMDILinks");
// IMDILink[] links = api.getIMDILinks(nodDom, baseURL, WSNodeType.CORPUS);
//// debugOut("links.length: " + links.length);
// if (links != null) {
// for (int linkCount = 0; linkCount < links.length; linkCount++) {
// childLinks.add(new String[]{links[linkCount].getRawURL().toString(), null});
// } catch (MalformedURLException mue) {
// System.out.println("Error getting links: " + mue);
// private boolean populateChildFields(String fieldNameString, boolean alwaysShow) {
// // this is called when loading children and when loading fields
// //System.out.println("fieldNameString: " + fieldNameString);
// boolean valueFound = false;
// int counterFieldPosition = fieldNameString.indexOf("(X)");
// if (-1 < counterFieldPosition) {
// int itemValueCounter = 1;
// valueFound = true;
// String firstHalf = fieldNameString.substring(0, counterFieldPosition + 1);
// String secondHalf = fieldNameString.substring(counterFieldPosition + 2);
// while (valueFound) {
// fieldNameString = firstHalf + itemValueCounter + secondHalf;
// if (-1 < fieldNameString.indexOf("(X)")) {
// valueFound = populateChildFields(fieldNameString, alwaysShow);
// } else {
// boolean isWrongFieldType = false;
// if (isImdi()) {
// if (isSession() && fieldNameString.startsWith("Corpus.")) {
// // TODO: we could speed things up by not asking the imdi.api for the value of this field, however if there is data so show (presumably erroneous data) it should still be shown
// isWrongFieldType = true;
// } else if (fieldNameString.startsWith("Session.")) {
// isWrongFieldType = true;
// //System.out.println("checking x value for: " + fieldNameString);
// String cellValue = this.getField(fieldNameString);
// valueFound = cellValue != null;
// if (valueFound && cellValue.length() > 0) {
// this.addField(fieldNameString, 0, cellValue);
// } else if (alwaysShow) {
// if (!isWrongFieldType) {
// this.addField(fieldNameString, 0, "");
// itemValueCounter++;
// } else {
// //System.out.println("checking value for: " + fieldNameString);
// String cellValue = this.getField(fieldNameString);
// valueFound = cellValue != null;
// if (valueFound && cellValue.length() > 0) {
// this.addField(fieldNameString, 0, cellValue);
// return valueFound;
/**
* Count the next level of child nodes. (non recursive)
* @return An integer of the next level of child nodes including corpus links and imdi child nodes.
*/
public int getChildCount() {
// System.out.println("getChildCount: " + childLinks.size() + childrenHashtable.size() + " : " + this.getUrlString());
return childArray.length;
}
/**
* Calls getAllChildren(Vector<ImdiTreeObject> allChildren) and returns the result as an array
* @return an array of all the child nodes
*/
public ImdiTreeObject[] getAllChildren() {
Vector<ImdiTreeObject> allChildren = new Vector<ImdiTreeObject>();
getAllChildren(allChildren);
return allChildren.toArray(new ImdiTreeObject[]{});
}
/**
* Used to get all the imdi child nodes (all levels) of a session or all the nodes contained in a corpus (one level only).
* @param An empty vector, to which all the child nodes will be added.
*/
public void getAllChildren(Vector<ImdiTreeObject> allChildren) {
System.out.println("getAllChildren: " + this.getUrlString());
if (this.isSession() || this.isCatalogue() || this.isImdiChild() || this.isCmdiMetaDataNode()) {
for (ImdiTreeObject currentChild : childArray) {
currentChild.getAllChildren(allChildren);
allChildren.add(currentChild);
}
}
}
/**
* Gets an array of the children of this node.
* @return An array of the next level child nodes.
*/
public ImdiTreeObject[] getChildArray() {
return childArray;
}
// /**
// * Used to populate the child list in the show child popup in the imditable.
// * @return An enumeration of the next level child nodes.
// */
// public Enumeration<ImdiTreeObject> getChildEnum() {
// return childObjectDomIdHash.elements();
// /**
// * Used to populate the child nodes in the table cell.
// * @return A collection of the next level child nodes.
// */
// public Collection<ImdiTreeObject> getChildCollection() {
// return childObjectDomIdHash.values();
/**
* Gets the second level child nodes from the fist level child node matching the child type string.
* Used to populate the child nodes in the table cell.
* @param childType The name of the first level child to query.
* @return An object array of all second level child nodes in the first level node.
*/
public ImdiTreeObject[] getChildNodesArray(String childType) {
for (ImdiTreeObject currentNode : childArray) {
if (currentNode.toString().equals(childType)) {
return currentNode.getChildArray();
}
}
return null;
}
public ArbilTemplate getNodeTemplate() {
if (nodeTemplate != null && !this.isCorpus()) {
return nodeTemplate;
} else if (this.isImdiChild()) {
return this.getParentDomNode().getNodeTemplate();
} else {
//new LinorgBugCatcher().logError(new Exception("Corpus Branch Null Template"));
return ArbilTemplateManager.getSingleInstance().getDefaultTemplate();
}
}
/**
* Attache a child node to this node.
* Only affects objects in memory and used when loading an imdi dom.
* Will not and should not add a node as a child of itself.
* To add a node to a dom use addChildNode.
* @return void
*/
// public void attachChildNode(ImdiTreeObject destinationNode) {
//// System.out.println("attachChildNodeTo: " + this.getUrlString());
//// System.out.println("attachChildNode: " + destinationNode.getUrlString());
// if (destinationNode != this) {
// childrenHashtable.put(destinationNode.getUrlString(), destinationNode);
// /**
// * Add a resource contained i an imdi object
// * @return String path to the added node
// */
// public String addChildNode(ImdiTreeObject nodeToAdd) {
// System.out.println("addChildNode: " + nodeToAdd);
// return addChildNode(null, nodeToAdd.getUrlString(), nodeToAdd.mpiMimeType);
// create a subdirectory based on the file name of the node
// if that fails then the current directory will be returned
public File getSubDirectory() {
String currentFileName = this.getFile().getParent();
if (ImdiTreeObject.isPathImdi(nodeUri.getPath()) || ImdiTreeObject.isPathCmdi(nodeUri.getPath())) {
currentFileName = currentFileName + File.separatorChar + this.getFile().getName().substring(0, this.getFile().getName().length() - 5);
File destinationDir = new File(currentFileName);
if (!destinationDir.exists()) {
destinationDir.mkdir();
}
return destinationDir;
}
return new File(this.getFile().getParent());
}
/**
* Loads the child links and returns them as an array
* @return ImdiTreeObject[] array of child nodes
*/
// public void loadChildNodes() {
// for (ImdiTreeObject currentChild : childArray) {
// GuiHelper.imdiLoader.getImdiObject(null, currentChild.getUrlString());
// System.out.println("loadChildNodes: " + this);
//waitTillLoaded();
// if (!getParentDomNode().imdiDataLoaded) {
// if this node has been loaded then do not load again
// to refresh the node and its children the node should be nulled and recreated
// autoLoadChildNodes = false;
// if (!this.isSession()) {
// //getImdiFieldLinks();
// for (Enumeration<String[]> childLinksEnum = childLinks.elements(); childLinksEnum.hasMoreElements();) {
// String currentChildPath = childLinksEnum.nextElement()[0];
// ImdiTreeObject currentImdi = GuiHelper.imdiLoader.getImdiObject(null, currentChildPath);
//// System.out.println("adding to list of child nodes 2: " + currentImdi);
// childrenHashtable.put(currentImdi.getUrlString(), currentImdi);
//// if (ImdiTreeObject.isStringImdi(currentChildPath)) {
//// currentImdi.loadImdiDom();
// START: this section uses the imdi.api to query the dom for available fields but it has been commented out in favour of the iterateChildNodes function
// System.err.println("Starting to load fields at: " + System.nanoTime());
// Long startTime = System.nanoTime();
// for (int rowNameCounter = 0; rowNameCounter < imdiFieldArray.length; rowNameCounter++) {
// if (imdiFieldArray[rowNameCounter][0] || imdiFieldArray[rowNameCounter][1]) {
// populateChildFields(imdiFieldViews.getMasterImdiFieldName(rowNameCounter), imdiFieldArray[rowNameCounter][1]);
// Long nextTime = System.nanoTime();
//// System.err.println("Starting to print fields at: " + System.nanoTime());
// if (nodDom != null) {
// iterateChildNodes(nodDom.getFirstChild(), "");
// System.err.println("Done loading fields at: " + System.nanoTime());
// Long lastTime = System.nanoTime();
// System.err.println("first method: " + (nextTime - startTime) + " second method: " + (lastTime - nextTime));
// System.err.println("second method took " + (lastTime - nextTime + 0.0) / (nextTime - startTime) * 100 + "% of the time used by the first");
// System.err.println("the imdi.api took " + ((nextTime - startTime) / lastTime - nextTime + 0.0) + " times longer");
// END: this section uses the imdi.api to query the dom for available fields but it has been commented out in favour of the iterateChildNodes function
// Vector<ImdiTreeObject> tempImdiVector = new Vector<ImdiTreeObject>();
// Enumeration nodesToAddEnumeration = childrenHashtable.elements();
// while (nodesToAddEnumeration.hasMoreElements()) {
// tempImdiVector.add((ImdiTreeObject) nodesToAddEnumeration.nextElement());
// ImdiTreeObject[] returnImdiArray = new ImdiTreeObject[tempImdiVector.size()];
// tempImdiVector.toArray(returnImdiArray);
// return returnImdiArray;
public boolean containsFieldValue(String fieldName, String searchValue) {
boolean findResult = false;
ImdiField[] currentFieldArray = this.fieldHashtable.get(fieldName);
if (currentFieldArray != null) {
for (ImdiField currentField : currentFieldArray) {
System.out.println("containsFieldValue: " + currentField.getFieldValue() + ":" + searchValue);
if (currentField.getFieldValue().toLowerCase().contains(searchValue.toLowerCase())) {
return true;
}
}
}
System.out.println("result: " + findResult + ":" + this);
return findResult;
}
public boolean containsFieldValue(String searchValue) {
boolean findResult = false;
for (ImdiField[] currentFieldArray : (Collection<ImdiField[]>) this.fieldHashtable.values()) {
for (ImdiField currentField : currentFieldArray) {
System.out.println("containsFieldValue: " + currentField.getFieldValue() + ":" + searchValue);
if (currentField.getFieldValue().toLowerCase().contains(searchValue.toLowerCase())) {
return true;
}
}
}
System.out.println("result: " + findResult + ":" + this);
return findResult;
}
// this is used to disable the node in the tree gui
public boolean getNodeEnabled() {
return nodeEnabled;
}
/**
* Tests if this node has child nodes even if they are not yet loaded.
* @return boolean
*/
public boolean canHaveChildren() {
return childArray.length > 0;
}
// /*
// * gets an array of
// */
// public int[] getRecursiveChildCount() {
//// debugOut("getChildCount: " + this.toString());
// int[] returnArray = new int[2];
// returnArray[0] = 0;
// returnArray[1] = 0;
// if (imdiDataLoaded) {
// returnArray[1] += 1; // count this node
// Enumeration nodesToAddEnumeration = childrenHashtable.elements();
// while (nodesToAddEnumeration.hasMoreElements()) {
// // count the child nodes
// int[] childCount = ((ImdiTreeObject) nodesToAddEnumeration.nextElement()).getRecursiveChildCount();
// returnArray[0] += childCount[0];
// returnArray[1] += childCount[1];
// } else {
// if (this.isImdi()) {
// returnArray[0] = 1;
// return returnArray;
// public void loadNextLevelOfChildren(long stopTime) {
//// debugOut("loadNextLevelOfChildren: " + this.toString() + ":" + (System.currentTimeMillis() - stopTime));
// if (System.currentTimeMillis() > stopTime) {
// return;
// if (this.isImdi()) {
// if (getParentDomNode().imdiDataLoaded) {
// Enumeration nodesToAddEnumeration = childrenHashtable.elements();
// while (nodesToAddEnumeration.hasMoreElements()) {
// // load one level of child nodes
// ((ImdiTreeObject) nodesToAddEnumeration.nextElement()).loadNextLevelOfChildren(stopTime);
// //((ImdiTreeObject) nodesToAddEnumeration.nextElement()).();
//// debugOut("listDiscardedOfAttributes: " + listDiscardedOfAttributes);
private void getAllFields(Vector<ImdiField[]> allFields) {
// returns all fields relevant to the parent node
// that includes all indinodechild fields but not from any other imdi file
System.out.println("getAllFields: " + this.toString());
allFields.addAll(fieldHashtable.values());
for (ImdiTreeObject currentChild : childArray) {
if (currentChild.isImdiChild()) {
currentChild.getAllFields(allFields);
}
}
}
// public void deleteFromParentDom(String[] childNodeXmlIdArray) {
//// System.out.println("deleteFromParentDom: " + childNodeXmlIdArray);
// if (this.isImdiChild()) {
// this.domParentImdi.deleteFromParentDom(new String[]{this.xmlNodeId});
// } else {
// // save the node if it need saving
// if (needsSaveToDisk) {
// saveChangesToCache(false);
//// System.out.println("attempting to remove nodes");
// try {
// OurURL inUrlLocal = new OurURL(nodeUri.toURL());
// Document nodDom;
// nodDom = api.loadIMDIDocument(inUrlLocal, false);
// for (String currentNodeXmlId : childNodeXmlIdArray) {
// IMDIElement target = new IMDIElement(null, currentNodeXmlId);
// api.removeIMDIElement(nodDom, target);
// api.writeDOM(nodDom, this.getFile(), false);
// reloadNode();
// } catch (Exception ex) {
// GuiHelper.linorgBugCatcher.logError(ex);
// public void deleteFeilds(ImdiField[] targetImdiFields) {
// ArrayList<String> pathList = new ArrayList<String>();
// for (ImdiField currentField : targetImdiFields) {
// pathList.add(currentField.getFullXmlPath());
// CmdiComponentBuilder componentBuilder = new CmdiComponentBuilder();
// boolean result = componentBuilder.removeChildNodes(this, pathList.toArray(new String[]{}));
//// deleteFromDomViaId(domIdList.toArray(new String[]{}));
// this is used to delete an IMDI node from a corpus branch
public void deleteCorpusLink(ImdiTreeObject[] targetImdiNodes) {
// TODO: There is an issue when deleting child nodes that the remaining nodes xml path (x) will be incorrect as will the xmlnode id hence the node in a table may be incorrect after a delete
if (needsSaveToDisk) {
saveChangesToCache(false);
}
bumpHistory();
copyLastHistoryToCurrent(); // bump history is normally used afteropen and before save, in this case we cannot use that order so we must make a copy
synchronized (domLockObject) {
System.out.println("deleting by corpus link");
URI[] copusUriList = new URI[targetImdiNodes.length];
for (int nodeCounter = 0; nodeCounter < targetImdiNodes.length; nodeCounter++) {
// if (targetImdiNodes[nodeCounter].hasResource()) {
// copusUriList[nodeCounter] = targetImdiNodes[nodeCounter].getFullResourceURI(); // todo: should this resouce case be used here? maybe just the uri
// } else {
copusUriList[nodeCounter] = targetImdiNodes[nodeCounter].getURI();
}
metadataUtils.removeCorpusLink(this.getURI(), copusUriList);
this.getParentDomNode().loadImdiDom();
}
// for (ImdiTreeObject currentChildNode : targetImdiNodes) {
//// currentChildNode.clearIcon();
// TreeHelper.getSingleInstance().updateTreeNodeChildren(currentChildNode);
this.getParentDomNode().clearIcon();
this.getParentDomNode().clearChildIcons();
// clearIcon(); // this must be cleared so that the leaf / branch flag gets set
TreeHelper.getSingleInstance().updateTreeNodeChildren(this.getParentDomNode());
// reloadNode();
}
public boolean hasCatalogue() {
for (ImdiTreeObject childNode : childArray) {
// String currentChildPath = currentLinkPair[0];
// ImdiTreeObject childNode = ImdiLoader.getSingleInstance().getImdiObject(null, currentChildPath);
//childNode.waitTillLoaded(); // if the child nodes have not been loaded this will fail so we must wait here
if (childNode.isCatalogue()) {
return true;
}
}
return false;
}
public boolean addCorpusLink(ImdiTreeObject targetImdiNode) {
boolean linkAlreadyExists = false;
if (targetImdiNode.isCatalogue()) {
if (this.hasCatalogue()) {
// LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Only one catalogue can be added", null);
// prevent adding a second catalogue file
return false;
}
}
for (String[] currentLinkPair : childLinks) {
String currentChildPath = currentLinkPair[0];
if (!targetImdiNode.waitTillLoaded()) { // we must wait here before we can tell if it is a catalogue or not
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error adding node, could not wait for file to load", "Loading Error");
return false;
}
if (currentChildPath.equals(targetImdiNode.getUrlString())) {
linkAlreadyExists = true;
}
}
if (targetImdiNode.getUrlString().equals(this.getUrlString())) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Cannot link or move a node into itself", null);
return false;
}
if (linkAlreadyExists) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue(targetImdiNode + " already exists in " + this + " and will not be added again", null);
return false;
} else {
// if link is not already there
// if needs saving then save now while you can
// TODO: it would be nice to warn the user about this, but its a corpus node so maybe it is not important
if (needsSaveToDisk) {
saveChangesToCache(true);
}
bumpHistory();
copyLastHistoryToCurrent(); // bump history is normally used afteropen and before save, in this case we cannot use that order so we must make a copy
synchronized (domLockObject) {
metadataUtils.addCorpusLink(this.getURI(), new URI[]{targetImdiNode.getURI()});
}
//loadChildNodes(); // this must not be done here
// clearIcon(); // this must be cleared so that the leaf / branch flag gets set
return true;
}
}
public void pasteIntoNode() {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transfer = clipboard.getContents(null);
try {
String clipBoardString = "";
Object clipBoardData = transfer.getTransferData(DataFlavor.stringFlavor);
if (clipBoardData != null) {//TODO: check that this is not null first but let it pass on null so that the no data to paste messages get sent to the user
clipBoardString = clipBoardData.toString();
System.out.println("clipBoardString: " + clipBoardString);
if (this.isCorpus()) {
if (ImdiTreeObject.isPathMetadata(clipBoardString) || ImdiTreeObject.isStringImdiChild(clipBoardString)) {
ImdiTreeObject clipboardNode = ImdiLoader.getSingleInstance().getImdiObject(null, conformStringToUrl(clipBoardString));
if (LinorgSessionStorage.getSingleInstance().pathIsInsideCache(clipboardNode.getFile())) {
if (!(ImdiTreeObject.isStringImdiChild(clipBoardString) && (!this.isSession() && !this.isImdiChild()))) {
if (this.getFile().exists()) {
// this must use merge like favoirite to prevent instances end endless loops in corpus branches
new MetadataBuilder().requestAddNode(this, "copy of " + clipboardNode, clipboardNode);
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The target node's file does not exist", null);
}
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Cannot paste session subnodes into a corpus", null);
}
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The target file is not in the cache", null);
}
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Pasted string is not and IMDI file", null);
}
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Only corpus branches can be pasted into at this stage", null);
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
/**
* Saves the current changes from memory into a new imdi file on disk.
* Previous imdi files are renamed and kept as a history.
* the caller is responsible for reloading the node if that is required
*/
public void saveChangesToCache(boolean updateUI) {
if (this.isImdiChild()) {
getParentDomNode().saveChangesToCache(updateUI);
return;
}
System.out.println("saveChangesToCache");
LinorgJournal.getSingleInstance().clearFieldChangeHistory();
if (!this.isLocal() /*nodeUri.getScheme().toLowerCase().startsWith("http") */) {
System.out.println("should not try to save remote files");
return;
}
ArrayList<FieldUpdateRequest> fieldUpdateRequests = new ArrayList<FieldUpdateRequest>();
Vector<ImdiField[]> allFields = new Vector<ImdiField[]>();
getAllFields(allFields);
for (Enumeration<ImdiField[]> fieldsEnum = allFields.elements(); fieldsEnum.hasMoreElements();) {
{
ImdiField[] currentFieldArray = fieldsEnum.nextElement();
for (int fieldCounter = 0; fieldCounter < currentFieldArray.length; fieldCounter++) {
ImdiField currentField = currentFieldArray[fieldCounter];
if (currentField.fieldNeedsSaveToDisk()) {
FieldUpdateRequest currentFieldUpdateRequest = new FieldUpdateRequest();
currentFieldUpdateRequest.keyNameValue = currentField.getKeyName();
currentFieldUpdateRequest.fieldOldValue = currentField.originalFieldValue;
currentFieldUpdateRequest.fieldNewValue = currentField.getFieldValue();
currentFieldUpdateRequest.fieldPath = currentField.getFullXmlPath();
currentFieldUpdateRequest.fieldLanguageId = currentField.getLanguageId();
fieldUpdateRequests.add(currentFieldUpdateRequest);
}
}
}
}
CmdiComponentBuilder componentBuilder = new CmdiComponentBuilder();
boolean result = componentBuilder.setFieldValues(this, fieldUpdateRequests.toArray(new FieldUpdateRequest[]{}));
if (result != true) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error saving changes to disk, check the log file via the help menu for ore information.", "Save");
} else {
this.needsSaveToDisk = false;
// // update the icon to indicate the change
// setImdiNeedsSaveToDisk(null, false);
}
// clearIcon(); this is called by setImdiNeedsSaveToDisk
}
/**
* Saves the node dom into the local cache.
* Before this is called it is recommended to confirm that the destinationDirectory path already exist and is correct, otherwise unintended directories maybe created
* @param nodDom The dom for this node that will be saved.
* @return A string path of the saved location.
*/
// public String saveNodeToCache(Document nodDom) {
// String cacheLocation = null;
// System.out.println("saveBranchToLocal: " + this.toString());
// if (this.isImdi() && !this.isImdiChild()) {
// if (nodDom != null) {
// //System.out.println("saveBranchToLocal: " + this.getUrl());
// //System.out.println("saveBranchToLocal: " + this.nodDom.);
// String destinationPath = GuiHelper.linorgSessionStorage.getSaveLocation(this.getUrlString());
//// debugOut("destinationPath: " + destinationPath);
// File tempFile = new File(destinationPath);
// // only save the file if it does not exist, otherwise local changes would be lost and it would be pointless anyway
// if (tempFile.exists()) {
// System.out.println("this imdi is already in the cache");
// } else {
// // this function of the imdi.api will modify the imdi file as it saves it "(will be normalized and possibly de-domId-ed)"
// // this will make it dificult to determin if changes are from this function of by the user deliberatly making a chage
// api.writeDOM(nodDom, new File(destinationPath), false);
// // create hash index with server url but basedon the saved file
// // note that if the imdi.api has changed this file then it will not be detected
// // TODO: it will be best to change this to use the server api get mb5 sum when it is written
// // TODO: there needs to be some mechanism to check for changes on the server and update the local copy
// //getHash(tempFile, this.getUrl());
// System.out.println("imdi should be saved in cache now");
// // no point iterating child nodes which have not been loaded, it is better to do the outside this function
//// Enumeration nodesToAddEnumeration = childrenHashtable.elements();
//// while (nodesToAddEnumeration.hasMoreElements()) {
////// ((ImdiTreeObject) nodesToAddEnumeration.nextElement()).saveBranchToLocal(destinationDirectory);
// cacheLocation = destinationPath;
// return cacheLocation;
public void addField(ImdiField fieldToAdd) {
// System.addField:out.println("addField: " + this.getUrlString() + " : " + fieldToAdd.xmlPath + " : " + fieldToAdd.getFieldValue());
ImdiField[] currentFieldsArray = fieldHashtable.get(fieldToAdd.getTranslateFieldName());
if (currentFieldsArray == null) {
currentFieldsArray = new ImdiField[]{fieldToAdd};
} else {
// System.out.println("appendingField: " + fieldToAdd);
ImdiField[] appendedFieldsArray = new ImdiField[currentFieldsArray.length + 1];
System.arraycopy(currentFieldsArray, 0, appendedFieldsArray, 0, currentFieldsArray.length);
appendedFieldsArray[appendedFieldsArray.length - 1] = fieldToAdd;
currentFieldsArray = appendedFieldsArray;
// for (ImdiField tempField : currentFieldsArray) {
// System.out.println("appended fields: " + tempField);
}
fieldHashtable.put(fieldToAdd.getTranslateFieldName(), currentFieldsArray);
if (fieldToAdd.xmlPath.endsWith(".ResourceLink") && fieldToAdd.parentImdi.isImdiChild()/* && fieldToAdd.parentImdi.getUrlString().contains("MediaFile")*/) {
resourceUrlField = fieldToAdd;
MimeHashQueue.getSingleInstance().addToQueue(this);
}
}
/**
* Adds a field to the imdi node and creates imdi child nodes if required.
* @param fieldToAdd The field to be added.
* @param childLevel For internal use and should be zero. Used to track the distance in imdi child nodes from the imdi node.
* @param addedImdiNodes Returns with all the imdi child nodes that have been added during the process.
* @param useCache If true the the imdi file will be saved to the cache.
*/
// private void addField(ImdiField fieldToAdd, int childLevel, Vector addedImdiNodes) {
// // TODO: modify this so that each child node gets the full filename and full xml path
//// if (isImdi()) {
//// if (fieldLabel.startsWith("Session.")) {
//// fieldLabel = fieldLabel.substring(8);
//// } else if (fieldLabel.startsWith("Corpus.")) {
//// fieldLabel = fieldLabel.substring(7);
// //fieldUrl.substring(firstSeparator + 1)
// // TODO: move this and we write to imdischema
// int nextChildLevel = fieldToAdd.translatedPath.replace(")", "(").indexOf("(", childLevel);
// debugOut("fieldLabel: " + fieldToAdd.translatedPath + " cellValue: " + fieldToAdd.fieldValue + " childLevel: " + childLevel + " nextChildLevel: " + nextChildLevel);
// if (nextChildLevel == -1) {
// // add the label to this level node
//// if (fieldLabel == null) fieldLabel = "oops null";
//// if (fieldValue == null) fieldValue = "oops null";
// String childsLabel = fieldToAdd.translatedPath.substring(childLevel);
// fieldHashtable.put(childsLabel, fieldToAdd);
//// if (childsLabel.endsWith(".Date")) {
//// DateFormat df = new SimpleDateFormat("yyyy-MM-DD");
//// try {
//// nodeDate = df.parse(fieldToAdd.fieldValue);
//// if (minNodeDate == null) {
//// minNodeDate = nodeDate;
//// maxNodeDate = nodeDate;
//// if (nodeDate.before(minNodeDate)) {
//// minNodeDate = nodeDate;
//// if (nodeDate.after(maxNodeDate)) {
//// maxNodeDate = nodeDate;
//// } catch (Exception ex) {
//// System.err.println(ex.getMessage());
// // if the node contains a ResourceLink then save the location in resourceUrlString and create a hash for the file
// if (childsLabel.equals(ImdiSchema.imdiPathSeparator + "ResourceLink")) {
//// // resolve the relative location of the file
//// File resourceFile = new File(this.getFile().getParent(), fieldToAdd.fieldValue);
//// resourceUrlString = resourceFile.getCanonicalPath();
// resourceUrlString = fieldToAdd.fieldValue;
//// if (useCache) {
//// GuiHelper.linorgSessionStorage.updateCache(getFullResourceURI());
// mimeHashQueue.addToQueue(this);
// } else {
// // pass the label to the child nodes
// String childsName = fieldToAdd.translatedPath.substring(childLevel, nextChildLevel);
// //String parentName = fieldLabel.substring(0, firstSeparator);
// debugOut("childsName: " + childsName);
// if (!childrenHashtable.containsKey(childsName)) {
// ImdiTreeObject tempImdiTreeObject = GuiHelper.imdiLoader.getImdiObject(childsName, this.getUrlString() + "#" + fieldToAdd.xmlPath);
// if (addedImdiNodes != null) {
// addedImdiNodes.add(tempImdiTreeObject);
// tempImdiTreeObject.imdiDataLoaded = true;
//// System.out.println("adding to list of child nodes 3: " + tempImdiTreeObject);
// childrenHashtable.put(childsName, tempImdiTreeObject);
// ((ImdiTreeObject) childrenHashtable.get(childsName)).addField(fieldToAdd, nextChildLevel + 1, addedImdiNodes);
/**
* Gets the fields in this node, this does not include any imdi child fields.
* To get all fields relevant the imdi file use "getAllFields()" which includes imdi child fields.
* @return A hashtable of the fields
*/
public Hashtable<String, ImdiField[]> getFields() {
// store the Hastable for next call
// if hashtable is null then load from imdi
return fieldHashtable;
}
// public String getCommonFieldPathString() {
// // find repetitious path strings in the fields for this node so they can be omitted from the table display
// if (commonFieldPathString == null) {
// if (fieldHashtable.size() < 2) {
// // if there is only one field name then it would be reduced to zero length which we do not want
// commonFieldPathString = "";
// } else {
// String commonPath = null;
// for (ImdiField[] currentField : fieldHashtable.values()) {
// if (commonPath == null) {
// commonPath = currentField[0].xmlPath;
// } else {
// int matchingIndex = commonPath.length();
// while (matchingIndex > 0 && !commonPath.substring(0, matchingIndex).equals(currentField[0].xmlPath.substring(0, matchingIndex))) {
// System.out.println("matchingIndex: " + matchingIndex + "\t" + commonPath.substring(0, matchingIndex));
// matchingIndex--;
// commonPath = commonPath.substring(0, matchingIndex);
// commonFieldPathString = commonPath;
// return commonFieldPathString;
/**
* Compares this node to another based on its type and string value.
* @return The string comparison result.
*/
public int compareTo(Object o) throws ClassCastException {
ImdiTreeNodeSorter imdiTreeNodeSorter = new ImdiTreeNodeSorter();
return imdiTreeNodeSorter.compare(this, o);
}
public synchronized void notifyLoaded() {
System.out.println("notifyAll");
getParentDomNode().notifyAll();
}
public synchronized boolean waitTillLoaded() {
System.out.println("waitTillLoaded");
if (isLoading()) {
System.out.println("isLoading");
try {
getParentDomNode().wait();
System.out.println("wait");
if (isLoading()) {
System.out.println("but still loading");
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
return false;
}
}
return true;
}
public void updateLoadingState(int countChange) {
if (this != getParentDomNode()) {
getParentDomNode().updateLoadingState(countChange);
} else {
synchronized (loadingCountLock) {
isLoadingCount += countChange;
}
System.out.println("isLoadingCount: " + isLoadingCount);
if (!isLoading()) {
// this.notifyAll();
clearChildIcons();
clearIcon();
}
}
}
public boolean isLoading() {
return getParentDomNode().isLoadingCount > 0;
}
@Override
public String toString() {
if (lastNodeText != null) {
return lastNodeText;
} else {
return "unknown";
}
}
public String refreshStringValue() {
if (isLoading()) {
// if (lastNodeText.length() > 0) {
// return lastNodeText;
// } else {asdasdasd
//// if (nodeText != null && nodeText.length() > 0) {
return lastNodeText;
} else if (lastNodeText.equals("loading imdi...") && getParentDomNode().imdiDataLoaded) {
lastNodeText = " ";
}
// if (commonFieldPathString != null && commonFieldPathString.length() > 0) {
// // todo: use the commonFieldPathString as the node name if not display preference is set or the ones that are set have no value
// nodeText = commonFieldPathString;
boolean foundPreferredNameField = false;
getLabelString:
for (String currentPreferredName : this.getNodeTemplate().preferredNameFields) {
//System.out.println("currentField: " + currentPreferredName);
for (ImdiField[] currentFieldArray : fieldHashtable.values()) {
// System.out.println(currentFieldArray[0].getFullXmlPath().replaceAll("\\(\\d+\\)", "") + " : " + currentPreferredName);
if (currentFieldArray[0].getFullXmlPath().replaceAll("\\(\\d+\\)", "").equals(currentPreferredName)) {
for (ImdiField currentField : currentFieldArray) {
if (currentField != null) {
if (currentField.toString().trim().length() > 0) {
nodeText = currentField.toString();
foundPreferredNameField = true;
break getLabelString;
}
}
}
}
}
ImdiField[] currentFieldArray = fieldHashtable.get(currentPreferredName);
if (currentFieldArray != null) {
for (ImdiField currentField : currentFieldArray) {
if (currentField != null) {
if (currentField.toString().trim().length() > 0) {
nodeText = currentField.toString();
// System.out.println("nodeText: " + nodeText);
foundPreferredNameField = true;
break getLabelString;
}
}
}
}
}
if (!foundPreferredNameField && isCmdiMetaDataNode() /*&& fieldHashtable.size() > 0 && domParentImdi == this*/ && this.nodeTemplate != null) {
// if (this.getNodeTemplate().preferredNameFields.length == 0) {
// nodeText = "no field specified to name this node (" + this.nodeTemplate.getTemplateName() + ")";
// } else {
nodeText = "unnamed (" + this.nodeTemplate.getTemplateName() + ")";
}
// if (!foundPreferredNameField && isCmdiMetaDataNode() && domParentImdi == this && fieldHashtable.size() > 0) {
// // only if no name has been found and only for cmdi nodes and only when this is the dom parent node
// nodeText = fieldHashtable.elements().nextElement()[0].getFullXmlPath().split("\\.")[3];
if (hasResource()) {
String resourcePathString = getFullResourceURI().toString();
int lastIndex = resourcePathString.lastIndexOf("/");
// if (lastIndex)
resourcePathString = resourcePathString.substring(lastIndex + 1);
try {
resourcePathString = URLDecoder.decode(resourcePathString, "UTF-8");
} catch (UnsupportedEncodingException encodingException) {
GuiHelper.linorgBugCatcher.logError(encodingException);
}
nodeText = resourcePathString;
}
if (isInfoLink) {
String infoTitle = fieldHashtable.values().iterator().next()[0].getFieldValue();
infoTitle = infoTitle.trim();
if (infoTitle.length() > 0) {
nodeText = infoTitle;
}
}
// nodeTextChanged = lastNodeText.equals(nodeText + nameText);
if (nodeText != null) {
if (isMetaDataNode()) {
File nodeFile = this.getFile();
if (nodeFile != null && !isHeadRevision()) {
nodeText = nodeText + " (rev:" + getHistoryLabelStringForFile(nodeFile) + ")";
}
}
lastNodeText = nodeText;
}
if (lastNodeText.length() == 0) {
lastNodeText = " ";
}
return lastNodeText;// + "-" + clearIconCounterGlobal + "-" + clearIconCounter;
}
/**
* Tests if there is file associated with this node and if it is an archivable type.
* The file could be either a resource file (getResource) or a loose file (getUrlString).
* @return boolean
*/
public boolean isArchivableFile() {
return mpiMimeType != null;
}
/**
* Tests if a resource file (local or remote) is associated with this node.
* @return boolean
*/
public boolean hasResource() {
return resourceUrlField != null;
}
/**
* Tests if a local resource file is associated with this node.
* @return boolean
*/
public boolean hasLocalResource() {
if (!hasResource()) {
return false;
}
if (resourceUrlField.getFieldValue().toLowerCase().startsWith("http")) {
return false;
}
if (!this.isLocal()) {
return false;
} else {
return true;
}
}
public boolean resourceFileNotFound() {
if (hasLocalResource()) {
if (resourceUrlField.getFieldValue().length() == 0) {
return true;
}
try {
return !(new File(this.getFullResourceURI())).exists();
} catch (Exception e) {
return true;
}
} else {
return false;
}
}
/**
* Gets the ULR string of the resource file if it is available.
* @return a URL string of the resource file
*/
private String getResource() {
return resourceUrlField.getFieldValue();
}
public boolean hasHistory() {
if (!this.isLocal()) {
// only local files can have a history
return false;
}
return !this.isImdiChild() && new File(this.getFile().getAbsolutePath() + ".0").exists();
}
private String getHistoryLabelStringForFile(File historyFile) {
Date mtime = new Date(historyFile.lastModified());
String mTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mtime);
return mTimeString;
}
private boolean isHeadRevision() {
return !(new File(this.getFile().getAbsolutePath() + ".x").exists());
}
public String[][] getHistoryList() {
Vector<String[]> historyVector = new Vector<String[]>();
int versionCounter = 0;
File currentHistoryFile;
// historyVector.add(new String[]{"Current", ""});
if (!isHeadRevision()) {
historyVector.add(new String[]{"Last Save", ".x"});
}
do {
currentHistoryFile = new File(this.getFile().getAbsolutePath() + "." + versionCounter);
if (currentHistoryFile.exists()) {
String mTimeString = getHistoryLabelStringForFile(currentHistoryFile);
historyVector.add(new String[]{mTimeString, "." + versionCounter});
}
versionCounter++;
} while (currentHistoryFile.exists());
return historyVector.toArray(new String[][]{{}});
}
public boolean resurrectHistory(String historyVersion) {
try {
if (historyVersion.equals(".x")) {
this.getFile().delete();
new File(this.getFile().getAbsolutePath() + ".x").renameTo(this.getFile());
} else {
LinorgWindowManager.getSingleInstance().offerUserToSaveChanges();
if (!new File(this.getFile().getAbsolutePath() + ".x").exists()) {
this.getFile().renameTo(new File(this.getFile().getAbsolutePath() + ".x"));
} else {
this.getFile().delete();
}
InputStream hisoryFile = new FileInputStream(new File(this.getFile().getAbsolutePath() + historyVersion));
OutputStream activeVersionFile = new FileOutputStream(this.getFile(), true);
byte[] copyBuffer = new byte[1024];
int len;
while ((len = hisoryFile.read(copyBuffer)) > 0) {
activeVersionFile.write(copyBuffer, 0, len);
}
hisoryFile.close();
activeVersionFile.close();
}
ImdiLoader.getSingleInstance().requestReload(getParentDomNode());
} catch (Exception e) {
// user canceled the save action
// todo: alert user that nothing was done
return false;
}
return true;
}
/*
* Increment the history file so that a new current file can be saved without overwritting the old
*/
public void bumpHistory() {
// update the files version number
//TODO: the template add does not create a new history file
int versionCounter = 0;
File headVersion = this.getFile();
// if the .x file (the last head) exist then replace the current with it
if (new File(this.getFile().getAbsolutePath() + ".x").exists()) {
versionCounter++;
headVersion = new File(this.getFile().getAbsolutePath() + ".x");
}
while (new File(this.getFile().getAbsolutePath() + "." + versionCounter).exists()) {
versionCounter++;
}
while (versionCounter >= 0) {
File lastFile = new File(this.getFile().getAbsolutePath() + "." + versionCounter);
versionCounter
File nextFile = new File(this.getFile().getAbsolutePath() + "." + versionCounter);
if (versionCounter >= 0) {
nextFile.renameTo(lastFile);
System.out.println("renaming: " + nextFile + " : " + lastFile);
} else {
headVersion.renameTo(lastFile);
System.out.println("renaming: " + headVersion + " : " + lastFile);
}
}
}
private void copyLastHistoryToCurrent() {
try {
FileOutputStream outFile = new FileOutputStream(this.getFile());
InputStream inputStream = new FileInputStream(new File(this.getFile().getAbsolutePath() + ".0"));
int bufferLength = 1024 * 4;
byte[] buffer = new byte[bufferLength];
int bytesread = 0;
while (bytesread >= 0) {
bytesread = inputStream.read(buffer);
if (bytesread == -1) {
break;
}
outFile.write(buffer, 0, bytesread);
}
outFile.close();
} catch (IOException iOException) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Could not copy file when recovering from the last history file.", "Recover History");
GuiHelper.linorgBugCatcher.logError(iOException);
}
}
/**
* Resolves the full path to a resource file if it exists.
* @return The path to remote resource if it exists.
*/
public URI getFullResourceURI() {
try {
String targetUriString = resourceUrlField.getFieldValue();
URI targetUri = new URI(null, targetUriString, null);
// System.out.println("nodeUri: " + nodeUri);
URI resourceUri = nodeUri.resolve(targetUri);
// System.out.println("targetUriString: " + targetUriString);
// System.out.println("targetUri: " + targetUri);
// System.out.println("resourceUri: " + resourceUri);
if (!targetUri.equals(resourceUri)) {
// maintain the UNC path
boolean isUncPath = nodeUri.toString().toLowerCase().startsWith("file:
if (isUncPath) {
try {
resourceUri = new URI("file:////" + resourceUri.toString().substring("file:/".length()));
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
}
return resourceUri;
} catch (Exception urise) {
GuiHelper.linorgBugCatcher.logError(urise);
System.out.println("URISyntaxException: " + urise.getMessage());
return null;
}
}
/**
* Gets the ULR string provided when the node was created.
* @return a URL string of the IMDI
*/
public String getUrlString() {
// TODO: update the uses of this to use the uri not a string
return nodeUri.toString();
}
/**
* Gets the ImdiTreeObject parent of an imdi child node.
* The returned node will be able to reload/save the dom for this node.
* Only relevant for imdi child nodes.
* @return ImdiTreeObject
*/
public ImdiTreeObject getParentDomNode() {
// System.out.println("nodeUri: " + nodeUri);
if (domParentImdi == null) {
if (nodeUri.getFragment() != null) {
try {
//domParentImdi = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(nodeUri.getScheme(), nodeUri.getUserInfo(), nodeUri.getHost(), nodeUri.getPort(), nodeUri.getPath(), nodeUri.getQuery(), null /* fragment removed */));
// the uri is created via the uri(string) constructor to prevent re-url-encoding the url
domParentImdi = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(nodeUri.toString().split("#")[0] /* fragment removed */));
// System.out.println("nodeUri: " + nodeUri);
} catch (URISyntaxException ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
} else {
domParentImdi = this;
}
}
return domParentImdi;
}
public boolean isDirectory() {
return isDirectory;
}
public boolean isMetaDataNode() {
if (nodeUri != null /* && nodDom != null*/) {
if (isImdiChild()) {
return true;
} else {
return ImdiTreeObject.isPathMetadata(nodeUri.getPath());
}
}
return false;
}
public boolean isCmdiMetaDataNode() {
if (nodeUri != null /* && nodDom != null*/) {
if (isImdiChild()) {
return getParentDomNode().isCmdiMetaDataNode();
} else {
return ImdiTreeObject.isPathCmdi(nodeUri.getPath());
}
}
return false;
}
public boolean isImdiChild() {
return ImdiTreeObject.isStringImdiChild(this.getUrlString());
}
public boolean isSession() {
// test if this node is a session
ImdiField[] nameFields = fieldHashtable.get("Name");
if (nameFields != null) {
return nameFields[0].xmlPath.equals(ImdiSchema.imdiPathSeparator + "METATRANSCRIPT" + ImdiSchema.imdiPathSeparator + "Session" + ImdiSchema.imdiPathSeparator + "Name");
}
return false;
}
/**
* Tests if this node is a meta node that contains no fields and only child nodes, such as the Languages, Actors, MediaFiles nodes etc..
* @return boolean
*/
public boolean isEmptyMetaNode() {
return this.getFields().size() == 0;
}
public boolean isCatalogue() {
// test if this node is a catalogue
ImdiField[] nameFields = fieldHashtable.get("Name");
if (nameFields != null) {
return nameFields[0].xmlPath.equals(ImdiSchema.imdiPathSeparator + "METATRANSCRIPT" + ImdiSchema.imdiPathSeparator + "Catalogue" + ImdiSchema.imdiPathSeparator + "Name");
}
return false;
}
public boolean isCorpus() {
if (isCmdiMetaDataNode()) {
return false;
}
// test if this node is a corpus
ImdiField[] nameFields = fieldHashtable.get("Name");
if (nameFields != null) {
return nameFields[0].xmlPath.equals(ImdiSchema.imdiPathSeparator + "METATRANSCRIPT" + ImdiSchema.imdiPathSeparator + "Corpus" + ImdiSchema.imdiPathSeparator + "Name");
}
return false;
}
public boolean isLocal() {
if (nodeUri != null) {
return ImdiTreeObject.isStringLocal(nodeUri.getScheme());
} else {
return false;
}
}
public boolean isEditable() {
if (isLocal()) {
return (LinorgSessionStorage.getSingleInstance().pathIsInsideCache(this.getFile()))
|| LinorgSessionStorage.getSingleInstance().pathIsInFavourites(this.getFile());
} else {
return false;
}
}
/**
* Returns the URI object for this node.
* @return A URI that this node represents.
*/
public URI getURI() {
try {
return nodeUri; // new URI(nodeUri.toString()); // a copy of
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
return null;
}
}
public File getFile() {
// System.out.println("getFile: " + nodeUri.toString());
if (nodeUri.getScheme().toLowerCase().equals("file")) {
try {
return new File(new URI(nodeUri.toString().split("#")[0] /* fragment removed */));
} catch (Exception urise) {
System.err.println("nodeUri: " + nodeUri);
GuiHelper.linorgBugCatcher.logError(urise);
}
}
return null;
}
public String getParentDirectory() {
String parentPath = this.getUrlString().substring(0, this.getUrlString().lastIndexOf("/")) + "/"; // this is a url so don't use the path separator
return parentPath;
}
public void registerContainer(Object containerToAdd) {
// System.out.println("registerContainer: " + containerToAdd + " : " + this);
if (!getParentDomNode().imdiDataLoaded && !isLoading()) { // TODO: this is probably not the best way to do this and might be better in a manager class
ImdiLoader.getSingleInstance().requestReload(getParentDomNode());
}
if (containerToAdd != null) {
// todo: handle null here more agressively
containersOfThisNode.add(containerToAdd);
}
}
public Object[] getRegisteredContainers() {
if (containersOfThisNode != null && containersOfThisNode.size() > 0) {
return containersOfThisNode.toArray();
} else {
return new Object[]{};
}
}
/**
* Removes a UI containers from the list of containers interested in this node.
* @param containerToRemove The container to be removed from the list.
*/
public void removeContainer(Object containerToRemove) {
// TODO: make sure that containers are removed when a node is removed from the tree, otherwise memory will not get freed
// System.out.println("de registerContainer: " + containerToRemove);
containersOfThisNode.remove(containerToRemove);
}
/**
* Clears the icon for all the imdi child nodes of this node.
* Used when loading a session dom.
*/
public void clearChildIcons() {
// System.out.println("clearChildIconsParent: " + this);
for (ImdiTreeObject currentChild : childArray) {
// if (!currentChild.equals(currentChild.getParentDomNode())) {
// System.out.println("clearChildIcons: " + currentChild);
currentChild.clearChildIcons();
currentChild.clearIcon();
}
}
// public void addJumpToInTreeRequest() {
// jumpToRequested = true;
/**
* Clears the icon calculated in "getIcon()" and notifies any UI containers of this node.
*/
public void clearIcon() {
refreshStringValue();
// System.out.println("clearIcon: " + this);
// System.out.println("containersOfThisNode: " + containersOfThisNode.size());
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
icon = ImdiIcons.getSingleInstance().getIconForImdi(ImdiTreeObject.this); // to avoid a race condition (where the loading icons remains after load) this is also set here rather than nulling the icon
// System.out.println("clearIcon invokeLater" + ImdiTreeObject.this.toString());
// System.out.println("containersOfThisNode: " + containersOfThisNode.size());
// here we need to cause an update in the tree and table gui so that the new icon can be loaded
for (Enumeration containersIterator = containersOfThisNode.elements(); containersIterator.hasMoreElements();) { // changed back to a vector due to threading issues here
try { // TODO: the need for this try catch indicates that there is a threading issue in the way that imdichild nodes are reloaded within an imdi parent node and this should be reorganised to be more systematic and hierarchical
Object currentContainer = containersIterator.nextElement();
// System.out.println("currentContainer: " + currentContainer.toString());
if (currentContainer instanceof ImdiTableModel) {
((ImdiTableModel) currentContainer).requestReloadTableData(); // this must be done because the fields have been replaced and nead to be reloaded in the tables
}
if (currentContainer instanceof ImdiChildCellEditor) {
((ImdiChildCellEditor) currentContainer).updateEditor(ImdiTreeObject.this);
}
if (currentContainer instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode currentTreeNode = (DefaultMutableTreeNode) currentContainer;
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) currentContainer).getParent();
if (parentNode != null) {
TreeHelper.getSingleInstance().addToSortQueue(parentNode);
} else {
TreeHelper.getSingleInstance().addToSortQueue(currentTreeNode);
}
}
} catch (java.util.NoSuchElementException ex) {
//GuiHelper.linorgBugCatcher.logError(ex);
}
}
// System.out.println("end clearIcon: " + this);
}
public boolean isFavorite() {
if (!this.isLocal()) {
// only local files can be favourites
return false;
}
return LinorgSessionStorage.getSingleInstance().pathIsInFavourites(this.getFile());
// return getParentDomNode().isFavourite;
}
// public void setFavouriteStatus(boolean favouriteStatus) {
// getParentDomNode().isFavourite = favouriteStatus;
// clearIcon();
/**
* If not already done calculates the required icon for this node in its current state.
* Once calculated the stored icon will be returned.
* To clear the icon and recalculate it "clearIcon()" should be called.
* @return The icon for this node.
*/
public ImageIcon getIcon() {
if (icon == null) {
return ImdiIcons.getSingleInstance().loadingIcon;
}
return icon;
}
}
|
package nl.mpi.arbil.data;
import nl.mpi.arbil.*;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import mpi.imdi.api.*;
import mpi.util.OurURL;
import org.w3c.dom.Document;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class ImdiTreeObject implements Comparable {
// TODO: move the api into a wrapper class
public static IMDIDom api = new IMDIDom();
public ArbilTemplate currentTemplate;
// static ImdiIcons imdiIcons = new ImdiIcons();
private static Vector listDiscardedOfAttributes = new Vector(); // a list of all unused imdi attributes, only used for testing
private boolean debugOn = false;
private Hashtable<String, ImdiField[]> fieldHashtable; //// TODO: this should be changed to a vector or contain an array so that duplicate named fields can be stored ////
private ImdiTreeObject[] childArray = new ImdiTreeObject[0];
public boolean imdiDataLoaded;
public int resourceFileServerResponse = -1; // -1 = not set otherwise this will be the http response code
public String hashString;
public String mpiMimeType = null;
public String typeCheckerMessage;
public int matchesInCache;
public int matchesRemote;
public int matchesLocalFileSystem;
public boolean fileNotFound;
private boolean needsSaveToDisk;
private String nodeText, lastNodeText = "loading imdi...";
// private boolean nodeTextChanged = false;
private URI nodeUri;
public ImdiField resourceUrlField;
public boolean isDirectory;
private ImageIcon icon;
private boolean nodeEnabled;
// merge to one array of domid url imditreeobject
private String[][] childLinks = new String[0][0]; // each element in this array is an array [linkPath, linkId]. When the link is from an imdi the id will be the node id, when from get links or list direcotry id will be null
private Vector/*<Component>*/ containersOfThisNode;
private int isLoadingCount = 0;
final private Object loadingCountLock = new Object();
public boolean lockedByLoadingThread = false;
// private boolean isFavourite;
public boolean hasArchiveHandle = false;
// public boolean autoLoadChildNodes = false;
public Vector<String[]> addQueue;
public boolean scrollToRequested = false;
// public Vector<ImdiTreeObject> mergeQueue;
// public boolean jumpToRequested = false; // dubious about this being here but it seems to fit here best
private ImdiTreeObject domParentImdi = null; // the parent imdi containing the dom, only set for imdi child nodes
public String xmlNodeId = null; // only set for imdi child nodes and is the xml node id relating to this imdi tree object
public File thumbnailFile = null;
private final Object domLockObject = new Object();
protected ImdiTreeObject(URI localUri) {
// System.out.println("ImdiTreeObject: " + localUri);
containersOfThisNode = new Vector<Component>();
addQueue = new Vector<String[]>();
nodeUri = localUri;
initNodeVariables();
}
// set the node text only if it is null
public void setNodeText(String localNodeText) {
if (nodeText == null) {
nodeText = localNodeText;
}
}
// TODO: this is not used yet but may be required for unicode paths
private String urlEncodePath(String inputPath) {
// url encode the path elements
String encodedString = null;
try {
for (String inputStringPart : inputPath.split("/")) {
// System.out.println("inputStringPart: " + inputStringPart);
if (encodedString == null) {
encodedString = URLEncoder.encode(inputStringPart, "UTF-8");
} else {
encodedString = encodedString + "/" + URLEncoder.encode(inputStringPart, "UTF-8");
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
return encodedString;
}
static public URI conformStringToUrl(String inputUrlString) {
// System.out.println("conformStringToUrl: " + inputUrlString);
URI returnUrl = null;
try {
// localUrlString = localUrlString.replace("\\", "/");
if (!inputUrlString.toLowerCase().startsWith("http:") && !inputUrlString.toLowerCase().startsWith("file:") && !inputUrlString.toLowerCase().startsWith(".")) {
returnUrl = new File(inputUrlString).toURI();
} else {
// apache method
// URI tempURI = new URI(inputUrlString);
// URI returnURI = URIUtils.createURI(tempURI.getScheme(), tempURI.getHost(), tempURI.getPort(), tempURI.getPath(), tempURI.getQuery(), tempURI.getFragment());
// return returnURI;
// end apache method : this requires the uri to be broken into its parts so we might as well do it with the standard classes
// mpi method
// URI returnURI = URIUtil.newURI(inputUrlString);
// end mpi method : this will url encode the # etc. and therefore loose the fragment and other parts
// boolean isUncPath = inputUrlString.toLowerCase().startsWith("file:////");
// if (isUncPath) {
// try {
// returnURI = new URI("file:////" + returnURI.toString().substring("file:/".length()));
// } catch (URISyntaxException urise) {
// GuiHelper.linorgBugCatcher.logError(urise);
// separate the path and protocol
int protocolEndIndex;
if (inputUrlString.startsWith(".")) {
// TODO: this is un tested for ./ paths, but at this stage it appears unlikey to ever be needed
protocolEndIndex = 0;
} else {
protocolEndIndex = "xxxx".length();
}
// while (inputUrlString.charAt(protocolEndIndex) == '/') {
// protocolEndIndex++;
String protocolComponent = inputUrlString.substring(0, protocolEndIndex);
String remainingComponents = inputUrlString.substring(protocolEndIndex + 1);
String[] pathComponentArray = remainingComponents.split("
String pathComponent = pathComponentArray[0];
String fragmentComponent = null;
if (pathComponentArray.length > 1) {
fragmentComponent = pathComponentArray[1];
}
// note that this must be done as separate parameters not a single string otherwise it will not get url encoded
// TODO: this could require the other url components to be added here
returnUrl = new URI(protocolComponent, pathComponent, fragmentComponent);
// System.out.println("returnUrl: " + returnUrl);
//// int protocolEndIndex = inputUrlString.lastIndexOf("/", "xxxx:".length());
// String pathComponentEncoded = URLEncoder.encode(pathComponent, "UTF-8");
// returnUrl = new URI(protocolComponent + pathComponentEncoded);
// System.out.println("returnUrl: " + returnUrl);
}
// // if the imdi api finds only one / after the file: it will interpret the url as relative and make a bit of a mess of it, so we have to make sure that we have two for the url and one for the root
// if (returnUrl.toString().toLowerCase().startsWith("file:") && !returnUrl.toString().toLowerCase().startsWith("file:///")) {
// // here we assume that this application does not use relative file paths
// returnUrl = new URL("file", "", "//" + returnUrl.getPath());
// System.out.println("conformStringToUrl URI: " + new URI(returnUrl.toString()));
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
// System.out.println("conformStringToUrl out: " + returnUrl.toString());
return normaliseURI(returnUrl);
}
static public URI normaliseURI(URI inputURI) {
// System.out.println("normaliseURI: " + inputURI);
boolean isUncPath = inputURI.toString().toLowerCase().startsWith("file:
URI returnURI = inputURI.normalize();
if (isUncPath) {
try {
// note that this must use the single string parameter to prevent re url encoding
returnURI = new URI("file:////" + returnURI.toString().substring("file:/".length()));
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
return returnURI;
}
// static methods for testing imdi file and object types
static public boolean isImdiNode(Object unknownObj) {
if (unknownObj == null) {
return false;
}
return (unknownObj instanceof ImdiTreeObject);
}
static public boolean isStringLocal(String urlString) {
return (!urlString.startsWith("http"));
}
static public boolean isStringImdiHistoryFile(String urlString) {
// System.out.println("isStringImdiHistoryFile" + urlString);
// System.out.println("isStringImdiHistoryFile" + urlString.replaceAll(".imdi.[0-9]*$", ".imdi"));
return isStringImdi(urlString.replaceAll(".imdi.[0-9]*$", ".imdi"));
}
static public boolean isStringImdi(String urlString) {
return urlString.endsWith(".imdi") || urlString.endsWith(".cmdi"); // change made for clarin
}
static public boolean isStringImdiChild(String urlString) {
return urlString.contains("#.METATRANSCRIPT") || urlString.contains("#.CMD"); // change made for clarin
}
static public void requestRootAddNode(String nodeType, String nodeTypeDisplayName) {
ImdiTreeObject imdiTreeObject;
imdiTreeObject = new ImdiTreeObject(LinorgSessionStorage.getSingleInstance().getNewImdiFileName(LinorgSessionStorage.getSingleInstance().getSaveLocation("")));
imdiTreeObject.requestAddNode(nodeType, nodeTypeDisplayName);
}
// end static methods for testing imdi file and object types
public boolean getNeedsSaveToDisk() {
// when the dom parent node is saved all the sub nodes are also saved so we need to clear this flag
if (needsSaveToDisk && !this.getParentDomNode().needsSaveToDisk) {
needsSaveToDisk = false;
}
return needsSaveToDisk;
}
public boolean hasChangedFields() {
boolean fieldsHaveChanges = false;
for (ImdiField[] currentFieldArray : this.fieldHashtable.values()) {
for (ImdiField currentField : currentFieldArray) {
if (currentField.fieldNeedsSaveToDisk()) {
fieldsHaveChanges = true;
}
}
}
return fieldsHaveChanges;
}
public void setImdiNeedsSaveToDisk(ImdiField originatingField, boolean updateUI) {
if (resourceUrlField != null && resourceUrlField.equals(originatingField)) {
hashString = null;
mpiMimeType = null;
thumbnailFile = null;
typeCheckerMessage = null;
MimeHashQueue.getSingleInstance().addToQueue(this);
}
boolean imdiNeedsSaveToDisk = hasChangedFields();
if (isImdi() && !isImdiChild()) {
if (imdiNeedsSaveToDisk == false) {
for (ImdiTreeObject childNode : getAllChildren()) {
if (childNode.needsSaveToDisk) {
imdiNeedsSaveToDisk = true;
}
}
}
if (this.needsSaveToDisk != imdiNeedsSaveToDisk) {
if (imdiNeedsSaveToDisk) {
ImdiLoader.getSingleInstance().addNodeNeedingSave(this);
} else {
ImdiLoader.getSingleInstance().removeNodesNeedingSave(this);
}
this.needsSaveToDisk = imdiNeedsSaveToDisk;
}
} else {
this.needsSaveToDisk = imdiNeedsSaveToDisk; // this must be set before setImdiNeedsSaveToDisk is called
this.getParentDomNode().setImdiNeedsSaveToDisk(originatingField, updateUI);
}
if (updateUI) {
this.clearIcon();
}
}
public String getAnyMimeType() {
if (mpiMimeType == null && hasResource()) { // use the format from the imdi file if the type checker failed eg if the file is on the server
ImdiField[] formatField = fieldHashtable.get("Format");
if (formatField != null && formatField.length > 0) {
return formatField[0].getFieldValue();
}
}
return mpiMimeType;
}
public void setMimeType(String[] typeCheckerMessageArray) {
mpiMimeType = typeCheckerMessageArray[0];
typeCheckerMessage = typeCheckerMessageArray[1];
if (!isImdi() && isLocal() && mpiMimeType != null) {
// add the mime type
ImdiField mimeTypeField = new ImdiField(this, "Format", this.mpiMimeType);
mimeTypeField.fieldID = "x" + fieldHashtable.size();
addField(mimeTypeField);
}
}
private void initNodeVariables() {
// loop any indichildnodes and init
if (childArray != null) {
for (ImdiTreeObject currentNode : childArray) {
if (currentNode.isImdiChild()) {
currentNode.initNodeVariables();
}
}
}
if (currentTemplate == null) {
// this will be overwritten when the imdi file is read, provided that a template is specified in the imdi file
currentTemplate = ArbilTemplateManager.getSingleInstance().getCurrentTemplate();
}
fieldHashtable = new Hashtable<String, ImdiField[]>();
imdiDataLoaded = false;
hashString = null;
//mpiMimeType = null;
matchesInCache = 0;
matchesRemote = 0;
matchesLocalFileSystem = 0;
fileNotFound = false;
needsSaveToDisk = false;
// nodeText = null;
// urlString = null;
// resourceUrlField = null;
isDirectory = false;
icon = null;
nodeEnabled = true;
// isLoadingCount = true;
if (nodeUri != null) {
if (!isImdi() && isLocal()) {
File fileObject = getFile();
if (fileObject != null) {
this.nodeText = fileObject.getName();
this.isDirectory = fileObject.isDirectory();
// TODO: check this on a windows box with a network drive and linux with symlinks
// this.isDirectory = !fileObject.isFile();
// System.out.println("isFile" + fileObject.isFile());
// System.out.println("isDirectory" + fileObject.isDirectory());
// System.out.println("getAbsolutePath" + fileObject.getAbsolutePath());
}
}
if (!isImdi() && nodeText == null) {
nodeText = this.getUrlString();
}
}
}
public void reloadNode() {
System.out.println("reloadNode: " + isLoading());
getParentDomNode().needsSaveToDisk = false; // clear any changes
// if (!this.isImdi()) {
// initNodeVariables();
// //loadChildNodes();
// clearIcon();
// // TODO: this could just remove the decendant nodes and let the user re open them
// TreeHelper.getSingleInstance().updateTreeNodeChildren(this);
//// this.clearIcon();
// } else {
//// if (getParentDomNode().isCorpus()) {
//// getParentDomNode().autoLoadChildNodes = true;
ImdiLoader.getSingleInstance().requestReload(getParentDomNode());
}
synchronized public void loadImdiDom() {
System.out.println("loadImdiDom: " + nodeUri.toString());
if (getParentDomNode() != this) {
getParentDomNode().loadImdiDom();
} else {
synchronized (domLockObject) {
initNodeVariables(); // this might be run too often here but it must be done in the loading thread and it also must be done when the object is created
if (!isImdi() && !isDirectory() && isLocal()) {
// if it is an not imdi or a loose file but not a direcotry then get the md5sum
MimeHashQueue.getSingleInstance().addToQueue(this);
imdiDataLoaded = true;
}
if (this.isDirectory()) {
getDirectoryLinks();
imdiDataLoaded = true;
// clearIcon();
}
if (isImdi()) {
Document nodDom = null;
// cacheLocation will be null if useCache = false hence no file has been saved
// String cacheLocation = null;
try {
//System.out.println("tempUrlString: " + tempUrlString);
if (false) {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
nodDom = builder.parse(nodeUri.toURL().openStream());
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
// System.out.println("Could not parse dom: " + this.getUrlString());
}
} else {
OurURL inUrlLocal = null;
inUrlLocal = new OurURL(nodeUri.toURL());
nodDom = api.loadIMDIDocument(inUrlLocal, false);
if (this.isLocal() && this.getFile().exists() && nodDom == null) { // if the file is local and the file exits then the we sould be able to expect the api to open the file so warn the user that something unusal occured
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The IMDI API could not load the file\n" + this.getUrlString(), "Load IMDI File");
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
// todo: if the file is zero bytes offer to revert to a previous version if it exists
}
}
// only read the fields into imdi tree objects if it is not going to be saved to the cache
// if (!useCache) {
if (nodDom == null) {
File nodeFile = this.getFile();
if (nodeFile != null && nodeFile.exists()) {
nodeText = "Could not load IMDI";
} else {
nodeText = "File not found";
fileNotFound = true;
}
} else {
//set the string name to unknown, it will be updated in the tostring function
nodeText = "unknown";
Vector<String[]> childLinksTemp = new Vector<String[]>();
Hashtable<ImdiTreeObject, HashSet<ImdiTreeObject>> parentChildTree = new Hashtable<ImdiTreeObject, HashSet<ImdiTreeObject>>();
// load the fields from the imdi file
ImdiSchema.getSingleInstance().iterateChildNodes(this, childLinksTemp, nodDom.getFirstChild(), "", parentChildTree);
childLinks = childLinksTemp.toArray(new String[][]{});
ImdiTreeObject[] childArrayTemp = new ImdiTreeObject[childLinks.length];
for (ImdiTreeObject currentNode : parentChildTree.keySet()) {
// System.out.println("setting childArray on: " + currentNode.getUrlString());
// save the old child array
ImdiTreeObject[] oldChildArray = currentNode.childArray;
// set the new child array
currentNode.childArray = parentChildTree.get(currentNode).toArray(new ImdiTreeObject[]{});
// check the old child array and for each that is no longer in the child array make sure they are removed from any containers (tables or trees)
List currentChildList = Arrays.asList(currentNode.childArray);
for (ImdiTreeObject currentOldChild : oldChildArray) {
if (currentChildList.indexOf(currentOldChild) == -1) {
// remove from any containers that its found in
for (Object currentContainer : currentOldChild.getRegisteredContainers()) {
if (currentContainer instanceof ImdiChildCellEditor) {
((ImdiChildCellEditor) currentContainer).stopCellEditing();
}
if (currentContainer instanceof ImdiTableModel) {
((ImdiTableModel) currentContainer).removeImdiObjects(new ImdiTreeObject[]{currentOldChild});
}
if (currentContainer instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode currentTreeNode = (DefaultMutableTreeNode) currentContainer;
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) currentContainer).getParent();
if (parentNode != null) { // TODO this could be reduced as it is also sort of done in clear icon
TreeHelper.getSingleInstance().addToSortQueue(parentNode);
} else {
TreeHelper.getSingleInstance().addToSortQueue(currentTreeNode);
}
}
}
}
}
}
}
// save this to the cache before deleting the dom
// if (useCache) {
// // get the links from the imdi before we dispose of the dom
// getImdiLinks(nodDom);
//// cacheLocation = saveNodeToCache(nodDom);
} catch (Exception mue) {
GuiHelper.linorgBugCatcher.logError(mue);
// System.out.println("Invalid input URL: " + mue);
}
//we are now done with the dom so free the memory
nodDom = null;
// return cacheLocation;
imdiDataLoaded = true;
getParentDomNode().notifyAll();
// clearChildIcons();
}
}
}
}
// private String getField(String fieldName) {
// Document itemDom = this.getNodeDom();
// if (itemDom == null) {
// return null;
// IMDIElement rowValue = api.getIMDIElement(itemDom, fieldName);
// if (rowValue != null) {
// return rowValue.getValue();
// } else {
// return null;
private void getDirectoryLinks() {
File[] dirLinkArray = null;
File nodeFile = this.getFile();
if (nodeFile != null) {
dirLinkArray = nodeFile.listFiles();
Vector<ImdiTreeObject> childLinksTemp = new Vector<ImdiTreeObject>();
for (int linkCount = 0; linkCount < dirLinkArray.length; linkCount++) {
try {
// System.out.println("nodeFile: " + nodeFile);
// System.out.println("dirLinkArray[linkCount]: " + dirLinkArray[linkCount]);
URI childURI = dirLinkArray[linkCount].toURI();
ImdiTreeObject currentImdi = ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(childURI);
if (TreeHelper.getSingleInstance().showHiddenFilesInTree || !currentImdi.getFile().isHidden()) {
childLinksTemp.add(currentImdi);
}
} catch (Exception ex) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue(dirLinkArray[linkCount] + " could not be loaded in\n" + nodeUri.toString(), "Load Directory");
new LinorgBugCatcher().logError(ex);
}
}
//childLinks = childLinksTemp.toArray(new String[][]{});
childArray = childLinksTemp.toArray(new ImdiTreeObject[]{});
}
}
// private void getImdiLinks(Document nodDom) {
// try {
// if (nodDom != null) {
// OurURL baseURL = new OurURL(nodeUri.toURL());
//// debugOut("getIMDILinks");
// IMDILink[] links = api.getIMDILinks(nodDom, baseURL, WSNodeType.CORPUS);
//// debugOut("links.length: " + links.length);
// if (links != null) {
// for (int linkCount = 0; linkCount < links.length; linkCount++) {
// childLinks.add(new String[]{links[linkCount].getRawURL().toString(), null});
// } catch (MalformedURLException mue) {
// System.out.println("Error getting links: " + mue);
// private boolean populateChildFields(String fieldNameString, boolean alwaysShow) {
// // this is called when loading children and when loading fields
// //System.out.println("fieldNameString: " + fieldNameString);
// boolean valueFound = false;
// int counterFieldPosition = fieldNameString.indexOf("(X)");
// if (-1 < counterFieldPosition) {
// int itemValueCounter = 1;
// valueFound = true;
// String firstHalf = fieldNameString.substring(0, counterFieldPosition + 1);
// String secondHalf = fieldNameString.substring(counterFieldPosition + 2);
// while (valueFound) {
// fieldNameString = firstHalf + itemValueCounter + secondHalf;
// if (-1 < fieldNameString.indexOf("(X)")) {
// valueFound = populateChildFields(fieldNameString, alwaysShow);
// } else {
// boolean isWrongFieldType = false;
// if (isImdi()) {
// if (isSession() && fieldNameString.startsWith("Corpus.")) {
// // TODO: we could speed things up by not asking the imdi.api for the value of this field, however if there is data so show (presumably erroneous data) it should still be shown
// isWrongFieldType = true;
// } else if (fieldNameString.startsWith("Session.")) {
// isWrongFieldType = true;
// //System.out.println("checking x value for: " + fieldNameString);
// String cellValue = this.getField(fieldNameString);
// valueFound = cellValue != null;
// if (valueFound && cellValue.length() > 0) {
// this.addField(fieldNameString, 0, cellValue);
// } else if (alwaysShow) {
// if (!isWrongFieldType) {
// this.addField(fieldNameString, 0, "");
// itemValueCounter++;
// } else {
// //System.out.println("checking value for: " + fieldNameString);
// String cellValue = this.getField(fieldNameString);
// valueFound = cellValue != null;
// if (valueFound && cellValue.length() > 0) {
// this.addField(fieldNameString, 0, cellValue);
// return valueFound;
/**
* Count the next level of child nodes. (non recursive)
* @return An integer of the next level of child nodes including corpus links and imdi child nodes.
*/
public int getChildCount() {
// System.out.println("getChildCount: " + childLinks.size() + childrenHashtable.size() + " : " + this.getUrlString());
return childArray.length;
}
/**
* Calls getAllChildren(Vector<ImdiTreeObject> allChildren) and returns the result as an array
* @return an array of all the child nodes
*/
public ImdiTreeObject[] getAllChildren() {
Vector<ImdiTreeObject> allChildren = new Vector<ImdiTreeObject>();
getAllChildren(allChildren);
return allChildren.toArray(new ImdiTreeObject[]{});
}
/**
* Used to get all the imdi child nodes (all levels) of a session or all the nodes contained in a corpus (one level only).
* @param An empty vector, to which all the child nodes will be added.
*/
public void getAllChildren(Vector<ImdiTreeObject> allChildren) {
System.out.println("getAllChildren: " + this.getUrlString());
if (this.isSession() || this.isImdiChild()) {
for (ImdiTreeObject currentChild : childArray) {
currentChild.getAllChildren(allChildren);
allChildren.add(currentChild);
}
}
}
/**
* Gets an array of the children of this node.
* @return An array of the next level child nodes.
*/
public ImdiTreeObject[] getChildArray() {
return childArray;
}
// /**
// * Used to populate the child list in the show child popup in the imditable.
// * @return An enumeration of the next level child nodes.
// */
// public Enumeration<ImdiTreeObject> getChildEnum() {
// return childObjectDomIdHash.elements();
// /**
// * Used to populate the child nodes in the table cell.
// * @return A collection of the next level child nodes.
// */
// public Collection<ImdiTreeObject> getChildCollection() {
// return childObjectDomIdHash.values();
/**
* Gets the second level child nodes from the fist level child node matching the child type string.
* Used to populate the child nodes in the table cell.
* @param childType The name of the first level child to query.
* @return An object array of all second level child nodes in the first level node.
*/
public ImdiTreeObject[] getChildNodesArray(String childType) {
for (ImdiTreeObject currentNode : childArray) {
if (currentNode.toString().equals(childType)) {
return currentNode.getChildArray();
}
}
return null;
}
/**
* Attache a child node to this node.
* Only affects objects in memory and used when loading an imdi dom.
* Will not and should not add a node as a child of itself.
* To add a node to a dom use addChildNode.
* @return void
*/
// public void attachChildNode(ImdiTreeObject destinationNode) {
//// System.out.println("attachChildNodeTo: " + this.getUrlString());
//// System.out.println("attachChildNode: " + destinationNode.getUrlString());
// if (destinationNode != this) {
// childrenHashtable.put(destinationNode.getUrlString(), destinationNode);
// /**
// * Add a resource contained i an imdi object
// * @return String path to the added node
// */
// public String addChildNode(ImdiTreeObject nodeToAdd) {
// System.out.println("addChildNode: " + nodeToAdd);
// return addChildNode(null, nodeToAdd.getUrlString(), nodeToAdd.mpiMimeType);
// create a subdirectory based on the file name of the node
// if that fails then the current directory will be returned
public File getSubDirectory() {
String currentFileName = this.getFile().getParent();
if (this.getFile().getName().endsWith(".imdi")) {
currentFileName = currentFileName + File.separatorChar + this.getFile().getName().substring(0, this.getFile().getName().length() - 5);
File destinationDir = new File(currentFileName);
if (!destinationDir.exists()) {
destinationDir.mkdir();
}
return destinationDir;
}
return new File(this.getFile().getParent());
}
/**
* Add a new node based on a template and optionally attach a resource
* @return String path to the added node
*/
public URI addChildNode(String nodeType, String targetXmlPath, URI resourceUri, String mimeType) {
System.out.println("addChildNode:: " + nodeType + " : " + resourceUri);
System.out.println("targetXmlPath:: " + targetXmlPath);
if (needsSaveToDisk) {
saveChangesToCache(true);
}
URI addedNodePath = null;
ImdiTreeObject destinationNode;
if (currentTemplate.isImdiChildType(nodeType) || (resourceUri != null && this.isSession())) {
System.out.println("adding to current node");
destinationNode = this;
try {
synchronized (domLockObject) {
OurURL inUrlLocal = new OurURL(nodeUri.toURL());
System.out.println("inUrlLocal: " + inUrlLocal);
Document nodDom = api.loadIMDIDocument(inUrlLocal, false);
if (nodDom == null) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The IMDI file could not be opened via the IMDI API", "Add Node");
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
} else {
// api.writeDOM(nodDom, this.getFile(), true); // remove the id attributes
// System.out.println("addChildNode: insertFromTemplate");
// System.out.println("inUrlLocal: " + inUrlLocal);
addedNodePath = ImdiSchema.getSingleInstance().insertFromTemplate(this.currentTemplate, this.getURI(), getSubDirectory(), nodeType, targetXmlPath, nodDom, resourceUri, mimeType);
// System.out.println("addChildNode: save");
// nodDom = api.loadIMDIDocument(inUrlLocal, false);
bumpHistory();
api.writeDOM(nodDom, this.getFile(), false); // add the id attributes
}
}
} catch (Exception ex) {
// System.out.println("addChildNode: " + ex.getMessage());
GuiHelper.linorgBugCatcher.logError(ex);
}
// needsSaveToDisk = true;
} else {
System.out.println("adding new node");
URI targetFileURI = LinorgSessionStorage.getSingleInstance().getNewImdiFileName(getSubDirectory());
addedNodePath = ImdiSchema.getSingleInstance().addFromTemplate(new File(targetFileURI), nodeType);
destinationNode = ImdiLoader.getSingleInstance().getImdiObject(null, targetFileURI);
if (this.getFile().exists()) {
this.addCorpusLink(destinationNode);
reloadNode();
} else {
// TODO: this should not really be here
TreeHelper.getSingleInstance().addLocation(destinationNode.getURI());
TreeHelper.getSingleInstance().applyRootLocations();
}
// destinationNode.saveChangesToCache();
// destinationNode.needsSaveToDisk = true;
}
// //load then save the dom via the api to make sure there are id fields to each node then reload this imdi object
// destinationNode.updateImdiFileNodeIds();
// begin temp test
// ImdiField fieldToAdd1 = new ImdiField("test.field", "unset");
// fieldToAdd1.translateFieldName("test.field.translated");
// addableImdiChild.addField(fieldToAdd1, 0);
// end temp test
//for (Enumeration fieldsToAdd = GuiHelper.imdiFieldViews.getCurrentGlobalView().getAlwaysShowColumns(); fieldsToAdd.hasMoreElements();) {
// for (Enumeration fieldsToAdd = GuiHelper.imdiSchema.listFieldsFor(this, nodeType, getNextImdiChildIdentifier(), resourcePath); fieldsToAdd.hasMoreElements();) {
// String[] currentField = (String[]) fieldsToAdd.nextElement();
// System.out.println("fieldToAdd: " + currentField[0]);
// System.out.println("valueToAdd: " + currentField[1]);
// ImdiField fieldToAdd = new ImdiField(destinationNode, currentField[0], currentField[1]);
// //fieldToAdd.translateFieldName(nodePath + siblingSpacer);
// fieldToAdd.translateFieldName(currentField[0]);
// if (GuiHelper.linorgJournal.saveJournalEntry(fieldToAdd.parentImdi.getUrlString(), fieldToAdd.xmlPath, null, fieldToAdd.fieldValue)) {
// destinationNode.addField(fieldToAdd, 0, addedImdiNodes, false);
// if (destinationNode != this) {
//// System.out.println("adding to list of child nodes 1: " + destinationNode);
// childrenHashtable.put(destinationNode.getUrlString(), destinationNode);
return addedNodePath;
}
/**
* Loads the child links and returns them as an array
* @return ImdiTreeObject[] array of child nodes
*/
// public void loadChildNodes() {
// for (ImdiTreeObject currentChild : childArray) {
// GuiHelper.imdiLoader.getImdiObject(null, currentChild.getUrlString());
// System.out.println("loadChildNodes: " + this);
//waitTillLoaded();
// if (!getParentDomNode().imdiDataLoaded) {
// if this node has been loaded then do not load again
// to refresh the node and its children the node should be nulled and recreated
// autoLoadChildNodes = false;
// if (!this.isSession()) {
// //getImdiFieldLinks();
// for (Enumeration<String[]> childLinksEnum = childLinks.elements(); childLinksEnum.hasMoreElements();) {
// String currentChildPath = childLinksEnum.nextElement()[0];
// ImdiTreeObject currentImdi = GuiHelper.imdiLoader.getImdiObject(null, currentChildPath);
//// System.out.println("adding to list of child nodes 2: " + currentImdi);
// childrenHashtable.put(currentImdi.getUrlString(), currentImdi);
//// if (ImdiTreeObject.isStringImdi(currentChildPath)) {
//// currentImdi.loadImdiDom();
// START: this section uses the imdi.api to query the dom for available fields but it has been commented out in favour of the iterateChildNodes function
// System.err.println("Starting to load fields at: " + System.nanoTime());
// Long startTime = System.nanoTime();
// for (int rowNameCounter = 0; rowNameCounter < imdiFieldArray.length; rowNameCounter++) {
// if (imdiFieldArray[rowNameCounter][0] || imdiFieldArray[rowNameCounter][1]) {
// populateChildFields(imdiFieldViews.getMasterImdiFieldName(rowNameCounter), imdiFieldArray[rowNameCounter][1]);
// Long nextTime = System.nanoTime();
//// System.err.println("Starting to print fields at: " + System.nanoTime());
// if (nodDom != null) {
// iterateChildNodes(nodDom.getFirstChild(), "");
// System.err.println("Done loading fields at: " + System.nanoTime());
// Long lastTime = System.nanoTime();
// System.err.println("first method: " + (nextTime - startTime) + " second method: " + (lastTime - nextTime));
// System.err.println("second method took " + (lastTime - nextTime + 0.0) / (nextTime - startTime) * 100 + "% of the time used by the first");
// System.err.println("the imdi.api took " + ((nextTime - startTime) / lastTime - nextTime + 0.0) + " times longer");
// END: this section uses the imdi.api to query the dom for available fields but it has been commented out in favour of the iterateChildNodes function
// Vector<ImdiTreeObject> tempImdiVector = new Vector<ImdiTreeObject>();
// Enumeration nodesToAddEnumeration = childrenHashtable.elements();
// while (nodesToAddEnumeration.hasMoreElements()) {
// tempImdiVector.add((ImdiTreeObject) nodesToAddEnumeration.nextElement());
// ImdiTreeObject[] returnImdiArray = new ImdiTreeObject[tempImdiVector.size()];
// tempImdiVector.toArray(returnImdiArray);
// return returnImdiArray;
public boolean containsFieldValue(String fieldName, String searchValue) {
boolean findResult = false;
ImdiField[] currentFieldArray = this.fieldHashtable.get(fieldName);
if (currentFieldArray != null) {
for (ImdiField currentField : currentFieldArray) {
System.out.println("containsFieldValue: " + currentField.fieldValue + ":" + searchValue);
if (currentField.fieldValue.toLowerCase().contains(searchValue.toLowerCase())) {
return true;
}
}
}
System.out.println("result: " + findResult + ":" + this);
return findResult;
}
public boolean containsFieldValue(String searchValue) {
boolean findResult = false;
for (ImdiField[] currentFieldArray : (Collection<ImdiField[]>) this.fieldHashtable.values()) {
for (ImdiField currentField : currentFieldArray) {
System.out.println("containsFieldValue: " + currentField.fieldValue + ":" + searchValue);
if (currentField.fieldValue.toLowerCase().contains(searchValue.toLowerCase())) {
return true;
}
}
}
System.out.println("result: " + findResult + ":" + this);
return findResult;
}
// this is used to disable the node in the tree gui
public boolean getNodeEnabled() {
return nodeEnabled;
}
/**
* Tests if this node has child nodes even if they are not yet loaded.
* @return boolean
*/
public boolean canHaveChildren() {
return childArray.length > 0;
}
// /*
// * gets an array of
// */
// public int[] getRecursiveChildCount() {
//// debugOut("getChildCount: " + this.toString());
// int[] returnArray = new int[2];
// returnArray[0] = 0;
// returnArray[1] = 0;
// if (imdiDataLoaded) {
// returnArray[1] += 1; // count this node
// Enumeration nodesToAddEnumeration = childrenHashtable.elements();
// while (nodesToAddEnumeration.hasMoreElements()) {
// // count the child nodes
// int[] childCount = ((ImdiTreeObject) nodesToAddEnumeration.nextElement()).getRecursiveChildCount();
// returnArray[0] += childCount[0];
// returnArray[1] += childCount[1];
// } else {
// if (this.isImdi()) {
// returnArray[0] = 1;
// return returnArray;
// public void loadNextLevelOfChildren(long stopTime) {
//// debugOut("loadNextLevelOfChildren: " + this.toString() + ":" + (System.currentTimeMillis() - stopTime));
// if (System.currentTimeMillis() > stopTime) {
// return;
// if (this.isImdi()) {
// if (getParentDomNode().imdiDataLoaded) {
// Enumeration nodesToAddEnumeration = childrenHashtable.elements();
// while (nodesToAddEnumeration.hasMoreElements()) {
// // load one level of child nodes
// ((ImdiTreeObject) nodesToAddEnumeration.nextElement()).loadNextLevelOfChildren(stopTime);
// //((ImdiTreeObject) nodesToAddEnumeration.nextElement()).();
//// debugOut("listDiscardedOfAttributes: " + listDiscardedOfAttributes);
private void getAllFields(Vector<ImdiField[]> allFields) {
// returns all fields relevant to the parent node
// that includes all indinodechild fields but not from any other imdi file
System.out.println("getAllFields: " + this.toString());
allFields.addAll(fieldHashtable.values());
for (ImdiTreeObject currentChild : childArray) {
if (currentChild.isImdiChild()) {
currentChild.getAllFields(allFields);
}
}
}
// public void deleteFromParentDom(String[] childNodeXmlIdArray) {
//// System.out.println("deleteFromParentDom: " + childNodeXmlIdArray);
// if (this.isImdiChild()) {
// this.domParentImdi.deleteFromParentDom(new String[]{this.xmlNodeId});
// } else {
// // save the node if it need saving
// if (needsSaveToDisk) {
// saveChangesToCache(false);
//// System.out.println("attempting to remove nodes");
// try {
// OurURL inUrlLocal = new OurURL(nodeUri.toURL());
// Document nodDom;
// nodDom = api.loadIMDIDocument(inUrlLocal, false);
// for (String currentNodeXmlId : childNodeXmlIdArray) {
// IMDIElement target = new IMDIElement(null, currentNodeXmlId);
// api.removeIMDIElement(nodDom, target);
// api.writeDOM(nodDom, this.getFile(), false);
// reloadNode();
// } catch (Exception ex) {
// GuiHelper.linorgBugCatcher.logError(ex);
public void deleteFeilds(ImdiField[] targetImdiFields) {
ArrayList<String> domIdList = new ArrayList<String>();
for (ImdiField currentField : targetImdiFields) {
domIdList.add(currentField.fieldID);
}
deleteFromDomViaId(domIdList.toArray(new String[]{}));
}
// this is used to delete an IMDI node from a corpus branch
public void deleteCorpusLink(ImdiTreeObject[] targetImdiNodes) {
// retrieve the node id for the link
ArrayList<String> fieldIdList = new ArrayList<String>();
String linkIdString = null;
for (String[] currentLinkPair : childLinks) {
String currentChildPath = currentLinkPair[0];
// System.out.println("currentChildPath: " + currentChildPath);
for (ImdiTreeObject currentImdiNode : targetImdiNodes) {
// System.out.println("targetImdiNode : " + currentImdiNode.getUrlString());
if (currentChildPath.equals(currentImdiNode.getUrlString())) {
// System.out.println("currentLinkPair[1]: " + currentLinkPair[1]);
linkIdString = currentLinkPair[1];
fieldIdList.add(linkIdString);
}
}
}
if (fieldIdList.size() > 0) {
deleteFromDomViaId(fieldIdList.toArray(new String[]{}));
}
for (ImdiTreeObject currentImdiNode : targetImdiNodes) {
if (currentImdiNode.isCatalogue()) {
// the catalogue implemention in the imdi api requires special treatment and so must be done in this way not via deleteFromDomViaId
// do this last because it might change the domid ordering
deleteCatalogueLink();
}
}
//loadChildNodes(); // this must not be done here
clearIcon(); // this must be cleared so that the leaf / branch flag gets set
}
public void deleteCatalogueLink() {
// the catalogue implemention in the imdi api requires special treatment and so must be done in this way not via deleteFromDomViaId
Document nodDom;
try {
if (needsSaveToDisk) {
saveChangesToCache(false);
}
synchronized (domLockObject) {
OurURL inUrlLocal = new OurURL(nodeUri.toURL());
nodDom = api.loadIMDIDocument(inUrlLocal, false);
if (nodDom == null) {
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error loading via the IMDI API", "Remove Catalogue");
} else {
api.createIMDILink(nodDom, null, "", "", WSNodeType.CATALOGUE, "");
bumpHistory();
api.writeDOM(nodDom, this.getFile(), false);
reloadNode();
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
// this is used to delete imdi child nodes and to delete individual fields
public void deleteFromDomViaId(String[] domIdArray) {
// TODO: There is an issue when deleting child nodes that the remaining nodes xml path (x) will be incorrect as will the xmlnode id hence the node in a table may be incorrect after a delete
Document nodDom;
try {
if (needsSaveToDisk) {
saveChangesToCache(false);
}
synchronized (domLockObject) {
OurURL inUrlLocal = new OurURL(nodeUri.toURL());
nodDom = api.loadIMDIDocument(inUrlLocal, false);
if (nodDom == null) {
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error removing via the IMDI API", "Remove");
} else {
for (String currentImdiDomId : domIdArray) {
IMDIElement target = new IMDIElement(null, currentImdiDomId);
api.removeIMDIElement(nodDom, target);
}
bumpHistory();
api.writeDOM(nodDom, this.getFile(), false);
reloadNode();
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
public boolean hasCatalogue() {
for (ImdiTreeObject childNode : childArray) {
// String currentChildPath = currentLinkPair[0];
// ImdiTreeObject childNode = ImdiLoader.getSingleInstance().getImdiObject(null, currentChildPath);
//childNode.waitTillLoaded(); // if the child nodes have not been loaded this will fail so we must wait here
if (childNode.isCatalogue()) {
return true;
}
}
return false;
}
public boolean addCorpusLink(ImdiTreeObject targetImdiNode) {
boolean linkAlreadyExists = false;
if (targetImdiNode.isCatalogue()) {
if (this.hasCatalogue()) {
// LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Only one catalogue can be added", null);
// prevent adding a second catalogue file
return false;
}
}
for (String[] currentLinkPair : childLinks) {
String currentChildPath = currentLinkPair[0];
if (!targetImdiNode.waitTillLoaded()) { // we must wait here before we can tell if it is a catalogue or not
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error adding node, could not wait for file to load", "Loading Error");
return false;
}
if (currentChildPath.equals(targetImdiNode.getUrlString())) {
linkAlreadyExists = true;
}
}
if (targetImdiNode.getUrlString().equals(this.getUrlString())) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Cannot link or move a node into itself", null);
return false;
}
if (linkAlreadyExists) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue(targetImdiNode + " already exists in " + this + " and will not be added again", null);
return false;
} else {
// if link is not already there
// if needs saving then save now while you can
// TODO: it would be nice to warn the user about this, but its a corpus node so maybe it is not important
if (needsSaveToDisk) {
saveChangesToCache(true);
}
Document nodDom;
try {
synchronized (domLockObject) {
OurURL inUrlLocal = new OurURL(nodeUri.toURL());
nodDom = api.loadIMDIDocument(inUrlLocal, false);
if (nodDom == null) {
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error reading via the IMDI API", "Add Link");
return false;
} else {
int nodeType = WSNodeType.CORPUS;
if (targetImdiNode.isSession()) {
nodeType = WSNodeType.SESSION; // url: IMDI location, for link normalization. urlToLink: target URL
// linkName: for CorpusLink name / for InfoFile description
// linkType: WSNodeType value spec: where to put the link in the IMDI,
// NOTE: spec should only be used for linkType InfoFile...
// public IMDILink createIMDILink(Document doc, OurURL url, String urlToLink, String linkName, int linkType, String spec);
} else if (targetImdiNode.isCatalogue()) {
nodeType = WSNodeType.CATALOGUE;
}
// TODO: at this point due to the api we cannot get the id of the newly created link, so we will probably have to unload this object and reload the dom
System.out.println("createIMDILink: " + targetImdiNode.getUrlString());
api.createIMDILink(nodDom, inUrlLocal, targetImdiNode.getUrlString(), /*targetImdiNode.toString()*/ "", nodeType, "");
bumpHistory();
api.writeDOM(nodDom, this.getFile(), false);
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
// System.out.println("Exception: " + ex.getMessage());
}
//loadChildNodes(); // this must not be done here
// clearIcon(); // this must be cleared so that the leaf / branch flag gets set
return true;
}
}
public void updateImdiFileNodeIds() {
if (getParentDomNode() != this) {
getParentDomNode().updateImdiFileNodeIds();
} else {
//load then save the dom via the api to make sure there are id fields to each node then reload this imdi object
System.out.println("updateImdiFileNodeIds");
try {
synchronized (domLockObject) {
// System.out.println("removing NodeIds");
OurURL inUrlLocal = new OurURL(nodeUri.toURL());
Document nodDom = api.loadIMDIDocument(inUrlLocal, false);
if (nodDom == null) {
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error reading via the IMDI API", "Update IMDI");
return;
}
api.writeDOM(nodDom, this.getFile(), true);
// System.out.println("adding NodeIds");
Document nodDomSecondLoad = api.loadIMDIDocument(inUrlLocal, false, null);
if (nodDom == null) {
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error reading via the IMDI API", "Update IMDI");
return;
}
api.writeDOM(nodDomSecondLoad, this.getFile(), false);
}
// System.out.println("reloading updateNodeIds");
// reloadImdiNode(false);
loadImdiDom();
} catch (Exception mue) {
GuiHelper.linorgBugCatcher.logError(mue);
System.out.println("Invalid input URL: " + mue);
}
}
}
/**
* Exports the imdi file for use in other applications.
* The exported file has the id attributes removed via the api.
* @param targetFile
*/
public void exportImdiFile(File exportFile) {
try {
synchronized (domLockObject) {
Document nodDom;
nodDom = api.loadIMDIDocument(new OurURL(nodeUri.toURL()), false);
if (nodDom == null) {
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error reading via the IMDI API", "Export IMDI");
} else {
api.writeDOM(nodDom, exportFile, true);
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
public void pasteIntoNode() {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transfer = clipboard.getContents(null);
try {
String clipBoardString = "";
Object clipBoardData = transfer.getTransferData(DataFlavor.stringFlavor);
if (clipBoardData != null) {//TODO: check that this is not null first but let it pass on null so that the no data to paste messages get sent to the user
clipBoardString = clipBoardData.toString();
System.out.println("clipBoardString: " + clipBoardString);
if (this.isCorpus()) {
if (ImdiTreeObject.isStringImdi(clipBoardString) || ImdiTreeObject.isStringImdiChild(clipBoardString)) {
ImdiTreeObject clipboardNode = ImdiLoader.getSingleInstance().getImdiObject(null, conformStringToUrl(clipBoardString));
if (LinorgSessionStorage.getSingleInstance().pathIsInsideCache(clipboardNode.getFile())) {
if (!(ImdiTreeObject.isStringImdiChild(clipBoardString) && (!this.isSession() && !this.isImdiChild()))) {
if (this.getFile().exists()) {
// this must use merge like favoirite to prevent instances end endless loops in corpus branches
this.requestAddNode("copy of " + clipboardNode, clipboardNode);
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The target node's file does not exist", null);
}
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Cannot paste session subnodes into a corpus", null);
}
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The target file is not in the cache", null);
}
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Pasted string is not and IMDI file", null);
}
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Only corpus branches can be pasted into at this stage", null);
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
public boolean requestAddNode(String nodeTypeDisplayName, ImdiTreeObject addableImdiNode) {
// TODO: move the arbil link on the tools page as Peter requested
boolean returnValue = true;
ImdiTreeObject[] sourceImdiNodeArray;
if (addableImdiNode.isMetaNode()) {
sourceImdiNodeArray = addableImdiNode.getChildArray();
} else {
sourceImdiNodeArray = new ImdiTreeObject[]{addableImdiNode};
}
for (ImdiTreeObject currentImdiNode : sourceImdiNodeArray) {
String nodeType;
String favouriteUrlString = null;
String resourceUrl = null;
String mimeType = null;
if (currentImdiNode.isArchivableFile() && !currentImdiNode.isImdi()) {
nodeType = ImdiSchema.getSingleInstance().getNodeTypeFromMimeType(currentImdiNode.mpiMimeType);
resourceUrl = currentImdiNode.getUrlString();
mimeType = currentImdiNode.mpiMimeType;
nodeTypeDisplayName = "Resource";
} else {
nodeType = LinorgFavourites.getSingleInstance().getNodeType(currentImdiNode, this);
favouriteUrlString = currentImdiNode.getUrlString();
}
if (nodeType == null) {
returnValue = false;
}
String targetXmlPath = nodeUri.getFragment();
if (nodeType == null) { // targetXmlPath hass been added at this point to preserve the sub node (N) which otherwise had been lost for the (x) and this is required to add to a sub node correctly
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Cannot add this type of node", null);
} else {
// if (this.isImdiChild()) {
// System.out.println("requestAddNodeChild: " + this.getUrlString());
// this.domParentImdi.requestAddNode(nodeType, this.nodeUrl.getRef(), nodeTypeDisplayName, favouriteUrlString, resourceUrl, mimeType);
// } else {
System.out.println("requestAddNode: " + nodeType + " : " + nodeTypeDisplayName + " : " + favouriteUrlString + " : " + resourceUrl);
this.getParentDomNode().addQueue.add(new String[]{nodeType, targetXmlPath, nodeTypeDisplayName, favouriteUrlString, resourceUrl, mimeType});
ImdiLoader.getSingleInstance().requestReload(this);
}
}
return returnValue;
}
public void requestAddNode(String nodeType, String nodeTypeDisplayName) {
System.out.println("requestAddNode: " + nodeType + " : " + nodeTypeDisplayName);
this.getParentDomNode().addQueue.add(new String[]{nodeType, null, nodeTypeDisplayName, null, null, null});
ImdiLoader.getSingleInstance().requestReload(this);
}
/**
* Saves the current changes from memory into a new imdi file on disk.
* Previous imdi files are renamed and kept as a history.
* the caller is responsible for reloading the node if that is required
*/
public void saveChangesToCache(boolean updateUI) {
if (this.isImdiChild()) {
getParentDomNode().saveChangesToCache(updateUI);
return;
}
System.out.println("saveChangesToCache");
LinorgJournal.getSingleInstance().clearFieldChangeHistory();
Document nodDom;
OurURL inUrlLocal = null;
if (!this.isLocal() /*nodeUri.getScheme().toLowerCase().startsWith("http") */) {
System.out.println("should not try to save remote files");
//this.setImdiNeedsSaveToDisk(null, updateUI);
return;
}
System.out.println("tempUrlString: " + this.getFile());
try {
// if (!this.getFile().exists()) {
// createFileInCache();
synchronized (domLockObject) {
inUrlLocal = new OurURL(nodeUri.toURL());
nodDom = api.loadIMDIDocument(inUrlLocal, false);
if (nodDom == null) {
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error reading via the IMDI API", "Save IMDI");
} else {
System.out.println("writeDOM");
// make the required changes to the dom
// TODO: make the changes to the dom before saving
// refer to: /data1/repos/trunk/src/java/mpi/imdi/api/TestDom.java
Vector<ImdiField[]> allFields = new Vector<ImdiField[]>();
getAllFields(allFields);
Vector<ImdiField> addedFields = new Vector<ImdiField>();
for (Enumeration<ImdiField[]> fieldsEnum = allFields.elements(); fieldsEnum.hasMoreElements();) {
{
ImdiField[] currentFieldArray = fieldsEnum.nextElement();
for (int fieldCounter = 0; fieldCounter < currentFieldArray.length; fieldCounter++) {
ImdiField currentField = currentFieldArray[fieldCounter];
if (currentField.fieldNeedsSaveToDisk()) {
if (currentField.fieldID == null) {
addedFields.add(currentField);
} else {
System.out.println("trying to save: " + currentField.fieldID + " : " + currentField.getFieldValue());
String keyName = currentField.getKeyName();
if (keyName != null) {
api.setKeyValuePair(nodDom, currentField.fieldID, keyName, currentField.getFieldValue());
// changedElement = new IMDIElement(null, currentField.fieldID);
// changedElement.setSpec("x:Name");
// changedElement.setValue(currentField.getFieldValue());
// IMDIElement ies = api.setIMDIElement(nodDom, changedElement);
} else {
IMDIElement changedElement;
changedElement = new IMDIElement(null, currentField.fieldID);
changedElement.setValue(currentField.getFieldValue());
IMDIElement ie = api.setIMDIElement(nodDom, changedElement);
System.out.println("ie spec: " + ie.getSpec());
System.out.println("ie.id: " + ie.getDomId());
System.out.println("ie.spec: " + ie.getSpec());
}
// currentField.fieldNeedsSaveToDisk = false;
// GuiHelper.linorgJournal.saveJournalEntry(currentField.parentImdi.getUrlString(), currentField.xmlPath, currentField.getFieldValue(), "", "save");
String fieldLanguageId = currentField.getLanguageId();
if (fieldLanguageId != null) {
IMDILink changedLink;
changedLink = api.getIMDILink(nodDom, null, currentField.fieldID);
System.out.println("trying to save language id: " + fieldLanguageId);
changedLink.setLanguageId(fieldLanguageId);
api.changeIMDILink(nodDom, null, changedLink);
LinorgJournal.getSingleInstance().saveJournalEntry(currentField.parentImdi.getUrlString(), currentField.xmlPath + ":LanguageId", fieldLanguageId, "", "save");
}
// String elementNameForApi = currentField.fieldID;
// if (currentField.fieldID == null) {
// elementNameForApi = apiPath;
// GuiHelper.linorgBugCatcher.logError(currentField.getFullXmlPath(), new Exception("No domid for field when trying to save"));
// api.setKeyValuePair(nodDom, apiPath, currentField.getKeyName(), currentField.getFieldValue());
//// TODO: keys must be added here and in the favourites copy
// if (currentField.fieldID == null) {
// GuiHelper.linorgBugCatcher.logError(currentField.getFullXmlPath(), new Exception("No domid for field when trying to save"));
// // if the field does not have an id attribite then it must now be created in the imdi file via the imdi api
// // Mangle the path to suit the imdi api
// System.out.println("trying to add: " + apiPath + " : " + currentField.getFieldValue());
// changedElement = api.addIMDIElement(nodDom, apiPath);
// } else {
// // set value
// System.out.println("changedElement: " + changedElement.getSpec());
// api.setKeyValuePair(nodDom, currentField.fieldID, keyName, currentField.getFieldValue());
//// changedElement.
//// mpi.imdi.api.IMDIXMLFormat imdiXmlFormat = new mpi.imdi.api.IMDIXMLFormat();
////// generateSpecFromNode(Node node)
//// mpi.imdi.api.IMDIXMLForma
// System.out.println("Warning: cannot save key name values");
// // there appears to be no other way to do this via the api
// //changedElement.
//// String elementSpec = changedElement.getSpec();
//// System.out.println("elementSpec: " + elementSpec);
//// elementSpec = elementSpec + ".Name";
//// System.out.println("elementSpec: " + elementSpec);
//// IMDIElement keyNameElement = api.getIMDIElement(nodDom, elementSpec);
//// System.out.println("keyNameElement: " + keyNameElement);
//// keyNameElement.setValue(keyName);
}
}
}
}
}
for (Enumeration<ImdiField> fieldsEnum = addedFields.elements(); fieldsEnum.hasMoreElements();) {
ImdiField currentField = fieldsEnum.nextElement();
}
bumpHistory();
api.writeDOM(nodDom, this.getFile(), true); // remove the id attributes
nodDom = api.loadIMDIDocument(inUrlLocal, false);
if (nodDom == null) {
GuiHelper.linorgBugCatcher.logError(new Exception(ImdiTreeObject.api.getMessage()));
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error reading via the IMDI API after save", "Update IMDI");
} else {
api.writeDOM(nodDom, this.getFile(), false); // add the id attributes in the correct order
}
// update the icon to indicate the change
// setImdiNeedsSaveToDisk(false, updateUI);
}
}
} catch (Exception mue) {
GuiHelper.linorgBugCatcher.logError(mue);
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error saving via the IMDI API", "Save Error");
}
// clearIcon(); this is called by setImdiNeedsSaveToDisk
}
/**
* Saves the node dom into the local cache.
* Before this is called it is recommended to confirm that the destinationDirectory path already exist and is correct, otherwise unintended directories maybe created
* @param nodDom The dom for this node that will be saved.
* @return A string path of the saved location.
*/
// public String saveNodeToCache(Document nodDom) {
// String cacheLocation = null;
// System.out.println("saveBranchToLocal: " + this.toString());
// if (this.isImdi() && !this.isImdiChild()) {
// if (nodDom != null) {
// //System.out.println("saveBranchToLocal: " + this.getUrl());
// //System.out.println("saveBranchToLocal: " + this.nodDom.);
// String destinationPath = GuiHelper.linorgSessionStorage.getSaveLocation(this.getUrlString());
//// debugOut("destinationPath: " + destinationPath);
// File tempFile = new File(destinationPath);
// // only save the file if it does not exist, otherwise local changes would be lost and it would be pointless anyway
// if (tempFile.exists()) {
// System.out.println("this imdi is already in the cache");
// } else {
// // this function of the imdi.api will modify the imdi file as it saves it "(will be normalized and possibly de-domId-ed)"
// // this will make it dificult to determin if changes are from this function of by the user deliberatly making a chage
// api.writeDOM(nodDom, new File(destinationPath), false);
// // create hash index with server url but basedon the saved file
// // note that if the imdi.api has changed this file then it will not be detected
// // TODO: it will be best to change this to use the server api get mb5 sum when it is written
// // TODO: there needs to be some mechanism to check for changes on the server and update the local copy
// //getHash(tempFile, this.getUrl());
// System.out.println("imdi should be saved in cache now");
// // no point iterating child nodes which have not been loaded, it is better to do the outside this function
//// Enumeration nodesToAddEnumeration = childrenHashtable.elements();
//// while (nodesToAddEnumeration.hasMoreElements()) {
////// ((ImdiTreeObject) nodesToAddEnumeration.nextElement()).saveBranchToLocal(destinationDirectory);
// cacheLocation = destinationPath;
// return cacheLocation;
public void addField(ImdiField fieldToAdd) {
// System.addField:out.println("addField: " + this.getUrlString() + " : " + fieldToAdd.xmlPath + " : " + fieldToAdd.getFieldValue());
ImdiField[] currentFieldsArray = fieldHashtable.get(fieldToAdd.getTranslateFieldName());
if (currentFieldsArray == null) {
currentFieldsArray = new ImdiField[]{fieldToAdd};
} else {
// System.out.println("appendingField: " + fieldToAdd);
ImdiField[] appendedFieldsArray = new ImdiField[currentFieldsArray.length + 1];
System.arraycopy(currentFieldsArray, 0, appendedFieldsArray, 0, currentFieldsArray.length);
appendedFieldsArray[appendedFieldsArray.length - 1] = fieldToAdd;
currentFieldsArray = appendedFieldsArray;
// for (ImdiField tempField : currentFieldsArray) {
// System.out.println("appended fields: " + tempField);
}
fieldHashtable.put(fieldToAdd.getTranslateFieldName(), currentFieldsArray);
if (fieldToAdd.xmlPath.endsWith(".ResourceLink") && fieldToAdd.parentImdi.isImdiChild()/* && fieldToAdd.parentImdi.getUrlString().contains("MediaFile")*/) {
resourceUrlField = fieldToAdd;
MimeHashQueue.getSingleInstance().addToQueue(this);
}
}
/**
* Adds a field to the imdi node and creates imdi child nodes if required.
* @param fieldToAdd The field to be added.
* @param childLevel For internal use and should be zero. Used to track the distance in imdi child nodes from the imdi node.
* @param addedImdiNodes Returns with all the imdi child nodes that have been added during the process.
* @param useCache If true the the imdi file will be saved to the cache.
*/
// private void addField(ImdiField fieldToAdd, int childLevel, Vector addedImdiNodes) {
// // TODO: modify this so that each child node gets the full filename and full xml path
//// if (isImdi()) {
//// if (fieldLabel.startsWith("Session.")) {
//// fieldLabel = fieldLabel.substring(8);
//// } else if (fieldLabel.startsWith("Corpus.")) {
//// fieldLabel = fieldLabel.substring(7);
// //fieldUrl.substring(firstSeparator + 1)
// // TODO: move this and we write to imdischema
// int nextChildLevel = fieldToAdd.translatedPath.replace(")", "(").indexOf("(", childLevel);
// debugOut("fieldLabel: " + fieldToAdd.translatedPath + " cellValue: " + fieldToAdd.fieldValue + " childLevel: " + childLevel + " nextChildLevel: " + nextChildLevel);
// if (nextChildLevel == -1) {
// // add the label to this level node
//// if (fieldLabel == null) fieldLabel = "oops null";
//// if (fieldValue == null) fieldValue = "oops null";
// String childsLabel = fieldToAdd.translatedPath.substring(childLevel);
// fieldHashtable.put(childsLabel, fieldToAdd);
//// if (childsLabel.endsWith(".Date")) {
//// DateFormat df = new SimpleDateFormat("yyyy-MM-DD");
//// try {
//// nodeDate = df.parse(fieldToAdd.fieldValue);
//// if (minNodeDate == null) {
//// minNodeDate = nodeDate;
//// maxNodeDate = nodeDate;
//// if (nodeDate.before(minNodeDate)) {
//// minNodeDate = nodeDate;
//// if (nodeDate.after(maxNodeDate)) {
//// maxNodeDate = nodeDate;
//// } catch (Exception ex) {
//// System.err.println(ex.getMessage());
// // if the node contains a ResourceLink then save the location in resourceUrlString and create a hash for the file
// if (childsLabel.equals(ImdiSchema.imdiPathSeparator + "ResourceLink")) {
//// // resolve the relative location of the file
//// File resourceFile = new File(this.getFile().getParent(), fieldToAdd.fieldValue);
//// resourceUrlString = resourceFile.getCanonicalPath();
// resourceUrlString = fieldToAdd.fieldValue;
//// if (useCache) {
//// GuiHelper.linorgSessionStorage.updateCache(getFullResourcePath());
// mimeHashQueue.addToQueue(this);
// } else {
// // pass the label to the child nodes
// String childsName = fieldToAdd.translatedPath.substring(childLevel, nextChildLevel);
// //String parentName = fieldLabel.substring(0, firstSeparator);
// debugOut("childsName: " + childsName);
// if (!childrenHashtable.containsKey(childsName)) {
// ImdiTreeObject tempImdiTreeObject = GuiHelper.imdiLoader.getImdiObject(childsName, this.getUrlString() + "#" + fieldToAdd.xmlPath);
// if (addedImdiNodes != null) {
// addedImdiNodes.add(tempImdiTreeObject);
// tempImdiTreeObject.imdiDataLoaded = true;
//// System.out.println("adding to list of child nodes 3: " + tempImdiTreeObject);
// childrenHashtable.put(childsName, tempImdiTreeObject);
// ((ImdiTreeObject) childrenHashtable.get(childsName)).addField(fieldToAdd, nextChildLevel + 1, addedImdiNodes);
/**
* Gets the fields in this node, this does not include any imdi child fields.
* To get all fields relevant the imdi file use "getAllFields()" which includes imdi child fields.
* @return A hashtable of the fields
*/
public Hashtable<String, ImdiField[]> getFields() {
// store the Hastable for next call
// if hashtable is null then load from imdi
return fieldHashtable;
}
/**
* Compares this node to another based on its type and string value.
* @return The string comparison result.
*/
public int compareTo(Object o) throws ClassCastException {
ImdiTreeNodeSorter imdiTreeNodeSorter = new ImdiTreeNodeSorter();
return imdiTreeNodeSorter.compare(this, o);
}
public synchronized boolean waitTillLoaded() {
if (isLoading()) {
try {
getParentDomNode().wait(1000);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
return false;
}
}
return true;
}
public void updateLoadingState(int countChange) {
if (this != getParentDomNode()) {
getParentDomNode().updateLoadingState(countChange);
} else {
synchronized (loadingCountLock) {
isLoadingCount += countChange;
}
System.out.println("isLoadingCount: " + isLoadingCount);
if (!isLoading()) {
// this.notifyAll();
clearChildIcons();
clearIcon();
}
}
}
public boolean isLoading() {
return getParentDomNode().isLoadingCount > 0;
}
@Override
public String toString() {
if (isLoading()) {
// if (lastNodeText.length() > 0) {
// return lastNodeText;
// } else {asdasdasd
//// if (nodeText != null && nodeText.length() > 0) {
return lastNodeText;
}
// String nameText = "";
// TODO: move this to a list loaded from the templates or similar
String[] preferredNameFields = {"Name", "Id"};
for (String currentPreferredName : preferredNameFields) {
ImdiField[] currentFieldArray = fieldHashtable.get(currentPreferredName);
if (currentFieldArray != null) {
for (ImdiField currentField : currentFieldArray) {
if (currentField != null) {
nodeText = currentField.toString();
break;
}
}
}
}
if (hasResource()) {
String resourcePathString = getFullResourceURI().toString();
int lastIndex = resourcePathString.lastIndexOf("/");
// if (lastIndex)
nodeText = resourcePathString.substring(lastIndex + 1);
}
// nodeTextChanged = lastNodeText.equals(nodeText + nameText);
if (nodeText != null) {
if (isImdi()) {
File nodeFile = this.getFile();
if (nodeFile != null && !isHeadRevision()) {
nodeText = nodeText + " (rev:" + getHistoryLabelStringForFile(nodeFile) + ")";
}
}
lastNodeText = nodeText;
}
if (lastNodeText.length() == 0) {
lastNodeText = " ";
}
return lastNodeText;
}
/**
* Tests if there is file associated with this node and if it is an archivable type.
* The file could be either a resource file (getResource) or a loose file (getUrlString).
* @return boolean
*/
public boolean isArchivableFile() {
return mpiMimeType != null;
}
/**
* Tests if a resource file (local or remote) is associated with this node.
* @return boolean
*/
public boolean hasResource() {
return resourceUrlField != null;
}
/**
* Tests if a local resource file is associated with this node.
* @return boolean
*/
public boolean hasLocalResource() {
if (!hasResource()) {
return false;
}
if (resourceUrlField.fieldValue.toLowerCase().startsWith("http")) {
return false;
}
if (!this.isLocal()) {
return false;
} else {
return true;
}
}
public boolean resourceFileNotFound() {
if (hasLocalResource()) {
if (resourceUrlField.fieldValue.length() == 0) {
return true;
}
try {
return !(new File(this.getFullResourceURI())).exists();
} catch (Exception e) {
return true;
}
} else {
return false;
}
}
/**
* Gets the ULR string of the resource file if it is available.
* @return a URL string of the resource file
*/
private String getResource() {
return resourceUrlField.fieldValue;
}
public boolean hasHistory() {
if (!this.isLocal()) {
// only local files can have a history
return false;
}
return !this.isImdiChild() && new File(this.getFile().getAbsolutePath() + ".0").exists();
}
private String getHistoryLabelStringForFile(File historyFile) {
Date mtime = new Date(historyFile.lastModified());
String mTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mtime);
return mTimeString;
}
private boolean isHeadRevision() {
return !(new File(this.getFile().getAbsolutePath() + ".x").exists());
}
public String[][] getHistoryList() {
Vector<String[]> historyVector = new Vector<String[]>();
int versionCounter = 0;
File currentHistoryFile;
// historyVector.add(new String[]{"Current", ""});
if (!isHeadRevision()) {
historyVector.add(new String[]{"Last Save", ".x"});
}
do {
currentHistoryFile = new File(this.getFile().getAbsolutePath() + "." + versionCounter);
if (currentHistoryFile.exists()) {
String mTimeString = getHistoryLabelStringForFile(currentHistoryFile);
historyVector.add(new String[]{mTimeString, "." + versionCounter});
}
versionCounter++;
} while (currentHistoryFile.exists());
return historyVector.toArray(new String[][]{{}});
}
public boolean resurrectHistory(String historyVersion) {
try {
if (historyVersion.equals(".x")) {
this.getFile().delete();
new File(this.getFile().getAbsolutePath() + ".x").renameTo(this.getFile());
} else {
LinorgWindowManager.getSingleInstance().offerUserToSaveChanges();
if (!new File(this.getFile().getAbsolutePath() + ".x").exists()) {
this.getFile().renameTo(new File(this.getFile().getAbsolutePath() + ".x"));
} else {
this.getFile().delete();
}
InputStream hisoryFile = new FileInputStream(new File(this.getFile().getAbsolutePath() + historyVersion));
OutputStream activeVersionFile = new FileOutputStream(this.getFile(), true);
byte[] copyBuffer = new byte[1024];
int len;
while ((len = hisoryFile.read(copyBuffer)) > 0) {
activeVersionFile.write(copyBuffer, 0, len);
}
hisoryFile.close();
activeVersionFile.close();
}
ImdiLoader.getSingleInstance().requestReload(getParentDomNode());
} catch (Exception e) {
// user canceled the save action
// todo: alert user that nothing was done
return false;
}
return true;
}
/*
* Increment the history file so that a new current file can be saved without overwritting the old
*/
public void bumpHistory() {
// update the files version number
//TODO: the template add does not create a new history file
int versionCounter = 0;
File headVersion = this.getFile();
// if the .x file (the last head) exist then replace the current with it
if (new File(this.getFile().getAbsolutePath() + ".x").exists()) {
versionCounter++;
headVersion = new File(this.getFile().getAbsolutePath() + ".x");
}
while (new File(this.getFile().getAbsolutePath() + "." + versionCounter).exists()) {
versionCounter++;
}
while (versionCounter >= 0) {
File lastFile = new File(this.getFile().getAbsolutePath() + "." + versionCounter);
versionCounter
File nextFile = new File(this.getFile().getAbsolutePath() + "." + versionCounter);
if (versionCounter >= 0) {
nextFile.renameTo(lastFile);
System.out.println("renaming: " + nextFile + " : " + lastFile);
} else {
headVersion.renameTo(lastFile);
System.out.println("renaming: " + headVersion + " : " + lastFile);
}
}
}
/**
* Resolves the full path to a resource file if it exists.
* @return The path to remote resource if it exists.
*/
public URI getFullResourceURI() {
try {
String targetUriString = resourceUrlField.fieldValue;
URI targetUri = new URI(null, targetUriString, null);
// System.out.println("nodeUri: " + nodeUri);
URI resourceUri = nodeUri.resolve(targetUri);
// System.out.println("targetUriString: " + targetUriString);
// System.out.println("targetUri: " + targetUri);
// System.out.println("resourceUri: " + resourceUri);
if (!targetUri.equals(resourceUri)) {
// maintain the UNC path
boolean isUncPath = nodeUri.toString().toLowerCase().startsWith("file:
if (isUncPath) {
try {
resourceUri = new URI("file:////" + resourceUri.toString().substring("file:/".length()));
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
}
return resourceUri;
} catch (Exception urise) {
GuiHelper.linorgBugCatcher.logError(urise);
System.out.println("URISyntaxException: " + urise.getMessage());
return null;
}
}
/**
* Gets the ULR string provided when the node was created.
* @return a URL string of the IMDI
*/
public String getUrlString() {
// TODO: update the uses of this to use the uri not a string
return nodeUri.toString();
}
/**
* Gets the ImdiTreeObject parent of an imdi child node.
* The returned node will be able to reload/save the dom for this node.
* Only relevant for imdi child nodes.
* @return ImdiTreeObject
*/
public ImdiTreeObject getParentDomNode() {
// System.out.println("nodeUri: " + nodeUri);
if (domParentImdi == null) {
if (nodeUri.getFragment() != null) {
try {
//domParentImdi = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(nodeUri.getScheme(), nodeUri.getUserInfo(), nodeUri.getHost(), nodeUri.getPort(), nodeUri.getPath(), nodeUri.getQuery(), null /* fragment removed */));
// the uri is created via the uri(string) constructor to prevent re-url-encoding the url
domParentImdi = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(nodeUri.toString().split("#")[0] /* fragment removed */));
// System.out.println("nodeUri: " + nodeUri);
} catch (URISyntaxException ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
} else {
domParentImdi = this;
}
}
return domParentImdi;
}
public boolean isDirectory() {
return isDirectory;
}
public boolean isImdi() {
if (nodeUri != null /* && nodDom != null*/) {
if (isImdiChild()) {
return true;
} else {
return ImdiTreeObject.isStringImdi(nodeUri.getPath());
}
}
return false;
}
public boolean isImdiChild() {
return ImdiTreeObject.isStringImdiChild(this.getUrlString());
}
public boolean isSession() {
// test if this node is a session
ImdiField[] nameFields = fieldHashtable.get("Name");
if (nameFields != null) {
return nameFields[0].xmlPath.equals(ImdiSchema.imdiPathSeparator + "METATRANSCRIPT" + ImdiSchema.imdiPathSeparator + "Session" + ImdiSchema.imdiPathSeparator + "Name");
}
return false;
}
/**
* Tests if this node is a meta node that contains no fields and only child nodes, such as the Languages, Actors, MediaFiles nodes etc..
* @return boolean
*/
public boolean isMetaNode() {
return this.getFields().size() == 0;
}
public boolean isCatalogue() {
// test if this node is a catalogue
ImdiField[] nameFields = fieldHashtable.get("Name");
if (nameFields != null) {
return nameFields[0].xmlPath.equals(ImdiSchema.imdiPathSeparator + "METATRANSCRIPT" + ImdiSchema.imdiPathSeparator + "Catalogue" + ImdiSchema.imdiPathSeparator + "Name");
}
return false;
}
public boolean isCorpus() {
// test if this node is a session
ImdiField[] nameFields = fieldHashtable.get("Name");
if (nameFields != null) {
return nameFields[0].xmlPath.equals(ImdiSchema.imdiPathSeparator + "METATRANSCRIPT" + ImdiSchema.imdiPathSeparator + "Corpus" + ImdiSchema.imdiPathSeparator + "Name");
}
return false;
}
public boolean isLocal() {
if (nodeUri != null) {
return ImdiTreeObject.isStringLocal(nodeUri.getScheme());
} else {
return false;
}
}
/**
* Returns the URI object for this node.
* @return A URI that this node represents.
*/
public URI getURI() {
try {
return nodeUri; // new URI(nodeUri.toString()); // a copy of
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
return null;
}
}
public File getFile() {
// System.out.println("getFile: " + nodeUri.toString());
if (nodeUri.getScheme().toLowerCase().equals("file")) {
try {
return new File(new URI(nodeUri.toString().split("#")[0] /* fragment removed */));
} catch (Exception urise) {
// System.err.println("nodeUri: " + nodeUri);
GuiHelper.linorgBugCatcher.logError(urise);
}
}
return null;
}
public String getParentDirectory() {
String parentPath = this.getUrlString().substring(0, this.getUrlString().lastIndexOf("/")) + "/"; // this is a url so don't use the path separator
return parentPath;
}
public void registerContainer(Object containerToAdd) {
// System.out.println("registerContainer: " + containerToAdd + " : " + this);
if (!getParentDomNode().imdiDataLoaded && !isLoading()) { // TODO: this is probably not the best way to do this and might be better in a manager class
ImdiLoader.getSingleInstance().requestReload(getParentDomNode());
}
if (containerToAdd != null) {
// todo: handle null here more agressively
containersOfThisNode.add(containerToAdd);
}
}
public Object[] getRegisteredContainers() {
if (containersOfThisNode != null && containersOfThisNode.size() > 0) {
return containersOfThisNode.toArray();
} else {
return new Object[]{};
}
}
/**
* Removes a UI containers from the list of containers interested in this node.
* @param containerToRemove The container to be removed from the list.
*/
public void removeContainer(Object containerToRemove) {
// TODO: make sure that containers are removed when a node is removed from the tree, otherwise memory will not get freed
// System.out.println("de registerContainer: " + containerToRemove);
containersOfThisNode.remove(containerToRemove);
}
/**
* Clears the icon for all the imdi child nodes of this node.
* Used when loading a session dom.
*/
public void clearChildIcons() {
for (ImdiTreeObject currentChild : childArray) {
currentChild.clearChildIcons();
currentChild.clearIcon();
}
}
// public void addJumpToInTreeRequest() {
// jumpToRequested = true;
/**
* Clears the icon calculated in "getIcon()" and notifies any UI containers of this node.
*/
public void clearIcon() {
// System.out.println("clearIcon: " + this);
// System.out.println("containersOfThisNode: " + containersOfThisNode.size());
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
icon = ImdiIcons.getSingleInstance().getIconForImdi(ImdiTreeObject.this); // to avoid a race condition (where the loading icons remains after load) this is also set here rather than nulling the icon
// System.out.println("clearIcon invokeLater" + ImdiTreeObject.this.toString());
// System.out.println("containersOfThisNode: " + containersOfThisNode.size());
// here we need to cause an update in the tree and table gui so that the new icon can be loaded
for (Enumeration containersIterator = containersOfThisNode.elements(); containersIterator.hasMoreElements();) { // changed back to a vector due to threading issues here
try { // TODO: the need for this try catch indicates that there is a threading issue in the way that imdichild nodes are reloaded within an imdi parent node and this should be reorganised to be more systematic and hierarchical
Object currentContainer = containersIterator.nextElement();
// System.out.println("currentContainer: " + currentContainer.toString());
if (currentContainer instanceof ImdiTableModel) {
((ImdiTableModel) currentContainer).requestReloadTableData(); // this must be done because the fields have been replaced and nead to be reloaded in the tables
}
if (currentContainer instanceof ImdiChildCellEditor) {
((ImdiChildCellEditor) currentContainer).updateEditor(ImdiTreeObject.this);
}
if (currentContainer instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode currentTreeNode = (DefaultMutableTreeNode) currentContainer;
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) currentContainer).getParent();
if (parentNode != null) {
TreeHelper.getSingleInstance().addToSortQueue(parentNode);
} else {
TreeHelper.getSingleInstance().addToSortQueue(currentTreeNode);
}
}
} catch (java.util.NoSuchElementException ex) {
//GuiHelper.linorgBugCatcher.logError(ex);
}
}
}
public boolean isFavorite() {
if (!this.isLocal()) {
// only local files can be favourites
return false;
}
return LinorgSessionStorage.getSingleInstance().pathIsInFavourites(this.getFile());
// return getParentDomNode().isFavourite;
}
// public void setFavouriteStatus(boolean favouriteStatus) {
// getParentDomNode().isFavourite = favouriteStatus;
// clearIcon();
/**
* If not already done calculates the required icon for this node in its current state.
* Once calculated the stored icon will be returned.
* To clear the icon and recalculate it "clearIcon()" should be called.
* @return The icon for this node.
*/
public ImageIcon getIcon() {
if (icon == null) {
return ImdiIcons.getSingleInstance().loadingIcon;
}
return icon;
}
}
|
package onion.compiler.pass;
import java.util.ArrayList;
import java.util.Arrays;
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.Stack;
import java.util.TreeSet;
import onion.compiler.*;
import onion.compiler.env.ClassTable;
import onion.compiler.env.ClosureLocalBinding;
import onion.compiler.env.ImportItem;
import onion.compiler.env.ImportList;
import onion.compiler.env.LocalContext;
import onion.compiler.env.LocalFrame;
import onion.compiler.env.StaticImportItem;
import onion.compiler.env.StaticImportList;
import onion.compiler.CompilationException;
import onion.compiler.util.Boxing;
import onion.compiler.util.Classes;
import onion.compiler.util.Paths;
import onion.compiler.util.Systems;
import onion.lang.syntax.*;
import onion.lang.syntax.visitor.ASTVisitor;
public class CodeAnalysis implements SemanticErrorReporter.Constants {
private SemanticErrorReporter reporter;
private CompilerConfig conf;
private ClassTable table;
private Map irt2ast;
private Map ast2irt;
private Map solvers;
private CompilationUnit unit;
private StaticImportList staticImport;
private ImportList currentImport;
private IxCode.ClassDefinition contextClass;
private NameResolution solver;
private int access;
public String topClass(){
ModuleDeclaration module = unit.getModuleDeclaration();
String moduleName = module != null ? module.getName() : null;
return createName(moduleName, Paths.cutExtension(unit.getSourceFileName()) + "Main");
}
public ClassTable getTable(){
return table;
}
public void setSolver(NameResolution resolver){
this.solver = resolver;
}
public NameResolution getSolver(){
return solver;
}
public void setUnit(CompilationUnit unit){
this.unit = unit;
}
public CompilationUnit getUnit(){
return unit;
}
public void setImport(ImportList imports){
currentImport = imports;
}
public ImportList getImport(){
return currentImport;
}
public void setStaticImport(StaticImportList imports){
staticImport = imports;
}
public StaticImportList getStaticImport(){
return staticImport;
}
public void setContextClass(IxCode.ClassDefinition contextClass){
this.contextClass = contextClass;
}
public IxCode.ClassDefinition getContextClass(){
return contextClass;
}
public void setAccess(int access){
this.access = access;
}
public int getAccess(){
return access;
}
public void put(AstNode astNode, IxCode.Node kernelNode){
ast2irt.put(astNode, kernelNode);
irt2ast.put(kernelNode, astNode);
}
public AstNode lookupAST(IxCode.Node kernelNode){
return (AstNode) irt2ast.get(kernelNode);
}
public IxCode.Node lookupKernelNode(AstNode astNode){
return (IxCode.Node) ast2irt.get(astNode);
}
public void addSolver(String className, NameResolution solver) {
solvers.put(className, solver);
}
public NameResolution findSolver(String className){
return (NameResolution) solvers.get(className);
}
private String createName(String moduleName, String simpleName){
return (moduleName != null ? moduleName + "." : "") + simpleName;
}
private static String classpath(String[] classPaths){
StringBuffer path = new StringBuffer();
if(classPaths.length > 0){
path.append(classPaths[0]);
for(int i = 1; i < classPaths.length; i++){
path.append(Systems.getPathSeparator());
path.append(classPaths[i]);
}
}
return new String(path);
}
public IxCode.TypeRef resolve(TypeSpec type, NameResolution resolver) {
IxCode.TypeRef resolvedType = (IxCode.TypeRef) resolver.resolve(type);
if(resolvedType == null){
report(CLASS_NOT_FOUND, type, new Object[]{type.getComponentName()});
}
return resolvedType;
}
public IxCode.TypeRef resolve(TypeSpec type) {
return resolve(type, getSolver());
}
public void report(int error, AstNode node, Object[] items) {
reporter.setSourceFile(unit.getSourceFileName());
reporter.report(error, node.getLocation(), items);
}
public static IxCode.TypeRef promoteNumericTypes(IxCode.TypeRef left, IxCode.TypeRef right) {
if(!numeric(left) || !numeric(right)) return null;
if(left == IxCode.BasicTypeRef.DOUBLE || right == IxCode.BasicTypeRef.DOUBLE){
return IxCode.BasicTypeRef.DOUBLE;
}
if(left == IxCode.BasicTypeRef.FLOAT || right == IxCode.BasicTypeRef.FLOAT){
return IxCode.BasicTypeRef.FLOAT;
}
if(left == IxCode.BasicTypeRef.LONG || right == IxCode.BasicTypeRef.LONG){
return IxCode.BasicTypeRef.LONG;
}
return IxCode.BasicTypeRef.INT;
}
public static boolean hasNumericType(IxCode.Expression expression) {
return numeric(expression.type());
}
private static boolean numeric(IxCode.TypeRef symbol) {
return
(symbol.isBasicType()) &&
( symbol == IxCode.BasicTypeRef.BYTE || symbol == IxCode.BasicTypeRef.SHORT ||
symbol == IxCode.BasicTypeRef.INT || symbol == IxCode.BasicTypeRef.LONG ||
symbol == IxCode.BasicTypeRef.FLOAT || symbol == IxCode.BasicTypeRef.DOUBLE);
}
public IxCode.ClassTypeRef load(String name) {
return table.load(name);
}
public IxCode.ClassTypeRef loadTopClass() {
return table.load(topClass());
}
public IxCode.ArrayTypeRef loadArray(IxCode.TypeRef type, int dimension) {
return table.loadArray(type, dimension);
}
public IxCode.ClassTypeRef rootClass() {
return table.rootClass();
}
public CompileError[] getProblems() {
return reporter.getProblems();
}
public IxCode.ClassDefinition[] getSourceClasses() {
return table.getSourceClasses();
}
private class ClassTableBuilder extends ASTVisitor<String> {
public ClassTableBuilder() {
}
public void process(CompilationUnit unit){
setUnit(unit);
ModuleDeclaration module = unit.getModuleDeclaration();
ImportListDeclaration imports = unit.getImportListDeclaration();
String moduleName = module != null ? module.getName() : null;
ImportList list = new ImportList();
list.add(new ImportItem("*", "java.lang.*"));
list.add(new ImportItem("*", "java.io.*"));
list.add(new ImportItem("*", "java.util.*"));
list.add(new ImportItem("*", "javax.swing.*"));
list.add(new ImportItem("*", "java.awt.event.*"));
list.add(new ImportItem("*", "onion.*"));
list.add(new ImportItem("*", moduleName != null ? moduleName + ".*" : "*"));
if(imports != null){
for(int i = 0; i < imports.size(); i++){
list.add(new ImportItem(imports.getName(i), imports.getFQCN(i)));
}
}
StaticImportList staticList = new StaticImportList();
staticList.add(new StaticImportItem("java.lang.System", true));
staticList.add(new StaticImportItem("java.lang.Runtime", true));
staticList.add(new StaticImportItem("java.lang.Math", true));
setImport(list);
setStaticImport(staticList);
TopLevelElement[] tops = unit.getTopLevels();
int count = 0;
for(int i = 0; i < tops.length; i++){
if(tops[i] instanceof TypeDeclaration){
accept(tops[i], moduleName);
continue;
}
count++;
}
ClassTable table = getTable();
if(count > 0){
IxCode.ClassDefinition node = IxCode.ClassDefinition.newClass(0, topClass(), table.rootClass(), new IxCode.ClassTypeRef[0]);
node.setSourceFile(Paths.nameOf(unit.getSourceFileName()));
node.setResolutionComplete(true);
table.addSourceClass(node);
node.addDefaultConstructor();
put(unit, node);
addSolver(node.name(), new NameResolution(list));
}
}
public Object visit(ClassDeclaration ast, String context) {
String module = context;
IxCode.ClassDefinition node = IxCode.ClassDefinition.newClass(ast.getModifier(), createFQCN(module, ast.getName()));
node.setSourceFile(Paths.nameOf(getUnit().getSourceFileName()));
if(getTable().lookup(node.name()) != null){
report(DUPLICATE_CLASS, ast, new Object[]{node.name()});
return null;
}
ClassTable table = getTable();
getTable().addSourceClass(node);
put(ast, node);
addSolver(node.name(), new NameResolution(getImport()));
return null;
}
public Object visit(InterfaceDeclaration ast, String context) {
String module = context;
IxCode.ClassDefinition node = IxCode.ClassDefinition.newInterface(ast.getModifier(), createFQCN(module, ast.getName()), null);
node.setSourceFile(Paths.nameOf(getUnit().getSourceFileName()));
ClassTable table = getTable();
if(table.lookup(node.name()) != null){
report(DUPLICATE_CLASS, ast, new Object[]{node.name()});
return null;
}
table.addSourceClass(node);
put(ast, node);
addSolver(node.name(), new NameResolution(getImport()) );
return null;
}
private String createFQCN(String moduleName, String simpleName) {
return (moduleName != null ? moduleName + "." : "") + simpleName;
}
}
private class TypeHeaderAnalysis extends ASTVisitor<Void> {
private int countConstructor;
public TypeHeaderAnalysis() {
}
public void process(CompilationUnit unit){
setUnit(unit);
TopLevelElement[] toplevels = unit.getTopLevels();
for(int i = 0; i < toplevels.length; i++){
setSolver(findSolver(topClass()));
accept(toplevels[i]);
}
}
public Object visit(ClassDeclaration ast, Void context) {
countConstructor = 0;
IxCode.ClassDefinition node = (IxCode.ClassDefinition) lookupKernelNode(ast);
setContextClass(node);
setSolver(findSolver(node.name()));
constructTypeHierarchy(node, new ArrayList());
if(hasCyclicity(node)){
report(CYCLIC_INHERITANCE, ast, new Object[]{node.name()});
}
if(ast.getDefaultSection() != null){
accept(ast.getDefaultSection());
}
AccessSection[] sections = ast.getSections();
for(int i = 0; i < sections.length; i++){
accept(sections[i]);
}
if(countConstructor == 0){
node.addDefaultConstructor();
}
return null;
}
public Object visit(InterfaceDeclaration ast, Void context) {
IxCode.ClassDefinition node = (IxCode.ClassDefinition) lookupKernelNode(ast);
setContextClass(node);
setSolver(findSolver(node.name()));
constructTypeHierarchy(node, new ArrayList());
if(hasCyclicity(node)){
report(CYCLIC_INHERITANCE, ast, new Object[]{node.name()});
}
InterfaceMethodDeclaration[] members = ast.getDeclarations();
for(int i = 0; i < members.length; i++){
accept(members[i], context);
}
return null;
}
public Object visit(DelegationDeclaration ast, Void context) {
IxCode.TypeRef type = resolve(ast.getType());
if(type == null) return null;
if(!(type.isObjectType() && ((IxCode.ObjectTypeRef)type).isInterface())){
report(INTERFACE_REQUIRED, ast.getType(), new Object[]{type});
return null;
}
IxCode.ClassDefinition contextClass = getContextClass();
int modifier = ast.getModifier() | getAccess() | Modifier.FORWARDED;
String name = ast.getName();
IxCode.FieldDefinition node = new IxCode.FieldDefinition(modifier, contextClass, name, type);
put(ast, node);
contextClass.addField(node);
return null;
}
public Object visit(ConstructorDeclaration ast, Void context) {
countConstructor++;
IxCode.TypeRef[] args = acceptTypes(ast.getArguments());
IxCode.ClassDefinition contextClass = getContextClass();
if(args == null) return null;
int modifier = ast.getModifier() | getAccess();
IxCode.ConstructorDefinition node = new IxCode.ConstructorDefinition(modifier, contextClass, args, null, null);
put(ast, node);
contextClass.addConstructor(node);
return null;
}
public Object visit(MethodDeclaration ast, Void context) {
IxCode.TypeRef[] args = acceptTypes(ast.getArguments());
IxCode.TypeRef returnType;
if(ast.getReturnType() != null){
returnType = resolve(ast.getReturnType());
}else{
returnType = IxCode.BasicTypeRef.VOID;
}
if(args == null || returnType == null) return null;
IxCode.ClassDefinition contextClass = getContextClass();
int modifier = ast.getModifier() | getAccess();
if(ast.getBlock() == null) modifier |= Modifier.ABSTRACT;
String name = ast.getName();
IxCode.MethodDefinition node = new IxCode.MethodDefinition(modifier, contextClass, name, args, returnType, null);
put(ast, node);
contextClass.addMethod(node);
return null;
}
public Object visit(FieldDeclaration ast, Void context) {
IxCode.TypeRef type = resolve(ast.getType());
if(type == null) return null;
IxCode.ClassDefinition contextClass = getContextClass();
int modifier = ast.getModifier() | getAccess();
String name = ast.getName();
IxCode.FieldDefinition node = new IxCode.FieldDefinition(modifier, contextClass, name, type);
put(ast, node);
contextClass.addField(node);
return node;
}
private IxCode.TypeRef[] acceptTypes(Argument[] ast){
IxCode.TypeRef[] types = new IxCode.TypeRef[ast.length];
boolean success = true;
for (int i = 0; i < ast.length; i++) {
types[i] = (IxCode.TypeRef) accept(ast[i]);
if(types[i] == null) success = false;
}
if(success){
return types;
}else{
return null;
}
}
public Object visit(Argument ast, Void context){
IxCode.TypeRef type = resolve(ast.getType());
return type;
}
private IxCode.FieldDefinition createFieldNode(FieldDeclaration ast){
IxCode.TypeRef type = resolve(ast.getType());
if(type == null) return null;
IxCode.FieldDefinition node = new IxCode.FieldDefinition(
ast.getModifier() | getAccess(), getContextClass(),
ast.getName(), type);
return node;
}
public Object visit(InterfaceMethodDeclaration ast, Void context) {
IxCode.TypeRef[] args = acceptTypes(ast.getArguments());
IxCode.TypeRef returnType;
if(ast.getReturnType() != null){
returnType = resolve(ast.getReturnType());
}else{
returnType = IxCode.BasicTypeRef.VOID;
}
if(args == null || returnType == null) return null;
int modifier = Modifier.PUBLIC | Modifier.ABSTRACT;
IxCode.ClassDefinition classType = getContextClass();
String name = ast.getName();
IxCode.MethodDefinition node =
new IxCode.MethodDefinition(modifier, classType, name, args, returnType, null);
put(ast, node);
classType.addMethod(node);
return null;
}
public Object visit(FunctionDeclaration ast, Void context) {
IxCode.TypeRef[] args = acceptTypes(ast.getArguments());
IxCode.TypeRef returnType;
if(ast.getReturnType() != null){
returnType = resolve(ast.getReturnType());
}else{
returnType = IxCode.BasicTypeRef.VOID;
}
if(args == null || returnType == null) return null;
IxCode.ClassDefinition classType = (IxCode.ClassDefinition) loadTopClass();
int modifier = ast.getModifier() | Modifier.PUBLIC;
String name = ast.getName();
IxCode.MethodDefinition node =
new IxCode.MethodDefinition(modifier, classType, name, args, returnType, null);
put(ast, node);
classType.addMethod(node);
return null;
}
public Object visit(GlobalVariableDeclaration ast, Void context) {
IxCode.TypeRef type = resolve(ast.getType());
if(type == null) return null;
int modifier = ast.getModifier() | Modifier.PUBLIC;
IxCode.ClassDefinition classType = (IxCode.ClassDefinition)loadTopClass();
String name = ast.getName();
IxCode.FieldDefinition node = new IxCode.FieldDefinition(modifier, classType, name, type);
put(ast, node);
classType.addField(node);
return null;
}
public Object visit(AccessSection section, Void context){
if(section == null) return null;
setAccess(section.getID());
MemberDeclaration[] members = section.getMembers();
for(int i = 0; i < members.length; i++){
accept(members[i], context);
}
return null;
}
public boolean hasCyclicity(IxCode.ClassDefinition start){
return hasCylicitySub(start, new HashSet());
}
private boolean hasCylicitySub(IxCode.ClassTypeRef symbol, HashSet visit){
if(symbol == null) return false;
if(visit.contains(symbol)){
return true;
}
visit.add(symbol);
if(hasCylicitySub(symbol.getSuperClass(), (HashSet)visit.clone())){
return true;
}
IxCode.ClassTypeRef[] interfaces = symbol.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if(hasCylicitySub(interfaces[i], (HashSet)visit.clone())){
return true;
}
}
return false;
}
private void constructTypeHierarchy(IxCode.ClassTypeRef symbol, List visit) {
if(symbol == null || visit.indexOf(symbol) >= 0) return;
visit.add(symbol);
if(symbol instanceof IxCode.ClassDefinition){
IxCode.ClassDefinition node = (IxCode.ClassDefinition) symbol;
if(node.isResolutionComplete()) return;
IxCode.ClassTypeRef superClass = null;
List interfaces = new ArrayList();
NameResolution resolver = findSolver(node.name());
if(node.isInterface()){
InterfaceDeclaration ast = (InterfaceDeclaration) lookupAST(node);
superClass = rootClass();
TypeSpec[] typeSpecifiers = ast.getInterfaces();
for(int i = 0; i < typeSpecifiers.length; i++){
IxCode.ClassTypeRef superType = validateSuperType(typeSpecifiers[i], true, resolver);
if(superType != null){
interfaces.add(superType);
}
}
}else{
ClassDeclaration ast = (ClassDeclaration) lookupAST(node);
superClass =
validateSuperType(ast.getSuperClass(), false, resolver);
TypeSpec[] typeSpecifiers = ast.getInterfaces();
for(int i = 0; i < typeSpecifiers.length; i++){
IxCode.ClassTypeRef superType = validateSuperType(typeSpecifiers[i], true, resolver);
if(superType != null){
interfaces.add(superType);
}
}
}
constructTypeHierarchy(superClass, visit);
for(Iterator i = interfaces.iterator(); i.hasNext();){
IxCode.ClassTypeRef superType = (IxCode.ClassTypeRef) i.next();
constructTypeHierarchy(superType, visit);
}
node.setSuperClass(superClass);
node.setInterfaces((IxCode.ClassTypeRef[]) interfaces.toArray(new IxCode.ClassTypeRef[0]));
node.setResolutionComplete(true);
}else{
constructTypeHierarchy(symbol.getSuperClass(), visit);
IxCode.ClassTypeRef[] interfaces = symbol.getInterfaces();
for(int i = 0; i < interfaces.length; i++){
constructTypeHierarchy(interfaces[i], visit);
}
}
}
private IxCode.ClassTypeRef validateSuperType(
TypeSpec ast, boolean shouldInterface, NameResolution resolver){
IxCode.ClassTypeRef symbol = null;
if(ast == null){
symbol = getTable().rootClass();
}else{
symbol = (IxCode.ClassTypeRef) resolve(ast, resolver);
}
if(symbol == null) return null;
boolean isInterface = symbol.isInterface();
if(((!isInterface) && shouldInterface) || (isInterface && (!shouldInterface))){
AstNode astNode = null;
if(symbol instanceof IxCode.ClassDefinition){
astNode = lookupAST((IxCode.ClassDefinition)symbol);
}
report(ILLEGAL_INHERITANCE, astNode, new Object[]{symbol.name()});
}
return symbol;
}
private void report(int error, AstNode ast, Object[] items){
report(error, ast, items);
}
}
private class DuplicationChecker extends ASTVisitor<Void> {
private Set methods;
private Set constructors;
private Set fields;
private Set variables;
private Set functions;
public DuplicationChecker() {
this.methods = new TreeSet(new IxCode.MethodRefComparator());
this.fields = new TreeSet(new IxCode.FieldRefComparator());
this.constructors = new TreeSet(new IxCode.ConstructorRefComparator());
this.variables = new TreeSet(new IxCode.FieldRefComparator());
this.functions = new TreeSet(new IxCode.MethodRefComparator());
}
public void process(CompilationUnit unit){
setUnit(unit);
variables.clear();
functions.clear();
TopLevelElement[] toplevels = unit.getTopLevels();
for(int i = 0; i < toplevels.length; i++){
setSolver(findSolver(topClass()));
accept(toplevels[i]);
}
}
public Object visit(ClassDeclaration ast, Void context) {
IxCode.ClassDefinition node = (IxCode.ClassDefinition) lookupKernelNode(ast);
if(node == null) return null;
methods.clear();
fields.clear();
constructors.clear();
setContextClass(node);
setSolver(findSolver(node.name()));
if(ast.getDefaultSection() != null){
accept(ast.getDefaultSection());
}
AccessSection[] sections = ast.getSections();
for(int i = 0; i < sections.length; i++){
accept(sections[i]);
}
generateMethods();
return null;
}
private void generateMethods(){
Set generated = new TreeSet(new IxCode.MethodRefComparator());
Set methodSet = new TreeSet(new IxCode.MethodRefComparator());
for(Iterator i = fields.iterator(); i.hasNext();){
IxCode.FieldDefinition node = (IxCode.FieldDefinition)i.next();
if(Modifier.isForwarded(node.modifier())){
generateDelegationMethods(node ,generated, methodSet);
}
}
}
private void generateDelegationMethods(IxCode.FieldDefinition node, Set generated, Set methodSet){
IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) node.getType();
Set src = Classes.getInterfaceMethods(type);
for (Iterator i = src.iterator(); i.hasNext();) {
IxCode.MethodRef method = (IxCode.MethodRef) i.next();
if(methodSet.contains(method)) continue;
if(generated.contains(method)){
report(
DUPLICATE_GENERATED_METHOD, lookupAST(node),
new Object[]{
method.affiliation(), method.name(), method.arguments()
});
continue;
}
IxCode.MethodDefinition generatedMethod = createEmptyMethod(node, method);
generated.add(generatedMethod);
getContextClass().addMethod(generatedMethod);
}
}
private IxCode.MethodDefinition createEmptyMethod(IxCode.FieldRef field, IxCode.MethodRef method){
IxCode.Expression target;
target = new IxCode.RefField(new IxCode.This(getContextClass()), field);
IxCode.TypeRef[] args = method.arguments();
IxCode.Expression[] params = new IxCode.Expression[args.length];
LocalFrame frame = new LocalFrame(null);
for(int i = 0; i < params.length; i++){
int index = frame.addEntry("arg" + i, args[i]);
params[i] = new IxCode.RefLocal(new ClosureLocalBinding(0, index, args[i]));
}
target = new IxCode.Call(target, method, params);
IxCode.StatementBlock statement;
if(method.returnType() != IxCode.BasicTypeRef.VOID){
statement = new IxCode.StatementBlock(new IxCode.Return(target));
}else{
statement = new IxCode.StatementBlock(new IxCode.ExpressionStatement(target), new IxCode.Return(null));
}
IxCode.MethodDefinition node = new IxCode.MethodDefinition(
Modifier.PUBLIC, getContextClass(), method.name(),
method.arguments(), method.returnType(), statement
);
node.setFrame(frame);
return node;
}
public Object visit(InterfaceDeclaration ast, Void context) {
IxCode.ClassDefinition node = (IxCode.ClassDefinition) lookupKernelNode(ast);
if(node == null) return null;
methods.clear();
fields.clear();
constructors.clear();
setContextClass(node);
setSolver(findSolver(node.name()));
InterfaceMethodDeclaration[] members = ast.getDeclarations();
for(int i = 0; i < members.length; i++){
accept(members[i], context);
}
return null;
}
public Object visit(ConstructorDeclaration ast, Void context) {
IxCode.ConstructorDefinition node = (IxCode.ConstructorDefinition) lookupKernelNode(ast);
if(node == null) return null;
if(constructors.contains(node)){
IxCode.ClassTypeRef classType = node.affiliation();
IxCode.TypeRef[] args = node.getArgs();
report(DUPLICATE_CONSTRUCTOR, ast, new Object[]{classType, args});
}else{
constructors.add(node);
}
return null;
}
public Object visit(DelegationDeclaration ast, Void context) {
IxCode.FieldDefinition node = (IxCode.FieldDefinition) lookupKernelNode(ast);
if(node == null) return null;
if(fields.contains(node)){
IxCode.ClassTypeRef classType = node.affiliation();
String name = node.name();
report(DUPLICATE_FIELD, ast, new Object[]{classType, name});
}else{
fields.add(node);
}
return null;
}
public Object visit(MethodDeclaration ast, Void context) {
IxCode.MethodDefinition node = (IxCode.MethodDefinition) lookupKernelNode(ast);
if(node == null) return null;
if(methods.contains(node)){
IxCode.ClassTypeRef classType = node.affiliation();
String name = node.name();
IxCode.TypeRef[] args = node.arguments();
report(DUPLICATE_METHOD, ast, new Object[]{classType, name, args});
}else{
methods.add(node);
}
return null;
}
public Object visit(FieldDeclaration ast, Void context) {
IxCode.FieldDefinition node = (IxCode.FieldDefinition) lookupKernelNode(ast);
if(node == null) return null;
if(fields.contains(node)){
IxCode.ClassTypeRef classType = node.affiliation();
String name = node.name();
report(DUPLICATE_FIELD, ast, new Object[]{classType, name});
}else{
fields.add(node);
}
return null;
}
public Object visit(InterfaceMethodDeclaration ast, Void context) {
IxCode.MethodDefinition node = (IxCode.MethodDefinition) lookupKernelNode(ast);
if(node == null) return null;
if(methods.contains(node)){
IxCode.ClassTypeRef classType = node.affiliation();
String name = node.name();
IxCode.TypeRef[] args = node.arguments();
report(DUPLICATE_METHOD, ast, new Object[]{classType, name, args});
}else{
methods.add(node);
}
return null;
}
public Object visit(FunctionDeclaration ast, Void context) {
IxCode.MethodDefinition node = (IxCode.MethodDefinition) lookupKernelNode(ast);
if(node == null) return null;
if(functions.contains(node)){
String name = node.name();
IxCode.TypeRef[] args = node.arguments();
report(DUPLICATE_FUNCTION, ast, new Object[]{name, args});
}else{
functions.add(node);
}
return null;
}
public Object visit(GlobalVariableDeclaration ast, Void context) {
IxCode.FieldDefinition node = (IxCode.FieldDefinition) lookupKernelNode(ast);
if(node == null) return null;
if(variables.contains(node)){
String name = node.name();
report(DUPLICATE_GLOBAL_VARIABLE, ast, new Object[]{name});
}else{
variables.add(node);
}
return null;
}
public Object visit(AccessSection section, Void context){
if(section == null) return null;
MemberDeclaration[] members = section.getMembers();
for(int i = 0; i < members.length; i++){
accept(members[i], context);
}
return null;
}
private void report(int error, AstNode ast, Object[] items){
report(error, ast, items);
}
}
private class TypeChecker extends ASTVisitor<LocalContext>
implements IxCode.BinaryExpression.Constants, IxCode.UnaryExpression.Constants {
public TypeChecker(){
}
public void process(CompilationUnit unit){
accept(unit);
}
public Object visit(CompilationUnit unit, LocalContext object) {
setUnit(unit);
TopLevelElement[] toplevels = unit.getTopLevels();
LocalContext context = new LocalContext();
List statements = new ArrayList();
String className = topClass();
setSolver(findSolver(className));
IxCode.ClassDefinition klass = (IxCode.ClassDefinition) loadTopClass();
IxCode.ArrayTypeRef argsType = loadArray(load("java.lang.String"), 1);
IxCode.MethodDefinition method = new IxCode.MethodDefinition(
Modifier.PUBLIC, klass,
"start", new IxCode.TypeRef[]{argsType}, IxCode.BasicTypeRef.VOID, null
);
context.addEntry("args", argsType);
for(int i = 0; i < toplevels.length; i++){
TopLevelElement element = toplevels[i];
if(!(element instanceof TypeDeclaration)){
setContextClass(klass);
}
if(element instanceof Statement){
context.setMethod(method);
IxCode.ActionStatement statement = (IxCode.ActionStatement) accept(toplevels[i], context);
statements.add(statement);
}else{
accept(toplevels[i], null);
}
}
if(klass != null){
statements.add(new IxCode.Return(null));
method.setBlock(new IxCode.StatementBlock(statements));
method.setFrame(context.getContextFrame());
klass.addMethod(method);
klass.addMethod(mainMethod(klass, method, "main", new IxCode.TypeRef[]{argsType}, IxCode.BasicTypeRef.VOID));
}
return null;
}
private IxCode.MethodDefinition mainMethod(IxCode.ClassTypeRef top, IxCode.MethodRef ref, String name, IxCode.TypeRef[] args, IxCode.TypeRef ret) {
IxCode.MethodDefinition method = new IxCode.MethodDefinition(
Modifier.STATIC | Modifier.PUBLIC, top, name, args, ret, null);
LocalFrame frame = new LocalFrame(null);
IxCode.Expression[] params = new IxCode.Expression[args.length];
for(int i = 0; i < args.length; i++){
int index = frame.addEntry("args" + i, args[i]);
params[i] = new IxCode.RefLocal(0, index, args[i]);
}
method.setFrame(frame);
IxCode.ConstructorRef c = top.findConstructor(new IxCode.Expression[0])[0];
IxCode.Expression exp = new IxCode.NewObject(c, new IxCode.Expression[0]);
exp = new IxCode.Call(exp, ref, params);
IxCode.StatementBlock block = new IxCode.StatementBlock(new IxCode.ExpressionStatement(exp));
block = addReturnNode(block, IxCode.BasicTypeRef.VOID);
method.setBlock(block);
return method;
}
public Object visit(InterfaceDeclaration ast, LocalContext context) {
setContextClass((IxCode.ClassDefinition) lookupKernelNode(ast));
return null;
}
public Object visit(ClassDeclaration ast, LocalContext context) {
setContextClass((IxCode.ClassDefinition) lookupKernelNode(ast));
setSolver(findSolver(getContextClass().name()));
if(ast.getDefaultSection() != null){
accept(ast.getDefaultSection(), context);
}
acceptEach(ast.getSections(), context);
return null;
}
public Object visit(AccessSection ast, LocalContext context) {
acceptEach(ast.getMembers(), context);
return null;
}
public Object visit(Addition ast, LocalContext context) {
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
if(left.isBasicType() && right.isBasicType()){
return checkNumExp(ADD, ast, left, right, context);
}
if(left.isBasicType()){
if(left.type() == IxCode.BasicTypeRef.VOID){
report(IS_NOT_BOXABLE_TYPE, ast.getLeft(), new Object[]{left.type()});
return null;
}else{
left = Boxing.boxing(getTable(), left);
}
}
if(right.isBasicType()){
if(right.type() == IxCode.BasicTypeRef.VOID){
report(IS_NOT_BOXABLE_TYPE, ast.getRight(), new Object[]{right.type()});
return null;
}else{
right = Boxing.boxing(getTable(), right);
}
}
IxCode.MethodRef toString;
toString = findMethod(ast.getLeft(), (IxCode.ObjectTypeRef)left.type(), "toString");
left = new IxCode.Call(left, toString, new IxCode.Expression[0]);
toString = findMethod(ast.getRight(), (IxCode.ObjectTypeRef)right.type(), "toString");
right = new IxCode.Call(right, toString, new IxCode.Expression[0]);
IxCode.MethodRef concat =
findMethod(ast, (IxCode.ObjectTypeRef)left.type(), "concat", new IxCode.Expression[]{right});
return new IxCode.Call(left, concat, new IxCode.Expression[]{right});
}
public Object visit(PostIncrement node, LocalContext context) {
LocalContext local = (LocalContext)context;
IxCode.Expression operand = typeCheck(node.getTarget(), context);
if(operand == null) return null;
if((!operand.isBasicType()) || !hasNumericType(operand)){
report(INCOMPATIBLE_OPERAND_TYPE, node, new Object[]{node.getSymbol(), new IxCode.TypeRef[]{operand.type()}});
return null;
}
IxCode.Expression result = null;
if(operand instanceof IxCode.RefLocal){
int varIndex = local.addEntry(local.newName(), operand.type());
IxCode.RefLocal ref = (IxCode.RefLocal)operand;
result = new IxCode.Begin(
new IxCode.SetLocal(0, varIndex, operand.type(), operand),
new IxCode.SetLocal(
ref.frame(), ref.index(), ref.type(),
new IxCode.BinaryExpression(
ADD, operand.type(),
new IxCode.RefLocal(0, varIndex, operand.type()),
new IxCode.IntLiteral(1)
)
),
new IxCode.RefLocal(0, varIndex, operand.type())
);
}else if(operand instanceof IxCode.RefField){
IxCode.RefField ref = (IxCode.RefField)operand;
int varIndex = local.addEntry(local.newName(), ref.target.type());
result = new IxCode.Begin(
new IxCode.SetLocal(0, varIndex, ref.target.type(), ref.target),
new IxCode.SetField(
new IxCode.RefLocal(0, varIndex, ref.target.type()),
ref.field,
new IxCode.BinaryExpression(
ADD, operand.type(),
new IxCode.RefField(new IxCode.RefLocal(0, varIndex, ref.target.type()), ref.field),
new IxCode.IntLiteral(1)
)
)
);
}else {
report(UNIMPLEMENTED_FEATURE, node, new Object[0]);
}
return result;
}
public Object visit(PostDecrement node, LocalContext context) {
LocalContext local = (LocalContext)context;
IxCode.Expression operand = typeCheck(node.getTarget(), context);
if(operand == null) return null;
if((!operand.isBasicType()) || !hasNumericType(operand)){
report(INCOMPATIBLE_OPERAND_TYPE, node, new Object[]{node.getSymbol(), new IxCode.TypeRef[]{operand.type()}});
return null;
}
IxCode.Expression result = null;
if(operand instanceof IxCode.RefLocal){
int varIndex = local.addEntry(local.newName(), operand.type());
IxCode.RefLocal ref = (IxCode.RefLocal)operand;
result = new IxCode.Begin(
new IxCode.SetLocal(0, varIndex, operand.type(), operand),
new IxCode.SetLocal(
ref.frame(), ref.index(), ref.type(),
new IxCode.BinaryExpression(
SUBTRACT, operand.type(),
new IxCode.RefLocal(0, varIndex, operand.type()),
new IxCode.IntLiteral(1)
)
),
new IxCode.RefLocal(0, varIndex, operand.type())
);
}else if(operand instanceof IxCode.RefField){
IxCode.RefField ref = (IxCode.RefField)operand;
int varIndex = local.addEntry(local.newName(), ref.target.type());
result = new IxCode.Begin(
new IxCode.SetLocal(0, varIndex, ref.target.type(), ref.target),
new IxCode.SetField(
new IxCode.RefLocal(0, varIndex, ref.target.type()),
ref.field,
new IxCode.BinaryExpression(
SUBTRACT, operand.type(),
new IxCode.RefField(new IxCode.RefLocal(0, varIndex, ref.target.type()), ref.field),
new IxCode.IntLiteral(1)
)
)
);
}else {
report(UNIMPLEMENTED_FEATURE, node, new Object[0]);
}
return result;
}
@Override
public Object visit(Elvis ast, LocalContext context) {
IxCode.Expression l = typeCheck(ast.getLeft(), context);
IxCode.Expression r = typeCheck(ast.getRight(), context);
if(l.isBasicType() || r.isBasicType() || !IxCode.TypeRules.isAssignable(l.type(), r.type())) {
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{l.type(), r.type()}});
return null;
}
return new IxCode.BinaryExpression(ELVIS, l.type(), l, r);
}
public Object visit(Subtraction ast, LocalContext context) {
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
return checkNumExp(SUBTRACT, ast, left, right, context);
}
public Object visit(Multiplication ast, LocalContext context) {
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
return checkNumExp(MULTIPLY, ast, left, right, context);
}
public Object visit(Division ast, LocalContext context) {
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
return checkNumExp(DIVIDE, ast, left, right, context);
}
public Object visit(Modulo ast, LocalContext context) {
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
return checkNumExp(MOD, ast, left, right, context);
}
public Object visit(XOR ast, LocalContext context) {
return checkBitExp(XOR, ast, context);
}
public Object visit(Equal ast, LocalContext context) {
return checkEqualExp(EQUAL, ast, context);
}
public Object visit(NotEqual ast, LocalContext context) {
return checkEqualExp(NOT_EQUAL, ast, context);
}
public Object visit(ReferenceEqual ast, LocalContext context) {
return checkRefEqualsExp(EQUAL, ast, context);
}
public Object visit(ReferenceNotEqual ast, LocalContext context) {
return checkRefEqualsExp(NOT_EQUAL, ast, context);
}
public Object visit(LessOrEqual ast, LocalContext context) {
IxCode.Expression[] ops = processComparableExpression(ast, context);
if(ops == null){
return null;
}
return new IxCode.BinaryExpression(LESS_OR_EQUAL, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]);
}
public Object visit(LessThan ast, LocalContext context) {
IxCode.Expression[] ops = processComparableExpression(ast, context);
if(ops == null) return null;
return new IxCode.BinaryExpression(
LESS_THAN, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]);
}
public Object visit(GreaterOrEqual ast, LocalContext context) {
IxCode.Expression[] ops = processComparableExpression(ast, context);
if(ops == null) return null;
return new IxCode.BinaryExpression(
GREATER_OR_EQUAL, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]);
}
public Object visit(GreaterThan ast, LocalContext context) {
IxCode.Expression[] ops = processComparableExpression(ast, context);
if(ops == null) return null;
return new IxCode.BinaryExpression(
GREATER_THAN, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]);
}
public Object visit(LogicalAnd ast, LocalContext context) {
IxCode.Expression[] ops = processLogicalExpression(ast, context);
if(ops == null) return null;
return new IxCode.BinaryExpression(
LOGICAL_AND, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]);
}
public Object visit(LogicalOr ast, LocalContext context) {
IxCode.Expression[] ops = processLogicalExpression(ast, context);
if(ops == null) return null;
return new IxCode.BinaryExpression(
LOGICAL_OR, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]);
}
public Object visit(LogicalRightShift ast, LocalContext context) {
return processShiftExpression(BIT_SHIFT_R3, ast, context);
}
public Object visit(MathLeftShift ast, LocalContext context) {
return processShiftExpression(BIT_SHIFT_L2, ast, context);
}
public Object visit(MathRightShift ast, LocalContext context) {
return processShiftExpression(BIT_SHIFT_R2, ast, context);
}
public Object visit(BitAnd ast, LocalContext context) {
return checkBitExp(BIT_AND, ast, context);
}
public Object visit(BitOr expression, LocalContext context) {
return checkBitExp(BIT_AND, expression, context);
}
IxCode.Expression[] processLogicalExpression(onion.lang.syntax.BinaryExpression ast, LocalContext context){
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
IxCode.TypeRef leftType = left.type(), rightType = right.type();
if((leftType != IxCode.BasicTypeRef.BOOLEAN) || (rightType != IxCode.BasicTypeRef.BOOLEAN)){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}});
return null;
}
return new IxCode.Expression[]{left, right};
}
IxCode.Expression processShiftExpression(
int kind, onion.lang.syntax.BinaryExpression ast, LocalContext context){
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
if(!left.type().isBasicType()){
IxCode.Expression[] params = new IxCode.Expression[]{right};
Pair<Boolean, IxCode.MethodRef> result = tryFindMethod(ast, (IxCode.ObjectTypeRef)left.type(), "add", params);
if(result._2 == null){
report(METHOD_NOT_FOUND, ast, new Object[]{left.type(), "add", types(params)});
return null;
}
return new IxCode.Call(left, result._2, params);
}
if(!right.type().isBasicType()){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}});
return null;
}
IxCode.BasicTypeRef leftType = (IxCode.BasicTypeRef)left.type();
IxCode.BasicTypeRef rightType = (IxCode.BasicTypeRef)right.type();
if((!leftType.isInteger()) || (!rightType.isInteger())){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}});
return null;
}
IxCode.TypeRef leftResultType = promoteInteger(leftType);
if(leftResultType != leftType){
left = new IxCode.AsInstanceOf(left, leftResultType);
}
if(rightType != IxCode.BasicTypeRef.INT){
right = new IxCode.AsInstanceOf(right, IxCode.BasicTypeRef.INT);
}
return new IxCode.BinaryExpression(kind, IxCode.BasicTypeRef.BOOLEAN, left, right);
}
IxCode.TypeRef promoteInteger(IxCode.TypeRef type){
if(type == IxCode.BasicTypeRef.BYTE || type == IxCode.BasicTypeRef.SHORT ||
type == IxCode.BasicTypeRef.CHAR || type == IxCode.BasicTypeRef.INT){
return IxCode.BasicTypeRef.INT;
}
if(type == IxCode.BasicTypeRef.LONG){
return IxCode.BasicTypeRef.LONG;
}
return null;
}
IxCode.Expression checkBitExp(int kind, onion.lang.syntax.BinaryExpression ast, LocalContext context){
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
if((!left.isBasicType()) || (!right.isBasicType())){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}});
return null;
}
IxCode.BasicTypeRef leftType = (IxCode.BasicTypeRef)left.type();
IxCode.BasicTypeRef rightType = (IxCode.BasicTypeRef)right.type();
IxCode.TypeRef resultType = null;
if(leftType.isInteger() && rightType.isInteger()){
resultType = promote(leftType, rightType);
}else if(leftType.isBoolean() && rightType.isBoolean()){
resultType = IxCode.BasicTypeRef.BOOLEAN;
}else{
report(INCOMPATIBLE_OPERAND_TYPE, ast, new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}});
return null;
}
if(left.type() != resultType){
left = new IxCode.AsInstanceOf(left, resultType);
}
if(right.type() != resultType){
right = new IxCode.AsInstanceOf(right, resultType);
}
return new IxCode.BinaryExpression(kind, resultType, left, right);
}
IxCode.Expression checkNumExp(int kind, onion.lang.syntax.BinaryExpression ast, IxCode.Expression left, IxCode.Expression right, LocalContext context) {
if((!hasNumericType(left)) || (!hasNumericType(right))){
report(INCOMPATIBLE_OPERAND_TYPE, ast, new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}});
return null;
}
IxCode.TypeRef resultType = promote(left.type(), right.type());
if(left.type() != resultType){
left = new IxCode.AsInstanceOf(left, resultType);
}
if(right.type() != resultType){
right = new IxCode.AsInstanceOf(right, resultType);
}
return new IxCode.BinaryExpression(kind, resultType, left, right);
}
IxCode.Expression checkRefEqualsExp(int kind, onion.lang.syntax.BinaryExpression ast, LocalContext context){
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
IxCode.TypeRef leftType = left.type();
IxCode.TypeRef rightType = right.type();
if(
(left.isBasicType() && (!right.isBasicType())) ||
((!left.isBasicType()) && (right.isBasicType()))){
report(INCOMPATIBLE_OPERAND_TYPE, ast, new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}});
return null;
}
if(left.isBasicType() && right.isBasicType()){
if(hasNumericType(left) && hasNumericType(right)){
IxCode.TypeRef resultType = promote(leftType, rightType);
if(resultType != left.type()){
left = new IxCode.AsInstanceOf(left, resultType);
}
if(resultType != right.type()){
right = new IxCode.AsInstanceOf(right, resultType);
}
}else if(leftType != IxCode.BasicTypeRef.BOOLEAN || rightType != IxCode.BasicTypeRef.BOOLEAN){
report(INCOMPATIBLE_OPERAND_TYPE, ast, new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}});
return null;
}
}
return new IxCode.BinaryExpression(kind, IxCode.BasicTypeRef.BOOLEAN, left, right);
}
IxCode.Expression checkEqualExp(int kind, onion.lang.syntax.BinaryExpression ast, LocalContext context){
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
IxCode.TypeRef leftType = left.type(), rightType = right.type();
if(
(left.isBasicType() && (!right.isBasicType())) ||
((!left.isBasicType()) && (right.isBasicType()))
){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}}
);
return null;
}
if(left.isBasicType() && right.isBasicType()){
if(hasNumericType(left) && hasNumericType(right)){
IxCode.TypeRef resultType = promote(leftType, rightType);
if(resultType != left.type()){
left = new IxCode.AsInstanceOf(left, resultType);
}
if(resultType != right.type()){
right = new IxCode.AsInstanceOf(right, resultType);
}
}else if(leftType != IxCode.BasicTypeRef.BOOLEAN || rightType != IxCode.BasicTypeRef.BOOLEAN){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}}
);
return null;
}
}else if(left.isReferenceType() && right.isReferenceType()){
return createEquals(kind, left, right);
}
return new IxCode.BinaryExpression(kind, IxCode.BasicTypeRef.BOOLEAN, left, right);
}
IxCode.Expression createEquals(int kind, IxCode.Expression left, IxCode.Expression right){
right = new IxCode.AsInstanceOf(right, rootClass());
IxCode.Expression[] params = {right};
IxCode.ObjectTypeRef target = (IxCode.ObjectTypeRef) left.type();
IxCode.MethodRef[] methods = target.findMethod("equals", params);
IxCode.Expression node = new IxCode.Call(left, methods[0], params);
if(kind == IxCode.BinaryExpression.Constants.NOT_EQUAL){
node = new IxCode.UnaryExpression(NOT, IxCode.BasicTypeRef.BOOLEAN, node);
}
return node;
}
IxCode.Expression[] processComparableExpression(onion.lang.syntax.BinaryExpression ast, LocalContext context) {
IxCode.Expression left = typeCheck(ast.getLeft(), context);
IxCode.Expression right = typeCheck(ast.getRight(), context);
if(left == null || right == null) return null;
IxCode.TypeRef leftType = left.type(), rightType = right.type();
if((!numeric(left.type())) || (!numeric(right.type()))){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}});
return null;
}
IxCode.TypeRef resultType = promote(leftType, rightType);
if(leftType != resultType){
left = new IxCode.AsInstanceOf(left, resultType);
}
if(rightType != resultType){
right = new IxCode.AsInstanceOf(right, resultType);
}
return new IxCode.Expression[]{left, right};
}
public Object visit(onion.lang.syntax.FloatLiteral ast, LocalContext context) {
return new IxCode.FloatLiteral(ast.getValue());
}
public Object visit(SuperMethodCall ast, LocalContext context) {
IxCode.Expression[] params;
params = typeCheckExps(ast.getParams(), context);
if(params == null) return null;
IxCode.ClassTypeRef contextClass = getContextClass();
Pair<Boolean, IxCode.MethodRef> result = tryFindMethod(ast, contextClass.getSuperClass(), ast.getName(), params);
if(result._2 == null){
if(result._1){
report(
METHOD_NOT_FOUND, ast,
new Object[]{contextClass, ast.getName(), types(params)});
}
return null;
}
return new IxCode.CallSuper(new IxCode.This(contextClass), result._2, params);
}
public Object visit(onion.lang.syntax.DoubleLiteral ast, LocalContext context) {
return new IxCode.DoubleLiteral(ast.getValue());
}
public Object visit(IntegerLiteral node, LocalContext context) {
return new IxCode.IntLiteral(node.getValue());
}
public Object visit(onion.lang.syntax.CharacterLiteral node, LocalContext context) {
return new IxCode.CharacterLiteral(node.getValue());
}
public Object visit(onion.lang.syntax.LongLiteral ast, LocalContext context) {
return new IxCode.LongLiteral(ast.getValue());
}
public Object visit(BooleanLiteral ast, LocalContext context) {
return new IxCode.BoolLiteral(ast.getValue());
}
public Object visit(onion.lang.syntax.ListLiteral ast, LocalContext context) {
IxCode.Expression[] elements = new IxCode.Expression[ast.size()];
for(int i = 0; i < ast.size(); i++){
elements[i] = typeCheck(ast.getExpression(i), context);
}
IxCode.ListLiteral node = new IxCode.ListLiteral(elements, load("java.util.List"));
return node;
}
public Object visit(onion.lang.syntax.StringLiteral ast, LocalContext context) {
return new IxCode.StringLiteral(ast.getValue(), load("java.lang.String"));
}
public Object visit(onion.lang.syntax.NullLiteral ast, LocalContext context) {
return new IxCode.NullLiteral();
}
public Object visit(Posit ast, LocalContext context) {
IxCode.Expression node = typeCheck(ast.getTarget(), context);
if(node == null) return null;
if(!hasNumericType(node)){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{"+", new IxCode.TypeRef[]{node.type()}});
return null;
}
node = new IxCode.UnaryExpression(PLUS, node.type(), node);
return node;
}
public Object visit(Negate ast, LocalContext context) {
IxCode.Expression node = typeCheck(ast.getTarget(), context);
if(node == null) return null;
if(!hasNumericType(node)){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{"-", new IxCode.TypeRef[]{node.type()}}
);
return null;
}
node = new IxCode.UnaryExpression(MINUS, node.type(), node);
return node;
}
public Object visit(Not ast, LocalContext context) {
IxCode.Expression node = typeCheck(ast.getTarget(), context);
if(node == null) return null;
if(node.type() != IxCode.BasicTypeRef.BOOLEAN){
report(
INCOMPATIBLE_OPERAND_TYPE, ast,
new Object[]{"!", new IxCode.TypeRef[]{node.type()}});
return null;
}
node = new IxCode.UnaryExpression(NOT, IxCode.BasicTypeRef.BOOLEAN, node);
return node;
}
public Object visit(Assignment ast, LocalContext context) {
onion.lang.syntax.Expression left = ast.getLeft();
if(left instanceof Id){
return processLocalAssign(ast, context);
}else if(left instanceof SelfFieldReference){
return processSelfFieldAssign(ast, context);
}else if(left instanceof Indexing){
return processArrayAssign(ast, context);
}else if(left instanceof FieldOrMethodRef){
return processFieldOrMethodAssign(ast, context);
}
return null;
}
private IxCode.Expression processLocalAssign(Assignment ast, LocalContext context){
IxCode.Expression value = typeCheck(ast.getRight(), context);
if(value == null) return null;
Id id = (Id) ast.getLeft();
LocalContext local = ((LocalContext)context);
ClosureLocalBinding bind = local.lookup(id.getName());
int frame, index;
IxCode.TypeRef leftType, rightType = value.type();
if(bind != null){
frame = bind.getFrame();
index = bind.getIndex();
leftType = bind.getType();
}else{
frame = 0;
if(rightType.isNullType()){
leftType = rootClass();
}else{
leftType = rightType;
}
index = local.addEntry(id.getName(), leftType);
}
value = processAssignable(ast.getRight(), leftType, value);
if(value == null) return null;
return new IxCode.SetLocal(frame, index, leftType, value);
}
private Object processSelfFieldAssign(Assignment ast, LocalContext context){
IxCode.Expression value = typeCheck(ast.getRight(), context);
if(value == null) return null;
SelfFieldReference ref = (SelfFieldReference) ast.getLeft();
LocalContext local = context;
IxCode.ClassTypeRef selfClass;
if(local.isGlobal()){
selfClass = loadTopClass();
}else {
if(local.getMethod() != null){
selfClass = local.getMethod().affiliation();
}else{
selfClass = local.getConstructor().affiliation();
}
}
IxCode.FieldRef field = findField(selfClass, ref.getName());
if(field == null){
report(FIELD_NOT_FOUND, ref, new Object[]{selfClass, ref.getName()});
return null;
}
if(!isAccessible(field, selfClass)){
report(
FIELD_NOT_ACCESSIBLE, ast,
new Object[]{field.affiliation(), field.name(), selfClass});
return null;
}
value = processAssignable(ast.getRight(), field.getType(), value);
if(value == null) return null;
return new IxCode.SetField(new IxCode.This(selfClass), field, value);
}
Object processArrayAssign(Assignment ast, LocalContext context){
IxCode.Expression value = typeCheck(ast.getRight(), context);
Indexing indexing = (Indexing) ast.getLeft();
IxCode.Expression target = typeCheck(indexing.getLeft(), context);
IxCode.Expression index = typeCheck(indexing.getRight(), context);
if(value == null || target == null || index == null) return null;
if(target.isBasicType()){
report(
INCOMPATIBLE_TYPE,
indexing.getLeft(), new Object[]{rootClass(), target.type()});
return null;
}
if(target.isArrayType()){
IxCode.ArrayTypeRef targetType = ((IxCode.ArrayTypeRef)target.type());
if(!(index.isBasicType() && ((IxCode.BasicTypeRef)index.type()).isInteger())){
report(
INCOMPATIBLE_TYPE,
indexing.getRight(), new Object[]{IxCode.BasicTypeRef.INT, index.type()});
return null;
}
IxCode.TypeRef base = targetType.getBase();
value = processAssignable(ast.getRight(), base, value);
if(value == null) return null;
return new IxCode.ArraySet(target, index, value);
}
IxCode.Expression[] params;
params = new IxCode.Expression[]{index, value};
Pair<Boolean, IxCode.MethodRef> result = tryFindMethod(ast, (IxCode.ObjectTypeRef)target.type(), "set", new IxCode.Expression[]{index, value});
if(result._2 == null){
report(
METHOD_NOT_FOUND, ast,
new Object[]{target.type(), "set", types(params)});
return null;
}
return new IxCode.Call(target, result._2, params);
}
Object processFieldOrMethodAssign(Assignment ast, LocalContext context){
IxCode.Expression right = typeCheck(ast.getRight(), context);
report(UNIMPLEMENTED_FEATURE, ast, new Object[0]);
return null;
}
public Object visit(AdditionAssignment ast, LocalContext context) {
IxCode.Expression right = typeCheck(ast.getRight(), context);
report(UNIMPLEMENTED_FEATURE, ast, new Object[0]);
return null;
}
public Object visit(SubtractionAssignment ast, LocalContext context) {
IxCode.Expression right = typeCheck(ast.getRight(), context);
report(UNIMPLEMENTED_FEATURE, ast, new Object[0]);
return null;
}
public Object visit(MultiplicationAssignment ast, LocalContext context) {
IxCode.Expression right = typeCheck(ast.getRight(), context);
report(UNIMPLEMENTED_FEATURE, ast, new Object[0]);
return null;
}
public Object visit(DivisionAssignment ast, LocalContext context) {
IxCode.Expression right = typeCheck(ast.getRight(), context);
report(UNIMPLEMENTED_FEATURE, ast, new Object[0]);
return null;
}
public Object visit(ModuloAssignment ast, LocalContext context) {
IxCode.Expression right = typeCheck(ast.getRight(), context);
report(UNIMPLEMENTED_FEATURE, ast, new Object[0]);
return null;
}
public Object visit(Id ast, LocalContext context) {
LocalContext local = context;
ClosureLocalBinding bind = local.lookup(ast.getName());
if(bind == null){
report(VARIABLE_NOT_FOUND, ast, new Object[]{ast.getName()});
return null;
}
return new IxCode.RefLocal(bind);
}
IxCode.MethodRef findMethod(AstNode ast, IxCode.ObjectTypeRef type, String name) {
IxCode.Expression[] params = new IxCode.Expression[0];
IxCode.MethodRef[] methods = type.findMethod(name, params);
if(methods.length == 0){
report(
METHOD_NOT_FOUND, ast,
new Object[]{type, name, types(params)});
return null;
}
return methods[0];
}
IxCode.MethodRef findMethod(
AstNode ast, IxCode.ObjectTypeRef type, String name, IxCode.Expression[] params
) {
IxCode.MethodRef[] methods = type.findMethod(name, params);
return methods[0];
}
public Object visit(CurrentInstance ast, LocalContext context) {
LocalContext local = context;
if(local.isStatic()) return null;
IxCode.ClassTypeRef selfClass = getContextClass();
return new IxCode.This(selfClass);
}
boolean hasSamePackage(IxCode.ClassTypeRef a, IxCode.ClassTypeRef b) {
String name1 = a.name();
String name2 = b.name();
int index;
index = name1.lastIndexOf(".");
if(index >= 0){
name1 = name1.substring(0, index);
}else{
name1 = "";
}
index = name2.lastIndexOf(".");
if(index >= 0){
name2 = name2.substring(0, index);
}else{
name2 = "";
}
return name1.equals(name2);
}
boolean isAccessible(IxCode.ClassTypeRef target, IxCode.ClassTypeRef context) {
if(hasSamePackage(target, context)){
return true;
}else{
if(Modifier.isInternal(target.getModifier())){
return false;
}else{
return true;
}
}
}
boolean isAccessible(IxCode.MemberRef member, IxCode.ClassTypeRef context) {
IxCode.ClassTypeRef targetType = member.affiliation();
if(targetType == context) return true;
int modifier = member.modifier();
if(IxCode.TypeRules.isSuperType(targetType, context)){
if(Modifier.isProtected(modifier) || Modifier.isPublic(modifier)){
return true;
}else{
return false;
}
}else{
if(Modifier.isPublic(modifier)){
return true;
}else{
return false;
}
}
}
private IxCode.FieldRef findField(IxCode.ObjectTypeRef target, String name) {
if(target == null) return null;
IxCode.FieldRef[] fields = target.getFields();
for (int i = 0; i < fields.length; i++) {
if(fields[i].name().equals(name)){
return fields[i];
}
}
IxCode.FieldRef field = findField(target.getSuperClass(), name);
if(field != null) return field;
IxCode.ClassTypeRef[] interfaces = target.getInterfaces();
for(int i = 0; i < interfaces.length; i++){
field = findField(interfaces[i], name);
if(field != null) return field;
}
return null;
}
private boolean checkAccessible(
AstNode ast, IxCode.ObjectTypeRef target, IxCode.ClassTypeRef context
) {
if(target.isArrayType()){
IxCode.TypeRef component = ((IxCode.ArrayTypeRef)target).getComponent();
if(!component.isBasicType()){
if(!isAccessible((IxCode.ClassTypeRef)component, getContextClass())){
report(CLASS_NOT_ACCESSIBLE, ast, new Object[]{target, context});
return false;
}
}
}else{
if(!isAccessible((IxCode.ClassTypeRef)target, context)){
report(CLASS_NOT_ACCESSIBLE, ast, new Object[]{target, context});
return false;
}
}
return true;
}
public Object visit(FieldOrMethodRef ast, LocalContext context) {
IxCode.ClassDefinition contextClass = getContextClass();
IxCode.Expression target = typeCheck(ast.getTarget(), context);
if(target == null) return null;
if(target.type().isBasicType() || target.type().isNullType()){
report(
INCOMPATIBLE_TYPE, ast.getTarget(),
new IxCode.TypeRef[]{rootClass(), target.type()});
return null;
}
IxCode.ObjectTypeRef targetType = (IxCode.ObjectTypeRef) target.type();
if(!checkAccessible(ast, targetType, contextClass)) return null;
String name = ast.getName();
if(target.type().isArrayType()){
if(name.equals("length") || name.equals("size")){
return new IxCode.ArrayLength(target);
}else{
return null;
}
}
IxCode.FieldRef field = findField(targetType, name);
if(field != null && isAccessible(field, getContextClass())){
return new IxCode.RefField(target, field);
}
Pair<Boolean, IxCode.MethodRef> result;
boolean continuable;
result = tryFindMethod(ast, targetType, name, new IxCode.Expression[0]);
if(result._2 != null){
return new IxCode.Call(target, result._2, new IxCode.Expression[0]);
}
continuable = result._1;
if(!continuable) return null;
String getterName;
getterName = getter(name);
result = tryFindMethod(ast, targetType, getterName, new IxCode.Expression[0]);
if(result._2 != null){
return new IxCode.Call(target, result._2, new IxCode.Expression[0]);
}
continuable = result._1;
if(!continuable) return null;
getterName = getterBoolean(name);
result = tryFindMethod(ast, targetType, getterName, new IxCode.Expression[0]);
if(result._2 != null){
return new IxCode.Call(target, result._2, new IxCode.Expression[0]);
}
if(field == null){
report(FIELD_NOT_FOUND, ast, new Object[]{targetType, ast.getName()});
}else{
report(
FIELD_NOT_ACCESSIBLE, ast,
new Object[]{targetType, ast.getName(), getContextClass()});
}
return null;
}
private Pair<Boolean, IxCode.MethodRef> tryFindMethod(
AstNode ast, IxCode.ObjectTypeRef target, String name, IxCode.Expression[] params
) {
IxCode.MethodRef[] methods;
methods = target.findMethod(name, params);
if(methods.length > 0){
if(methods.length > 1){
report(
AMBIGUOUS_METHOD, ast,
new Object[]{
new Object[]{
methods[0].affiliation(), name, methods[0].arguments()
},
new Object[]{
methods[1].affiliation(), name, methods[1].arguments()
}
});
return Pair.make(false, null);
}
if(!isAccessible(methods[0], getContextClass())){
report(
METHOD_NOT_ACCESSIBLE, ast,
new Object[]{
methods[0].affiliation(), name, methods[0].arguments(),
getContextClass()
}
);
return Pair.make(false, null);
}
return Pair.make(false, methods[0]);
}
return Pair.make(true, null);
}
private String getter(String name) {
return "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
private String getterBoolean(String name) {
return "is" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
private String setter(String name) {
return "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
public Object visit(Argument ast, LocalContext context) {
LocalContext local = ((LocalContext)context);
String name = ast.getName();
ClosureLocalBinding binding = local.lookupOnlyCurrentScope(name);
if(binding != null){
report(DUPLICATE_LOCAL_VARIABLE, ast, new Object[]{name});
return null;
}
IxCode.TypeRef type = resolve(ast.getType(), getSolver());
if(type == null) return null;
local.addEntry(name, type);
return type;
}
public Object visit(onion.lang.syntax.NewArray ast, LocalContext context) {
IxCode.TypeRef type = resolve(ast.getType(), getSolver());
IxCode.Expression[] parameters = typeCheckExps(ast.getArguments(), context);
if(type == null || parameters == null) return null;
IxCode.ArrayTypeRef resultType = loadArray(type, parameters.length);
return new IxCode.NewArray(resultType, parameters);
}
public Object visit(Cast ast, LocalContext context) {
IxCode.Expression node = typeCheck(ast.getTarget(), context);
if(node == null) return null;
IxCode.TypeRef conversion = resolve(ast.getType(), getSolver());
if(conversion == null) return null;
node = new IxCode.AsInstanceOf(node, conversion);
return node;
}
public boolean equals(IxCode.TypeRef[] types1, IxCode.TypeRef[] types2) {
if(types1.length != types2.length) return false;
for(int i = 0; i < types1.length; i++){
if(types1[i] != types2[i]) return false;
}
return true;
}
public Object visit(ClosureExpression ast, LocalContext context) {
LocalContext local = ((LocalContext)context);
IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) CodeAnalysis.this.resolve(ast.getType());
Argument[] args = ast.getArguments();
IxCode.TypeRef[] argTypes = new IxCode.TypeRef[args.length];
String name = ast.getName();
try {
local.openFrame();
boolean error = false;
for(int i = 0; i < args.length; i++){
argTypes[i] = (IxCode.TypeRef)accept(args[i], context);
if(argTypes[i] == null){
error = true;
}
}
if(type == null) return null;
if(!type.isInterface()){
report(INTERFACE_REQUIRED, ast.getType(), new Object[]{type});
return null;
}
if(error) return null;
IxCode.MethodRef[] methods = type.getMethods();
IxCode.MethodRef method = null;
for(int i = 0; i < methods.length; i++){
IxCode.TypeRef[] types = methods[i].arguments();
if(name.equals(methods[i].name()) && equals(argTypes, types)){
method = methods[i];
break;
}
}
if(method == null){
report(METHOD_NOT_FOUND, ast, new Object[]{type, name, argTypes});
return null;
}
local.setMethod(method);
local.getContextFrame().getParent().setAllClosed(true);
IxCode.ActionStatement block = translate(ast.getBlock(), context);
block = addReturnNode(block, method.returnType());
IxCode.NewClosure node = new IxCode.NewClosure(type, method, block);
node.setFrame(local.getContextFrame());
return node;
}finally{
local.closeFrame();
}
}
public Object visit(Indexing ast, LocalContext context) {
IxCode.Expression target = typeCheck(ast.getLeft(), context);
IxCode.Expression index = typeCheck(ast.getRight(), context);
if(target == null || index == null) return null;
if(target.isArrayType()){
if(!(index.isBasicType() && ((IxCode.BasicTypeRef)index.type()).isInteger())){
report(
INCOMPATIBLE_TYPE, ast, new Object[]{IxCode.BasicTypeRef.INT, index.type()});
return null;
}
return new IxCode.ArrayRef(target, index);
}
if(target.isBasicType()){
report(
INCOMPATIBLE_TYPE,
ast.getLeft(), new Object[]{rootClass(), target.type()});
return null;
}
if(target.isArrayType()){
if(!(index.isBasicType() && ((IxCode.BasicTypeRef)index.type()).isInteger())){
report(
INCOMPATIBLE_TYPE,
ast.getRight(), new Object[]{IxCode.BasicTypeRef.INT, index.type()}
);
return null;
}
return new IxCode.ArrayRef(target, index);
}
IxCode.Expression[] params = {index};
Pair<Boolean, IxCode.MethodRef> result = tryFindMethod(ast, (IxCode.ObjectTypeRef)target.type(), "get", new IxCode.Expression[]{index});
if(result._2 == null){
report(
METHOD_NOT_FOUND, ast,
new Object[]{target.type(), "get", types(params)});
return null;
}
return new IxCode.Call(target, result._2, params);
}
public Object visit(SelfFieldReference ast, LocalContext context) {
LocalContext local = context;
IxCode.ClassTypeRef selfClass = null;
if(local.isStatic()) return null;
selfClass = getContextClass();
IxCode.FieldRef field = findField(selfClass, ast.getName());
if(field == null){
report(FIELD_NOT_FOUND, ast, new Object[]{selfClass, ast.getName()});
return null;
}
if(!isAccessible(field, selfClass)){
report(
FIELD_NOT_ACCESSIBLE, ast,
new Object[]{field.affiliation(), ast.getName(), selfClass});
return null;
}
return new IxCode.RefField(new IxCode.This(selfClass), field);
}
public Object visit(onion.lang.syntax.NewObject ast, LocalContext context) {
IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) CodeAnalysis.this.resolve(ast.getType());
IxCode.Expression[] parameters = typeCheckExps(ast.getArguments(), context);
if(parameters == null || type == null) return null;
IxCode.ConstructorRef[] constructors = type.findConstructor(parameters);
if(constructors.length == 0){
report(CONSTRUCTOR_NOT_FOUND, ast, new Object[]{type, types(parameters)});
return null;
}
if(constructors.length > 1){
report(
AMBIGUOUS_CONSTRUCTOR, ast,
new Object[]{
new Object[]{
constructors[0].affiliation(),
constructors[0].getArgs()
},
new Object[]{
constructors[1].affiliation(),
constructors[1].getArgs()
}
});
return null;
}
return new IxCode.NewObject(constructors[0], parameters);
}
public Object visit(IsInstance ast, LocalContext context) {
IxCode.Expression target = typeCheck(ast.getTarget(), context);
IxCode.TypeRef checkType = resolve(ast.getType(), getSolver());
if(target == null || checkType == null) return null;
return new IxCode.InstanceOf(target, checkType);
}
private IxCode.TypeRef[] types(IxCode.Expression[] parameters){
IxCode.TypeRef[] types = new IxCode.TypeRef[parameters.length];
for(int i = 0; i < types.length; i++){
types[i] = parameters[i].type();
}
return types;
}
public Object visit(SelfMethodCall ast, LocalContext context) {
IxCode.Expression[] params = typeCheckExps(ast.getArguments(), context);
if(params == null) return null;
IxCode.ClassDefinition targetType = getContextClass();
String name = ast.getName();
IxCode.MethodRef[] methods = targetType.findMethod(ast.getName(), params);
if(methods.length == 0){
report(
METHOD_NOT_FOUND, ast,
new Object[]{targetType, name, types(params)});
return null;
}
if(methods.length > 1){
report(
AMBIGUOUS_METHOD, ast,
new Object[]{
new Object[]{
methods[0].affiliation(), name, methods[0].arguments()
},
new Object[]{
methods[1].affiliation(), name, methods[1].arguments()
}
});
return null;
}
params = convert(methods[0].arguments(), params);
if((methods[0].modifier() & Modifier.STATIC) != 0){
return new IxCode.CallStatic(targetType, methods[0], params);
}else {
return new IxCode.Call(new IxCode.This(targetType), methods[0], params);
}
}
private IxCode.Expression[] convert(IxCode.TypeRef[] arguments, IxCode.Expression[] params){
for(int i = 0; i < params.length; i++){
if(arguments[i] != params[i].type()){
params[i] = new IxCode.AsInstanceOf(params[i], arguments[i]);
}
}
return params;
}
public Object visit(MethodCall ast, LocalContext context) {
IxCode.Expression target = typeCheck(ast.getTarget(), context);
if(target == null) return null;
IxCode.Expression[] params = typeCheckExps(ast.getArguments(), context);
if(params == null) return null;
IxCode.ObjectTypeRef targetType = (IxCode.ObjectTypeRef) target.type();
final String name = ast.getName();
IxCode.MethodRef[] methods = targetType.findMethod(name, params);
if(methods.length == 0){
report(
METHOD_NOT_FOUND, ast, new Object[]{targetType, name, types(params)});
return null;
}
if(methods.length > 1){
report(
AMBIGUOUS_METHOD, ast,
new Object[]{
new Object[]{
methods[0].affiliation(), name, methods[0].arguments()
},
new Object[]{
methods[1].affiliation(), name, methods[1].arguments()
}
});
return null;
}
if((methods[0].modifier() & Modifier.STATIC) != 0){
report(
ILLEGAL_METHOD_CALL, ast,
new Object[]{
methods[0].affiliation(), name, methods[0].arguments()
});
return null;
}
params = convert(methods[0].arguments(), params);
return new IxCode.Call(target, methods[0], params);
}
public Object visit(StaticIDExpression ast, LocalContext context) {
IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) CodeAnalysis.this.resolve(ast.getType());
if(type == null) return null;
IxCode.FieldRef field = findField(type, ast.getName());
if(field == null){
report(FIELD_NOT_FOUND, ast, new Object[]{type, ast.getName()});
return null;
}
return new IxCode.StaticFieldRef(type, field);
}
public Object visit(StaticMethodCall ast, LocalContext context) {
IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) CodeAnalysis.this.resolve(ast.getTarget());
IxCode.Expression[] params = typeCheckExps(ast.getArgs(), context);
if(type == null) return null;
if(params == null) return null;
IxCode.MethodRef[] methods = type.findMethod(ast.getName(), params);
if(methods.length == 0){
report(
METHOD_NOT_FOUND, ast,
new Object[]{type, ast.getName(), types(params)});
return null;
}
if(methods.length > 1){
report(
AMBIGUOUS_METHOD, ast,
new Object[]{
ast.getName(),
typeNames(methods[0].arguments()), typeNames(methods[1].arguments())
});
return null;
}
params = convert(methods[0].arguments(), params);
return new IxCode.CallStatic(type, methods[0], params);
}
private String[] typeNames(IxCode.TypeRef[] types) {
String[] names = new String[types.length];
for(int i = 0; i < names.length; i++){
names[i] = types[i].name();
}
return names;
}
private IxCode.Expression[] typeCheckExps(onion.lang.syntax.Expression[] ast, LocalContext context){
IxCode.Expression[] expressions = new IxCode.Expression[ast.length];
boolean success = true;
for(int i = 0; i < ast.length; i++){
expressions[i] = typeCheck(ast[i], context);
if(expressions[i] == null){
success = false;
}
}
if(success){
return expressions;
}else{
return null;
}
}
public Object visit(ForeachStatement ast, LocalContext context) {
onion.lang.syntax.Expression collectionAST = ast.getCollection();
LocalContext local = context;
try {
local.openScope();
IxCode.Expression collection = typeCheck(collectionAST, context);
Argument arg = ast.getDeclaration();
accept(arg, context);
ClosureLocalBinding bind = local.lookupOnlyCurrentScope(arg.getName());
IxCode.ActionStatement block = translate(ast.getStatement(), context);
if(collection.isBasicType()){
report(
INCOMPATIBLE_TYPE, collectionAST,
new Object[]{load("java.util.Collection"), collection.type()});
return null;
}
ClosureLocalBinding bind2 = new ClosureLocalBinding(
0, local.addEntry(local.newName(), collection.type()), collection.type());
IxCode.ActionStatement init =
new IxCode.ExpressionStatement(new IxCode.SetLocal(bind2, collection));
if(collection.isArrayType()){
ClosureLocalBinding bind3 = new ClosureLocalBinding(
0, local.addEntry(local.newName(), IxCode.BasicTypeRef.INT), IxCode.BasicTypeRef.INT
);
init = new IxCode.StatementBlock(init, new IxCode.ExpressionStatement(new IxCode.SetLocal(bind3, new IxCode.IntLiteral(0))));
block = new IxCode.ConditionalLoop(
new IxCode.BinaryExpression(
LESS_THAN, IxCode.BasicTypeRef.BOOLEAN,
ref(bind3),
new IxCode.ArrayLength(ref(bind2))
),
new IxCode.StatementBlock(
assign(bind, indexref(bind2, ref(bind3))),
block,
assign(
bind3,
new IxCode.BinaryExpression(ADD, IxCode.BasicTypeRef.INT, ref(bind3), new IxCode.IntLiteral(1))
)
)
);
return new IxCode.StatementBlock(init, block);
}else{
IxCode.ObjectTypeRef iterator = load("java.util.Iterator");
ClosureLocalBinding bind3 = new ClosureLocalBinding(
0, local.addEntry(local.newName(), iterator), iterator
);
IxCode.MethodRef mIterator, mNext, mHasNext;
mIterator = findMethod(collectionAST, (IxCode.ObjectTypeRef) collection.type(), "iterator");
mNext = findMethod(ast.getCollection(), iterator, "next");
mHasNext = findMethod(ast.getCollection(), iterator, "hasNext");
init = new IxCode.StatementBlock(
init,
assign(bind3, new IxCode.Call(ref(bind2), mIterator, new IxCode.Expression[0]))
);
IxCode.Expression callNext = new IxCode.Call(
ref(bind3), mNext, new IxCode.Expression[0]
);
if(bind.getType() != rootClass()){
callNext = new IxCode.AsInstanceOf(callNext, bind.getType());
}
block = new IxCode.ConditionalLoop(
new IxCode.Call(ref(bind3), mHasNext, new IxCode.Expression[0]),
new IxCode.StatementBlock(assign(bind, callNext), block)
);
return new IxCode.StatementBlock(init, block);
}
}finally{
local.closeScope();
}
}
private IxCode.Expression indexref(ClosureLocalBinding bind, IxCode.Expression value) {
return new IxCode.ArrayRef(new IxCode.RefLocal(bind), value);
}
private IxCode.ActionStatement assign(ClosureLocalBinding bind, IxCode.Expression value) {
return new IxCode.ExpressionStatement(new IxCode.SetLocal(bind, value));
}
private IxCode.Expression ref(ClosureLocalBinding bind) {
return new IxCode.RefLocal(bind);
}
public Object visit(onion.lang.syntax.ExpressionStatement ast, LocalContext context) {
IxCode.Expression expression = typeCheck(ast.getExpression(), context);
return new IxCode.ExpressionStatement(expression);
}
public Object visit(CondStatement node, LocalContext context) {
LocalContext local = context;
try {
local.openScope();
int size = node.size();
Stack exprs = new Stack();
Stack stmts = new Stack();
for(int i = 0; i < size; i++){
onion.lang.syntax.Expression expr = node.getCondition(i);
Statement stmt = node.getBlock(i);
IxCode.Expression texpr = typeCheck(expr, context);
if(texpr != null && texpr.type() != IxCode.BasicTypeRef.BOOLEAN){
IxCode.TypeRef expect = IxCode.BasicTypeRef.BOOLEAN;
IxCode.TypeRef actual = texpr.type();
report(INCOMPATIBLE_TYPE, expr, new Object[]{expect, actual});
}
exprs.push(texpr);
IxCode.ActionStatement tstmt = translate(stmt, context);
stmts.push(tstmt);
}
Statement elseStmt = node.getElseBlock();
IxCode.ActionStatement result = null;
if(elseStmt != null){
result = translate(elseStmt, context);
}
for(int i = 0; i < size; i++){
IxCode.Expression expr = (IxCode.Expression)exprs.pop();
IxCode.ActionStatement stmt = (IxCode.ActionStatement)stmts.pop();
result = new IxCode.IfStatement(expr, stmt, result);
}
return result;
}finally{
local.closeScope();
}
}
public Object visit(ForStatement ast, LocalContext context) {
LocalContext local = context;
try{
local.openScope();
IxCode.ActionStatement init = null;
if(ast.getInit() != null){
init = translate(ast.getInit(), context);
}else{
init = new IxCode.NOP();
}
IxCode.Expression condition;
onion.lang.syntax.Expression astCondition = ast.getCondition();
if(astCondition != null){
condition = typeCheck(ast.getCondition(), context);
IxCode.TypeRef expected = IxCode.BasicTypeRef.BOOLEAN;
if(condition != null && condition.type() != expected){
IxCode.TypeRef appeared = condition.type();
report(INCOMPATIBLE_TYPE, astCondition, new Object[]{expected, appeared});
}
}else{
condition = new IxCode.BoolLiteral(true);
}
IxCode.Expression update = null;
if(ast.getUpdate() != null){
update = typeCheck(ast.getUpdate(), context);
}
IxCode.ActionStatement loop = translate(
ast.getBlock(), context);
if(update != null){
loop = new IxCode.StatementBlock(loop, new IxCode.ExpressionStatement(update));
}
IxCode.ActionStatement result = new IxCode.ConditionalLoop(condition, loop);
result = new IxCode.StatementBlock(init, result);
return result;
}finally{
local.closeScope();
}
}
public Object visit(BlockStatement ast, LocalContext context) {
Statement[] astStatements = ast.getStatements();
IxCode.ActionStatement[] statements = new IxCode.ActionStatement[astStatements.length];
LocalContext local = context;
try{
local.openScope();
for(int i = 0; i < astStatements.length; i++){
statements[i] = translate(astStatements[i], context);
}
return new IxCode.StatementBlock(statements);
}finally{
local.closeScope();
}
}
public Object visit(onion.lang.syntax.IfStatement ast, LocalContext context) {
LocalContext local = ((LocalContext)context);
try{
local.openScope();
IxCode.Expression condition = typeCheck(ast.getCondition(), context);
IxCode.TypeRef expected = IxCode.BasicTypeRef.BOOLEAN;
if(condition != null && condition.type() != expected){
report(INCOMPATIBLE_TYPE, ast.getCondition(), new Object[]{expected, condition.type()});
}
IxCode.ActionStatement thenBlock = translate(ast.getThenBlock(), context);
IxCode.ActionStatement elseBlock = ast.getElseBlock() == null ? null : translate(ast.getElseBlock(), context);
return new IxCode.IfStatement(condition, thenBlock, elseBlock);
}finally{
local.closeScope();
}
}
public Object visit(WhileStatement ast, LocalContext context) {
LocalContext local = ((LocalContext)context);
try{
local.openScope();
IxCode.Expression condition = typeCheck(ast.getCondition(), context);
IxCode.TypeRef expected = IxCode.BasicTypeRef.BOOLEAN;
if(condition != null && condition.type() != expected){
IxCode.TypeRef actual = condition.type();
report(INCOMPATIBLE_TYPE, ast, new Object[]{expected, actual});
}
IxCode.ActionStatement thenBlock = translate(ast.getBlock(), context);
return new IxCode.ConditionalLoop(condition, thenBlock);
}finally{
local.closeScope();
}
}
public Object visit(ReturnStatement ast, LocalContext context) {
IxCode.TypeRef returnType = ((LocalContext)context).getReturnType();
if(ast.getExpression() == null){
IxCode.TypeRef expected = IxCode.BasicTypeRef.VOID;
if(returnType != expected){
report(CANNOT_RETURN_VALUE, ast, new Object[0]);
}
return new IxCode.Return(null);
}else{
IxCode.Expression returned = typeCheck(ast.getExpression(), context);
if(returned == null) return new IxCode.Return(null);
if(returned.type() == IxCode.BasicTypeRef.VOID){
report(CANNOT_RETURN_VALUE, ast, new Object[0]);
}else {
returned = processAssignable(ast.getExpression(), returnType, returned);
if(returned == null) return new IxCode.Return(null);
}
return new IxCode.Return(returned);
}
}
IxCode.Expression processAssignable(AstNode ast, IxCode.TypeRef a, IxCode.Expression b){
if(b == null) return null;
if(a == b.type()) return b;
if(!IxCode.TypeRules.isAssignable(a, b.type())){
report(INCOMPATIBLE_TYPE, ast, new Object[]{ a, b.type() });
return null;
}
b = new IxCode.AsInstanceOf(b, a);
return b;
}
public Object visit(SelectStatement ast, LocalContext context) {
LocalContext local = context;
try{
local.openScope();
IxCode.Expression condition = typeCheck(ast.getCondition(), context);
if(condition == null){
return new IxCode.NOP();
}
String name = local.newName();
int index = local.addEntry(name, condition.type());
IxCode.ActionStatement statement;
if(ast.getCases().length == 0){
if(ast.getElseBlock() != null){
statement = translate(ast.getElseBlock(), context);
}else{
statement = new IxCode.NOP();
}
}else{
statement = processCases(ast, condition, name, context);
}
IxCode.StatementBlock block = new IxCode.StatementBlock(
new IxCode.ExpressionStatement(new IxCode.SetLocal(0, index, condition.type(), condition)),
statement
);
return block;
}finally{
local.closeScope();
}
}
IxCode.ActionStatement processCases(
SelectStatement ast, IxCode.Expression cond, String var, LocalContext context
) {
CaseBranch[] cases = ast.getCases();
List nodes = new ArrayList();
List thens = new ArrayList();
for(int i = 0; i < cases.length; i++){
onion.lang.syntax.Expression[] astExpressions = cases[i].getExpressions();
ClosureLocalBinding bind = context.lookup(var);
nodes.add(processNodes(astExpressions, cond.type(), bind, context));
thens.add(translate(cases[i].getBlock(), context));
}
IxCode.ActionStatement statement;
if(ast.getElseBlock() != null){
statement = translate(ast.getElseBlock(), context);
}else{
statement = null;
}
for(int i = cases.length - 1; i >= 0; i
IxCode.Expression value = (IxCode.Expression) nodes.get(i);
IxCode.ActionStatement then = (IxCode.ActionStatement) thens.get(i);
statement = new IxCode.IfStatement(value, then, statement);
}
return statement;
}
IxCode.Expression processNodes(
onion.lang.syntax.Expression[] asts, IxCode.TypeRef type, ClosureLocalBinding bind, LocalContext context
) {
IxCode.Expression[] nodes = new IxCode.Expression[asts.length];
boolean error = false;
for(int i = 0; i < asts.length; i++){
nodes[i] = typeCheck(asts[i], context);
if(nodes[i] == null){
error = true;
continue;
}
if(!IxCode.TypeRules.isAssignable(type, nodes[i].type())){
report(INCOMPATIBLE_TYPE, asts[i], new IxCode.TypeRef[]{type, nodes[i].type()});
error = true;
continue;
}
if(nodes[i].isBasicType() && nodes[i].type() != type){
nodes[i] = new IxCode.AsInstanceOf(nodes[i], type);
}
if(nodes[i].isReferenceType() && nodes[i].type() != rootClass()){
nodes[i] = new IxCode.AsInstanceOf(nodes[i], rootClass());
}
}
if(!error){
IxCode.Expression node;
if(nodes[0].isReferenceType()){
node = createEquals(IxCode.BinaryExpression.Constants.EQUAL, new IxCode.RefLocal(bind), nodes[0]);
}else{
node = new IxCode.BinaryExpression(EQUAL, IxCode.BasicTypeRef.BOOLEAN, new IxCode.RefLocal(bind), nodes[0]);
}
for(int i = 1; i < nodes.length; i++){
node = new IxCode.BinaryExpression(
LOGICAL_OR, IxCode.BasicTypeRef.BOOLEAN, node,
new IxCode.BinaryExpression(EQUAL, IxCode.BasicTypeRef.BOOLEAN, new IxCode.RefLocal(bind), nodes[i])
);
}
return node;
}else{
return null;
}
}
public Object visit(ThrowStatement ast, LocalContext context) {
IxCode.Expression expression = typeCheck(ast.getExpression(), context);
if(expression != null){
IxCode.TypeRef expected = load("java.lang.Throwable");
IxCode.TypeRef detected = expression.type();
if(!IxCode.TypeRules.isSuperType(expected, detected)){
report(
INCOMPATIBLE_TYPE, ast.getExpression(),
new Object[]{ expected, detected}
);
}
}
return new IxCode.Throw(expression);
}
public Object visit(LocalVariableDeclaration ast, LocalContext context) {
onion.lang.syntax.Expression initializer = ast.getInit();
LocalContext localContext = ((LocalContext)context);
ClosureLocalBinding
binding = localContext.lookupOnlyCurrentScope(ast.getName());
if(binding != null){
report(
DUPLICATE_LOCAL_VARIABLE, ast,
new Object[]{ast.getName()});
return new IxCode.NOP();
}
IxCode.TypeRef leftType = CodeAnalysis.this.resolve(ast.getType());
if(leftType == null) return new IxCode.NOP();
int index = localContext.addEntry(ast.getName(), leftType);
IxCode.SetLocal node;
if(initializer != null){
IxCode.Expression valueNode = typeCheck(initializer, context);
if(valueNode == null) return new IxCode.NOP();
valueNode = processAssignable(initializer, leftType, valueNode);
if(valueNode == null) return new IxCode.NOP();
node = new IxCode.SetLocal(0, index, leftType, valueNode);
}else{
node = new IxCode.SetLocal(0, index, leftType, defaultValue(leftType));
}
return new IxCode.ExpressionStatement(node);
}
public IxCode.Expression defaultValue(IxCode.TypeRef type) {
return IxCode.Expression.defaultValue(type);
}
public Object visit(EmptyStatement ast, LocalContext context) {
return new IxCode.NOP();
}
public Object visit(TryStatement ast, LocalContext context) {
LocalContext local = context;
IxCode.ActionStatement tryStatement = translate(ast.getTryBlock(), context);
ClosureLocalBinding[] binds = new ClosureLocalBinding[ast.getArguments().length];
IxCode.ActionStatement[] catchBlocks = new IxCode.ActionStatement[ast.getArguments().length];
for(int i = 0; i < ast.getArguments().length; i++){
local.openScope();
IxCode.TypeRef arg = (IxCode.TypeRef)accept(ast.getArguments()[i], context);
IxCode.TypeRef expected = load("java.lang.Throwable");
if(!IxCode.TypeRules.isSuperType(expected, arg)){
report(INCOMPATIBLE_TYPE, ast.getArguments()[i], new Object[]{expected, arg});
}
binds[i] = local.lookupOnlyCurrentScope(ast.getArguments()[i].getName());
catchBlocks[i] = translate(ast.getRecBlocks()[i], context);
local.closeScope();
}
return new IxCode.Try(tryStatement, binds, catchBlocks);
}
public Object visit(SynchronizedStatement ast, LocalContext context) {
IxCode.Expression lock = typeCheck(ast.getTarget(), context);
IxCode.ActionStatement block = translate(ast.getBlock(), context);
report(UNIMPLEMENTED_FEATURE, ast, new Object[0]);
return new IxCode.Synchronized(lock, block);
}
public Object visit(BreakStatement ast, LocalContext context) {
report(UNIMPLEMENTED_FEATURE, ast, new Object[0]);
return new IxCode.Break();
}
public Object visit(ContinueStatement ast, LocalContext context) {
report(UNIMPLEMENTED_FEATURE, ast, new Object[0]);
return new IxCode.Continue();
}
public Object visit(FunctionDeclaration ast, LocalContext context) {
IxCode.MethodDefinition function = (IxCode.MethodDefinition) lookupKernelNode(ast);
if(function == null) return null;
LocalContext local = new LocalContext();
if(Modifier.isStatic(function.modifier())){
local.setStatic(true);
}
local.setMethod(function);
IxCode.TypeRef[] arguments = function.arguments();
for(int i = 0; i < arguments.length; i++){
local.addEntry(ast.getArguments()[i].getName(), arguments[i]);
}
IxCode.StatementBlock block = (IxCode.StatementBlock) accept(ast.getBlock(), local);
block = addReturnNode(block, function.returnType());
function.setBlock(block);
function.setFrame(local.getContextFrame());
return null;
}
public IxCode.StatementBlock addReturnNode(IxCode.ActionStatement node, IxCode.TypeRef returnType) {
return new IxCode.StatementBlock(node, new IxCode.Return(defaultValue(returnType)));
}
public Object visit(GlobalVariableDeclaration ast, LocalContext context) {
return null;
}
public Object visit(FieldDeclaration ast, LocalContext context) {
return null;
}
public Object visit(DelegationDeclaration ast, LocalContext context) {
return null;
}
public Object visit(InterfaceMethodDeclaration ast, LocalContext context) {
return null;
}
public Object visit(MethodDeclaration ast, LocalContext context) {
IxCode.MethodDefinition method = (IxCode.MethodDefinition) lookupKernelNode(ast);
if(method == null) return null;
if(ast.getBlock() == null) return null;
LocalContext local = new LocalContext();
if(Modifier.isStatic(method.modifier())){
local.setStatic(true);
}
local.setMethod(method);
IxCode.TypeRef[] arguments = method.arguments();
for(int i = 0; i < arguments.length; i++){
local.addEntry(ast.getArguments()[i].getName(), arguments[i]);
}
IxCode.StatementBlock block = (IxCode.StatementBlock) accept(ast.getBlock(), local);
block = addReturnNode(block, method.returnType());
method.setBlock(block);
method.setFrame(local.getContextFrame());
return null;
}
public Object visit(ConstructorDeclaration ast, LocalContext context) {
IxCode.ConstructorDefinition constructor = (IxCode.ConstructorDefinition) lookupKernelNode(ast);
if(constructor == null) return null;
LocalContext local = new LocalContext();
local.setConstructor(constructor);
IxCode.TypeRef[] args = constructor.getArgs();
for(int i = 0; i < args.length; i++){
local.addEntry(ast.getArguments()[i].getName(), args[i]);
}
IxCode.Expression[] params = typeCheckExps(ast.getInitializers(), local);
IxCode.StatementBlock block = (IxCode.StatementBlock) accept(ast.getBody(), local);
IxCode.ClassDefinition currentClass = getContextClass();
IxCode.ClassTypeRef superClass = currentClass.getSuperClass();
IxCode.ConstructorRef[] matched = superClass.findConstructor(params);
if(matched.length == 0){
report(CONSTRUCTOR_NOT_FOUND, ast, new Object[]{superClass, types(params)});
return null;
}
if(matched.length > 1){
report(
AMBIGUOUS_CONSTRUCTOR, ast,
new Object[]{
new Object[]{superClass, types(params)},
new Object[]{superClass, types(params)}
});
return null;
}
IxCode.Super init = new IxCode.Super(
superClass, matched[0].getArgs(), params
);
constructor.setSuperInitializer(init);
block = addReturnNode(block, IxCode.BasicTypeRef.VOID);
constructor.setBlock(block);
constructor.setFrame(local.getContextFrame());
return null;
}
public IxCode.TypeRef resolve(TypeSpec type, NameResolution resolver) {
IxCode.TypeRef resolvedType = (IxCode.TypeRef) resolver.resolve(type);
if(resolvedType == null){
report(CLASS_NOT_FOUND, type, new Object[]{type.getComponentName()});
}
return resolvedType;
}
IxCode.TypeRef promote(IxCode.TypeRef left, IxCode.TypeRef right) {
if(!numeric(left) || !numeric(right)) return null;
if(left == IxCode.BasicTypeRef.DOUBLE || right == IxCode.BasicTypeRef.DOUBLE){
return IxCode.BasicTypeRef.DOUBLE;
}
if(left == IxCode.BasicTypeRef.FLOAT || right == IxCode.BasicTypeRef.FLOAT){
return IxCode.BasicTypeRef.FLOAT;
}
if(left == IxCode.BasicTypeRef.LONG || right == IxCode.BasicTypeRef.LONG){
return IxCode.BasicTypeRef.LONG;
}
return IxCode.BasicTypeRef.INT;
}
boolean hasNumericType(IxCode.Expression expression){
return numeric(expression.type());
}
boolean numeric(IxCode.TypeRef symbol){
return
(symbol.isBasicType()) &&
(symbol == IxCode.BasicTypeRef.BYTE ||
symbol == IxCode.BasicTypeRef.SHORT ||
symbol == IxCode.BasicTypeRef.CHAR ||
symbol == IxCode.BasicTypeRef.INT ||
symbol == IxCode.BasicTypeRef.LONG ||
symbol == IxCode.BasicTypeRef.FLOAT ||
symbol == IxCode.BasicTypeRef.DOUBLE
);
}
IxCode.Expression typeCheck(onion.lang.syntax.Expression expression, LocalContext context){
return (IxCode.Expression) expression.accept(this, context);
}
IxCode.ActionStatement translate(Statement statement, LocalContext context){
return (IxCode.ActionStatement) statement.accept(this, context);
}
}
public CodeAnalysis(CompilerConfig conf) {
this.conf = conf;
this.table = new ClassTable(classpath(this.conf.getClassPath()));
this.irt2ast = new HashMap();
this.ast2irt = new HashMap();
this.solvers = new HashMap();
this.reporter = new SemanticErrorReporter(this.conf.getMaxErrorReports());
}
public IxCode.ClassDefinition[] process(CompilationUnit[] units){
ClassTableBuilder builder = new ClassTableBuilder();
for(int i = 0; i < units.length; i++){
builder.process(units[i]);
}
TypeHeaderAnalysis analysis = new TypeHeaderAnalysis();
for(int i = 0; i < units.length; i++){
analysis.process(units[i]);
}
TypeChecker checker = new TypeChecker();
for(int i = 0; i < units.length; i++){
checker.process(units[i]);
}
DuplicationChecker duplicationChecker = new DuplicationChecker();
for(int i = 0; i < units.length; i++){
duplicationChecker.process(units[i]);
}
CompileError[] problems = getProblems();
if(problems.length > 0){
throw new CompilationException(Arrays.asList(problems));
}
return getSourceClasses();
}
public class NameResolution {
private ImportList imports;
public NameResolution(ImportList imports) {
this.imports = imports;
}
public IxCode.TypeRef resolve(TypeSpec specifier) {
RawTypeNode component = specifier.getComponent();
String name = component.name();
IxCode.TypeRef resolvedType;
if(component.kind() == RawTypeNode.BASIC){
resolvedType =
name.equals("char") ? IxCode.BasicTypeRef.CHAR :
name.equals("byte") ? IxCode.BasicTypeRef.BYTE :
name.equals("short") ? IxCode.BasicTypeRef.SHORT :
name.equals("int") ? IxCode.BasicTypeRef.INT :
name.equals("long") ? IxCode.BasicTypeRef.LONG :
name.equals("float") ? IxCode.BasicTypeRef.FLOAT :
name.equals("double") ? IxCode.BasicTypeRef.DOUBLE :
name.equals("boolean") ? IxCode.BasicTypeRef.BOOLEAN :
IxCode.BasicTypeRef.VOID;
}else if(component.kind() == RawTypeNode.NOT_QUALIFIED){
resolvedType = forName(name, false);
}else{
resolvedType = forName(name, true);
}
IxCode.TypeRef componentType = resolvedType;
if(specifier.getDimension() > 0){
return table.loadArray(componentType, specifier.getDimension());
}else{
return componentType;
}
}
private IxCode.ClassTypeRef forName(String name, boolean qualified) {
if(qualified) {
return table.load(name);
}else {
for(int i = 0; i < imports.size(); i++){
String qualifiedName = imports.get(i).match(name);
if(qualifiedName != null){
IxCode.ClassTypeRef resolvedSymbol = forName(qualifiedName, true);
if(resolvedSymbol != null) return resolvedSymbol;
}
}
return null;
}
}
}
}
|
package servidor.serverController;
import java.io.FileInputStream;
import util.*;
import util.excepciones.SearchException;
import servidor.serverModel.InteraccionDB;
final class Request implements Runnable {
final static String CRLF = "\r\n";
SocketManager sockManager;
int estado;
String usuario;
String idPlacaAccion;
String variableAccion;
String accion;
// Constructor
public Request(SocketManager sockMan) throws Exception {
sockManager = sockMan;
}
// Implement the run() method of the Runnable interface.
public void run() {
try {
processRequest();
}
catch (Exception e) {
System.out.println(e);
}
}
@SuppressWarnings("unused")
private void sendBytes(FileInputStream fis) throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while ( (bytes = fis.read(buffer)) != -1) {
sockManager.Escribir(buffer, bytes);
}
}
private void processRequest() throws Exception {
String requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
boolean stop = false;
while(!stop)
{
switch (estado) {
case 0:
if (requestLine.startsWith("USER"))
{
usuario = requestLine.substring(5);
int respuesta = InteraccionDB.metodoUser(usuario);
System.out.println("USER: " + respuesta);
if(respuesta == 200){
sockManager.Escribir("200 OK Bienvenido " + usuario + "\n");
estado = 1;
}
else if(respuesta == 400)
sockManager.Escribir("400 ERR Falta el nombre de usuario\n");
else if(respuesta == 401)
sockManager.Escribir("401 ERR Usuario desconocido\n");
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("SALIR"))
{
sockManager.Escribir("209 OK Adios\n");
estado = 4;
}
else{
sockManager.Escribir("\n");
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
break;
case 1:
if (requestLine.startsWith("PASS"))
{
String pass = requestLine.substring(5);
int respuesta = InteraccionDB.metodoPass(usuario, pass);
System.out.println("PASS: " + pass + "resptuesta= " + respuesta);
if(respuesta == 201){
sockManager.Escribir("200 OK Bienvenido al sistema\n");
estado = 2;
}
else if(respuesta == 402){
sockManager.Escribir("402 ERR La clave es incorrecta\n");
estado = 0;
}
else if(respuesta == 403)
sockManager.Escribir("403 ERR Falta la clave\n");
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("SALIR"))
{
sockManager.Escribir("209 OK Adios\n");
estado = 4;
}
else{
sockManager.Escribir("\n");
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
break;
case 2:
if (requestLine.startsWith("ON"))
{
String variables = requestLine.substring(requestLine.indexOf(" ") + 1);
String idPlaca = variables.substring(0, variables.indexOf(" "));
String Variable = variables.substring(variables.indexOf(" ")+1, variables.length());
try
{
if(InteraccionDB.comprobarEstado(Variable, idPlaca))
{
sockManager.Escribir("405 ERROR "+Variable+" en estado ON \n");
}
else
{//Continuar con el proceso de poner a ON
InteraccionDB.actualizarEstado(Variable, idPlaca, "ON");
sockManager.Escribir("203 OK "+Variable+" activo \n");
}
}
catch(SearchException E)
{
sockManager.Escribir("404 ERROR "+Variable+" no existe \n");
}
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("OFF"))
{
String variables = requestLine.substring(requestLine.indexOf(" ") + 1);
String idPlaca = variables.substring(0, variables.indexOf(" "));
String Variable = variables.substring(variables.indexOf(" ")+1, variables.length());
try
{
if(InteraccionDB.comprobarEstado(Variable, idPlaca))
{//Continuar con el proceso de poner a OFF
InteraccionDB.actualizarEstado(Variable, idPlaca, "OFF");
sockManager.Escribir("204 OK "+Variable+" desactivo \n");
}
else
{
sockManager.Escribir("405 ERROR "+Variable+" en estado OFF \n");
}
}
catch(SearchException E)
{
sockManager.Escribir("404 ERROR "+Variable+" no existe\n");
}
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("ACCION"))
{
String variables = requestLine.substring(requestLine.indexOf(" ") + 1);
String idPlaca = variables.substring(0, variables.indexOf(" "));
String accionyVariable = variables.substring(variables.indexOf(" ")+1, variables.length());
String variable = accionyVariable.substring(0, accionyVariable.indexOf(" "));
String accion = accionyVariable.substring(accionyVariable.indexOf(" ")+1, accionyVariable.length());
try
{
if(InteraccionDB.comprobarEstado(variable, idPlaca))
{
idPlacaAccion = idPlaca;
variableAccion = variable;
this.accion = accion;
estado = 3;
sockManager.Escribir("205 OK Esperando confirmación\n");
}
else
{
sockManager.Escribir("406 ERROR "+variable+" en estado OFF\n");
}
}
catch(SearchException E)
{
sockManager.Escribir("404 ERROR "+variable+" no existe\n");
}
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("LISTADO"))
{
sockManager.Escribir(InteraccionDB.listado(usuario)); //Cuidado con los \n
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("BUSCAR"))
{
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("OBTENER_FOTO"))
{
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("SALIR"))
{
sockManager.Escribir("209 OK Adios\n");
estado = 4;
}
else
{
sockManager.Escribir("\n");
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
break;
case 3:
if(requestLine.startsWith("CONFIRMAR_ACCION"))
{
estado = 2;
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("RECHAZAR_ACCION"))
{
sockManager.Escribir("207 OK ACCION CANCELADA\n");
estado = 2;
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
else if(requestLine.startsWith("SALIR"))
{
sockManager.Escribir("209 OK Adios\n");
estado = 4;
}
else
{
sockManager.Escribir("\n");
requestLine = sockManager.Leer();
System.out.println("RequestLine: " + requestLine);
}
break;
case 4:
sockManager.CerrarStreams();
sockManager.CerrarSocket();
System.out.println("Cerrando");
stop = true;
break;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.