answer
stringlengths 17
10.2M
|
|---|
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.inspect.core.examples;
import static java.lang.System.out;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import phasereditor.inspect.core.examples.PhaserExampleModel.Mapping;
@SuppressWarnings("boxing")
public class PhaserExamplesRepoModel {
Path _examplesFolderPath;
List<PhaserExampleCategoryModel> _examplesCategories;
Map<Object, Object> _lookupTable;
private int _counter;
public PhaserExamplesRepoModel(Path reposDir) {
_examplesFolderPath = reposDir.resolve("phaser3-examples/public");
_examplesCategories = new ArrayList<>();
}
private void buildLookupTable() {
_counter = 0;
_lookupTable = new HashMap<>();
buildLookupTable(_examplesCategories);
}
private void buildLookupTable(List<PhaserExampleCategoryModel> categories) {
for (PhaserExampleCategoryModel category : categories) {
int id = _counter++;
_lookupTable.put(id, category);
_lookupTable.put(category, id);
for (PhaserExampleModel example : category.getTemplates()) {
id = _counter++;
_lookupTable.put(id, example);
_lookupTable.put(example, id);
}
buildLookupTable(category.getSubCategories());
}
}
public Object lookup(Object obj) {
return _lookupTable.get(obj);
}
public void build() throws IOException {
Path assetsPath = _examplesFolderPath.resolve("assets");
Path srcPath = _examplesFolderPath.resolve("src");
List<Path> requiredFiles = new ArrayList<>();
{
Path[] inAssets = Files.walk(assetsPath).filter(p -> !Files.isDirectory(p)).toArray(Path[]::new);
requiredFiles.addAll(Arrays.asList(inAssets));
}
Comparator<PhaserExampleCategoryModel> comparator = new Comparator<>() {
@Override
public int compare(PhaserExampleCategoryModel o1, PhaserExampleCategoryModel o2) {
return o1.getName().compareTo(o2.getName());
}
};
Files.walkFileTree(srcPath, new SimpleFileVisitor<Path>() {
Stack<PhaserExampleCategoryModel> _stack = new Stack<>();
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (dir.equals(srcPath)) {
return FileVisitResult.CONTINUE;
}
String filename = dir.getFileName().toString();
if (filename.startsWith("_") || filename.equals("archived")) {
out.println("Skip " + dir);
return FileVisitResult.SKIP_SUBTREE;
}
if (Files.exists(dir.resolve("boot.json"))) {
out.println("Skip boot based examples " + dir);
return FileVisitResult.SKIP_SIBLINGS;
}
PhaserExampleCategoryModel parent = _stack.isEmpty() ? null : _stack.peek();
PhaserExampleCategoryModel category = new PhaserExampleCategoryModel(parent, dir,
getName(dir.getFileName()));
_stack.push(category);
if (parent == null) {
_examplesCategories.add(category);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path jsFile, BasicFileAttributes attrs) throws IOException {
PhaserExampleCategoryModel category = _stack.peek();
if (!isExampleJSFile(jsFile)) {
out.println("Skip " + jsFile);
return FileVisitResult.CONTINUE;
}
PhaserExampleModel exampleModel = new PhaserExampleModel(category, jsFile);
// add main example file
exampleModel.addMapping(_examplesFolderPath.relativize(jsFile), jsFile.getFileName().toString());
category.addExample(exampleModel);
// add assets files
String content = new String(Files.readAllBytes(jsFile));
String loaderPath = null;
// detect loader base path
try {
int i = content.indexOf("this.load.path = 'assets/");
if (i != -1) {
int j = content.indexOf("'", i);
int k = content.indexOf("'", j + 1);
loaderPath = content.substring(j + 1, k);
out.println("Detected loader path: " + loaderPath);
}
i = content.indexOf("this.load.setPath('assets/");
if (i != -1) {
int j = content.indexOf("'", i);
int k = content.indexOf("'", j + 1);
loaderPath = content.substring(j + 1, k);
out.println("Detected loader path: " + loaderPath);
}
} catch (Exception e) {
}
for (Path file : requiredFiles) {
String assetRelPath = _examplesFolderPath.relativize(file).toString().replace("\\", "/");
boolean fileAdded = false;
if (content.contains(assetRelPath) || content.contains("../" + assetRelPath)) {
exampleModel.addMapping(_examplesFolderPath.relativize(file), assetRelPath);
fileAdded = true;
}
if (!fileAdded) {
if (loaderPath != null) {
String loaderRelPath = _examplesFolderPath.resolve(loaderPath).relativize(file).toString()
.replace("\\", "/");
// out.println("Test with loader path: " + assetRelPath);
if (content.contains(loaderRelPath)) {
out.println("Mapping from loader sub-path: " + loaderRelPath + " -> " + assetRelPath);
exampleModel.addMapping(_examplesFolderPath.relativize(file), assetRelPath);
fileAdded = true;
}
}
}
if (fileAdded) {
if (file.getFileName().toString().endsWith(".json")) {
// check if it is an asset pack
try {
JSONObject jsonPack = new JSONObject(file);
JSONObject jsonMeta = jsonPack.getJSONObject("meta");
if (jsonMeta.getString("url").equals("https://phaser.io")) {
if (jsonMeta.getString("app").toLowerCase().contains("asset")) {
// ok, it is a pack
out.println("Processing pack: " + assetRelPath);
for (var key : jsonPack.keySet()) {
if (key.equals("meta")) {
continue;
}
var jsonSection = jsonPack.getJSONObject(key);
var path = jsonSection.optString("path", null);
if (path != null) {
if (path.endsWith("/")) {
path += path.substring(0, path.length() - 1);
}
out.println("\tDetecting section path: " + path);
}
var jsonFiles = jsonSection.getJSONArray("files");
for (int i = 0; i < jsonFiles.length(); i++) {
String url = null;
var jsonFile = jsonFiles.getJSONObject(i);
boolean hasExplicitUrl = jsonFile.has("url");
if (hasExplicitUrl) {
url = jsonFile.getString("url");
if (path != null) {
url = path + "/" + url;
}
} else {
if (path != null) {
var fileKey = jsonFile.getString("key");
url = path + "/" + fileKey;
}
}
if (url != null) {
var fileExt = jsonFile.optString("extension", null);
if (fileExt == null) {
// TODO: add the extension in dependence of the file type.
} else {
url += "." + fileExt;
out.println("\t\tAdding extension: " + fileExt);
}
out.println("\tPack url: " + url);
}
}
}
}
}
} catch (Exception e) {
// nothing
}
// check if it is a multi-atlas
// TODO: missing implementation
}
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (dir.equals(srcPath) || _stack.isEmpty()) {
return FileVisitResult.CONTINUE;
}
PhaserExampleCategoryModel category = _stack.pop();
category.getSubCategories().sort(comparator);
category.getTemplates().sort((t1, t2) -> t1.getName().compareTo(t2.getName()));
return FileVisitResult.CONTINUE;
}
});
_examplesCategories.sort(comparator);
for (PhaserExampleCategoryModel c : _examplesCategories) {
c.printTree(0);
}
}
static String getName(Path path) {
String name = path.toString().replace("\\", "/");
if (name.endsWith(".js")) {
name = name.substring(0, name.length() - 3);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (i == 0) {
c = Character.toUpperCase(c);
} else {
char prev = name.charAt(i - 1);
if (prev == ' ') {
c = Character.toUpperCase(c);
}
}
sb.append(c);
}
return sb.toString();
}
public List<PhaserExampleCategoryModel> getExamplesCategories() {
return _examplesCategories;
}
static boolean isExampleJSFile(Path p) {
String filename = p.getFileName().toString();
return !filename.startsWith("_") && filename.endsWith(".js");
}
public Path getExamplesRepoPath() {
return _examplesFolderPath;
}
public void loadCache(Path cache) throws IOException {
_examplesCategories = new ArrayList<>();
JSONObject jsonDoc;
try (InputStream input = Files.newInputStream(cache)) {
jsonDoc = new JSONObject(new JSONTokener(input));
}
loadCategories(jsonDoc.getJSONArray("examplesCategories"), null);
buildLookupTable();
}
private void loadCategories(JSONArray jsonCategories, PhaserExampleCategoryModel parent) {
for (int i = 0; i < jsonCategories.length(); i++) {
JSONObject jsonCategory = jsonCategories.getJSONObject(i);
String relPath = jsonCategory.getString("relPath");
Path path = _examplesFolderPath.resolve(relPath);
PhaserExampleCategoryModel category = new PhaserExampleCategoryModel(parent, path,
jsonCategory.getString("name"));
if (parent == null) {
_examplesCategories.add(category);
}
JSONArray jsonSubCategories = jsonCategory.getJSONArray("subCategories");
loadCategories(jsonSubCategories, category);
JSONArray jsonExamples = jsonCategory.getJSONArray("examples");
for (int j = 0; j < jsonExamples.length(); j++) {
JSONObject jsonExample = jsonExamples.getJSONObject(j);
String mainFilePathStr = jsonExample.getString("mainFile");
Path mainFile = _examplesFolderPath.resolve(mainFilePathStr);
PhaserExampleModel example = new PhaserExampleModel(category, mainFile);
category.addExample(example);
JSONArray jsonMaps = jsonExample.getJSONArray("map");
for (int k = 0; k < jsonMaps.length(); k++) {
JSONObject jsonMap = jsonMaps.getJSONObject(k);
String orig = jsonMap.getString("orig");
String dst = jsonMap.optString("dst", orig);
example.addMapping(_examplesFolderPath.resolve(orig), dst);
}
}
}
}
public void saveCache(Path cache) throws JSONException, IOException {
JSONObject jsonDoc = new JSONObject();
JSONArray jsonExamplesCategories = new JSONArray();
jsonDoc.put("examplesCategories", jsonExamplesCategories);
saveCategories(jsonExamplesCategories, _examplesCategories);
Files.write(cache, jsonDoc.toString(2).getBytes());
}
private void saveCategories(JSONArray jsonExamplesCategories, List<PhaserExampleCategoryModel> categories) {
for (PhaserExampleCategoryModel category : categories) {
JSONObject jsonCategory = new JSONObject();
String relPath = _examplesFolderPath.relativize(category.getPath()).toString().replace("\\", "/");
jsonCategory.put("name", category.getName());
jsonCategory.put("relPath", relPath);
jsonExamplesCategories.put(jsonCategory);
JSONArray jsonSubCategories = new JSONArray();
jsonCategory.put("subCategories", jsonSubCategories);
saveCategories(jsonSubCategories, category.getSubCategories());
JSONArray jsonExamples = new JSONArray();
jsonCategory.put("examples", jsonExamples);
for (PhaserExampleModel example : category.getTemplates()) {
JSONObject jsonExample = new JSONObject();
jsonExamples.put(jsonExample);
jsonExample.put("mainFile", _examplesFolderPath.relativize(example.getMainFilePath()));
JSONArray jsonMaps = new JSONArray();
jsonExample.put("map", jsonMaps);
for (Mapping map : example.getFilesMapping()) {
JSONObject jsonMap = new JSONObject();
jsonMaps.put(jsonMap);
String orig = map.getOriginal().toString().replace("\\", "/");
String dst = map.getDestiny();
jsonMap.put("orig", orig);
if (!orig.equals(dst)) {
jsonMap.put("dst", dst);
}
}
}
}
}
}
|
package org.jboss.as.test.manualmode.logging;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*;
/**
* @author <a href="mailto:pkremens@redhat.com">Petr Kremensky</a>
*/
@RunWith(Arquillian.class)
@RunAsClient
public class SizeAppenderRestartTestCase {
private static final Logger log = Logger.getLogger(SizeAppenderRestartTestCase.class);
private static final String CONTAINER = "default-jbossas";
private static final String DEPLOYMENT = "logging-deployment";
private static final String FILE_NAME = "sizeAppenderRestartTestCase.log";
private static final String SIZE_HANDLER_NAME = "sizeAppenderRestartTestCase";
private static final ModelNode SIZE_HANDLER_ADDRESS = new ModelNode();
private static final ModelNode ROOT_LOGGER_ADDRESS = new ModelNode();
private static File logFile;
@ArquillianResource
private ContainerController container;
@ArquillianResource
private Deployer deployer;
private final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
private final ManagementClient managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "http-remoting");
@Deployment(name = DEPLOYMENT, managed = false, testable = false)
public static WebArchive createDeployment() {
WebArchive archive = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war");
archive.addClasses(LoggingServlet.class);
return archive;
}
@Test
@InSequence(-1)
public void startContainer() throws Exception {
SIZE_HANDLER_ADDRESS.add(SUBSYSTEM, "logging")
.add("size-rotating-file-handler", SIZE_HANDLER_NAME);
ROOT_LOGGER_ADDRESS.add(SUBSYSTEM, "logging")
.add("root-logger", "ROOT");
// Start the server
container.start(CONTAINER);
Assert.assertTrue("Container is not started", managementClient.isServerInRunningState());
// Deploy the servlet
deployer.deploy(DEPLOYMENT);
logFile = getAbsoluteLogFilePath(client);
// Create the size-rotating handler
ModelNode op = Operations.createAddOperation(SIZE_HANDLER_ADDRESS);
ModelNode file = new ModelNode();
file.get("path").set(logFile.getAbsolutePath());
op.get(FILE).set(file);
validateResponse(op);
// Add the handler to the root-logger
op = Operations.createOperation("add-handler", ROOT_LOGGER_ADDRESS);
op.get(NAME).set(SIZE_HANDLER_NAME);
validateResponse(op);
}
@Test
@InSequence(1)
public void stopContainer() throws Exception {
// Remove the servlet
deployer.undeploy(DEPLOYMENT);
// Remove the handler from the root-logger
ModelNode op = Operations.createOperation("remove-handler", ROOT_LOGGER_ADDRESS);
op.get(NAME).set(SIZE_HANDLER_NAME);
validateResponse(op);
// Remove the size-rotating handler
op = Operations.createRemoveOperation(SIZE_HANDLER_ADDRESS);
validateResponse(op);
// Stop the container
container.stop(CONTAINER);
Assert.assertFalse("Container is not stopped", managementClient.isServerInRunningState());
// Remove log files
clearLogs(logFile);
safeClose(client);
safeClose(managementClient);
}
/*
* append = true: restart -> logs are appended to same log file, unless it reach rotate-size
*/
@Test
public void appendTrueTest(@ArquillianResource URL url) throws Exception {
long fileSize = appendTest("true", url);
log.info("original file size = " + fileSize);
log.info("new file size = " + logFile.length());
Assert.assertTrue("Size of log file should be bigger after reload", fileSize < logFile.length());
}
/*
* append = false: restart -> original log file is rewritten
*/
@Test
public void appendFalseTest(@ArquillianResource URL url) throws Exception {
long fileSize = appendTest("false", url);
log.info("original file size = " + fileSize);
log.info("new file size = " + logFile.length());
Assert.assertTrue("Size of log file should be smaller after reload", fileSize > logFile.length());
}
private long appendTest(String append, URL url) throws Exception {
final String message = "SizeAppenderRestartTestCase - This is my dummy message which is gonna fill my log file";
long fileSize;
// set append attribute, rotate-on boot and reload server
ModelNode op = Operations.createWriteAttributeOperation(SIZE_HANDLER_ADDRESS, "append", append);
validateResponse(op);
op = Operations.createWriteAttributeOperation(SIZE_HANDLER_ADDRESS, "rotate-on-boot", false);
validateResponse(op);
restartServer(true);
// make some (more than server start) logs, remember the size of log file, reload server, check new size of file
op = Operations.createReadResourceOperation(SIZE_HANDLER_ADDRESS);
validateResponse(op);
for (int i = 0; i < 100; i++) {
makeLog(message, url);
}
checkLogs(message);
fileSize = logFile.length();
restartServer(false);
// logFile.getParentFile().listFiles().length creates array with length of 3
int count = 0;
for (File f : listLogFiles()) {
if (f.getName().contains(logFile.getName())) {
count++;
}
}
Assert.assertEquals("There should be only one log file", 1, count);
return fileSize;
}
/*
* rotate-on-boot = true: restart -> log file is rotated, logs are written to new file
*/
@Test
public void rotateFileOnRestartTest(@ArquillianResource URL url) throws Exception {
final String oldMessage = "SizeAppenderRestartTestCase - This is old message";
final String newMessage = "SizeAppenderRestartTestCase - This is new message";
ModelNode op = Operations.createWriteAttributeOperation(SIZE_HANDLER_ADDRESS, "rotate-on-boot", true);
validateResponse(op);
restartServer(true);
// make some logs, remember file size, restart
makeLog(oldMessage, url);
checkLogs(oldMessage);
restartServer(false);
// make log to new rotated log file
makeLog(newMessage, url);
checkLogs(newMessage);
// verify that file was rotated
int count = 0;
for (File file : listLogFiles()) {
if (file.getName().contains(logFile.getName())) {
count++;
if (file.getName().equals(logFile.getName() + ".1")) {
checkLogs(newMessage, false, file);
checkLogs(oldMessage, true, file);
}
}
}
Assert.assertEquals("There should be two log files", 2, count);
}
private void restartServer(boolean deleteLogs) {
Assert.assertTrue("Container is not running", managementClient.isServerInRunningState());
// Stop the container
container.stop(CONTAINER);
if (deleteLogs) {
clearLogs(logFile);
}
// Start the server again
container.start(CONTAINER);
Assert.assertTrue("Container is not started", managementClient.isServerInRunningState());
}
private void checkLogs(final String msg) throws Exception {
checkLogs(msg, true, logFile);
}
/*
* Search file for message
*/
private void checkLogs(final String msg, final boolean expected, File file) throws Exception {
BufferedReader reader = null;
// check logs
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
String line;
boolean logFound = false;
while ((line = reader.readLine()) != null) {
if (line.contains(msg)) {
logFound = true;
break;
}
}
Assert.assertTrue("Message: \"" + msg + "\" was not found in file: " + file.getName(), logFound == expected);
} finally {
safeClose(reader);
}
log.info("Message: \"" + msg + "\" was found in file: " + file.getName());
}
private void makeLog(String msg, URL url) throws Exception {
int statusCode = getResponse(new java.net.URL(url, "logger?msg=" + URLEncoder.encode(msg, "utf-8")));
Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpServletResponse.SC_OK);
}
private int getResponse(URL url) throws IOException {
return ((HttpURLConnection) url.openConnection()).getResponseCode();
}
private void validateResponse(ModelNode operation) throws Exception {
ModelNode response;
log.info(operation.asString());
response = client.execute(operation);
log.info(response.asString());
if (!SUCCESS.equals(response.get(OUTCOME).asString())) {
Assert.fail(response.get(FAILURE_DESCRIPTION).toString());
}
}
private void clearLogs(File file) {
for (File f : listLogFiles()) {
if (f.getName().contains(file.getName())) {
f.delete();
log.info("Deleted: " + f.getAbsolutePath());
if (f.exists()) {
Assert.fail("Unable to delete file: " + f.getName());
}
}
}
}
private static File getAbsoluteLogFilePath(final ModelControllerClient client) throws IOException, MgmtOperationException {
final ModelNode address = new ModelNode().setEmptyList();
address.add(PATH, "jboss.server.log.dir");
final ModelNode op = Operations.createReadAttributeOperation(address, PATH);
final ModelNode result = client.execute(op);
if (Operations.isSuccessfulOutcome(result)) {
return new File(Operations.readResult(result).asString(), FILE_NAME);
}
throw new MgmtOperationException("Failed to read the path resource", op, result);
}
private static void safeClose(final Closeable closeable) {
if (closeable != null) try {
closeable.close();
} catch (Exception ignore) {
// ignore
}
}
private static File[] listLogFiles() {
File logDir = logFile.getParentFile();
Assert.assertNotNull("Log directory not found", logDir);
return logDir.listFiles();
}
}
|
package info.bitrich.xchangestream.bitstamp.v2;
import com.fasterxml.jackson.databind.ObjectMapper;
import info.bitrich.xchangestream.bitstamp.dto.BitstampWebSocketTransaction;
import info.bitrich.xchangestream.core.StreamingMarketDataService;
import info.bitrich.xchangestream.service.netty.StreamingObjectMapperHelper;
import io.reactivex.Observable;
import org.knowm.xchange.bitstamp.BitstampAdapters;
import org.knowm.xchange.bitstamp.dto.marketdata.BitstampOrderBook;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.dto.trade.LimitOrder;
public class BitstampStreamingMarketDataService implements StreamingMarketDataService {
private final BitstampStreamingService service;
public BitstampStreamingMarketDataService(BitstampStreamingService service) {
this.service = service;
}
public Observable<OrderBook> getFullOrderBook(CurrencyPair currencyPair, Object... args) {
return getOrderBook("diff_order_book", currencyPair, args);
}
@Override
public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) {
return getOrderBook("order_book", currencyPair, args);
}
private Observable<OrderBook> getOrderBook(
String channelPrefix, CurrencyPair currencyPair, Object... args) {
String channelName = channelPrefix + getChannelPostfix(currencyPair);
return service
.subscribeChannel(channelName, BitstampStreamingService.EVENT_ORDERBOOK)
.map(
s -> {
ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
BitstampOrderBook orderBook =
mapper.treeToValue(s.get("data"), BitstampOrderBook.class);
return BitstampAdapters.adaptOrderBook(orderBook, currencyPair);
});
}
@Override
public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) {
return getOrderBook(currencyPair, args)
.map(orderBook -> mapOrderBookToTicker(currencyPair, orderBook));
}
private Ticker mapOrderBookToTicker(CurrencyPair currencyPair, OrderBook orderBook) {
final LimitOrder ask = orderBook.getAsks().get(0);
final LimitOrder bid = orderBook.getBids().get(0);
return new Ticker.Builder()
.instrument(currencyPair)
.bid(bid.getLimitPrice())
.bidSize(bid.getOriginalAmount())
.ask(ask.getLimitPrice())
.askSize(ask.getOriginalAmount())
.timestamp(orderBook.getTimeStamp())
.build();
}
@Override
public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) {
String channelName = "live_trades" + getChannelPostfix(currencyPair);
return service
.subscribeChannel(channelName, BitstampStreamingService.EVENT_TRADE)
.map(
s -> {
ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
BitstampWebSocketTransaction transactions =
mapper.treeToValue(s.get("data"), BitstampWebSocketTransaction.class);
return BitstampAdapters.adaptTrade(transactions, currencyPair, 1);
});
}
private String getChannelPostfix(CurrencyPair currencyPair) {
return "_"
+ currencyPair.base.toString().toLowerCase()
+ currencyPair.counter.toString().toLowerCase();
}
}
|
package org.eclipse.birt.report.designer.ui.dialogs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.designer.internal.ui.util.DataUtil;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.ui.expressions.ExpressionFilter;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSetParameterHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.olap.TabularCubeHandle;
import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle;
/**
* BindingExpressionProvider
*/
public class BindingExpressionProvider extends ExpressionProvider
{
private DataSetHandle dataSetHandle = null;
public BindingExpressionProvider( final DesignElementHandle handle,
final ComputedColumnHandle computedColumnHandle )
{
super( handle );
if ( handle instanceof TabularCubeHandle )
{
dataSetHandle = ( (TabularCubeHandle) handle ).getDataSet( );
}
else if ( handle instanceof TabularHierarchyHandle )
{
dataSetHandle = ( (TabularHierarchyHandle) handle ).getDataSet( );
if ( dataSetHandle == null
&& ( (TabularHierarchyHandle) handle ).getLevelCount( ) > 0 )
{
dataSetHandle = ( (TabularCubeHandle) ( (TabularHierarchyHandle) handle ).getContainer( )
.getContainer( ) ).getDataSet( );
}
}
if ( handle instanceof ReportItemHandle )
{
dataSetHandle = ( (ReportItemHandle) handle ).getDataSet( );
}
else if ( handle instanceof GroupHandle )
{
dataSetHandle = ( (ReportItemHandle) ( (GroupHandle) handle ).getContainer( ) ).getDataSet( );
}
if ( computedColumnHandle != null )
{
addFilter( new ExpressionFilter( ) {
public boolean select( Object parentElement, Object element )
{
if ( element instanceof ComputedColumnHandle
&& computedColumnHandle != null )
{
ComputedColumnHandle column = (ComputedColumnHandle) element;
if ( column.getName( )
.equals( computedColumnHandle.getName( ) ) )
return false;
}
return true;
}
} );
}
}
protected DataSetHandle getDataSetHandle()
{
return this.dataSetHandle;
}
protected List getCategoryList( )
{
List categoryList = super.getCategoryList( );
if ( dataSetHandle != null )
{
// 185280
categoryList.add( 0, DATASETS );
}
return categoryList;
}
protected List getChildrenList( Object parent )
{
if ( DATASETS.equals( parent ) )
{
List dataSeList = new ArrayList( );
dataSeList.add( dataSetHandle );
return dataSeList;
}
if ( parent instanceof DataSetHandle )
{
try
{
List columnList = DataUtil.getColumnList( (DataSetHandle) parent );
List outputList = getOutputList( (DataSetHandle) parent );
columnList.addAll( outputList );
return columnList;
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
return Collections.EMPTY_LIST;
}
}
return super.getChildrenList( parent );
}
/**
* Get output parameters if handle has.
*
* @param handle
* @return
*/
private List getOutputList( DataSetHandle handle )
{
List outputList = new ArrayList( );
PropertyHandle parameters = handle.getPropertyHandle( DataSetHandle.PARAMETERS_PROP );
Iterator iter = parameters.iterator( );
if ( iter != null )
{
while ( iter.hasNext( ) )
{
Object dataSetParameter = iter.next( );
if ( ( (DataSetParameterHandle) dataSetParameter ).isOutput( ) == true )
{
outputList.add( dataSetParameter );
}
}
}
return outputList;
}
public String getDisplayText( Object element )
{
if ( element instanceof DataSetHandle )
{
return ( (DataSetHandle) element ).getName( );
}
else if ( element instanceof ResultSetColumnHandle )
{
return ( (ResultSetColumnHandle) element ).getColumnName( );
}
else if ( element instanceof DataSetParameterHandle )
{
return ( (DataSetParameterHandle) element ).getName( );
}
return super.getDisplayText( element );
}
public String getInsertText( Object element )
{
if ( element instanceof ResultSetColumnHandle
|| element instanceof DataSetParameterHandle )
{
return DEUtil.getExpression( element );
}
return super.getInsertText( element );
}
}
|
package org.eclipse.birt.report.designer.ui.dialogs;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.birt.report.designer.internal.ui.dialogs.helper.IDialogHelper;
import org.eclipse.birt.report.designer.internal.ui.dialogs.helper.IDialogHelperProvider;
import org.eclipse.birt.report.designer.internal.ui.util.ExpressionButtonUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.views.ElementAdapterManager;
import org.eclipse.birt.report.model.api.AbstractScalarParameterHandle;
import org.eclipse.birt.report.model.api.ActionHandle;
import org.eclipse.birt.report.model.api.Expression;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.elements.structures.ParamBinding;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
public class HyperlinkParameterBuilder extends BaseDialog
{
public static final String HYPERLINK_PARAMETER = "HyperlinkParameter"; //$NON-NLS-1$
public static final String TARGET_REPORT = "TargetReport"; //$NON-NLS-1$
public static final String PARAMETER_HANDLE = "ParameterHandle"; //$NON-NLS-1$
public static final String PARAMETER_VALUE = "ParameterValue"; //$NON-NLS-1$
public static final String HYPERLINK_EXPRESSIONPROVIDER = "HyperlinkExpressionProvider";//$NON-NLS-1$
public static final String HYPERLINK_EXPRESSIONCONTEXT = "HyperlinkExpressionContext";//$NON-NLS-1$
private String[] items;
private Combo paramChooser;
private HyperlinkBuilder hyperlinkBuilder;
private Composite valueControl;
private Label valueLabel;
private Composite container;
public void setHyperlinkBuilder( HyperlinkBuilder hyperlinkBuilder )
{
this.hyperlinkBuilder = hyperlinkBuilder;
}
protected HyperlinkParameterBuilder( String title )
{
super( title );
}
protected Control createDialogArea( Composite parent )
{
Composite composite = (Composite) super.createDialogArea( parent );
container = new Composite( composite, SWT.NONE );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.minimumHeight = 80;
container.setLayoutData( gd );
GridLayout layout = new GridLayout( );
layout.numColumns = 2;
layout.verticalSpacing = 10;
container.setLayout( layout );
new Label( container, SWT.NONE ).setText( Messages.getString( "HyperlinkParameterBuilder.Label.Parameter" ) ); //$NON-NLS-1$
paramChooser = new Combo( container, SWT.BORDER );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.widthHint = 250;
paramChooser.setLayoutData( gd );
paramChooser.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
updateValueControl( );
}
} );
paramChooser.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
updateValueControl( );
checkOkButton( );
}
} );
Label requiredLabel = new Label( container, SWT.NONE );
requiredLabel.setText( Messages.getString( "HyperlinkParameterBuilder.Lable.Required" ) ); //$NON-NLS-1$
requiredValue = new Text( container, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
requiredValue.setLayoutData( gd );
Label typeLabel = new Label( container, SWT.NONE );
typeLabel.setText( Messages.getString( "HyperlinkParameterBuilder.Label.DataType" ) ); //$NON-NLS-1$
typeValue = new Text( container, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
typeValue.setLayoutData( gd );
valueLabel = new Label( container, SWT.NONE );
valueLabel.setText( Messages.getString( "HyperlinkParameterBuilder.Label.Value" ) ); //$NON-NLS-1$
gd = new GridData( );
gd.exclude = true;
valueLabel.setLayoutData( gd );
valueLabel.setVisible( false );
// UIUtil.bindHelp( parent, IHelpContextIds.EXPRESSION_EDITOR_ID );
populateComboBoxItems( );
return composite;
}
protected void updateValueControl( )
{
if ( hyperlinkBuilder != null )
{
final Object object = hyperlinkBuilder.getParameter( paramChooser.getText( ) );
if ( valueControl != null && !valueControl.isDisposed( ) )
{
valueControl.dispose( );
}
if ( object instanceof ScalarParameterHandle || object == null )
{
GridData gd = (GridData) valueLabel.getLayoutData( );
gd.exclude = false;
valueLabel.setLayoutData( gd );
valueLabel.setVisible( true );
valueControl = new Composite( container, SWT.NONE );
gd = new GridData( GridData.FILL_HORIZONTAL );
valueControl.setLayoutData( gd );
GridLayout layout = new GridLayout( );
layout.marginWidth = layout.marginHeight = 0;
layout.numColumns = 2;
valueControl.setLayout( layout );
text = new Text( valueControl, SWT.BORDER );
text.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
text.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkOkButton( );
}
} );
ExpressionButtonUtil.createExpressionButton( valueControl,
text,
hyperlinkBuilder.getExpressionProvider( ),
handle == null ? null : handle.getElementHandle( ) );
if ( paramBinding != null )
{
ExpressionButtonUtil.initExpressionButtonControl( text,
hyperlinkBuilder.getParamBindingExpression( paramBinding ) );
text.setFocus( );
}
if ( object instanceof ScalarParameterHandle )
{
typeValue.setText( hyperlinkBuilder.getDisplayDataType( ( (ScalarParameterHandle) object ).getDataType( ) ) );
requiredValue.setText( ( (ScalarParameterHandle) object ).isRequired( ) ? Messages.getString( "HyperlinkParameterBuilder.Required.Choice.Yes" ) //$NON-NLS-1$
: Messages.getString( "HyperlinkParameterBuilder.Required.Choice.No" ) ); //$NON-NLS-1$
}
else
{
typeValue.setText( "" ); //$NON-NLS-1$
requiredValue.setText( "" ); //$NON-NLS-1$
}
}
else
{
if ( object instanceof AbstractScalarParameterHandle )
{
typeValue.setText( hyperlinkBuilder.getDisplayDataType( ( (AbstractScalarParameterHandle) object ).getDataType( ) ) );
requiredValue.setText( ( (AbstractScalarParameterHandle) object ).isRequired( ) ? Messages.getString( "HyperlinkParameterBuilder.Required.Choice.Yes" ) //$NON-NLS-1$
: Messages.getString( "HyperlinkParameterBuilder.Required.Choice.No" ) ); //$NON-NLS-1$
}
valueEditor = createValueEditor( container, object );
if ( valueEditor == null )
{
GridData gd = (GridData) valueLabel.getLayoutData( );
gd.exclude = true;
valueLabel.setLayoutData( gd );
valueLabel.setVisible( false );
}
else
{
GridData gd = (GridData) valueLabel.getLayoutData( );
gd.exclude = false;
valueLabel.setLayoutData( gd );
valueLabel.setVisible( true );
valueEditor.getControl( )
.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
valueEditor.addListener( SWT.Modify, new Listener( ) {
public void handleEvent( Event event )
{
checkOkButton( );
}
} );
valueEditor.setProperty( PARAMETER_HANDLE, object );
valueEditor.setProperty( TARGET_REPORT,
hyperlinkBuilder.getTargetReportFile( ) );
valueEditor.setProperty( PARAMETER_VALUE,
paramBinding == null ? null
: hyperlinkBuilder.getParamBindingExpression( paramBinding ) );
valueEditor.update( true );
valueControl = (Composite) valueEditor.getControl( );
if ( paramBinding != null )
{
valueEditor.getControl( ).setFocus( );
}
}
}
container.layout( );
}
}
private IDialogHelper createValueEditor( Composite parent, Object parameter )
{
Object[] helperProviders = ElementAdapterManager.getAdapters( parameter,
IDialogHelperProvider.class );
if ( helperProviders != null )
{
for ( int i = 0; i < helperProviders.length; i++ )
{
IDialogHelperProvider helperProvider = (IDialogHelperProvider) helperProviders[i];
if ( helperProvider != null )
{
final IDialogHelper helper = helperProvider.createHelper( this,
HYPERLINK_PARAMETER );
if ( helper != null )
{
helper.setProperty( HYPERLINK_EXPRESSIONPROVIDER,
hyperlinkBuilder.getExpressionProvider( ) );
helper.setProperty( HYPERLINK_EXPRESSIONCONTEXT, handle );
helper.createContent( parent );
return helper;
}
}
}
}
return null;
}
protected void okPressed( )
{
if ( paramBinding != null )
{
List<Expression> expressions = new ArrayList<Expression>( );
if ( text != null && !text.isDisposed( ) )
{
expressions.add( ExpressionButtonUtil.getExpression( text ) );
paramBinding.setExpression( expressions );
}
else if ( valueEditor != null
&& !valueEditor.getControl( ).isDisposed( ) )
{
valueEditor.update( false );
expressions.add( (Expression) valueEditor.getProperty( PARAMETER_VALUE ) );
paramBinding.setExpression( expressions );
}
}
else
{
ParamBinding paramBinding = StructureFactory.createParamBinding( );
paramBinding.setParamName( paramChooser.getText( ) );
List<Expression> expressions = new ArrayList<Expression>( );
if ( text != null && !text.isDisposed( ) )
{
expressions.add( ExpressionButtonUtil.getExpression( text ) );
paramBinding.setExpression( expressions );
}
else if ( valueEditor != null
&& !valueEditor.getControl( ).isDisposed( ) )
{
valueEditor.update( false );
expressions.add( (Expression) valueEditor.getProperty( PARAMETER_VALUE ) );
paramBinding.setExpression( expressions );
}
setResult( paramBinding );
}
super.okPressed( );
}
private ParamBinding paramBinding;
public void setParamBinding( ParamBinding paramBinding )
{
this.paramBinding = paramBinding;
if ( paramBinding != null )
{
this.items = new String[]{
paramBinding.getParamName( )
};
}
}
public void setItems( String[] items )
{
this.items = items;
}
/**
* Updates the list of choices for the combo box for the current control.
*/
private void populateComboBoxItems( )
{
if ( paramChooser != null && items != null )
{
paramChooser.removeAll( );
for ( int i = 0; i < items.length; i++ )
paramChooser.add( items[i], i );
if ( items.length > 0 )
{
paramChooser.select( 0 );
updateValueControl( );
}
if ( paramBinding != null )
paramChooser.setEnabled( false );
}
}
private ActionHandle handle;
private Text text;
private IDialogHelper valueEditor;
private Text typeValue;
private Text requiredValue;
public void setActionHandle( ActionHandle handle )
{
this.handle = handle;
}
protected Control createButtonBar( Composite parent )
{
Control control = super.createButtonBar( parent );
checkOkButton( );
return control;
}
private void checkOkButton( )
{
if ( hyperlinkBuilder == null
|| HyperlinkParameterBuilder.this.getOkButton( ) == null )
return;
Object object = hyperlinkBuilder.getParameter( paramChooser.getText( ) );
if ( object instanceof AbstractScalarParameterHandle )
{
if ( ( (AbstractScalarParameterHandle) object ).isRequired( ) )
{
if ( text != null && !text.isDisposed( ) )
{
HyperlinkParameterBuilder.this.getOkButton( )
.setEnabled( text.getText( ).trim( ).length( ) != 0 );
}
else if ( valueEditor != null
&& !valueEditor.getControl( ).isDisposed( ) )
{
Expression expression = (Expression) valueEditor.getProperty( PARAMETER_VALUE );
if ( expression == null )
HyperlinkParameterBuilder.this.getOkButton( )
.setEnabled( false );
else if ( expression.getStringExpression( ) == null
|| expression.getStringExpression( )
.trim( )
.length( ) == 0 )
HyperlinkParameterBuilder.this.getOkButton( )
.setEnabled( false );
else
HyperlinkParameterBuilder.this.getOkButton( )
.setEnabled( true );
}
}
else
{
HyperlinkParameterBuilder.this.getOkButton( ).setEnabled( true );
}
}
else
{
if ( paramChooser.getText( ).trim( ).length( ) == 0 )
HyperlinkParameterBuilder.this.getOkButton( )
.setEnabled( false );
else
HyperlinkParameterBuilder.this.getOkButton( ).setEnabled( true );
}
}
}
|
package com.microsoft.applicationinsights.channel.contracts;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.io.IOException;
import java.io.StringWriter;
/// <summary>
/// Data contract test class DeviceTests.
/// </summary>
public class DeviceTests extends TestCase
{
public void testIdPropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setId(expected);
String actual = item.getId();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setId(expected);
actual = item.getId();
Assert.assertEquals(expected, actual);
}
public void testIpPropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setIp(expected);
String actual = item.getIp();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setIp(expected);
actual = item.getIp();
Assert.assertEquals(expected, actual);
}
public void testLanguagePropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setLanguage(expected);
String actual = item.getLanguage();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setLanguage(expected);
actual = item.getLanguage();
Assert.assertEquals(expected, actual);
}
public void testLocalePropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setLocale(expected);
String actual = item.getLocale();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setLocale(expected);
actual = item.getLocale();
Assert.assertEquals(expected, actual);
}
public void testModelPropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setModel(expected);
String actual = item.getModel();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setModel(expected);
actual = item.getModel();
Assert.assertEquals(expected, actual);
}
public void testNetworkPropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setNetwork(expected);
String actual = item.getNetwork();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setNetwork(expected);
actual = item.getNetwork();
Assert.assertEquals(expected, actual);
}
public void testOem_namePropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setOemName(expected);
String actual = item.getOemName();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setOemName(expected);
actual = item.getOemName();
Assert.assertEquals(expected, actual);
}
public void testOsPropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setOs(expected);
String actual = item.getOs();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setOs(expected);
actual = item.getOs();
Assert.assertEquals(expected, actual);
}
public void testOs_versionPropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setOsVersion(expected);
String actual = item.getOsVersion();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setOsVersion(expected);
actual = item.getOsVersion();
Assert.assertEquals(expected, actual);
}
public void testRole_instancePropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setRoleInstance(expected);
String actual = item.getRoleInstance();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setRoleInstance(expected);
actual = item.getRoleInstance();
Assert.assertEquals(expected, actual);
}
public void testRole_namePropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setRoleName(expected);
String actual = item.getRoleName();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setRoleName(expected);
actual = item.getRoleName();
Assert.assertEquals(expected, actual);
}
public void testScreen_resolutionPropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setScreenResolution(expected);
String actual = item.getScreenResolution();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setScreenResolution(expected);
actual = item.getScreenResolution();
Assert.assertEquals(expected, actual);
}
public void testTypePropertyWorksAsExpected()
{
String expected = "Test string";
Device item = new Device();
item.setType(expected);
String actual = item.getType();
Assert.assertEquals(expected, actual);
expected = "Other string";
item.setType(expected);
actual = item.getType();
Assert.assertEquals(expected, actual);
}
public void testSerialize() throws IOException
{
Device item = new Device();
item.setId("Test string");
item.setIp("Test string");
item.setLanguage("Test string");
item.setLocale("Test string");
item.setModel("Test string");
item.setNetwork("Test string");
item.setOemName("Test string");
item.setOs("Test string");
item.setOsVersion("Test string");
item.setRoleInstance("Test string");
item.setRoleName("Test string");
item.setScreenResolution("Test string");
item.setType("Test string");
StringWriter writer = new StringWriter();
item.serialize(writer);
String expected = "{\"ai.device.id\":\"Test string\",\"ai.device.ip\":\"Test string\",\"ai.device.language\":\"Test string\",\"ai.device.locale\":\"Test string\",\"ai.device.model\":\"Test string\",\"ai.device.network\":\"Test string\",\"ai.device.oemName\":\"Test string\",\"ai.device.os\":\"Test string\",\"ai.device.osVersion\":\"Test string\",\"ai.device.roleInstance\":\"Test string\",\"ai.device.roleName\":\"Test string\",\"ai.device.screenResolution\":\"Test string\",\"ai.device.type\":\"Test string\"}";
Assert.assertEquals(expected, writer.toString());
}
}
|
package io.debezium.connector.oracle.logminer;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.buildDataDictionary;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.checkSupplementalLogging;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.createFlushTable;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.endMining;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.flushLogWriter;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.getCurrentRedoLogFiles;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.getEndScn;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.getFirstOnlineLogScn;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.getLastScnToAbandon;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.getTimeDifference;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.instantiateFlushConnections;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.logError;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.setNlsSessionParameters;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.setRedoLogFilesForMining;
import static io.debezium.connector.oracle.logminer.LogMinerHelper.startLogMining;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.DebeziumException;
import io.debezium.connector.oracle.OracleConnection;
import io.debezium.connector.oracle.OracleConnectorConfig;
import io.debezium.connector.oracle.OracleDatabaseSchema;
import io.debezium.connector.oracle.OracleOffsetContext;
import io.debezium.connector.oracle.OracleTaskContext;
import io.debezium.jdbc.JdbcConfiguration;
import io.debezium.pipeline.ErrorHandler;
import io.debezium.pipeline.EventDispatcher;
import io.debezium.pipeline.source.spi.StreamingChangeEventSource;
import io.debezium.relational.TableId;
import io.debezium.util.Clock;
import io.debezium.util.Metronome;
import io.debezium.util.Stopwatch;
/**
* A {@link StreamingChangeEventSource} based on Oracle's LogMiner utility.
* The event handler loop is executed in a separate executor.
*/
public class LogMinerStreamingChangeEventSource implements StreamingChangeEventSource {
private static final Logger LOGGER = LoggerFactory.getLogger(LogMinerStreamingChangeEventSource.class);
private final OracleConnection jdbcConnection;
private final EventDispatcher<TableId> dispatcher;
private final Clock clock;
private final OracleDatabaseSchema schema;
private final OracleOffsetContext offsetContext;
private final String catalogName;
private final boolean isRac;
private final Set<String> racHosts = new HashSet<>();
private final JdbcConfiguration jdbcConfiguration;
private final OracleConnectorConfig.LogMiningStrategy strategy;
private final OracleTaskContext taskContext;
private final ErrorHandler errorHandler;
private final boolean isContinuousMining;
private OracleConnectorConfig connectorConfig;
private LogMinerMetrics logMinerMetrics;
private long startScn;
private long endScn;
private Duration archiveLogRetention;
public LogMinerStreamingChangeEventSource(OracleConnectorConfig connectorConfig, OracleOffsetContext offsetContext,
OracleConnection jdbcConnection, EventDispatcher<TableId> dispatcher,
ErrorHandler errorHandler, Clock clock, OracleDatabaseSchema schema,
OracleTaskContext taskContext) {
this.jdbcConnection = jdbcConnection;
this.dispatcher = dispatcher;
this.clock = clock;
this.schema = schema;
this.offsetContext = offsetContext;
this.connectorConfig = connectorConfig;
this.catalogName = (connectorConfig.getPdbName() != null) ? connectorConfig.getPdbName() : connectorConfig.getDatabaseName();
this.strategy = connectorConfig.getLogMiningStrategy();
this.isContinuousMining = connectorConfig.isContinuousMining();
this.errorHandler = errorHandler;
this.taskContext = taskContext;
this.jdbcConfiguration = JdbcConfiguration.adapt(connectorConfig.getConfig().subset("database.", true));
this.isRac = connectorConfig.isRacSystem();
if (this.isRac) {
this.racHosts.addAll(connectorConfig.getRacNodes().stream().map(String::toUpperCase).collect(Collectors.toSet()));
instantiateFlushConnections(jdbcConfiguration, racHosts);
}
this.archiveLogRetention = connectorConfig.getLogMiningArchiveLogRetention();
}
/**
* This is the loop to get changes from LogMiner
*
* @param context
* change event source context
*/
@Override
public void execute(ChangeEventSourceContext context) {
try (TransactionalBuffer transactionalBuffer = new TransactionalBuffer(taskContext, errorHandler)) {
try {
// Perform registration
registerLogMinerMetrics();
long databaseTimeMs = getTimeDifference(jdbcConnection).toMillis();
LOGGER.trace("Current time {} ms, database difference {} ms", System.currentTimeMillis(), databaseTimeMs);
transactionalBuffer.setDatabaseTimeDifference(databaseTimeMs);
startScn = offsetContext.getScn();
createFlushTable(jdbcConnection);
if (!isContinuousMining && startScn < getFirstOnlineLogScn(jdbcConnection, archiveLogRetention)) {
throw new DebeziumException(
"Online REDO LOG files or archive log files do not contain the offset scn " + startScn + ". Please perform a new snapshot.");
}
setNlsSessionParameters(jdbcConnection);
checkSupplementalLogging(jdbcConnection, connectorConfig.getPdbName(), schema);
initializeRedoLogsForMining(jdbcConnection, false, archiveLogRetention);
HistoryRecorder historyRecorder = connectorConfig.getLogMiningHistoryRecorder();
Duration processTime = Duration.ZERO;
try {
// todo: why can't OracleConnection be used rather than a Factory+JdbcConfiguration?
historyRecorder.prepare(logMinerMetrics, jdbcConfiguration, connectorConfig.getLogMinerHistoryRetentionHours());
final LogMinerQueryResultProcessor processor = new LogMinerQueryResultProcessor(context, jdbcConnection,
connectorConfig, logMinerMetrics, transactionalBuffer, offsetContext, schema, dispatcher,
catalogName, clock, historyRecorder);
final String query = SqlUtils.logMinerContentsQuery(connectorConfig.getSchemaName(), jdbcConnection.username(), schema);
try (PreparedStatement miningView = jdbcConnection.connection().prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT)) {
Set<String> currentRedoLogFiles = getCurrentRedoLogFiles(jdbcConnection, logMinerMetrics);
Stopwatch stopwatch = Stopwatch.reusable();
while (context.isRunning()) {
Instant start = Instant.now();
endScn = getEndScn(jdbcConnection, startScn, logMinerMetrics, connectorConfig.getLogMiningBatchSizeDefault());
flushLogWriter(jdbcConnection, jdbcConfiguration, isRac, racHosts);
Set<String> possibleNewCurrentLogFile = getCurrentRedoLogFiles(jdbcConnection, logMinerMetrics);
if (!currentRedoLogFiles.equals(possibleNewCurrentLogFile)) {
LOGGER.debug("Redo log switch detected, from {} to {}", currentRedoLogFiles, possibleNewCurrentLogFile);
// This is the way to mitigate PGA leaks.
// With one mining session, it grows and maybe there is another way to flush PGA.
// At this point we use a new mining session
LOGGER.trace("Ending log mining startScn={}, endScn={}, offsetContext.getScn={}, strategy={}, continuous={}",
startScn, endScn, offsetContext.getScn(), strategy, isContinuousMining);
endMining(jdbcConnection);
initializeRedoLogsForMining(jdbcConnection, true, archiveLogRetention);
abandonOldTransactionsIfExist(jdbcConnection, transactionalBuffer);
currentRedoLogFiles = getCurrentRedoLogFiles(jdbcConnection, logMinerMetrics);
}
startLogMining(jdbcConnection, startScn, endScn, strategy, isContinuousMining, logMinerMetrics);
stopwatch.start();
miningView.setFetchSize(connectorConfig.getMaxQueueSize());
miningView.setFetchDirection(ResultSet.FETCH_FORWARD);
miningView.setLong(1, startScn);
miningView.setLong(2, endScn);
try (ResultSet rs = miningView.executeQuery()) {
Duration lastDurationOfBatchCapturing = stopwatch.stop().durations().statistics().getTotal();
logMinerMetrics.setLastDurationOfBatchCapturing(lastDurationOfBatchCapturing);
processor.processResult(rs);
startScn = endScn;
if (transactionalBuffer.isEmpty()) {
LOGGER.debug("Transactional buffer empty, updating offset's SCN {}", startScn);
offsetContext.setScn(startScn);
}
}
processTime = processTime.plus(Duration.between(start, Instant.now()));
logMinerMetrics.setTotalProcessingTime(processTime);
pauseBetweenMiningSessions();
}
}
}
finally {
historyRecorder.close();
}
}
catch (Throwable t) {
logError(transactionalBuffer.getMetrics(), "Mining session stopped due to the {}", t);
errorHandler.setProducerThrowable(t);
}
finally {
LOGGER.info("startScn={}, endScn={}, offsetContext.getScn()={}", startScn, endScn, offsetContext.getScn());
LOGGER.info("Transactional buffer metrics dump: {}", transactionalBuffer.getMetrics().toString());
LOGGER.info("Transactional buffer dump: {}", transactionalBuffer.getMetrics().toString());
LOGGER.info("LogMiner metrics dump: {}", logMinerMetrics.toString());
// Perform unregistration
unregisterLogMinerMetrics();
}
}
}
private void registerLogMinerMetrics() {
logMinerMetrics = new LogMinerMetrics(taskContext, connectorConfig);
logMinerMetrics.register(LOGGER);
if (connectorConfig.isLogMiningHistoryRecorded()) {
logMinerMetrics.setRecordMiningHistory(true);
}
}
private void unregisterLogMinerMetrics() {
if (logMinerMetrics != null) {
logMinerMetrics.unregister(LOGGER);
}
}
private void abandonOldTransactionsIfExist(OracleConnection connection, TransactionalBuffer transactionalBuffer) {
Optional<Long> lastScnToAbandonTransactions = getLastScnToAbandon(connection, offsetContext.getScn(), connectorConfig.getLogMiningTransactionRetention());
lastScnToAbandonTransactions.ifPresent(thresholdScn -> {
transactionalBuffer.abandonLongTransactions(thresholdScn, offsetContext);
offsetContext.setScn(thresholdScn);
startScn = endScn;
});
}
private void initializeRedoLogsForMining(OracleConnection connection, boolean postEndMiningSession, Duration archiveLogRetention) throws SQLException {
if (!postEndMiningSession) {
if (OracleConnectorConfig.LogMiningStrategy.CATALOG_IN_REDO.equals(strategy)) {
buildDataDictionary(connection);
}
if (!isContinuousMining) {
setRedoLogFilesForMining(connection, startScn, archiveLogRetention);
}
}
else {
if (!isContinuousMining) {
if (OracleConnectorConfig.LogMiningStrategy.CATALOG_IN_REDO.equals(strategy)) {
buildDataDictionary(connection);
}
setRedoLogFilesForMining(connection, startScn, archiveLogRetention);
}
}
}
private void pauseBetweenMiningSessions() throws InterruptedException {
Duration period = Duration.ofMillis(logMinerMetrics.getMillisecondToSleepBetweenMiningQuery());
Metronome.sleeper(period, clock).pause();
}
@Override
public void commitOffset(Map<String, ?> offset) {
// nothing to do
}
}
|
package org.innovateuk.ifs.testdata.services;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.innovateuk.ifs.BaseBuilder;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.ApplicationState;
import org.innovateuk.ifs.application.resource.FundingDecision;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionStatus;
import org.innovateuk.ifs.finance.resource.OrganisationSize;
import org.innovateuk.ifs.finance.resource.cost.AdditionalCompanyCost;
import org.innovateuk.ifs.finance.resource.cost.FinanceRowType;
import org.innovateuk.ifs.finance.resource.cost.KtpTravelCost;
import org.innovateuk.ifs.form.resource.*;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum;
import org.innovateuk.ifs.testdata.builders.*;
import org.innovateuk.ifs.testdata.builders.data.*;
import org.innovateuk.ifs.user.resource.UserResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import static java.lang.Boolean.TRUE;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.innovateuk.ifs.competition.resource.FundingRules.SUBSIDY_CONTROL;
import static org.innovateuk.ifs.finance.resource.OrganisationSize.SMALL;
import static org.innovateuk.ifs.question.resource.QuestionSetupType.SUBSIDY_BASIS;
import static org.innovateuk.ifs.testdata.builders.ApplicationDataBuilder.newApplicationData;
import static org.innovateuk.ifs.testdata.builders.ApplicationFinanceDataBuilder.newApplicationFinanceData;
import static org.innovateuk.ifs.testdata.builders.CompetitionDataBuilder.newCompetitionData;
import static org.innovateuk.ifs.testdata.builders.ProcurementMilestoneDataBuilder.newProcurementMilestoneDataBuilder;
import static org.innovateuk.ifs.testdata.builders.QuestionResponseDataBuilder.newApplicationQuestionResponseData;
import static org.innovateuk.ifs.testdata.builders.QuestionnaireResponseDataBuilder.newQuestionnaireResponseDataBuilder;
import static org.innovateuk.ifs.testdata.builders.SubsidyBasisDataBuilder.newSubsidyBasisDataBuilder;
import static org.innovateuk.ifs.testdata.services.CsvUtils.*;
import static org.innovateuk.ifs.util.CollectionFunctions.*;
/**
* A service that {@link org.innovateuk.ifs.testdata.BaseGenerateTestData} uses to generate Application data. While
* {@link org.innovateuk.ifs.testdata.BaseGenerateTestData} is responsible for gathering CSV information and
* orchestarting the building of it, this service is responsible for taking the CSV data passed to it and using
* the appropriate builders to generate and update entities.
*/
@Component
@Lazy
public class ApplicationDataBuilderService extends BaseDataBuilderService {
private static final Logger LOG = LoggerFactory.getLogger(ApplicationDataBuilderService.class);
@Autowired
private GenericApplicationContext applicationContext;
private ApplicationDataBuilder applicationDataBuilder;
private CompetitionDataBuilder competitionDataBuilder;
private ApplicationFinanceDataBuilder applicationFinanceDataBuilder;
private ProcurementMilestoneDataBuilder procurementMilestoneDataBuilder;
private QuestionResponseDataBuilder questionResponseDataBuilder;
private QuestionnaireResponseDataBuilder questionnaireResponseDataBuilder;
private SubsidyBasisDataBuilder subsidyBasisDataBuilder;
@PostConstruct
public void readCsvs() {
ServiceLocator serviceLocator = new ServiceLocator(applicationContext, COMP_ADMIN_EMAIL, PROJECT_FINANCE_EMAIL);
applicationDataBuilder = newApplicationData(serviceLocator);
competitionDataBuilder = newCompetitionData(serviceLocator);
applicationFinanceDataBuilder = newApplicationFinanceData(serviceLocator);
questionResponseDataBuilder = newApplicationQuestionResponseData(serviceLocator);
procurementMilestoneDataBuilder = newProcurementMilestoneDataBuilder(serviceLocator);
questionnaireResponseDataBuilder = newQuestionnaireResponseDataBuilder(serviceLocator);
subsidyBasisDataBuilder = newSubsidyBasisDataBuilder(serviceLocator);
}
public List<ApplicationQuestionResponseData> createApplicationQuestionResponses(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ApplicationQuestionResponseLine> questionResponseLines) {
QuestionResponseDataBuilder baseBuilder =
questionResponseDataBuilder.withApplication(applicationData.getApplication());
if (!applicationLine.createApplicationResponses) {
return emptyList();
}
List<CsvUtils.ApplicationQuestionResponseLine> responsesForApplication =
simpleFilter(questionResponseLines, r ->
r.competitionName.equals(applicationLine.competitionName) &&
r.applicationName.equals(applicationLine.title));
// if we have specific answers for questions in the application-questions.csv file, fill them in here now
if (!responsesForApplication.isEmpty()) {
List<QuestionResponseDataBuilder> responseBuilders = questionResponsesFromCsv(
baseBuilder,
applicationLine.leadApplicant,
responsesForApplication);
return simpleMap(responseBuilders, BaseBuilder::build);
}
// otherwise provide a default set of marked as complete questions if the application is to be submitted
else if (applicationLine.markQuestionsComplete || applicationLine.submittedDate != null) {
Long competitionId = applicationData.getCompetition().getId();
List<QuestionResource> competitionQuestions = retrieveCachedQuestionsByCompetitionId(competitionId);
List<QuestionResource> questionsToAnswer = simpleFilter(competitionQuestions, q ->
!q.getMultipleStatuses() &&
q.getMarkAsCompletedEnabled() &&
q.getQuestionSetupType().hasFormInputResponses());
if (applicationData.getCompetition().isEnabledForPreRegistration()) {
questionsToAnswer = questionsToAnswer.stream()
.filter(questionResource -> questionResource.isEnabledForPreRegistration())
.collect(toList());
}
List<QuestionResponseDataBuilder> responseBuilders = simpleMap(questionsToAnswer, question -> {
String answerValue = "This is the applicant response for " + question.getName().toLowerCase() + ".";
String leadApplicantEmail = applicationData.getLeadApplicant().getEmail();
QuestionResponseDataBuilder responseBuilder = baseBuilder.
forQuestion(question.getName()).
withAssignee(leadApplicantEmail);
List<FormInputResource> formInputs = retrieveCachedFormInputsByQuestionId(question);
if (formInputs.stream().anyMatch(fi -> fi.getScope().equals(FormInputScope.APPLICATION) && fi.getType().equals(FormInputType.TEXTAREA))) {
responseBuilder = responseBuilder.withAnswer(answerValue, leadApplicantEmail);
}
if (formInputs.stream().anyMatch(fi -> fi.getScope().equals(FormInputScope.APPLICATION) && fi.getType().equals(FormInputType.MULTIPLE_CHOICE))) {
FormInputResource multipleChoice = formInputs.stream().filter(fi -> fi.getType().equals(FormInputType.MULTIPLE_CHOICE)).findFirst().get();
List<MultipleChoiceOptionResource> choices = multipleChoice.getMultipleChoiceOptions();
String applicationName = applicationData.getApplication().getName();
String questionName = question.getName();
//Pick a choice based on the application name and question name. Ensures we have a random choice, but is the same choice each time generator is ran.
int choice = (applicationName + questionName).length() % choices.size();
responseBuilder = responseBuilder.withChoice(choices.get(choice), leadApplicantEmail);
}
if (formInputs.stream().anyMatch(fi -> fi.getScope().equals(FormInputScope.APPLICATION) && fi.getType().equals(FormInputType.FILEUPLOAD))) {
String applicationName = applicationData.getApplication().getName();
String questionName = question.getShortName().toLowerCase();
String fileUploadName = (applicationName + "-" + questionName + ".pdf")
.toLowerCase().replace(' ', '-') ;
responseBuilder = responseBuilder.
withFileUploads(singletonList(fileUploadName), leadApplicantEmail);
}
return responseBuilder;
});
return simpleMap(responseBuilders, BaseBuilder::build);
}
return emptyList();
}
public List<ApplicationFinanceData> createApplicationFinances(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ApplicationOrganisationFinanceBlock> applicationFinanceLines,
List<ExternalUserLine> externalUsers) {
if (!applicationLine.createFinanceResponses) {
return emptyList();
}
Map<String, String> usersOrganisations = simpleToMap(externalUsers, user -> user.emailAddress, user -> user.organisationName);
List<String> applicants = combineLists(applicationLine.leadApplicant, applicationLine.collaborators);
List<Triple<String, String, OrganisationTypeEnum>> organisations = simpleMap(applicants, email -> {
UserResource user = retrieveUserByEmail(email);
OrganisationResource organisation = organisationByName(usersOrganisations.get(email));
return Triple.of(user.getEmail(), organisation.getName(),
OrganisationTypeEnum.getFromId(organisation.getOrganisationType()));
});
List<Triple<String, String, OrganisationTypeEnum>> uniqueOrganisations = simpleFilter(organisations, triple ->
isUniqueOrFirstDuplicateOrganisation(triple, organisations));
List<ApplicationFinanceDataBuilder> builders = simpleMap(uniqueOrganisations, orgDetails -> {
String user = orgDetails.getLeft();
String organisationName = orgDetails.getMiddle();
OrganisationTypeEnum organisationType = orgDetails.getRight();
Optional<CsvUtils.ApplicationOrganisationFinanceBlock> organisationFinances =
simpleFindFirst(applicationFinanceLines, finances ->
finances.competitionName.equals(applicationLine.competitionName) &&
finances.applicationName.equals(applicationLine.title) &&
finances.organisationName.equals(organisationName));
if (applicationData.getCompetition().applicantShouldUseJesFinances(organisationType)) {
return organisationFinances.map(suppliedFinances ->
generateAcademicFinancesFromSuppliedData(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName)
).orElseGet(() ->
generateAcademicFinances(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName)
);
} else {
return organisationFinances.map(suppliedFinances ->
generateIndustrialCostsFromSuppliedData(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName,
suppliedFinances)
).orElseGet(() ->
generateIndustrialCosts(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName,
organisationType)
);
}
});
return simpleMap(builders, BaseBuilder::build);
}
private List<QuestionnaireResponseLine> defaultApplicationQuestionnaireResponseLines(ApplicationData applicationData,
ApplicationLine applicationLine,
List<ExternalUserLine> externalUsers){
if (applicationLine.markQuestionsComplete && applicationData.getCompetition().getFundingRules().equals(SUBSIDY_CONTROL)){
// Generate the default for the application.
return uniqueOrganisations(applicationLine, externalUsers).stream()
.map(organisation -> new QuestionnaireResponseLine(
organisation.getLeft(),
applicationData.getCompetition().getName(),
applicationData.getApplication().getName(),
organisation.getMiddle(),
SUBSIDY_BASIS,
asList("No", "No")))
.collect(toList());
}
return emptyList();
}
private List<QuestionnaireResponseLine> specifiedQuestionnaireResponseLines(ApplicationLine applicationLine,
List<QuestionnaireResponseLine> questionnaireResponseLines){
return questionnaireResponseLines.stream()
.filter(line -> line.competitionName.equals(applicationLine.competitionName))
.filter(line -> line.applicationName.equals(applicationLine.title))
.collect(toList());
}
public List<QuestionnaireResponseData> createQuestionnaireResponse(ApplicationData applicationData,
ApplicationLine applicationLine,
List<QuestionnaireResponseLine> questionnaireResponseLines,
List<ExternalUserLine> externalUsers) {
List<QuestionnaireResponseLine> specifiedLines = specifiedQuestionnaireResponseLines(applicationLine, questionnaireResponseLines);
List<QuestionnaireResponseLine> defaultLines = defaultApplicationQuestionnaireResponseLines(applicationData, applicationLine, externalUsers);
// Override defaults.
List<QuestionnaireResponseLine> lines = defaultLines.stream()
.map(defaultLine -> specifiedLines.stream()
.filter(specifiedLine -> defaultLine.organisationName.equals(specifiedLine.organisationName))
.findFirst()
.orElse(defaultLine))
.collect(toList());
return lines.stream()
.map(line -> questionnaireResponseDataBuilder
.withCompetition(applicationData.getCompetition())
.withQuestionSetup(line.questionSetupType)
.withApplication(applicationData.getApplication())
.withOrganisationName(line.organisationName)
.withUser(line.user)
.withSelectedOptions(line.options)
.withQuestionnaireResponse())
.map(QuestionnaireResponseDataBuilder::build).collect(toList());
}
public List<SubsidyBasisData> createSubsidyBasis(ApplicationLine applicationLine,
List<QuestionnaireResponseData> questionnaireResponseData) {
return questionnaireResponseData.stream()
.filter(line -> line.getQuestionSetupType().equals(SUBSIDY_BASIS) &&
line.getCompetition().getName().equals(applicationLine.competitionName) &&
line.getApplication().getName().equals(applicationLine.title))
.map(line -> subsidyBasisDataBuilder
.withCompetition(line.getCompetition())
.withQuestionnaireResponseUuid(line.getQuestionnaireResponseUuid())
.withApplication(line.getApplication())
.withOrganisationName(line.getOrganisationName())
.withUser(line.getUser())
.withOutcome(line.getOutcome())
.withSubsidyBasis())
.map(SubsidyBasisDataBuilder::build).collect(toList());
}
private List<Triple<String, String, OrganisationTypeEnum>> uniqueOrganisations(ApplicationLine applicationLine, List<ExternalUserLine> externalUsers){
Map<String, String> usersOrganisations = simpleToMap(externalUsers, user -> user.emailAddress, user -> user.organisationName);
List<String> applicants = combineLists(applicationLine.leadApplicant, applicationLine.collaborators);
List<Triple<String, String, OrganisationTypeEnum>> organisations = simpleMap(applicants, email -> {
UserResource user = retrieveUserByEmail(email);
OrganisationResource organisation = organisationByName(usersOrganisations.get(email));
return Triple.of(user.getEmail(), organisation.getName(),
OrganisationTypeEnum.getFromId(organisation.getOrganisationType()));
});
return simpleFilter(organisations, triple ->
isUniqueOrFirstDuplicateOrganisation(triple, organisations));
}
public List<ProcurementMilestoneData> createProcurementMilestones(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ExternalUserLine> externalUsers) {
if (applicationData.getCompetition().isProcurement() && applicationLine.createFinanceResponses) {
List<Triple<String, String, OrganisationTypeEnum>> uniqueOrganisations = uniqueOrganisations(applicationLine, externalUsers);
List<ProcurementMilestoneDataBuilder> builders = simpleMap(uniqueOrganisations, orgDetails -> {
String user = orgDetails.getLeft();
String organisationName = orgDetails.getMiddle();
return procurementMilestoneDataBuilder
.withApplication(applicationData.getApplication())
.withCompetition(applicationData.getCompetition())
.withOrganisation(organisationName)
.withUser(user)
.withMilestones();
});
return simpleMap(builders, BaseBuilder::build);
} else {
return emptyList();
}
}
public void completeApplication(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ApplicationQuestionResponseData> questionResponseData,
List<ApplicationFinanceData> financeData) {
if (applicationLine.markQuestionsComplete) {
forEachWithIndex(questionResponseData, (i, response) -> {
boolean lastElement = i == questionResponseData.size() - 1;
questionResponseDataBuilder.
withExistingResponse(response).
markAsComplete(lastElement).
build();
});
}
if (applicationLine.markFinancesComplete) {
forEachWithIndex(financeData, (i, finance) -> {
boolean lastElement = i == financeData.size() - 1;
applicationFinanceDataBuilder.
withExistingFinances(
finance.getApplication(),
finance.getCompetition(),
finance.getUser(),
finance.getOrganisation()).
markAsComplete(true, lastElement).
build();
});
}
ApplicationDataBuilder applicationBuilder = this.applicationDataBuilder.
withExistingApplication(applicationData).
markApplicationDetailsComplete(applicationLine.markQuestionsComplete).
markApplicationTeamComplete(applicationLine.markQuestionsComplete).
markResearchCategoryComplete(applicationLine.markQuestionsComplete);
if (applicationLine.submittedDate != null) {
applicationBuilder = applicationBuilder.submitApplication();
}
if (asLinkedSet(ApplicationState.INELIGIBLE, ApplicationState.INELIGIBLE_INFORMED).
contains(applicationLine.status)) {
applicationBuilder = applicationBuilder.markApplicationIneligible(applicationLine.ineligibleReason);
if (applicationLine.status == ApplicationState.INELIGIBLE_INFORMED) {
applicationBuilder = applicationBuilder.informApplicationIneligible();
}
}
applicationBuilder.build();
}
public void createFundingDecisions(
CompetitionData competition,
CompetitionLine competitionLine,
List<ApplicationLine> applicationLines) {
CompetitionDataBuilder basicCompetitionInformation = competitionDataBuilder.withExistingCompetition(competition);
LOG.info("createFundingDecisions basicCompetitionInformation name->" + competitionLine.getName());
if (!competition.getCompetition().isKtp()
&& (asList(CompetitionStatus.PROJECT_SETUP, CompetitionStatus.ASSESSOR_FEEDBACK).contains(competitionLine.getCompetitionStatus())
|| (competition.getCompetition().isAlwaysOpen() && CompetitionStatus.OPEN == competitionLine.getCompetitionStatus()))) {
basicCompetitionInformation.
moveCompetitionIntoFundersPanelStatus().
sendFundingDecisions(createFundingDecisionsFromCsv(competitionLine.getName(), applicationLines)).
build();
}
}
private List<Pair<String, FundingDecision>> createFundingDecisionsFromCsv(
String competitionName,
List<ApplicationLine> applicationLines) {
List<CsvUtils.ApplicationLine> matchingApplications = simpleFilter(applicationLines, a ->
a.competitionName.equals(competitionName));
List<CsvUtils.ApplicationLine> applicationsWithDecisions = simpleFilter(matchingApplications, a ->
asList(ApplicationState.APPROVED, ApplicationState.REJECTED).contains(a.status));
return simpleMap(applicationsWithDecisions, ma -> {
FundingDecision fundingDecision = ma.status == ApplicationState.APPROVED ? FundingDecision.FUNDED : FundingDecision.UNFUNDED;
return Pair.of(ma.title, fundingDecision);
});
}
private List<QuestionResponseDataBuilder> questionResponsesFromCsv(
QuestionResponseDataBuilder baseBuilder,
String leadApplicant,
List<CsvUtils.ApplicationQuestionResponseLine> responsesForApplication) {
return simpleMap(responsesForApplication, line -> {
String answeringUser = !isBlank(line.answeredBy) ? line.answeredBy : (!isBlank(line.assignedTo) ? line.assignedTo : leadApplicant);
UnaryOperator<QuestionResponseDataBuilder> withQuestion = builder -> builder.forQuestion(line.questionName);
UnaryOperator<QuestionResponseDataBuilder> answerIfNecessary = builder ->
!isBlank(line.value) ? builder.withAssignee(answeringUser).withAnswer(line.value, answeringUser)
: builder;
UnaryOperator<QuestionResponseDataBuilder> uploadFilesIfNecessary = builder ->
!line.filesUploaded.isEmpty() ?
builder.withAssignee(answeringUser).withFileUploads(line.filesUploaded, answeringUser) :
builder;
UnaryOperator<QuestionResponseDataBuilder> assignIfNecessary = builder ->
!isBlank(line.assignedTo) ? builder.withAssignee(line.assignedTo) : builder;
return withQuestion.
andThen(answerIfNecessary).
andThen(uploadFilesIfNecessary).
andThen(assignIfNecessary).
apply(baseBuilder);
});
}
public ApplicationData createApplication(
CompetitionData competition,
ApplicationLine line,
List<InviteLine> inviteLines,
List<ExternalUserLine> externalUsers) {
UserResource leadApplicant = retrieveUserByEmail(line.leadApplicant);
Map<String, String> usersOrganisations = simpleToMap(externalUsers, user -> user.emailAddress, user -> user.organisationName);
Organisation org = organisationRepository.findOneByName(usersOrganisations.get(line.leadApplicant));
ApplicationDataBuilder baseBuilder = applicationDataBuilder.withCompetition(competition.getCompetition()).
withBasicDetails(leadApplicant, line.title, line.researchCategory, line.resubmission, org.getId(), line.enabledForExpressionOfInterest).
withInnovationArea(line.innovationArea).
withStartDate(line.startDate).
withDurationInMonths(line.durationInMonths);
for (String collaborator : line.collaborators) {
baseBuilder = baseBuilder.inviteCollaborator(retrieveUserByEmail(collaborator), organisationRepository.findOneByName(usersOrganisations.get(collaborator)));
}
if (competition.getCompetition().isKtp() && line.submittedDate != null) {
baseBuilder = baseBuilder.inviteKta();
}
List<CsvUtils.InviteLine> pendingInvites = simpleFilter(inviteLines,
invite -> "APPLICATION".equals(invite.type) && line.title.equals(invite.targetName));
for (CsvUtils.InviteLine invite : pendingInvites) {
baseBuilder = baseBuilder.inviteCollaboratorNotYetRegistered(invite.email, invite.hash, invite.name,
invite.ownerName);
}
if (line.status != ApplicationState.CREATED) {
baseBuilder = baseBuilder.beginApplication();
}
return baseBuilder.build();
}
private boolean isUniqueOrFirstDuplicateOrganisation(
Triple<String, String, OrganisationTypeEnum> currentOrganisation,
List<Triple<String, String, OrganisationTypeEnum>> organisationList) {
Triple<String, String, OrganisationTypeEnum> matchingRecord = simpleFindFirstMandatory(organisationList, triple ->
triple.getMiddle().equals(currentOrganisation.getMiddle()));
return matchingRecord.equals(currentOrganisation);
}
private IndustrialCostDataBuilder addFinanceRow(
IndustrialCostDataBuilder builder,
CsvUtils.ApplicationFinanceRow financeRow) {
switch (financeRow.category) {
case "Working days per year":
return builder.withWorkingDaysPerYear(Integer.valueOf(financeRow.metadata.get(0)));
case "Grant claim amount":
return builder.withGrantClaimAmount(Integer.valueOf(financeRow.metadata.get(0)));
case "Grant claim":
return builder.withGrantClaim(BigDecimal.valueOf(Integer.valueOf(financeRow.metadata.get(0))));
case "Organisation size":
return builder.withOrganisationSize(OrganisationSize.findById(Long.valueOf(financeRow.metadata.get(0))));
case "Work postcode":
return builder.withWorkPostcode(financeRow.metadata.get(0));
case "Fec model enabled":
return builder.withFecEnabled(Boolean.valueOf(financeRow.metadata.get(0)));
case "Fec file uploaded":
return builder.withUploadedFecFile();
case "Fec cert expiry date":
return builder.withFecCertExpiryDate(LocalDate.parse(financeRow.metadata.get(0), DATE_PATTERN));
case "Labour":
return builder.withLabourEntry(
financeRow.metadata.get(0),
Integer.valueOf(financeRow.metadata.get(1)),
Integer.valueOf(financeRow.metadata.get(2)));
case "Overheads":
switch (financeRow.metadata.get(0).toLowerCase()) {
case "total":
return builder.withAdministrationSupportCostsTotalRate(
Integer.valueOf(financeRow.metadata.get(1)));
case "default":
return builder.withAdministrationSupportCostsDefaultRate();
case "none":
return builder.withAdministrationSupportCostsNone();
default:
throw new RuntimeException("Unknown rate type " + financeRow.metadata.get(0).toLowerCase());
}
case "Hecp indirect costs":
switch (financeRow.metadata.get(0).toLowerCase()) {
case "total":
return builder.withHecpAdministrationSupportCostsTotalRate(
Integer.valueOf(financeRow.metadata.get(1)));
case "default":
return builder.withHecpAdministrationSupportCostsDefaultRate();
case "none":
return builder.withHecpAdministrationSupportCostsNone();
default:
throw new RuntimeException("Unknown rate type " + financeRow.metadata.get(0).toLowerCase());
}
case "Materials":
return builder.withMaterials(
financeRow.metadata.get(0),
bd(financeRow.metadata.get(1)),
Integer.valueOf(financeRow.metadata.get(2)));
case "Equipment":
return builder.withEquipment(
financeRow.metadata.get(0),
bd(financeRow.metadata.get(1)),
Integer.valueOf(financeRow.metadata.get(2)));
case "Capital usage":
return builder.withCapitalUsage(
Integer.valueOf(financeRow.metadata.get(4)),
financeRow.metadata.get(0),
Boolean.parseBoolean(financeRow.metadata.get(1)),
bd(financeRow.metadata.get(2)),
bd(financeRow.metadata.get(3)),
Integer.valueOf(financeRow.metadata.get(5)));
case "Other goods":
return builder.withOtherGoods(
Integer.valueOf(financeRow.metadata.get(4)),
financeRow.metadata.get(0),
Boolean.parseBoolean(financeRow.metadata.get(1)),
bd(financeRow.metadata.get(2)),
bd(financeRow.metadata.get(3)),
Integer.valueOf(financeRow.metadata.get(5)));
case "Subcontracting":
return builder.withSubcontractingCost(
financeRow.metadata.get(0),
financeRow.metadata.get(1),
financeRow.metadata.get(2),
bd(financeRow.metadata.get(3)));
case "Travel and subsistence":
return builder.withTravelAndSubsistence(
financeRow.metadata.get(0),
Integer.valueOf(financeRow.metadata.get(1)),
bd(financeRow.metadata.get(2)));
case "Other costs":
return builder.withOtherCosts(
financeRow.metadata.get(0),
bd(financeRow.metadata.get(1)));
case "Other funding":
return builder.withOtherFunding(
financeRow.metadata.get(0),
LocalDate.parse(financeRow.metadata.get(1), DATE_PATTERN),
bd(financeRow.metadata.get(2)));
case "Associate Employment":
return builder.withAssociateSalaryCosts(
financeRow.metadata.get(0),
Integer.valueOf(financeRow.metadata.get(1)),
bi(financeRow.metadata.get(2))
);
case "Associate development":
return builder.withAssociateDevelopmentCosts(
financeRow.metadata.get(0),
Integer.valueOf(financeRow.metadata.get(1)),
bi(financeRow.metadata.get(2))
);
case "Ktp Travel and subsistence":
return builder.withKtpTravel(
KtpTravelCost.KtpTravelCostType.valueOf(financeRow.metadata.get(0)),
financeRow.metadata.get(1),
bd(financeRow.metadata.get(2)),
Integer.valueOf(financeRow.metadata.get(3)));
case "Consumables":
return builder.withConsumables(
financeRow.metadata.get(0),
bi(financeRow.metadata.get(1)),
Integer.valueOf(financeRow.metadata.get(2))
);
case "Additional company costs":
return builder.withAdditionalCompanyCosts(
AdditionalCompanyCost.AdditionalCompanyCostType.valueOf(financeRow.metadata.get(0)),
financeRow.metadata.get(1),
bi(financeRow.metadata.get(2))
);
case "Academic and secretarial support":
return builder.withAcademicAndSecretarialSupport(
bi(financeRow.metadata.get(0))
);
case "Indirect costs":
return builder.withIndirectCosts(
bi(financeRow.metadata.get(0))
);
default:
throw new RuntimeException("Unknown category " + financeRow.category);
}
}
private ApplicationFinanceDataBuilder generateIndustrialCostsFromSuppliedData(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName,
CsvUtils.ApplicationOrganisationFinanceBlock organisationFinances) {
ApplicationFinanceDataBuilder finance = this.applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user);
List<CsvUtils.ApplicationFinanceRow> financeRows = organisationFinances.rows;
UnaryOperator<IndustrialCostDataBuilder> costBuilder = costs -> {
IndustrialCostDataBuilder costsWithData = costs;
for (CsvUtils.ApplicationFinanceRow financeRow : financeRows) {
costsWithData = addFinanceRow(costsWithData, financeRow);
}
return costsWithData;
};
return finance.
withIndustrialCosts(costBuilder);
}
private ApplicationFinanceDataBuilder generateIndustrialCosts(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName,
OrganisationTypeEnum organisationType) {
UnaryOperator<IndustrialCostDataBuilder> costBuilder = costs -> {
final IndustrialCostDataBuilder[] builder = {costs};
Consumer<? super FinanceRowType> costPopulator = type -> {
switch(type) {
case LABOUR:
builder[0] = builder[0].withWorkingDaysPerYear(123).
withLabourEntry("Role 1", 200, 200).
withLabourEntry("Role 2", 400, 300).
withLabourEntry("Role 3", 600, 365);
break;
case OVERHEADS:
builder[0] = builder[0].withAdministrationSupportCostsNone();
break;
case HECP_INDIRECT_COSTS:
builder[0] = builder[0].withHecpAdministrationSupportCostsNone();
break;
case PROCUREMENT_OVERHEADS:
builder[0] = builder[0].withProcurementOverheads("procurement overhead" , 1000, 2000);
break;
case MATERIALS:
builder[0] = builder[0].withMaterials("Generator", bd("10020"), 10);
break;
case EQUIPMENT:
builder[0] = builder[0].withEquipment("Generator", bd("10020"), 10);
break;
case CAPITAL_USAGE:
builder[0] = builder[0].withCapitalUsage(12, "Depreciating Stuff", true, bd("2120"), bd("1200"), 60);
break;
case SUBCONTRACTING_COSTS:
builder[0] = builder[0].withSubcontractingCost("Developers", "UK", "To develop stuff", bd("90000"));
break;
case TRAVEL:
builder[0] = builder[0].withTravelAndSubsistence("To visit colleagues", 15, bd("398"));
break;
case OTHER_COSTS:
builder[0] = builder[0].withOtherCosts("Some more costs", bd("1100"));
break;
case VAT:
builder[0] = builder[0].withVat(true);
break;
case FINANCE:
if (!competition.isFullyFunded()) {
builder[0] = builder[0].withGrantClaim(BigDecimal.valueOf(30));
}
break;
case GRANT_CLAIM_AMOUNT:
builder[0] = builder[0].withGrantClaimAmount(12000);
break;
case OTHER_FUNDING:
if (!competition.isFullyFunded()) {
builder[0] = builder[0].withOtherFunding("Lottery", LocalDate.of(2016, 4, 1), bd("2468"));
}
break;
case YOUR_FINANCE:
//none for industrial costs.
break;
case ASSOCIATE_SALARY_COSTS:
builder[0] = builder[0].withAssociateSalaryCosts("role", 4, new BigInteger("6"));
break;
case ASSOCIATE_DEVELOPMENT_COSTS:
builder[0] = builder[0].withAssociateDevelopmentCosts("role", 4, new BigInteger("7"));
break;
case CONSUMABLES:
builder[0] = builder[0].withConsumables("item", new BigInteger("8"), 3);
break;
case ASSOCIATE_SUPPORT:
builder[0] = builder[0].withAssociateSupport("supp", new BigInteger("13"));
break;
case KNOWLEDGE_BASE:
builder[0] = builder[0].withKnowledgeBase("desc", new BigInteger("15"));
break;
case ESTATE_COSTS:
builder[0] = builder[0].withEstateCosts("desc", new BigInteger("16"));
break;
case KTP_TRAVEL:
builder[0] = builder[0].withKtpTravel(KtpTravelCost.KtpTravelCostType.ASSOCIATE, "desc", new BigDecimal("17.00"), 1);
break;
case ADDITIONAL_COMPANY_COSTS:
builder[0] = builder[0].withAdditionalCompanyCosts(AdditionalCompanyCost.AdditionalCompanyCostType.ASSOCIATE_SALARY, "desc", new BigInteger("18"));
break;
case PREVIOUS_FUNDING:
builder[0] = builder[0].withPreviousFunding("a", "b", "c", new BigDecimal("23"));
break;
case ACADEMIC_AND_SECRETARIAL_SUPPORT:
builder[0] = builder[0].withAcademicAndSecretarialSupport(new BigInteger("18"));
break;
case INDIRECT_COSTS:
builder[0] = builder[0].withIndirectCosts(new BigInteger("20"));
break;
}
};
if (competition.isKtp()) {
if (OrganisationTypeEnum.KNOWLEDGE_BASE == organisationType) {
getFinanceRowTypes(competition, true).forEach(costPopulator);
}
} else {
competition.getFinanceRowTypes().forEach(costPopulator);
if (TRUE.equals(competition.getIncludeProjectGrowthTable())) {
builder[0] = builder[0].withProjectGrowthTable(YearMonth.of(2020, 1),
60L,
new BigDecimal("100000"),
new BigDecimal("200000"),
new BigDecimal("300000"),
new BigDecimal("400000"));
} else {
builder[0] = builder[0].withEmployeesAndTurnover(50L,
new BigDecimal("700000"));
}
}
if (competition.getFundingRules() == SUBSIDY_CONTROL) {
if (organisationName.equals("Northern Irish Ltd.")) {
builder[0] = builder[0]
.withNorthernIrelandDeclaration(true);
} else {
builder[0] = builder[0]
.withNorthernIrelandDeclaration(false);
}
}
if (organisationType == OrganisationTypeEnum.KNOWLEDGE_BASE) {
return builder[0].withOrganisationSize(SMALL)
.withLocation()
.withFecEnabled(true)
.withUploadedFecFile();
} else {
return builder[0].withOrganisationSize(SMALL)
.withLocation();
}
};
return applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user).
withIndustrialCosts(costBuilder);
}
private List<FinanceRowType> getFinanceRowTypes(CompetitionResource competition, Boolean fecModelEnabled) {
return competition.getFinanceRowTypes().stream()
.filter(financeRowType -> BooleanUtils.isFalse(fecModelEnabled)
? !FinanceRowType.getFecSpecificFinanceRowTypes().contains(financeRowType)
: !FinanceRowType.getNonFecSpecificFinanceRowTypes().contains(financeRowType))
.collect(Collectors.toList());
}
private ApplicationFinanceDataBuilder generateAcademicFinances(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName) {
return applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user).
withAcademicCosts(costs -> costs.
withTsbReference("My REF").
withGrantClaim(BigDecimal.valueOf(100)).
withOtherFunding("Lottery", LocalDate.of(2016, 4, 1), bd("2468")).
withDirectlyIncurredStaff(bd("22")).
withDirectlyIncurredTravelAndSubsistence(bd("44")).
withDirectlyIncurredOtherCosts(bd("66")).
withDirectlyAllocatedInvestigators(bd("88")).
withDirectlyAllocatedEstateCosts(bd("110")).
withDirectlyAllocatedOtherCosts(bd("132")).
withIndirectCosts(bd("154")).
withExceptionsStaff(bd("176")).
withExceptionsOtherCosts(bd("198")).
withUploadedJesForm().
withLocation());
}
private ApplicationFinanceDataBuilder generateAcademicFinancesFromSuppliedData(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName) {
return applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user).
withAcademicCosts(costs -> costs.
withTsbReference("My REF").
withUploadedJesForm());
}
private BigDecimal bd(String value) {
return new BigDecimal(value);
}
private BigInteger bi(String value) {
return new BigInteger(value);
}
}
|
package de.mrapp.android.adapter.expandablelist.filterable;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.widget.ExpandableListView;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import de.mrapp.android.adapter.Filter;
import de.mrapp.android.adapter.FilterQuery;
import de.mrapp.android.adapter.Filterable;
import de.mrapp.android.adapter.MultipleChoiceListAdapter;
import de.mrapp.android.adapter.datastructure.group.Group;
import de.mrapp.android.adapter.datastructure.group.GroupFilter;
import de.mrapp.android.adapter.decorator.AbstractExpandableListDecorator;
import de.mrapp.android.adapter.expandablelist.ExpandableListAdapterItemClickListener;
import de.mrapp.android.adapter.expandablelist.ExpandableListAdapterItemLongClickListener;
import de.mrapp.android.adapter.expandablelist.ExpandableListAdapterListener;
import de.mrapp.android.adapter.expandablelist.ExpansionListener;
import de.mrapp.android.adapter.expandablelist.enablestate.ExpandableListEnableStateListener;
import de.mrapp.android.adapter.expandablelist.itemstate.ExpandableListItemStateListener;
import de.mrapp.android.adapter.expandablelist.sortable.AbstractSortableExpandableListAdapter;
import de.mrapp.android.adapter.expandablelist.sortable.ExpandableListSortingListener;
import de.mrapp.android.adapter.logging.LogLevel;
import static de.mrapp.android.util.Condition.ensureNotNull;
/**
* An abstract base class for all adapters, whose underlying data is managed as a filterable list of
* arbitrary group and child items. Such an adapter's purpose is to provide the underlying data for
* visualization using a {@link ExpandableListView} widget.
*
* @param <GroupType>
* The type of the underlying data of the adapter's group items
* @param <ChildType>
* The type of the underlying data of the adapter's child items
* @param <DecoratorType>
* The type of the decorator, which allows to customize the appearance of the views, which
* are used to visualize the group and child items of the adapter
* @author Michael Rapp
* @since 0.1.0
*/
public abstract class AbstractFilterableExpandableListAdapter<GroupType, ChildType, DecoratorType extends AbstractExpandableListDecorator<GroupType, ChildType>>
extends AbstractSortableExpandableListAdapter<GroupType, ChildType, DecoratorType>
implements FilterableExpandableListAdapter<GroupType, ChildType> {
/**
* The constant serial version UID.
*/
private static final long serialVersionUID = 1L;
/**
* A set, which contains the listeners, which should be notified, when the adapter's underlying
* data has been filtered.
*/
private transient Set<ExpandableListFilterListener<GroupType, ChildType>> filterListeners;
/**
* Notifies all listeners, which have been registered to be notified, when the adapter's
* underlying data has been filtered, when a filter has been applied on the adapter's group
* items.
*
* @param query
* The query, which has been used to filter the adapter's group items, as a {@link
* String}. The query may not be null
* @param flags
* The flags, which have been used to filter the adapter's group items, as an {@link
* Integer} value, or 0, if no flags have been used
* @param filter
* The filter, which has been used to apply the query on the single items, as an
* instance of the type {@link Filter} or null, if the items' implementations of the
* interface {@link Filterable} has been used instead
* @param filteredGroups
* A collection, which contains the adapter's filtered group items, as an instance of
* the type {@link List} or an empty collection, if the adapter does not contain any
* group items
*/
private void notifyOnApplyGroupFilter(@NonNull final String query, final int flags,
@Nullable final Filter<GroupType> filter,
@NonNull final List<GroupType> filteredGroups) {
for (ExpandableListFilterListener<GroupType, ChildType> listener : filterListeners) {
listener.onApplyGroupFilter(this, query, flags, filter, filteredGroups);
}
}
/**
* Notifies all listeners, which have been registered to be notified, when the adapter's
* underlying data has been filtered, when a filter, which has been used to filter the adapter's
* group items, has been reseted.
*
* @param query
* The query of the filter, which has been reseted, as a {@link String}. The query may
* not be null
* @param flags
* The flags of the filter, which has been reseted, as an {@link Integer} value
* @param unfilteredGroups
* A collection, which contains the adapter's unfiltered group items, as an instance of
* the type {@link List} or an empty collection, if the adapter does not contain any
* group items
*/
private void notifyOnResetGroupFilter(@NonNull final String query, final int flags,
@NonNull final List<GroupType> unfilteredGroups) {
for (ExpandableListFilterListener<GroupType, ChildType> listener : filterListeners) {
listener.onResetGroupFilter(this, query, flags, unfilteredGroups);
}
}
/**
* Notifies all listeners, which have been registered to be notified, when the adapter's
* underlying data has been filtered, when a filter has been applied on the adapter's child
* items.
*
* @param query
* The query, which has been used to filter the adapter's child items, as a {@link
* String}. The query may not be null
* @param flags
* The flags, which have been used to filter the adapter's child items, as an {@link
* Integer} value, or 0, if no flags have been used
* @param filter
* The filter, which has been used to apply the query on the single items, as an
* instance of the type {@link Filter} or null, if the items' implementations of the
* interface {@link Filterable} has been used instead
* @param group
* The group, whose child items have been filtered, as an instance of the generic type
* GroupType. The group may not be null
* @param groupIndex
* The index of the group, whose child items have been filtered, as an {@link Integer}
* value
* @param filteredChildren
* A collection, which contains the adapter's filtered child items, as an instance of
* the type {@link List} or an empty collection, if the adapter does not contain any
* child items
*/
private void notifyOnApplyChildFilter(@NonNull final String query, final int flags,
@Nullable final Filter<ChildType> filter,
@NonNull final GroupType group, final int groupIndex,
@NonNull final List<ChildType> filteredChildren) {
for (ExpandableListFilterListener<GroupType, ChildType> listener : filterListeners) {
listener.onApplyChildFilter(this, query, flags, filter, group, groupIndex,
filteredChildren);
}
}
/**
* Notifies all listeners, which have been registered to be notified, when the adapter's
* underlying data has been filtered, when a filter, which has been used to filter the adapter's
* child items, has been reseted.
*
* @param query
* The query of the filter, which has been reseted, as a {@link String}. The query may
* not be null
* @param flags
* The flags of the filter, which has been reseted, as an {@link Integer} value
* @param group
* The group, whose child items have been filtered, as an instance of the generic type
* GroupType. The group may not be null
* @param groupIndex
* The index of the group, whose child items have been filtered, as an {@link Integer}
* value
* @param unfilteredChildren
* A collection, which contains the adapter's unfiltered child items, as an instance of
* the type {@link List} or an empty collection, if the adapter does not contain any
* child items
*/
private void notifyOnResetChildFilter(@NonNull final String query, final int flags,
@NonNull final GroupType group, final int groupIndex,
@NonNull final List<ChildType> unfilteredChildren) {
for (ExpandableListFilterListener<GroupType, ChildType> listener : filterListeners) {
listener.onResetChildFilter(this, query, flags, group, groupIndex, unfilteredChildren);
}
}
/**
* Returns a set, which contains the listeners, which should be notified, when the adapter's
* underlying data has been filtered.
*
* @return A set, which contains the listeners, which should be notified, when the adapter's
* underlying data has been filtered, as an instance of the type {@link Set} or an empty set, if
* no listeners should be notified
*/
protected final Set<ExpandableListFilterListener<GroupType, ChildType>> getFilterListeners() {
return filterListeners;
}
/**
* Sets the set, which contains the listeners, which should be notified, when the adapter's
* underlying data has been filtered.
*
* @param filterListeners
* The set, which should be set, as an instance of the type {@link Set} or an empty set,
* if no listeners should be notified
*/
protected final void setFilterListeners(
@NonNull final Set<ExpandableListFilterListener<GroupType, ChildType>> filterListeners) {
ensureNotNull(filterListeners, "The listeners may not be null");
this.filterListeners = filterListeners;
}
/**
* Creates a new adapter, whose underlying data is managed as a filterable list of arbitrary
* group and child items.
*
* @param context
* The context, the adapter belongs to, as an instance of the class {@link Context}. The
* context may not be null
* @param decorator
* The decorator, which should be used to customize the appearance of the views, which
* are used to visualize the group and child items of the adapter, as an instance of the
* generic type DecoratorType. The decorator may not be null
* @param logLevel
* The log level, which should be used for logging, as a value of the enum {@link
* LogLevel}. The log level may not be null
* @param groupAdapter
* The adapter, which should manage the adapter's group items, as an instance of the
* type {@link MultipleChoiceListAdapter}. The adapter may not be null
* @param allowDuplicateChildren
* True, if duplicate child items, regardless from the group they belong to, should be
* allowed, false otherwise
* @param notifyOnChange
* True, if the method <code>notifyDataSetChanged():void</code> should be automatically
* called when the adapter's underlying data has been changed, false otherwise
* @param expandGroupOnClick
* True, if a group should be expanded, when it is clicked by the user, false otherwise
* @param itemClickListeners
* A set, which contains the listeners, which should be notified, when an item of the
* adapter has been clicked by the user, as an instance of the type {@link Set}, or an
* empty set, if no listeners should be notified
* @param itemLongClickListeners
* A set, which contains the listeners, which should be notified, when an item of the
* adapter has been long-clicked by the user, as an instance of the type {@link Set}, or
* an empty set, if no listeners should be notified
* @param adapterListeners
* A set, which contains the listeners, which should be notified, when the adapter's
* underlying data has been modified, as an instance of the type {@link Set}, or an
* empty set, if no listeners should be notified
* @param expansionListeners
* A set, which contains the listeners, which should be notified, when a group item has
* been expanded or collapsed, as an instance of the type {@link Set}, or an empty set,
* if no listeners should be notified
* @param setChildEnableStatesImplicitly
* True, if the enable states of children should be also set, when the enable state of
* the group, they belong to, is set
* @param enableStateListeners
* A set, which contains the listeners, which should be notified, when an item has been
* disabled or enabled, as an instance of the type {@link Set}, or an empty set, if no
* listeners should be notified
* @param numberOfGroupStates
* The number of states, the adapter's group items may have, as an {@link Integer}
* value. The value must be at least 1
* @param numberOfChildStates
* The number of states, the adapter's child items may have, as an {@link Integer}
* value. The value must be at least 1
* @param triggerGroupStateOnClick
* True, if the state of a group item should be triggered, when it is clicked by the
* user, false otherwise
* @param triggerChildStateOnClick
* True, if the state of a child item should be triggered, when it is clicked by the
* user, false otherwise
* @param setChildStatesImplicitly
* True, if the states of children should be also set, when the state of the group, they
* belong to, is set, false otherwise
* @param itemStateListeners
* A set, which contains the listeners, which should be notified, when the state of an
* item has been changed, or an empty set, if no listeners should be notified
* @param sortingListeners
* A set, which contains the listeners, which should be notified, when the adapter's
* underlying data has been sorted, or an empty set, if no listeners should be notified
* @param filterListeners
* A set, which contains the listeners, which should be notified, when the adapter's
* underlying data has been filtered, or an empty set, if no listeners should be
* notified
*/
protected AbstractFilterableExpandableListAdapter(@NonNull final Context context,
@NonNull final DecoratorType decorator,
@NonNull final LogLevel logLevel,
@NonNull final MultipleChoiceListAdapter<Group<GroupType, ChildType>> groupAdapter,
final boolean allowDuplicateChildren,
final boolean notifyOnChange,
final boolean expandGroupOnClick,
@NonNull final Set<ExpandableListAdapterItemClickListener<GroupType, ChildType>> itemClickListeners,
@NonNull final Set<ExpandableListAdapterItemLongClickListener<GroupType, ChildType>> itemLongClickListeners,
@NonNull final Set<ExpandableListAdapterListener<GroupType, ChildType>> adapterListeners,
@NonNull final Set<ExpansionListener<GroupType, ChildType>> expansionListeners,
final boolean setChildEnableStatesImplicitly,
@NonNull final Set<ExpandableListEnableStateListener<GroupType, ChildType>> enableStateListeners,
final int numberOfGroupStates,
final int numberOfChildStates,
final boolean triggerGroupStateOnClick,
final boolean triggerChildStateOnClick,
final boolean setChildStatesImplicitly,
@NonNull final Set<ExpandableListItemStateListener<GroupType, ChildType>> itemStateListeners,
@NonNull final Set<ExpandableListSortingListener<GroupType, ChildType>> sortingListeners,
@NonNull final Set<ExpandableListFilterListener<GroupType, ChildType>> filterListeners) {
super(context, decorator, logLevel, groupAdapter, allowDuplicateChildren, notifyOnChange,
expandGroupOnClick, itemClickListeners, itemLongClickListeners, adapterListeners,
expansionListeners, setChildEnableStatesImplicitly, enableStateListeners,
numberOfGroupStates, numberOfChildStates, triggerGroupStateOnClick,
triggerChildStateOnClick, setChildStatesImplicitly, itemStateListeners,
sortingListeners);
setFilterListeners(filterListeners);
}
@Override
public final boolean isFiltered() {
return areGroupsFiltered() || areChildrenFiltered();
}
@Override
public final boolean applyGroupFilter(@NonNull final String query, final int flags) {
boolean result = getGroupAdapter().applyFilter(query, flags);
if (result) {
notifyOnApplyGroupFilter(query, flags, null, getAllGroups());
notifyOnDataSetChanged();
String message =
"Applied group filter using the query \"" + query + "\" and flags \"" + flags +
"\"";
getLogger().logInfo(getClass(), message);
} else {
String message = "Group filter using the query \"" + query + "\" and flags \"" + flags +
"\" not applied, because a filter using the same query and flags is already " +
"applied on the adapter";
getLogger().logDebug(getClass(), message);
}
return result;
}
@Override
public final boolean applyGroupFilter(@NonNull final String query, final int flags,
@NonNull final Filter<GroupType> filter) {
boolean result = getGroupAdapter()
.applyFilter(query, flags, new GroupFilter<GroupType, ChildType>(filter));
if (result) {
notifyOnApplyGroupFilter(query, flags, filter, getAllGroups());
notifyOnDataSetChanged();
String message =
"Applied group filter using the query \"" + query + "\", flags \"" + flags +
"\" and filter \"" + filter + "\"";
getLogger().logInfo(getClass(), message);
} else {
String message = "Group filter using the query \"" + query + "\" flags \"" + flags +
"\" and filter \"" + filter +
"\" not applied, because a filter using the same query, flags and filter is already " +
"applied on the adapter";
getLogger().logDebug(getClass(), message);
}
return result;
}
@Override
public final boolean resetGroupFilter(@NonNull final String query, final int flags) {
boolean result = getGroupAdapter().resetFilter(query, flags);
if (result) {
notifyOnDataSetChanged();
notifyOnResetGroupFilter(query, flags, getAllGroups());
String message =
"Reseted group filter with query \"" + query + "\" and flags \"" + flags + "\"";
getLogger().logInfo(getClass(), message);
} else {
String message = "Group filter with query \"" + query + "\" and flags \"" + flags +
"\" not reseted, because no such filter is applied on the adapter";
getLogger().logDebug(getClass(), message);
}
return result;
}
@Override
public final void resetAllGroupFilters() {
for (FilterQuery filterQuery : getGroupFilterQueries()) {
resetGroupFilter(filterQuery.getQuery(), filterQuery.getFlags());
}
String message = "Reseted all previously applied group filters";
getLogger().logInfo(getClass(), message);
}
@Override
public final boolean isGroupFilterApplied(@NonNull final String query, final int flags) {
return getGroupAdapter().isFilterApplied(query, flags);
}
@Override
public final boolean areGroupsFiltered() {
return getGroupAdapter().isFiltered();
}
@Override
public final Set<? extends FilterQuery> getGroupFilterQueries() {
return getGroupAdapter().getFilterQueries();
}
@Override
public final boolean applyChildFilter(@NonNull final String query, final int flags) {
return applyChildFilter(false, query, flags);
}
@Override
public final boolean applyChildFilter(final boolean filterEmptyGroups,
@NonNull final String query, final int flags) {
boolean result = true;
for (int i = 0; i < getGroupCount(); i++) {
result &= applyChildFilter(i, query, flags);
}
if (filterEmptyGroups) {
applyGroupFilter("", Group.FLAG_FILTER_EMPTY_GROUPS);
}
return result;
}
@Override
public final boolean applyChildFilter(@NonNull final GroupType group,
@NonNull final String query, final int flags) {
return applyChildFilter(false, group, query, flags);
}
@Override
public final boolean applyChildFilter(final boolean filterEmptyGroup,
@NonNull final GroupType group,
@NonNull final String query, final int flags) {
return applyChildFilter(filterEmptyGroup, indexOfGroupOrThrowException(group), query,
flags);
}
@Override
public final boolean applyChildFilter(final int groupIndex, @NonNull final String query,
final int flags) {
return applyChildFilter(false, groupIndex, query, flags);
}
@Override
public final boolean applyChildFilter(final boolean filterEmptyGroup, final int groupIndex,
@NonNull final String query, final int flags) {
Group<GroupType, ChildType> group = getGroupAdapter().getItem(groupIndex);
boolean result = group.getChildAdapter().applyFilter(query, flags);
if (result) {
notifyOnApplyChildFilter(query, flags, null, group.getData(), groupIndex,
getAllChildren(groupIndex));
notifyOnDataSetChanged();
String message =
"Applied child filter using the query \"" + query + "\" and flags \"" + flags +
"\" on the group \"" + group.getData() + "\" at index " + groupIndex;
getLogger().logInfo(getClass(), message);
if (filterEmptyGroup) {
applyGroupFilter("", Group.FLAG_FILTER_EMPTY_GROUPS);
}
} else {
String message = "Child filter using the query \"" + query + "\" and flags \"" + flags +
"\" not applied on group \"" + group.getData() + "\" at index " + groupIndex +
", because a filter using the same query and flags is already applied on the group";
getLogger().logDebug(getClass(), message);
}
return result;
}
@Override
public final boolean applyChildFilter(@NonNull final String query, final int flags,
@NonNull final Filter<ChildType> filter) {
return applyChildFilter(false, query, flags, filter);
}
@Override
public final boolean applyChildFilter(final boolean filterEmptyGroups,
@NonNull final String query, final int flags,
@NonNull final Filter<ChildType> filter) {
boolean result = true;
for (int i = 0; i < getGroupCount(); i++) {
result &= applyChildFilter(i, query, flags, filter);
}
if (filterEmptyGroups) {
applyGroupFilter("", Group.FLAG_FILTER_EMPTY_GROUPS);
}
return result;
}
@Override
public final boolean applyChildFilter(@NonNull final GroupType group,
@NonNull final String query, final int flags,
@NonNull final Filter<ChildType> filter) {
return applyChildFilter(false, group, query, flags, filter);
}
@Override
public final boolean applyChildFilter(final boolean filterEmptyGroup,
@NonNull final GroupType group,
@NonNull final String query, final int flags,
@NonNull final Filter<ChildType> filter) {
return applyChildFilter(filterEmptyGroup, indexOfGroupOrThrowException(group), query, flags,
filter);
}
@Override
public final boolean applyChildFilter(final int groupIndex, @NonNull final String query,
final int flags,
@NonNull final Filter<ChildType> filter) {
return applyChildFilter(false, groupIndex, query, flags, filter);
}
@Override
public final boolean applyChildFilter(final boolean filterEmptyGroup, final int groupIndex,
@NonNull final String query, final int flags,
@NonNull final Filter<ChildType> filter) {
Group<GroupType, ChildType> group = getGroupAdapter().getItem(groupIndex);
boolean result = group.getChildAdapter().applyFilter(query, flags, filter);
if (result) {
notifyOnApplyChildFilter(query, flags, filter, group.getData(), groupIndex,
getAllChildren(groupIndex));
notifyOnDataSetChanged();
String message =
"Applied child filter using the query \"" + query + "\", flags \"" + flags +
"\" and filter \"" + filter + "\" on the group \"" + group.getData() +
"\" at index " + groupIndex;
getLogger().logInfo(getClass(), message);
if (filterEmptyGroup) {
applyGroupFilter("", Group.FLAG_FILTER_EMPTY_GROUPS);
}
} else {
String message = "Child filter using the query \"" + query + "\", flags \"" + flags +
"\" and filter \"" + filter + "\" not applied on group \"" + group.getData() +
"\" at index " + groupIndex +
", because a filter using the same query, flags and filter is already applied on the group";
getLogger().logDebug(getClass(), message);
}
return result;
}
@Override
public final boolean resetChildFilter(@NonNull final String query, final int flags) {
boolean result = true;
for (int i = 0; i < getGroupCount(); i++) {
result &= resetChildFilter(i, query, flags);
}
return result;
}
@Override
public final boolean resetChildFilter(@NonNull final GroupType group,
@NonNull final String query, final int flags) {
return resetChildFilter(indexOfGroupOrThrowException(group), query, flags);
}
@Override
public final boolean resetChildFilter(final int groupIndex, @NonNull final String query,
final int flags) {
Group<GroupType, ChildType> group = getGroupAdapter().getItem(groupIndex);
boolean result = group.getChildAdapter().resetFilter(query, flags);
if (result) {
notifyOnResetChildFilter(query, flags, group.getData(), groupIndex,
getAllChildren(groupIndex));
notifyOnDataSetChanged();
String message = "Reseted child filter of group \"" + group.getData() + "\" at index " +
groupIndex + " with query \"" + query + "\" and flags \"" + flags + "\"";
getLogger().logInfo(getClass(), message);
if (isGroupFilterApplied("", Group.FLAG_FILTER_EMPTY_GROUPS)) {
resetGroupFilter("", Group.FLAG_FILTER_EMPTY_GROUPS);
}
} else {
String message =
"Child filter of group \"" + group.getData() + "\" at index " + groupIndex +
" with query \"" + query + "\" and flags \"" + flags +
"\" not reseted, because no such filter is applied on the adapter";
getLogger().logDebug(getClass(), message);
}
return result;
}
@Override
public final void resetAllChildFilters() {
resetGroupFilter("", Group.FLAG_FILTER_EMPTY_GROUPS);
for (int i = 0; i < getGroupCount(); i++) {
resetAllChildFilters(i);
}
}
@Override
public final void resetAllChildFilters(@NonNull final GroupType group) {
resetAllChildFilters(indexOfGroupOrThrowException(group));
}
@Override
public final void resetAllChildFilters(final int groupIndex) {
resetGroupFilter("", Group.FLAG_FILTER_EMPTY_GROUPS);
for (FilterQuery filterQuery : getChildFilterQueries(groupIndex)) {
resetChildFilter(groupIndex, filterQuery.getQuery(), filterQuery.getFlags());
}
String message =
"Reseted all previously applied child filters of group \"" + getGroup(groupIndex) +
"\" at index " + groupIndex;
getLogger().logInfo(getClass(), message);
}
@Override
public final void addFilterListener(
@NonNull final ExpandableListFilterListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
filterListeners.add(listener);
String message = "Added filter listener \"" + listener + "\"";
getLogger().logDebug(getClass(), message);
}
@Override
public final void removeFilterListener(
@NonNull final ExpandableListFilterListener<GroupType, ChildType> listener) {
ensureNotNull(listener, "The listener may not be null");
filterListeners.remove(listener);
String message = "Removed filter listener \"" + listener + "\"";
getLogger().logDebug(getClass(), message);
}
@Override
public final boolean isChildFilterApplied(@NonNull final String query, final int flags) {
for (int i = 0; i < getGroupCount(); i++) {
if (isChildFilterApplied(i, query, flags)) {
return true;
}
}
return false;
}
@Override
public final boolean areChildrenFiltered() {
for (int i = 0; i < getGroupCount(); i++) {
if (areChildrenFiltered(i)) {
return true;
}
}
return false;
}
@Override
public final boolean isChildFilterApplied(@NonNull final GroupType group,
@NonNull final String query, final int flags) {
return isChildFilterApplied(indexOfGroupOrThrowException(group), query, flags);
}
@Override
public final boolean isChildFilterApplied(final int groupIndex, @NonNull final String query,
final int flags) {
return getGroupAdapter().getItem(groupIndex).getChildAdapter()
.isFilterApplied(query, flags);
}
@Override
public final boolean areChildrenFiltered(@NonNull final GroupType group) {
return areChildrenFiltered(indexOfGroupOrThrowException(group));
}
@Override
public final boolean areChildrenFiltered(final int groupIndex) {
return getGroupAdapter().getItem(groupIndex).getChildAdapter().isFiltered();
}
@Override
public final Set<? extends FilterQuery> getChildFilterQueries() {
Set<FilterQuery> queries = new LinkedHashSet<>();
for (int i = 0; i < getGroupCount(); i++) {
queries.addAll(getChildFilterQueries(i));
}
return queries;
}
@Override
public final Set<? extends FilterQuery> getChildFilterQueries(final int groupIndex) {
return getGroupAdapter().getItem(groupIndex).getChildAdapter().getFilterQueries();
}
@Override
public final Set<? extends FilterQuery> getChildFilterQueries(final GroupType group) {
return getChildFilterQueries(indexOfGroupOrThrowException(group));
}
@Override
public abstract AbstractFilterableExpandableListAdapter<GroupType, ChildType, DecoratorType> clone()
throws CloneNotSupportedException;
}
|
package org.venice.piazza.servicecontroller.messaging.handlers;
// Remove System.out.println
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import model.job.PiazzaJobType;
import model.job.metadata.ExecuteServiceData;
import model.job.metadata.ResourceMetadata;
import model.job.type.ExecuteServiceJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor;
import org.venice.piazza.servicecontroller.util.CoreLogger;
import org.venice.piazza.servicecontroller.util.CoreServiceProperties;
/**
* Handler for handling executeService requests. This handler is used
* when execute-service kafka topics are received or when clients utilize the
* ServiceController service.
* @author mlynum
* @version 1.0
*
*/
public class ExecuteServiceHandler implements PiazzaJobHandler {
private MongoAccessor accessor;
private CoreLogger coreLogger;
private CoreServiceProperties coreServiceProperties;
private RestTemplate template;
private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteServiceHandler.class);
public ExecuteServiceHandler(MongoAccessor accessor, CoreServiceProperties coreServiceProperties, CoreLogger coreLogger) {
this.accessor = accessor;
this.coreServiceProperties = coreServiceProperties;
this.template = new RestTemplate();
this.coreLogger = coreLogger;
}
/*
* Handler for handling execute service requets. This
* method will execute a service given the resourceId and return a response to
* the job manager.
* MongoDB
* (non-Javadoc)
* @see org.venice.piazza.servicecontroller.messaging.handlers.Handler#handle(model.job.PiazzaJobType)
*/
public ResponseEntity<List<String>> handle (PiazzaJobType jobRequest ) {
ExecuteServiceJob job = (ExecuteServiceJob)jobRequest;
LOGGER.debug("Executing a service");
if (job != null) {
// Get the ResourceMetadata
ExecuteServiceData esData = job.data;
ResponseEntity<String> handleResult = handle(esData);
ArrayList<String> resultList = new ArrayList<String>();
resultList.add(handleResult.getBody());
ResponseEntity<List<String>> result = new ResponseEntity<List<String>>(resultList,handleResult.getStatusCode());
// TODO Use the result, send a message with the resource ID
// and jobId
return result;
}
else {
return null;
}
}//handle
/**
* Handles requests to execute a service. T
* TODO this needs to change to levarage pz-jbcommon ExecuteServiceMessage
* after it builds.
* @param message
* @return the Response as a String
*/
public ResponseEntity<String> handle (ExecuteServiceData data) {
ResponseEntity<String> responseEntity = null;
// Get the id from the data
String resourceId = data.getResourceId();
ResourceMetadata rMetadata = accessor.getResourceById(resourceId);
// Now get the mimeType for the request not using for now..
String requestMimeType = rMetadata.requestMimeType;
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
// If there are parameters
if (data.dataInputs.size() > 0) {
LOGGER.info("number of inputs are" + data.dataInputs.size());
LOGGER.info("The inputs are " + data.dataInputs.toString());
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(rMetadata.url);
// Loop Through and add the parameters for the call
Iterator<Entry<String, String>> it = data.dataInputs.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
LOGGER.debug(pair.getKey() + " = " + pair.getValue());
map.add((String)pair.getKey(), (String)pair.getValue());
builder.queryParam((String)pair.getKey(), (String)pair.getValue());
}
// Determine the method type to execute the service
// Just handling Post and get for now
// If there is no Json or body coming with this the just execute
if (data.dataInput == null || data.dataInput.length() <= 0) {
if (rMetadata.method.toUpperCase().equals("POST")) {
LOGGER.debug("The url to be executed is " + rMetadata.url);
responseEntity = template.postForEntity(rMetadata.url, map, String.class);
LOGGER.debug("The Response is " + responseEntity.toString());
coreLogger.log("Service with resourceID " + resourceId + " was executed with the following result " + responseEntity, CoreLogger.INFO);
}
else if (rMetadata.method.toUpperCase().equals("GET")) {
LOGGER.debug("The map of parameters is " + map.size());
LOGGER.debug("The url to be executed is " + rMetadata.url);
LOGGER.debug("The built URI is " + builder.toUriString());
responseEntity = template.getForEntity(builder.toUriString(), String.class, map);
LOGGER.debug("The Response is " + responseEntity.toString());
coreLogger.log("Service " + rMetadata.name + " with resourceID " + rMetadata.id + " was executed with the following result " + responseEntity, CoreLogger.INFO);
}
}
// There are parameters and a request BODY (POST) so handle
else {
// If it is a post with a body then build the enttiy adding teh body
if (rMetadata.method.toUpperCase().equals("POST")) {
HttpEntity<String> requestEntity = buildHttpEntity(rMetadata, map, data.dataInput);
LOGGER.debug("The url to be executed is " + rMetadata.url);
responseEntity = template.postForEntity(rMetadata.url, requestEntity, String.class);
LOGGER.debug("The Response is " + responseEntity.toString());
coreLogger.log("Service with resourceID " + resourceId + " was executed with the following result " + responseEntity, CoreLogger.INFO);
}
}
}// If there were named parameters
// Else there were no named parameters so if there is just a blob of data
else {
// Check to see if there is a value in the dataInput assume JSON mass post
if (data.dataInput.length() > 0) {
if (rMetadata.method.toUpperCase().equals("POST")) {
HttpHeaders headers = new HttpHeaders();
// Set the mimeType of the request
MediaType mediaType = createMediaType(rMetadata.requestMimeType);
headers.setContentType(mediaType);
LOGGER.debug("Json to be used " + data.dataInput);
LOGGER.debug("Mimetype is " + mediaType.getType());
HttpEntity<String> requestEntity = new HttpEntity<String>(data.dataInput,headers);
responseEntity = template.postForEntity(rMetadata.url, requestEntity, String.class);
LOGGER.debug("Service " + rMetadata.name + " with resourceID " + rMetadata.id + " was executed with the following result " + responseEntity.getBody());
coreLogger.log("Service " + rMetadata.name + " with resourceID " + rMetadata.id + " was executed with the following result " + responseEntity.getBody(), CoreLogger.INFO);
}
else if (rMetadata.method.toUpperCase().equals("GET")) {
LOGGER.debug("Json to be used " + data.dataInput);
String uri = rMetadata.url + "?" + data.dataInput;
responseEntity = template.getForEntity(uri, String.class);
coreLogger.log("Service " + rMetadata.name + " with resourceID " + rMetadata.id + " was executed with the following result " + responseEntity.getBody(), CoreLogger.INFO);
}
}
// There are no parameters, just make a call
else {
if (rMetadata.method.toUpperCase().equals("POST")) {
HttpHeaders headers = new HttpHeaders();
MediaType mediaType = createMediaType(rMetadata.requestMimeType);
headers.setContentType(mediaType);
LOGGER.debug("Calling URL POST " + rMetadata.url);
LOGGER.debug("Mimetype is " + mediaType.getType() + mediaType.getSubtype());
responseEntity = template.postForEntity(rMetadata.url, null, String.class);
LOGGER.debug("Service " + rMetadata.name + " with resourceID " + rMetadata.id + " was executed with the following result " + responseEntity.getBody());
coreLogger.log("Service " + rMetadata.name + " with resourceID " + rMetadata.id + " was executed with the following result " + responseEntity.getBody(), CoreLogger.INFO);
}
else if (rMetadata.method.toUpperCase().equals("GET")) {
LOGGER.debug("Calling URL GET" + rMetadata.url);
responseEntity = template.getForEntity(rMetadata.url, String.class);
coreLogger.log("Service " + rMetadata.name + " with resourceID " + rMetadata.id + " was executed with the following result " + responseEntity.getBody(), CoreLogger.INFO);
}
}
}
return responseEntity;
}
/**
* This method creates a MediaType based on the mimetype that was
* provided
* @param mimeType
* @return MediaType
*/
private MediaType createMediaType(String mimeType) {
MediaType mediaType;
String type, subtype;
StringBuffer sb = new StringBuffer(mimeType);
int index = sb.indexOf("/");
// If a slash was found then there is a type and subtype
if (index != -1) {
type = sb.substring(0, index);
subtype = sb.substring(index+1, mimeType.length());
mediaType = new MediaType(type, subtype);
LOGGER.debug("The type is="+type);
LOGGER.debug("The subtype="+subtype);
}
else {
// Assume there is just a type for the mime, no subtype
mediaType = new MediaType(mimeType);
}
return mediaType;
}
public HttpEntity<String> buildHttpEntity(ResourceMetadata rMetadata, MultiValueMap<String, String> headers, String data) {
// Set the mimeType of the request
headers.add("Content-type", rMetadata.requestMimeType);
//MediaType mediaType = createMediaType(rMetadata.requestMimeType);
//headers.setContentType(mediaType);
LOGGER.debug("data to be used " + data);
LOGGER.debug("Mimetype is " + rMetadata.requestMimeType);
HttpEntity<String> requestEntity = new HttpEntity<String>(data,headers);
return requestEntity;
}
}
|
package org.mifosplatform.portfolio.savings.service;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.joda.time.LocalDate;
import org.joda.time.MonthDay;
import org.mifosplatform.infrastructure.codes.data.CodeValueData;
import org.mifosplatform.infrastructure.core.data.EnumOptionData;
import org.mifosplatform.infrastructure.core.domain.JdbcSupport;
import org.mifosplatform.infrastructure.core.service.DateUtils;
import org.mifosplatform.infrastructure.core.service.Page;
import org.mifosplatform.infrastructure.core.service.PaginationHelper;
import org.mifosplatform.infrastructure.core.service.RoutingDataSource;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.monetary.data.CurrencyData;
import org.mifosplatform.organisation.staff.data.StaffData;
import org.mifosplatform.organisation.staff.service.StaffReadPlatformService;
import org.mifosplatform.portfolio.client.data.ClientData;
import org.mifosplatform.portfolio.client.service.ClientReadPlatformService;
import org.mifosplatform.portfolio.group.data.GroupGeneralData;
import org.mifosplatform.portfolio.group.service.GroupReadPlatformService;
import org.mifosplatform.portfolio.group.service.SearchParameters;
import org.mifosplatform.portfolio.paymentdetail.data.PaymentDetailData;
import org.mifosplatform.portfolio.savings.SavingsCompoundingInterestPeriodType;
import org.mifosplatform.portfolio.savings.SavingsInterestCalculationDaysInYearType;
import org.mifosplatform.portfolio.savings.SavingsInterestCalculationType;
import org.mifosplatform.portfolio.savings.SavingsPeriodFrequencyType;
import org.mifosplatform.portfolio.savings.SavingsPostingInterestPeriodType;
import org.mifosplatform.portfolio.savings.data.SavingsAccountAnnualFeeData;
import org.mifosplatform.portfolio.savings.data.SavingsAccountApplicationTimelineData;
import org.mifosplatform.portfolio.savings.data.SavingsAccountData;
import org.mifosplatform.portfolio.savings.data.SavingsAccountStatusEnumData;
import org.mifosplatform.portfolio.savings.data.SavingsAccountSummaryData;
import org.mifosplatform.portfolio.savings.data.SavingsAccountTransactionData;
import org.mifosplatform.portfolio.savings.data.SavingsAccountTransactionEnumData;
import org.mifosplatform.portfolio.savings.data.SavingsProductData;
import org.mifosplatform.portfolio.savings.exception.SavingsAccountNotFoundException;
import org.mifosplatform.useradministration.domain.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
@Service
public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountReadPlatformService {
private final PlatformSecurityContext context;
private final JdbcTemplate jdbcTemplate;
private final ClientReadPlatformService clientReadPlatformService;
private final GroupReadPlatformService groupReadPlatformService;
private final SavingsProductReadPlatformService savingsProductReadPlatformService;
private final StaffReadPlatformService staffReadPlatformService;
private final SavingsDropdownReadPlatformService dropdownReadPlatformService;
// mappers
private final SavingsAccountTransactionTemplateMapper transactionTemplateMapper;
private final SavingsAccountTransactionsMapper transactionsMapper;
private final SavingAccountMapper savingAccountMapper;
private final SavingsAccountAnnualFeeMapper annualFeeMapper;
// pagination
private final PaginationHelper<SavingsAccountData> paginationHelper = new PaginationHelper<SavingsAccountData>();
@Autowired
public SavingsAccountReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource,
final ClientReadPlatformService clientReadPlatformService, final GroupReadPlatformService groupReadPlatformService,
final SavingsProductReadPlatformService savingProductReadPlatformService,
final StaffReadPlatformService staffReadPlatformService, final SavingsDropdownReadPlatformService dropdownReadPlatformService) {
this.context = context;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.clientReadPlatformService = clientReadPlatformService;
this.groupReadPlatformService = groupReadPlatformService;
this.savingsProductReadPlatformService = savingProductReadPlatformService;
this.staffReadPlatformService = staffReadPlatformService;
this.dropdownReadPlatformService = dropdownReadPlatformService;
this.transactionTemplateMapper = new SavingsAccountTransactionTemplateMapper();
this.transactionsMapper = new SavingsAccountTransactionsMapper();
this.savingAccountMapper = new SavingAccountMapper();
this.annualFeeMapper = new SavingsAccountAnnualFeeMapper();
}
@Override
public Page<SavingsAccountData> retrieveAll(final SearchParameters searchParameters) {
final AppUser currentUser = context.authenticatedUser();
final String hierarchy = currentUser.getOffice().getHierarchy();
final String hierarchySearchString = hierarchy + "%";
StringBuilder sqlBuilder = new StringBuilder(200);
sqlBuilder.append("select SQL_CALC_FOUND_ROWS ");
sqlBuilder.append(savingAccountMapper.schema());
sqlBuilder.append(" join m_office o on o.id = c.office_id");
sqlBuilder.append(" where o.hierarchy like ?");
final Object[] objectArray = new Object[2];
objectArray[0] = hierarchySearchString;
int arrayPos = 1;
String sqlQueryCriteria = searchParameters.getSqlSearch();
if (StringUtils.isNotBlank(sqlQueryCriteria)) {
sqlQueryCriteria = sqlQueryCriteria.replaceAll("accountNo", "sa.account_no");
sqlBuilder.append(" and (").append(sqlQueryCriteria).append(")");
}
if (StringUtils.isNotBlank(searchParameters.getExternalId())) {
sqlBuilder.append(" and sa.external_id = ?");
objectArray[arrayPos] = searchParameters.getExternalId();
arrayPos = arrayPos + 1;
}
if (searchParameters.isOrderByRequested()) {
sqlBuilder.append(" order by ").append(searchParameters.getOrderBy());
if (searchParameters.isSortOrderProvided()) {
sqlBuilder.append(' ').append(searchParameters.getSortOrder());
}
}
if (searchParameters.isLimited()) {
sqlBuilder.append(" limit ").append(searchParameters.getLimit());
if (searchParameters.isOffset()) {
sqlBuilder.append(" offset ").append(searchParameters.getOffset());
}
}
final Object[] finalObjectArray = Arrays.copyOf(objectArray, arrayPos);
final String sqlCountRows = "SELECT FOUND_ROWS()";
return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), finalObjectArray,
this.savingAccountMapper);
}
@Override
public SavingsAccountData retrieveOne(final Long accountId) {
try {
this.context.authenticatedUser();
final SavingAccountMapper mapper = new SavingAccountMapper();
final String sql = "select " + mapper.schema() + " where sa.id = ?";
return this.jdbcTemplate.queryForObject(sql, mapper, new Object[] { accountId });
} catch (EmptyResultDataAccessException e) {
throw new SavingsAccountNotFoundException(accountId);
}
}
private static final class SavingAccountMapper implements RowMapper<SavingsAccountData> {
private final String schemaSql;
public SavingAccountMapper() {
final StringBuilder sqlBuilder = new StringBuilder(400);
sqlBuilder.append("sa.id as id, sa.account_no as accountNo, sa.external_id as externalId, ");
sqlBuilder.append("c.id as clientId, c.display_name as clientName, ");
sqlBuilder.append("g.id as groupId, g.display_name as groupName, ");
sqlBuilder.append("sp.id as productId, sp.name as productName, ");
sqlBuilder.append("s.id fieldOfficerId, s.display_name as fieldOfficerName, ");
sqlBuilder.append("sa.status_enum as statusEnum, ");
sqlBuilder.append("sa.submittedon_date as submittedOnDate,");
sqlBuilder.append("sbu.username as submittedByUsername,");
sqlBuilder.append("sbu.firstname as submittedByFirstname, sbu.lastname as submittedByLastname,");
sqlBuilder.append("sa.rejectedon_date as rejectedOnDate,");
sqlBuilder.append("rbu.username as rejectedByUsername,");
sqlBuilder.append("rbu.firstname as rejectedByFirstname, rbu.lastname as rejectedByLastname,");
sqlBuilder.append("sa.withdrawnon_date as withdrawnOnDate,");
sqlBuilder.append("wbu.username as withdrawnByUsername,");
sqlBuilder.append("wbu.firstname as withdrawnByFirstname, wbu.lastname as withdrawnByLastname,");
sqlBuilder.append("sa.approvedon_date as approvedOnDate,");
sqlBuilder.append("abu.username as approvedByUsername,");
sqlBuilder.append("abu.firstname as approvedByFirstname, abu.lastname as approvedByLastname,");
sqlBuilder.append("sa.activatedon_date as activatedOnDate,");
sqlBuilder.append("avbu.username as activatedByUsername,");
sqlBuilder.append("avbu.firstname as activatedByFirstname, avbu.lastname as activatedByLastname,");
sqlBuilder.append("sa.closedon_date as closedOnDate,");
sqlBuilder.append("cbu.username as closedByUsername,");
sqlBuilder.append("cbu.firstname as closedByFirstname, cbu.lastname as closedByLastname,");
sqlBuilder.append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, ");
sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ");
sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, ");
sqlBuilder.append("sa.nominal_annual_interest_rate as nominalAnnualInterestRate, ");
sqlBuilder.append("sa.interest_compounding_period_enum as interestCompoundingPeriodType, ");
sqlBuilder.append("sa.interest_posting_period_enum as interestPostingPeriodType, ");
sqlBuilder.append("sa.interest_calculation_type_enum as interestCalculationType, ");
sqlBuilder.append("sa.interest_calculation_days_in_year_type_enum as interestCalculationDaysInYearType, ");
sqlBuilder.append("sa.min_required_opening_balance as minRequiredOpeningBalance, ");
sqlBuilder.append("sa.lockin_period_frequency as lockinPeriodFrequency,");
sqlBuilder.append("sa.lockin_period_frequency_enum as lockinPeriodFrequencyType, ");
sqlBuilder.append("sa.withdrawal_fee_amount as withdrawalFeeAmount,");
sqlBuilder.append("sa.withdrawal_fee_type_enum as withdrawalFeeTypeEnum, ");
sqlBuilder.append("sa.annual_fee_amount as annualFeeAmount,");
sqlBuilder.append("sa.annual_fee_on_month as annualFeeOnMonth, ");
sqlBuilder.append("sa.annual_fee_on_day as annualFeeOnDay, ");
sqlBuilder.append("sa.annual_fee_next_due_date as annualFeeNextDueDate, ");
sqlBuilder.append("sa.total_deposits_derived as totalDeposits, ");
sqlBuilder.append("sa.total_withdrawals_derived as totalWithdrawals, ");
sqlBuilder.append("sa.total_withdrawal_fees_derived as totalWithdrawalFees, ");
sqlBuilder.append("sa.total_annual_fees_derived as totalAnnualFees, ");
sqlBuilder.append("sa.total_interest_earned_derived as totalInterestEarned, ");
sqlBuilder.append("sa.total_interest_posted_derived as totalInterestPosted, ");
sqlBuilder.append("sa.account_balance_derived as accountBalance ");
sqlBuilder.append("from m_savings_account sa ");
sqlBuilder.append("join m_savings_product sp ON sa.product_id = sp.id ");
sqlBuilder.append("join m_currency curr on curr.code = sa.currency_code ");
sqlBuilder.append("left join m_client c ON c.id = sa.client_id ");
sqlBuilder.append("left join m_group g ON g.id = sa.group_id ");
sqlBuilder.append("left join m_staff s ON s.id = sa.field_officer_id ");
sqlBuilder.append("left join m_appuser sbu on sbu.id = sa.submittedon_userid ");
sqlBuilder.append("left join m_appuser rbu on rbu.id = sa.rejectedon_userid ");
sqlBuilder.append("left join m_appuser wbu on wbu.id = sa.withdrawnon_userid ");
sqlBuilder.append("left join m_appuser abu on abu.id = sa.approvedon_userid ");
sqlBuilder.append("left join m_appuser avbu on rbu.id = sa.activatedon_userid ");
sqlBuilder.append("left join m_appuser cbu on cbu.id = sa.closedon_userid ");
this.schemaSql = sqlBuilder.toString();
}
public String schema() {
return this.schemaSql;
}
@Override
public SavingsAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = rs.getLong("id");
final String accountNo = rs.getString("accountNo");
final String externalId = rs.getString("externalId");
final Long groupId = JdbcSupport.getLong(rs, "groupId");
final String groupName = rs.getString("groupName");
final Long clientId = JdbcSupport.getLong(rs, "clientId");
final String clientName = rs.getString("clientName");
final Long productId = rs.getLong("productId");
final String productName = rs.getString("productName");
final Long fieldOfficerId = rs.getLong("fieldOfficerId");
final String fieldOfficerName = rs.getString("fieldOfficerName");
final Integer statusEnum = JdbcSupport.getInteger(rs, "statusEnum");
final SavingsAccountStatusEnumData status = SavingsEnumerations.status(statusEnum);
final LocalDate submittedOnDate = JdbcSupport.getLocalDate(rs, "submittedOnDate");
final String submittedByUsername = rs.getString("submittedByUsername");
final String submittedByFirstname = rs.getString("submittedByFirstname");
final String submittedByLastname = rs.getString("submittedByLastname");
final LocalDate rejectedOnDate = JdbcSupport.getLocalDate(rs, "rejectedOnDate");
final String rejectedByUsername = rs.getString("rejectedByUsername");
final String rejectedByFirstname = rs.getString("rejectedByFirstname");
final String rejectedByLastname = rs.getString("rejectedByLastname");
final LocalDate withdrawnOnDate = JdbcSupport.getLocalDate(rs, "withdrawnOnDate");
final String withdrawnByUsername = rs.getString("withdrawnByUsername");
final String withdrawnByFirstname = rs.getString("withdrawnByFirstname");
final String withdrawnByLastname = rs.getString("withdrawnByLastname");
final LocalDate approvedOnDate = JdbcSupport.getLocalDate(rs, "approvedOnDate");
final String approvedByUsername = rs.getString("approvedByUsername");
final String approvedByFirstname = rs.getString("approvedByFirstname");
final String approvedByLastname = rs.getString("approvedByLastname");
final LocalDate activatedOnDate = JdbcSupport.getLocalDate(rs, "activatedOnDate");
final String activatedByUsername = rs.getString("activatedByUsername");
final String activatedByFirstname = rs.getString("activatedByFirstname");
final String activatedByLastname = rs.getString("activatedByLastname");
final LocalDate closedOnDate = JdbcSupport.getLocalDate(rs, "closedOnDate");
final String closedByUsername = rs.getString("closedByUsername");
final String closedByFirstname = rs.getString("closedByFirstname");
final String closedByLastname = rs.getString("closedByLastname");
final SavingsAccountApplicationTimelineData timeline = new SavingsAccountApplicationTimelineData(submittedOnDate,
submittedByUsername, submittedByFirstname, submittedByLastname, rejectedOnDate, rejectedByUsername,
rejectedByFirstname, rejectedByLastname, withdrawnOnDate, withdrawnByUsername, withdrawnByFirstname,
withdrawnByLastname, approvedOnDate, approvedByUsername, approvedByFirstname, approvedByLastname, activatedOnDate,
activatedByUsername, activatedByFirstname, activatedByLastname, closedOnDate, closedByUsername, closedByFirstname,
closedByLastname);
final String currencyCode = rs.getString("currencyCode");
final String currencyName = rs.getString("currencyName");
final String currencyNameCode = rs.getString("currencyNameCode");
final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol,
currencyNameCode);
final BigDecimal nominalAnnualInterestRate = rs.getBigDecimal("nominalAnnualInterestRate");
final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations
.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs,
"interestCompoundingPeriodType")));
final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType
.fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType")));
final EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType
.fromInt(JdbcSupport.getInteger(rs, "interestCalculationType")));
final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations
.interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs,
"interestCalculationDaysInYearType")));
final BigDecimal minRequiredOpeningBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "minRequiredOpeningBalance");
final Integer lockinPeriodFrequency = JdbcSupport.getInteger(rs, "lockinPeriodFrequency");
EnumOptionData lockinPeriodFrequencyType = null;
final Integer lockinPeriodFrequencyTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodFrequencyType");
if (lockinPeriodFrequencyTypeValue != null) {
final SavingsPeriodFrequencyType lockinPeriodType = SavingsPeriodFrequencyType.fromInt(lockinPeriodFrequencyTypeValue);
lockinPeriodFrequencyType = SavingsEnumerations.lockinPeriodFrequencyType(lockinPeriodType);
}
final BigDecimal withdrawalFeeAmount = rs.getBigDecimal("withdrawalFeeAmount");
EnumOptionData withdrawalFeeType = null;
final Integer withdrawalFeeTypeValue = JdbcSupport.getInteger(rs, "withdrawalFeeTypeEnum");
if (withdrawalFeeTypeValue != null) {
withdrawalFeeType = SavingsEnumerations.withdrawalFeeType(withdrawalFeeTypeValue);
}
final BigDecimal annualFeeAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "annualFeeAmount");
MonthDay annualFeeOnMonthDay = null;
final Integer annualFeeOnMonth = JdbcSupport.getInteger(rs, "annualFeeOnMonth");
final Integer annualFeeOnDay = JdbcSupport.getInteger(rs, "annualFeeOnDay");
if (annualFeeAmount != null && annualFeeOnDay != null) {
annualFeeOnMonthDay = new MonthDay(annualFeeOnMonth, annualFeeOnDay);
}
final LocalDate annualFeeNextDueDate = JdbcSupport.getLocalDate(rs, "annualFeeNextDueDate");
final BigDecimal totalDeposits = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalDeposits");
final BigDecimal totalWithdrawals = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalWithdrawals");
final BigDecimal totalWithdrawalFees = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalWithdrawalFees");
final BigDecimal totalAnnualFees = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalAnnualFees");
final BigDecimal totalInterestEarned = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalInterestEarned");
final BigDecimal totalInterestPosted = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalInterestPosted");
final BigDecimal accountBalance = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "accountBalance");
final SavingsAccountSummaryData summary = new SavingsAccountSummaryData(currency, totalDeposits, totalWithdrawals,
totalWithdrawalFees, totalAnnualFees, totalInterestEarned, totalInterestPosted, accountBalance);
return SavingsAccountData.instance(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName,
fieldOfficerId, fieldOfficerName, status, timeline, currency, nominalAnnualInterestRate, interestCompoundingPeriodType,
interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance,
lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, annualFeeAmount,
annualFeeOnMonthDay, annualFeeNextDueDate, summary);
}
}
@Override
public SavingsAccountData retrieveTemplate(final Long clientId, final Long groupId, final Long productId,
final boolean staffInSelectedOfficeOnly) {
AppUser loggedInUser = context.authenticatedUser();
Long officeId = loggedInUser.getOffice().getId();
ClientData client = null;
if (clientId != null) {
client = this.clientReadPlatformService.retrieveOne(clientId);
officeId = client.officeId();
}
GroupGeneralData group = null;
if (groupId != null) {
group = this.groupReadPlatformService.retrieveOne(groupId);
officeId = group.officeId();
}
final Collection<SavingsProductData> productOptions = this.savingsProductReadPlatformService.retrieveAllForLookup();
SavingsAccountData template = null;
if (productId != null) {
SavingAccountTemplateMapper mapper = new SavingAccountTemplateMapper(client, group);
final String sql = "select " + mapper.schema() + " where sp.id = ?";
template = this.jdbcTemplate.queryForObject(sql, mapper, new Object[] { productId });
final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = this.dropdownReadPlatformService
.retrieveCompoundingInterestPeriodTypeOptions();
final Collection<EnumOptionData> interestPostingPeriodTypeOptions = this.dropdownReadPlatformService
.retrieveInterestPostingPeriodTypeOptions();
final Collection<EnumOptionData> interestCalculationTypeOptions = this.dropdownReadPlatformService
.retrieveInterestCalculationTypeOptions();
final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = this.dropdownReadPlatformService
.retrieveInterestCalculationDaysInYearTypeOptions();
final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = this.dropdownReadPlatformService
.retrieveLockinPeriodFrequencyTypeOptions();
final Collection<EnumOptionData> withdrawalFeeTypeOptions = this.dropdownReadPlatformService.retrievewithdrawalFeeTypeOptions();
final Collection<SavingsAccountTransactionData> transactions = null;
Collection<StaffData> fieldOfficerOptions = null;
if (officeId != null) {
if (staffInSelectedOfficeOnly) {
// only bring back loan officers in selected branch/office
Collection<StaffData> fieldOfficersInBranch = this.staffReadPlatformService
.retrieveAllLoanOfficersInOfficeById(officeId);
if (!CollectionUtils.isEmpty(fieldOfficersInBranch)) {
fieldOfficerOptions = new ArrayList<StaffData>(fieldOfficersInBranch);
}
} else {
// by default bring back all officers in selected
// branch/office as well as officers in office above
// this office
final boolean restrictToLoanOfficersOnly = true;
Collection<StaffData> loanOfficersInHierarchy = this.staffReadPlatformService
.retrieveAllStaffInOfficeAndItsParentOfficeHierarchy(officeId, restrictToLoanOfficersOnly);
if (!CollectionUtils.isEmpty(loanOfficersInHierarchy)) {
fieldOfficerOptions = new ArrayList<StaffData>(loanOfficersInHierarchy);
}
}
}
template = SavingsAccountData.withTemplateOptions(template, productOptions, fieldOfficerOptions,
interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions,
interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, transactions);
} else {
String clientName = null;
if (client != null) {
clientName = client.displayName();
}
String groupName = null;
if (group != null) {
groupName = group.getName();
}
template = SavingsAccountData.withClientTemplate(clientId, clientName, groupId, groupName);
final Collection<StaffData> fieldOfficerOptions = null;
final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
final Collection<EnumOptionData> interestCalculationTypeOptions = null;
final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;
final Collection<SavingsAccountTransactionData> transactions = null;
template = SavingsAccountData.withTemplateOptions(template, productOptions, fieldOfficerOptions,
interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions,
interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, transactions);
}
return template;
}
@Override
public SavingsAccountTransactionData retrieveDepositTransactionTemplate(final Long savingsId) {
try {
final String sql = "select " + transactionTemplateMapper.schema() + " where sa.id = ?";
return this.jdbcTemplate.queryForObject(sql, transactionTemplateMapper, new Object[] { savingsId });
} catch (EmptyResultDataAccessException e) {
throw new SavingsAccountNotFoundException(savingsId);
}
}
@Override
public Collection<SavingsAccountTransactionData> retrieveAllTransactions(final Long savingsId) {
final String sql = "select " + this.transactionsMapper.schema() + " where sa.id = ? order by tr.transaction_date DESC, tr.id DESC";
return this.jdbcTemplate.query(sql, this.transactionsMapper, new Object[] { savingsId });
}
@Override
public Collection<SavingsAccountAnnualFeeData> retrieveAccountsWithAnnualFeeDue() {
final String sql = "select " + annualFeeMapper.schema()
+ " where sa.annual_fee_next_due_date not null and sa.annual_fee_next_due_date <= NOW()";
return this.jdbcTemplate.query(sql, this.annualFeeMapper, new Object[] {});
}
private static final class SavingsAccountTransactionsMapper implements RowMapper<SavingsAccountTransactionData> {
private final String schemaSql;
public SavingsAccountTransactionsMapper() {
final StringBuilder sqlBuilder = new StringBuilder(400);
sqlBuilder.append("tr.id as transactionId, tr.transaction_type_enum as transactionType, ");
sqlBuilder.append("tr.transaction_date as transactionDate, tr.amount as transactionAmount,");
sqlBuilder.append("tr.running_balance_derived as runningBalance, tr.is_reversed as reversed,");
sqlBuilder.append("sa.id as savingsId, sa.account_no as accountNo,");
sqlBuilder.append("pd.payment_type_cv_id as paymentType,pd.account_number as accountNumber,pd.check_number as checkNumber, ");
sqlBuilder.append("pd.receipt_number as receiptNumber, pd.bank_number as bankNumber,pd.routing_code as routingCode, ");
sqlBuilder.append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, ");
sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ");
sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, ");
sqlBuilder.append("cv.code_value as paymentTypeName ");
sqlBuilder.append("from m_savings_account sa ");
sqlBuilder.append("join m_savings_account_transaction tr on tr.savings_account_id = sa.id ");
sqlBuilder.append("join m_currency curr on curr.code = sa.currency_code ");
sqlBuilder.append("left join m_payment_detail pd on tr.payment_detail_id = pd.id ");
sqlBuilder.append("left join m_code_value cv on pd.payment_type_cv_id = cv.id ");
this.schemaSql = sqlBuilder.toString();
}
public String schema() {
return this.schemaSql;
}
@Override
public SavingsAccountTransactionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = rs.getLong("transactionId");
final int transactionTypeInt = JdbcSupport.getInteger(rs, "transactionType");
final SavingsAccountTransactionEnumData transactionType = SavingsEnumerations.transactionType(transactionTypeInt);
final LocalDate date = JdbcSupport.getLocalDate(rs, "transactionDate");
final BigDecimal amount = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "transactionAmount");
final BigDecimal runningBalance = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "runningBalance");
final boolean reversed = rs.getBoolean("reversed");
final Long savingsId = rs.getLong("savingsId");
final String accountNo = rs.getString("accountNo");
PaymentDetailData paymentDetailData = null;
if (transactionType.isDepositOrWithdrawal()) {
final Long paymentTypeId = JdbcSupport.getLong(rs, "paymentType");
if (paymentTypeId != null) {
final String typeName = rs.getString("paymentTypeName");
CodeValueData paymentType = CodeValueData.instance(paymentTypeId, typeName);
final String accountNumber = rs.getString("accountNumber");
final String checkNumber = rs.getString("checkNumber");
final String routingCode = rs.getString("routingCode");
final String receiptNumber = rs.getString("receiptNumber");
final String bankNumber = rs.getString("bankNumber");
paymentDetailData = new PaymentDetailData(id, paymentType, accountNumber, checkNumber, routingCode, receiptNumber,
bankNumber);
}
}
final String currencyCode = rs.getString("currencyCode");
final String currencyName = rs.getString("currencyName");
final String currencyNameCode = rs.getString("currencyNameCode");
final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol,
currencyNameCode);
return SavingsAccountTransactionData.create(id, transactionType, paymentDetailData, savingsId, accountNo, date, currency,
amount, runningBalance, reversed);
}
}
private static final class SavingsAccountTransactionTemplateMapper implements RowMapper<SavingsAccountTransactionData> {
private final String schemaSql;
public SavingsAccountTransactionTemplateMapper() {
final StringBuilder sqlBuilder = new StringBuilder(400);
sqlBuilder.append("sa.id as id, sa.account_no as accountNo, ");
sqlBuilder.append("sa.currency_code as currencyCode, sa.currency_digits as currencyDigits, ");
sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ");
sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, ");
sqlBuilder.append("sa.min_required_opening_balance as minRequiredOpeningBalance ");
sqlBuilder.append("from m_savings_account sa ");
sqlBuilder.append("join m_currency curr on curr.code = sa.currency_code ");
this.schemaSql = sqlBuilder.toString();
}
public String schema() {
return this.schemaSql;
}
@Override
public SavingsAccountTransactionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long savingsId = rs.getLong("id");
final String accountNo = rs.getString("accountNo");
final String currencyCode = rs.getString("currencyCode");
final String currencyName = rs.getString("currencyName");
final String currencyNameCode = rs.getString("currencyNameCode");
final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol,
currencyNameCode);
return SavingsAccountTransactionData.template(savingsId, accountNo, DateUtils.getLocalDateOfTenant(), currency);
}
}
private static final class SavingAccountTemplateMapper implements RowMapper<SavingsAccountData> {
private final ClientData client;
private final GroupGeneralData group;
private final String schemaSql;
public SavingAccountTemplateMapper(final ClientData client, final GroupGeneralData group) {
this.client = client;
this.group = group;
final StringBuilder sqlBuilder = new StringBuilder(400);
sqlBuilder.append("sp.id as productId, sp.name as productName, ");
sqlBuilder.append("sp.currency_code as currencyCode, sp.currency_digits as currencyDigits, ");
sqlBuilder.append("curr.name as currencyName, curr.internationalized_name_code as currencyNameCode, ");
sqlBuilder.append("curr.display_symbol as currencyDisplaySymbol, ");
sqlBuilder.append("sp.nominal_annual_interest_rate as nominalAnnualIterestRate, ");
sqlBuilder.append("sp.interest_compounding_period_enum as interestCompoundingPeriodType, ");
sqlBuilder.append("sp.interest_posting_period_enum as interestPostingPeriodType, ");
sqlBuilder.append("sp.interest_calculation_type_enum as interestCalculationType, ");
sqlBuilder.append("sp.interest_calculation_days_in_year_type_enum as interestCalculationDaysInYearType, ");
sqlBuilder.append("sp.min_required_opening_balance as minRequiredOpeningBalance, ");
sqlBuilder.append("sp.lockin_period_frequency as lockinPeriodFrequency,");
sqlBuilder.append("sp.lockin_period_frequency_enum as lockinPeriodFrequencyType, ");
sqlBuilder.append("sp.withdrawal_fee_amount as withdrawalFeeAmount,");
sqlBuilder.append("sp.withdrawal_fee_type_enum as withdrawalFeeTypeEnum, ");
sqlBuilder.append("sp.annual_fee_amount as annualFeeAmount,");
sqlBuilder.append("sp.annual_fee_on_month as annualFeeOnMonth, ");
sqlBuilder.append("sp.annual_fee_on_day as annualFeeOnDay ");
sqlBuilder.append("from m_savings_product sp ");
sqlBuilder.append("join m_currency curr on curr.code = sp.currency_code ");
this.schemaSql = sqlBuilder.toString();
}
public String schema() {
return this.schemaSql;
}
@Override
public SavingsAccountData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long productId = rs.getLong("productId");
final String productName = rs.getString("productName");
final String currencyCode = rs.getString("currencyCode");
final String currencyName = rs.getString("currencyName");
final String currencyNameCode = rs.getString("currencyNameCode");
final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol");
final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits");
final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, currencyDisplaySymbol,
currencyNameCode);
final BigDecimal nominalAnnualIterestRate = rs.getBigDecimal("nominalAnnualIterestRate");
EnumOptionData interestCompoundingPeriodType = SavingsEnumerations
.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs,
"interestCompoundingPeriodType")));
final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType
.fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType")));
EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType
.fromInt(JdbcSupport.getInteger(rs, "interestCalculationType")));
EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations
.interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs,
"interestCalculationDaysInYearType")));
final BigDecimal minRequiredOpeningBalance = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "minRequiredOpeningBalance");
final Integer lockinPeriodFrequency = JdbcSupport.getInteger(rs, "lockinPeriodFrequency");
EnumOptionData lockinPeriodFrequencyType = null;
final Integer lockinPeriodFrequencyTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodFrequencyType");
if (lockinPeriodFrequencyTypeValue != null) {
final SavingsPeriodFrequencyType lockinPeriodType = SavingsPeriodFrequencyType.fromInt(lockinPeriodFrequencyTypeValue);
lockinPeriodFrequencyType = SavingsEnumerations.lockinPeriodFrequencyType(lockinPeriodType);
}
final BigDecimal withdrawalFeeAmount = rs.getBigDecimal("withdrawalFeeAmount");
EnumOptionData withdrawalFeeType = null;
final Integer withdrawalFeeTypeValue = JdbcSupport.getInteger(rs, "withdrawalFeeTypeEnum");
if (withdrawalFeeTypeValue != null) {
withdrawalFeeType = SavingsEnumerations.withdrawalFeeType(withdrawalFeeTypeValue);
}
final BigDecimal annualFeeAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "annualFeeAmount");
MonthDay annualFeeOnMonthDay = null;
final Integer annualFeeOnMonth = JdbcSupport.getInteger(rs, "annualFeeOnMonth");
final Integer annualFeeOnDay = JdbcSupport.getInteger(rs, "annualFeeOnDay");
if (annualFeeAmount != null && annualFeeOnDay != null) {
annualFeeOnMonthDay = new MonthDay(annualFeeOnMonth, annualFeeOnDay);
}
Long clientId = null;
String clientName = null;
if (client != null) {
clientId = client.id();
clientName = client.displayName();
}
Long groupId = null;
String groupName = null;
if (group != null) {
groupId = group.getId();
groupName = group.getName();
}
final Long fieldOfficerId = null;
final String fieldOfficerName = null;
final SavingsAccountStatusEnumData status = null;
final LocalDate annualFeeNextDueDate = null;
final SavingsAccountSummaryData summary = null;
final SavingsAccountApplicationTimelineData timeline = SavingsAccountApplicationTimelineData.templateDefault();
return SavingsAccountData.instance(null, null, null, groupId, groupName, clientId, clientName, productId, productName,
fieldOfficerId, fieldOfficerName, status, timeline, currency, nominalAnnualIterestRate, interestCompoundingPeriodType,
interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance,
lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, annualFeeAmount,
annualFeeOnMonthDay, annualFeeNextDueDate, summary);
}
}
private static final class SavingsAccountAnnualFeeMapper implements RowMapper<SavingsAccountAnnualFeeData> {
private final String schemaSql;
public SavingsAccountAnnualFeeMapper() {
final StringBuilder sqlBuilder = new StringBuilder(200);
sqlBuilder.append("sa.id as id, sa.account_no as accountNo, ");
sqlBuilder.append("sa.annual_fee_next_due_date as annualFeeNextDueDate ");
sqlBuilder.append("from m_savings_account sa ");
this.schemaSql = sqlBuilder.toString();
}
public String schema() {
return this.schemaSql;
}
@Override
public SavingsAccountAnnualFeeData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = rs.getLong("id");
final String accountNo = rs.getString("accountNo");
final LocalDate annualFeeNextDueDate = JdbcSupport.getLocalDate(rs, "annualFeeNextDueDate");
return SavingsAccountAnnualFeeData.instance(id, accountNo, annualFeeNextDueDate);
}
}
}
|
package org.mockserver.integration.proxy;
import com.google.common.base.Charsets;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.util.EntityUtils;
import org.junit.Ignore;
import org.junit.Test;
import org.mockserver.client.proxy.ProxyClient;
import org.mockserver.model.HttpStatusCode;
import org.mockserver.socket.SSLFactory;
import org.mockserver.streams.IOStreamUtils;
import java.io.OutputStream;
import java.net.ProxySelector;
import java.net.Socket;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.junit.Assert.*;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.test.Assert.assertContains;
import static org.mockserver.verify.VerificationTimes.atLeast;
import static org.mockserver.verify.VerificationTimes.exactly;
/**
* @author jamesdbloom
*/
public abstract class AbstractClientProxyIntegrationTest {
protected static String servletContext = "";
protected HttpClient createHttpClient() throws Exception {
HttpClientBuilder httpClientBuilder = HttpClients
.custom()
.setSslcontext(SSLFactory.getInstance().sslContext())
.setHostnameVerifier(new AllowAllHostnameVerifier());
if (Boolean.parseBoolean(System.getProperty("socksProxySet"))) {
HttpRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
httpClientBuilder.setRoutePlanner(routePlanner).build();
} else if (Boolean.parseBoolean(System.getProperty("proxySet"))) {
HttpHost httpHost = new HttpHost(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")));
HttpRoutePlanner defaultProxyRoutePlanner = new DefaultProxyRoutePlanner(httpHost);
httpClientBuilder.setRoutePlanner(defaultProxyRoutePlanner).build();
} else {
HttpHost httpHost = new HttpHost("localhost", getProxyPort());
DefaultProxyRoutePlanner defaultProxyRoutePlanner = new DefaultProxyRoutePlanner(httpHost);
httpClientBuilder.setRoutePlanner(defaultProxyRoutePlanner);
}
return httpClientBuilder.build();
}
public abstract int getProxyPort();
public abstract ProxyClient getProxyClient();
public abstract int getServerPort();
protected String calculatePath(String path) {
return "/" + servletContext.replaceAll("/", "") + "/" + path;
}
@Test
public void shouldForwardRequestsUsingSocketDirectly() throws Exception {
Socket socket = null;
try {
socket = new Socket("localhost", getProxyPort());
// given
OutputStream output = socket.getOutputStream();
// when
// - send GET request for headers only
output.write(("" +
"GET " + calculatePath("test_headers_only") + " HTTP/1.1\r\n" +
"Host: localhost:" + getServerPort() + "\r\n" +
"x-test: test_headers_only\r\n" +
"Connection: keep-alive\r\n" +
"\r\n"
).getBytes(Charsets.UTF_8));
output.flush();
// then
assertContains(IOStreamUtils.readInputStreamToString(socket), "x-test: test_headers_only");
// - send GET request for headers and body
output.write(("" +
"GET " + calculatePath("test_headers_and_body") + " HTTP/1.1\r\n" +
"Host: localhost:" + getServerPort() + "\r\n" +
"Content-Length: " + "an_example_body".getBytes(Charsets.UTF_8).length + "\r\n" +
"x-test: test_headers_and_body\r\n" +
"\r\n" +
"an_example_body"
).getBytes(Charsets.UTF_8));
output.flush();
// then
String response = IOStreamUtils.readInputStreamToString(socket);
assertContains(response, "x-test: test_headers_and_body");
assertContains(response, "an_example_body");
} finally {
if (socket != null) {
socket.close();
}
}
}
@Test
public void shouldForwardRequestsUsingHttpClient() throws Exception {
// given
HttpClient httpClient = createHttpClient();
// when
HttpPost request = new HttpPost(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_and_body"))
.build()
);
request.setEntity(new StringEntity("an_example_body"));
HttpResponse response = httpClient.execute(request);
// then
assertEquals(HttpStatusCode.OK_200.code(), response.getStatusLine().getStatusCode());
assertEquals("an_example_body", new String(EntityUtils.toByteArray(response.getEntity()), com.google.common.base.Charsets.UTF_8));
}
@Test
public void shouldForwardRequestsToUnknownPath() throws Exception {
Socket socket = null;
try {
socket = new Socket("localhost", getProxyPort());
// given
OutputStream output = socket.getOutputStream();
// when
// - send GET request
output.write(("" +
"GET /not_found HTTP/1.1\r\n" +
"Host: localhost:" + getServerPort() + "\r\n" +
"Connection: close\r\n" +
"\r\n"
).getBytes(Charsets.UTF_8));
output.flush();
// then
assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 404 Not Found");
} finally {
if (socket != null) {
socket.close();
}
}
}
@Test
@Ignore("ignoring several tests until drone.io is fixed to stop the incorrect forcing the use of HTTP CONNECT protocol")
public void shouldVerifyRequests() throws Exception {
// given
HttpClient httpClient = createHttpClient();
// when
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_and_body"))
.build()
)
);
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_only"))
.build()
)
);
// then
getProxyClient()
.verify(
request()
.withMethod("GET")
.withPath("/test_headers_and_body")
);
getProxyClient()
.verify(
request()
.withMethod("GET")
.withPath("/test_headers_and_body"),
exactly(1)
);
getProxyClient()
.verify(
request()
.withPath("/test_headers_.*"),
atLeast(1)
);
getProxyClient()
.verify(
request()
.withPath("/test_headers_.*"),
exactly(2)
);
getProxyClient()
.verify(
request()
.withPath("/other_path"),
exactly(0)
);
}
@Test
@Ignore("ignoring several tests until drone.io is fixed to stop the incorrect forcing the use of HTTP CONNECT protocol")
public void shouldVerifyZeroRequests() throws Exception {
// given
HttpClient httpClient = createHttpClient();
// when
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_and_body"))
.build()
)
);
// then
try {
getProxyClient()
.verify(
request()
.withPath("/test_headers_and_body"), exactly(0)
);
fail();
} catch (AssertionError ae) {
assertThat(ae.getMessage(), startsWith("Request not found exactly 0 times, expected:<{" + System.getProperty("line.separator") +
" \"path\" : \"" + "/test_headers_and_body" + "\"" + System.getProperty("line.separator") +
"}> but was:<{" + System.getProperty("line.separator") +
" \"method\" : \"GET\"," + System.getProperty("line.separator") +
" \"path\" : \"" + "/test_headers_and_body" + "\"," + System.getProperty("line.separator")));
}
}
@Test
@Ignore("ignoring several tests until drone.io is fixed to stop the incorrect forcing the use of HTTP CONNECT protocol")
public void shouldVerifyNoRequestsExactly() throws Exception {
// given
HttpClient httpClient = createHttpClient();
// when
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_and_body"))
.build()
)
);
// then
try {
getProxyClient()
.verify(
request()
.withPath("/other_path"),
exactly(1)
);
fail();
} catch (AssertionError ae) {
assertThat(ae.getMessage(), startsWith("Request not found exactly once, expected:<{" + System.getProperty("line.separator") +
" \"path\" : \"" + "/other_path" + "\"" + System.getProperty("line.separator") +
"}> but was:<{" + System.getProperty("line.separator") +
" \"method\" : \"GET\"," + System.getProperty("line.separator") +
" \"path\" : \"" + "/test_headers_and_body" + "\"," + System.getProperty("line.separator")));
}
}
@Test
@Ignore("ignoring several tests until drone.io is fixed to stop the incorrect forcing the use of HTTP CONNECT protocol")
public void shouldVerifyNoRequestsTimesNotSpecified() throws Exception {
// given
HttpClient httpClient = createHttpClient();
// when
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_and_body"))
.build()
)
);
// then
try {
getProxyClient()
.verify(
request()
.withPath("/other_path")
);
fail();
} catch (AssertionError ae) {
assertThat(ae.getMessage(), startsWith("Request sequence not found, expected:<[ {" + System.getProperty("line.separator") +
" \"path\" : \"" + "/other_path" + "\"" + System.getProperty("line.separator") +
"} ]> but was:<[ {" + System.getProperty("line.separator") +
" \"method\" : \"GET\"," + System.getProperty("line.separator") +
" \"path\" : \"" + "/test_headers_and_body" + "\"," + System.getProperty("line.separator")));
}
}
@Test
@Ignore("ignoring several tests until drone.io is fixed to stop the incorrect forcing the use of HTTP CONNECT protocol")
public void shouldVerifyNotEnoughRequests() throws Exception {
// given
HttpClient httpClient = createHttpClient();
// when
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_and_body"))
.build()
)
);
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_and_body"))
.build()
)
);
// then
try {
getProxyClient()
.verify(
request()
.withPath("/test_headers_and_body"),
atLeast(3)
);
fail();
} catch (AssertionError ae) {
assertThat(ae.getMessage(), startsWith("Request not found at least 3 times, expected:<{" + System.getProperty("line.separator") +
" \"path\" : \"" + "/test_headers_and_body" + "\"" + System.getProperty("line.separator") +
"}> but was:<[ {" + System.getProperty("line.separator") +
" \"method\" : \"GET\"," + System.getProperty("line.separator") +
" \"path\" : \"" + "/test_headers_and_body" + "\"," + System.getProperty("line.separator")));
}
}
@Test
@Ignore("ignoring several tests until drone.io is fixed to stop the incorrect forcing the use of HTTP CONNECT protocol")
public void shouldClearRequests() throws Exception {
// given
HttpClient httpClient = createHttpClient();
// when
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_and_body"))
.build()
)
);
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_only"))
.build()
)
);
getProxyClient()
.clear(
request()
.withMethod("GET")
.withPath("/test_headers_and_body")
);
// then
getProxyClient()
.verify(
request()
.withMethod("GET")
.withPath("/test_headers_and_body"),
exactly(0)
);
getProxyClient()
.verify(
request()
.withPath("/test_headers_.*"),
exactly(1)
);
}
@Test
@Ignore("ignoring several tests until drone.io is fixed to stop the incorrect forcing the use of HTTP CONNECT protocol")
public void shouldResetRequests() throws Exception {
// given
HttpClient httpClient = createHttpClient();
// when
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_and_body"))
.build()
)
);
httpClient.execute(
new HttpGet(
new URIBuilder()
.setScheme("http")
.setHost("localhost")
.setPort(getServerPort())
.setPath(calculatePath("test_headers_only"))
.build()
)
);
getProxyClient().reset();
// then
getProxyClient()
.verify(
request()
.withMethod("GET")
.withPath("/test_headers_and_body"),
exactly(0)
);
getProxyClient()
.verify(
request()
.withPath("/test_headers_.*"),
atLeast(0)
);
getProxyClient()
.verify(
request()
.withPath("/test_headers_.*"),
exactly(0)
);
}
}
|
package org.apache.airavata.db.event.manager.messaging.impl;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.db.event.manager.messaging.DBEventManagerException;
import org.apache.airavata.db.event.manager.messaging.DBEventManagerMessagingFactory;
import org.apache.airavata.db.event.manager.utils.DbEventManagerZkUtils;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessageHandler;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.model.dbevent.DBEventMessage;
import org.apache.airavata.model.dbevent.DBEventMessageContext;
import org.apache.airavata.model.dbevent.DBEventType;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class DBEventMessageHandler implements MessageHandler {
private final static Logger log = LoggerFactory.getLogger(DBEventMessageHandler.class);
private CuratorFramework curatorClient;
public DBEventMessageHandler() throws ApplicationSettingsException {
startCuratorClient();
}
private void startCuratorClient() throws ApplicationSettingsException {
curatorClient = DbEventManagerZkUtils.getCuratorClient();
curatorClient.start();
}
@Override
public void onMessage(MessageContext messageContext) {
log.info("Incoming DB event message. Message Id : " + messageContext.getMessageId());
try {
byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent());
DBEventMessage dbEventMessage = new DBEventMessage();
ThriftUtils.createThriftFromBytes(bytes, dbEventMessage);
DBEventMessageContext dBEventMessageContext = dbEventMessage.getMessageContext();
switch (dbEventMessage.getDbEventType()){
case SUBSCRIBER:
log.info("Registering " + dBEventMessageContext.getSubscriber().getSubscriberService() + " subscriber for " + dbEventMessage.getPublisherService());
DbEventManagerZkUtils.createDBEventMgrZkNode(curatorClient, dbEventMessage.getPublisherService(), dBEventMessageContext.getSubscriber().getSubscriberService());
break;
case PUBLISHER:
List<String> subscribers = DbEventManagerZkUtils.getSubscribersForPublisher(curatorClient, dbEventMessage.getPublisherService());
if(subscribers.isEmpty()){
log.error("No Subscribers registered for the service");
throw new DBEventManagerException("No Subscribers registered for the service");
}
String routingKey = getRoutingKeyFromList(subscribers);
log.info("Publishing " + dbEventMessage.getPublisherService() + " db event to " + subscribers.toString());
MessageContext messageCtx = new MessageContext(dBEventMessageContext.getPublisher().getPublisherContext(), MessageType.DB_EVENT, "", "");
messageCtx.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
DBEventManagerMessagingFactory.getDBEventPublisher().publish(messageCtx, routingKey);
break;
}
} catch (Exception e) {
log.error("Error processing message.", e);
}
}
private String getRoutingKeyFromList(final List<String> subscribers){
StringBuilder sb = new StringBuilder();
String separator = ".";
Collections.sort(subscribers);
for(String subscriber : subscribers){
sb.append(subscriber).append(separator);
}
return sb.substring(0, sb.length() - 1);
}
}
|
package org.nuxeo.drive.operations;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.Serializable;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.drive.service.MockChangeFinder;
import org.nuxeo.drive.service.NuxeoDriveManager;
import org.nuxeo.drive.service.impl.FileSystemChangeSummary;
import org.nuxeo.drive.service.impl.FileSystemItemChange;
import org.nuxeo.ecm.automation.client.OperationRequest;
import org.nuxeo.ecm.automation.client.Session;
import org.nuxeo.ecm.automation.client.jaxrs.impl.HttpAutomationClient;
import org.nuxeo.ecm.automation.client.model.Blob;
import org.nuxeo.ecm.automation.test.RestFeature;
import org.nuxeo.ecm.core.NXCore;
import org.nuxeo.ecm.core.api.CoreInstance;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.PathRef;
import org.nuxeo.ecm.core.api.impl.blob.StringBlob;
import org.nuxeo.ecm.core.api.repository.Repository;
import org.nuxeo.ecm.core.api.repository.RepositoryManager;
import org.nuxeo.ecm.core.storage.sql.DatabaseH2;
import org.nuxeo.ecm.core.storage.sql.DatabaseHelper;
import org.nuxeo.ecm.core.test.annotations.Granularity;
import org.nuxeo.ecm.core.test.annotations.RepositoryConfig;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import org.nuxeo.runtime.test.runner.Jetty;
import org.nuxeo.runtime.test.runner.LocalDeploy;
import com.google.inject.Inject;
/**
* Tests the {@link NuxeoDriveGetChangeSummary} operation on multiple
* repositories.
*
* @author Antoine Taillefer
*/
@RunWith(FeaturesRunner.class)
@Features(RestFeature.class)
@RepositoryConfig(cleanup = Granularity.METHOD)
@Deploy({ "org.nuxeo.drive.core", "org.nuxeo.drive.operations" })
@LocalDeploy("org.nuxeo.drive.operations:test-other-repository-config.xml")
@Jetty(port = 18080)
public class TestGetChangeSummaryMultiRepo {
@Inject
protected CoreSession session;
@Inject
protected RepositoryManager repositoryManager;
@Inject
protected NuxeoDriveManager nuxeoDriveManager;
@Inject
protected HttpAutomationClient automationClient;
protected Repository otherRepo;
protected CoreSession otherSession;
protected long lastSuccessfulSync;
protected DocumentModel folder1;
protected DocumentModel folder2;
protected DocumentModel folder3;
protected Session clientSession;
protected ObjectMapper mapper;
@Before
public void init() throws Exception {
if (!(DatabaseHelper.DATABASE instanceof DatabaseH2)) {
return;
}
Map<String, Serializable> context = new HashMap<String, Serializable>();
context.put("username", "Administrator");
otherRepo = repositoryManager.getRepository("other");
otherSession = otherRepo.open(context);
nuxeoDriveManager.setChangeFinder(new MockChangeFinder());
lastSuccessfulSync = Calendar.getInstance().getTimeInMillis();
folder1 = session.createDocument(session.createDocumentModel("/",
"folder1", "Folder"));
folder2 = session.createDocument(session.createDocumentModel("/",
"folder2", "Folder"));
folder3 = otherSession.createDocument(otherSession.createDocumentModel(
"/", "folder3", "Folder"));
clientSession = automationClient.getSession("Administrator",
"Administrator");
mapper = new ObjectMapper();
}
@After
public void cleanUp() throws Exception {
// Reset 'other' repository
otherSession.removeChildren(new PathRef("/"));
otherSession.save();
// Close session bound to the 'other' repository
assert otherSession != null;
CoreInstance.getInstance().close(otherSession);
otherSession = null;
// Shutdown 'other' repository
NXCore.getRepositoryService().getRepositoryManager().getRepository(
"other").shutdown();
}
@Test
public void testGetDocumentChangesSummary() throws Exception {
// Register 3 sync roots and create 3 documents: 2 in the 'test'
// repository, 1 in the 'other' repository
nuxeoDriveManager.registerSynchronizationRoot("Administrator", folder1,
session);
nuxeoDriveManager.registerSynchronizationRoot("Administrator", folder2,
session);
nuxeoDriveManager.registerSynchronizationRoot("Administrator", folder3,
otherSession);
DocumentModel doc1 = session.createDocumentModel("/folder1", "doc1",
"File");
doc1.setPropertyValue("file:content", new StringBlob(
"The content of file 1."));
doc1 = session.createDocument(doc1);
Thread.sleep(1000);
DocumentModel doc2 = session.createDocumentModel("/folder2", "doc2",
"File");
doc2.setPropertyValue("file:content", new StringBlob(
"The content of file 2."));
doc2 = session.createDocument(doc2);
Thread.sleep(1000);
DocumentModel doc3 = otherSession.createDocumentModel("/folder3",
"doc3", "File");
doc3.setPropertyValue("file:content", new StringBlob(
"The content of file 3."));
doc3 = otherSession.createDocument(doc3);
session.save();
otherSession.save();
// Look in all repositories => should find 3 changes
FileSystemChangeSummary changeSummary = getDocumentChangeSummary();
Set<String> expectedSyncRootPaths = new HashSet<String>();
expectedSyncRootPaths.add("/folder1");
expectedSyncRootPaths.add("/folder2");
expectedSyncRootPaths.add("/folder3");
List<FileSystemItemChange> docChanges = changeSummary.getFileSystemChanges();
assertEquals(3, docChanges.size());
FileSystemItemChange docChange = docChanges.get(0);
assertEquals("other", docChange.getRepositoryId());
assertEquals("documentChanged", docChange.getEventId());
assertEquals("project", docChange.getDocLifeCycleState());
assertEquals("/folder3/doc3", docChange.getDocPath());
assertEquals(doc3.getId(), docChange.getDocUuid());
docChange = docChanges.get(1);
assertEquals("test", docChange.getRepositoryId());
assertEquals("documentChanged", docChange.getEventId());
assertEquals("project", docChange.getDocLifeCycleState());
assertEquals("/folder2/doc2", docChange.getDocPath());
assertEquals(doc2.getId(), docChange.getDocUuid());
docChange = docChanges.get(2);
assertEquals("test", docChange.getRepositoryId());
assertEquals("documentChanged", docChange.getEventId());
assertEquals("project", docChange.getDocLifeCycleState());
assertEquals("/folder1/doc1", docChange.getDocPath());
assertEquals(doc1.getId(), docChange.getDocUuid());
assertEquals(Boolean.FALSE, changeSummary.getHasTooManyChanges());
// Update documents
doc1.setPropertyValue("dc:description", "Added description to doc1.");
doc2.setPropertyValue("dc:description", "Added description to doc1.");
doc3.setPropertyValue("dc:description", "Added description to doc1.");
session.saveDocument(doc1);
session.saveDocument(doc2);
otherSession.saveDocument(doc3);
session.save();
otherSession.save();
// Look in 'other' repository => should find only 1 change
changeSummary = getDocumentChangeSummary("other");
expectedSyncRootPaths = new HashSet<String>();
expectedSyncRootPaths.add("/folder3");
docChanges = changeSummary.getFileSystemChanges();
assertEquals(1, docChanges.size());
docChange = docChanges.get(0);
assertEquals("other", docChange.getRepositoryId());
assertEquals("documentChanged", docChange.getEventId());
assertEquals("project", docChange.getDocLifeCycleState());
assertEquals("/folder3/doc3", docChange.getDocPath());
assertEquals(doc3.getId(), docChange.getDocUuid());
}
/**
* Gets the document changes summary looking in all repositories for the
* user bound to the {@link #session} using the
* {@link NuxeoDriveGetChangeSummary} automation operation and
* updates the {@link #lastSuccessfulSync} date.
*/
protected FileSystemChangeSummary getDocumentChangeSummary() throws Exception {
return getDocumentChangeSummary(null);
}
/**
* Gets the document changes summary looking in the given repository for the
* user bound to the {@link #session} using the
* {@link NuxeoDriveGetChangeSummary} automation operation and
* updates the {@link #lastSuccessfulSync} date.
*/
protected FileSystemChangeSummary getDocumentChangeSummary(
String repositoryName) throws Exception {
// Wait 1 second as the mock change finder relies on steps of 1 second
Thread.sleep(1000);
OperationRequest opRequest = clientSession.newRequest(
NuxeoDriveGetChangeSummary.ID).set(
"lastSuccessfulSync", lastSuccessfulSync);
if (!StringUtils.isEmpty(repositoryName)) {
opRequest.setHeader("X-NXRepository", repositoryName);
}
Blob docChangeSummaryJSON = (Blob) opRequest.execute();
assertNotNull(docChangeSummaryJSON);
FileSystemChangeSummary docChangeSummary = mapper.readValue(
docChangeSummaryJSON.getStream(), FileSystemChangeSummary.class);
assertNotNull(docChangeSummary);
lastSuccessfulSync = docChangeSummary.getSyncDate();
return docChangeSummary;
}
}
|
package com.quickblox.q_municate_contact_list_service;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBContactList;
import com.quickblox.chat.QBRoster;
import com.quickblox.chat.listeners.QBRosterListener;
import com.quickblox.chat.listeners.QBSubscriptionListener;
import com.quickblox.chat.model.QBContactEntry;
import com.quickblox.chat.model.QBPresence;
import com.quickblox.chat.model.QBRosterEntry;
import com.quickblox.core.QBSettings;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.q_municate_base_service.QMBaseService;
import com.quickblox.q_municate_contact_list_service.cache.QMContactListCache;
import com.quickblox.q_municate_core.service.QBServiceConsts;
import com.quickblox.q_municate_core.utils.UserFriendUtils;
import com.quickblox.q_municate_db.utils.ErrorUtils;
import com.quickblox.users.model.QBUser;
import org.jivesoftware.smack.roster.packet.RosterPacket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import rx.Observable;
import rx.functions.Func0;
public class QMContactListService extends QMBaseService {
private static final String TAG = QMContactListService.class.getSimpleName();
private static final String PRESENCE_CHANGE_ERROR = "Presence change error: could not find contact in DB by id = ";
private static final String ENTRIES_CREATING_ERROR = "Failed to create contact list";
private static final String ENTRIES_UPDATING_ERROR = "Failed to update contact list";
private static final String ENTRIES_DELETED_ERROR = "Failed to delete contact";
private static final String SUBSCRIPTION_ERROR = "Failed to confirm subscription";
private static final String ROSTER_INIT_ERROR = "ROSTER isn't initialized. Please make relogin";
private Context context;
private QMContactListCache contactListCache;
private QBContactList qbContacntList;
public QMContactListService(QMContactListCache contactListCache) {
super();
init(contactListCache);
}
private void init(QMContactListCache contactListCache) {
this.context = QBSettings.getInstance().getContext();
this.contactListCache = contactListCache;
qbContacntList = QBChatService.getInstance().getRoster(QBRoster.SubscriptionMode.mutual,
new SubscriptionListener());
qbContacntList.setSubscriptionMode(QBRoster.SubscriptionMode.mutual);
qbContacntList.addRosterListener(new ContactListListener());
}
@Override
protected void serviceWillStart() {
}
public void addUserToContactListRequest(int userId) throws Exception {
invite(userId);
}
public void acceptContactRequest(int userId) throws Exception {
qbContacntList.confirmSubscription(userId);
}
public void rejectContactRequest(int userId) throws Exception {
qbContacntList.reject(userId);
clearRosterEntry(userId);
deleteContactRequest(userId);
}
public void removeUserFromContactList(int userId) throws Exception {
qbContacntList.unsubscribe(userId);
clearRosterEntry(userId);
deleteContactRequest(userId);
}
public Observable<List<QBContactEntry>> getAllContacts(boolean forceLoad){
Observable<List<QBContactEntry>> result = null;
if (!forceLoad) {
result = Observable.defer(new Func0<Observable<List<QBContactEntry>>>() {
@Override
public Observable<List<QBContactEntry>> call() {
List<QBContactEntry> qbContacts = contactListCache.getAll();
return qbContacts.size() == 0 ? getAllContacts(true): Observable.just(qbContacts);
}
});
return result;
}
result = Observable.defer(new Func0<Observable<List<QBContactEntry>>>() {
@Override
public Observable<List<QBContactEntry>> call() {
List<QBContactEntry> list = new ArrayList<QBContactEntry>(qbContacntList.getEntries());
return Observable.just(list);
}
});
return result;
}
private void invite(int userId) throws Exception {
sendInvitation(userId);
}
private void clearRosterEntry(int userId) throws Exception {
QBRosterEntry rosterEntry = qbContacntList.getEntry(userId);
if (rosterEntry != null && qbContacntList.contains(userId)) {
qbContacntList.removeEntry(rosterEntry);
}
}
private boolean isInvited(int userId) {
QBRosterEntry rosterEntry = qbContacntList.getEntry(userId);
if (rosterEntry == null) {
return false;
}
boolean isSubscribedToUser = rosterEntry.getType() == RosterPacket.ItemType.from;
boolean isBothSubscribed = rosterEntry.getType() == RosterPacket.ItemType.both;
return isSubscribedToUser || isBothSubscribed;
}
private boolean isNotInvited(int userId) {
return !isInvited(userId);
}
private void sendInvitation(int userId) throws Exception {
if (qbContacntList.contains(userId)) {
qbContacntList.subscribe(userId);
} else {
qbContacntList.createEntry(userId, null);
}
}
public Collection<Integer> updateContactList() throws QBResponseException {
Collection<Integer> userIdsList = new ArrayList<>();
if (qbContacntList != null) {
if (!qbContacntList.getEntries().isEmpty()) {
userIdsList = createContactList(qbContacntList.getEntries());
updateContacts(userIdsList);
}
} else {
ErrorUtils.logError(TAG, ROSTER_INIT_ERROR);
}
return userIdsList;
}
private Collection<Integer> createContactList(
Collection<QBRosterEntry> rosterEntryCollection) throws QBResponseException {
Collection<Integer> contactList = new ArrayList<>();
Collection<Integer> userList = new ArrayList<>();
for (QBRosterEntry rosterEntry : rosterEntryCollection) {
if (!UserFriendUtils.isOutgoingFriend(rosterEntry) && !UserFriendUtils.isNoneFriend(rosterEntry)) {
contactList.add(rosterEntry.getUserId());
}
if (UserFriendUtils.isOutgoingFriend(rosterEntry)) {
userList.add(rosterEntry.getUserId());
}
}
return contactList;
}
private void updateContacts(Collection<Integer> idsList) throws QBResponseException {
for (Integer userId : idsList) {
updateContact(userId);
}
}
private void updateContact(int userId) throws QBResponseException {
QBRosterEntry rosterEntry = qbContacntList.getEntry(userId);
contactListCache.update(rosterEntry);
}
private void addContact(int userId) throws QBResponseException {
QBRosterEntry rosterEntry = qbContacntList.getEntry(userId);
contactListCache.createOrUpdate(rosterEntry);
}
private void addContacts(Collection<Integer> userIdsList) throws QBResponseException {
for (Integer userId : userIdsList) {
addContact(userId);
}
}
private void deleteContact(int userId) throws QBResponseException {
contactListCache.deleteById(Long.valueOf(userId));
}
private void deleteContactRequest(int userId) {
contactListCache.deleteById(Long.valueOf(userId));
}
private void deleteContacts(Collection<Integer> userIdsList) throws QBResponseException {
for (Integer userId : userIdsList) {
deleteContact(userId);
}
}
private boolean isUserOnline(QBPresence presence) {
return QBPresence.Type.online.equals(presence.getType());
}
public boolean isUserOnline(int userId) {
return qbContacntList != null
&& qbContacntList.getPresence(userId) != null
&& isUserOnline(qbContacntList.getPresence(userId));
}
private void notifyContactRequest(int userId) {
Intent intent = new Intent(QBServiceConsts.GOT_CONTACT_REQUEST);
intent.putExtra(QBServiceConsts.EXTRA_MESSAGE, context.getResources().getString(com.quickblox.q_municate_core.R.string.cht_notification_message));
intent.putExtra(QBServiceConsts.EXTRA_USER_ID, userId);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
private void notifyUserStatusChanged(int userId) {
Intent intent = new Intent(QBServiceConsts.USER_STATUS_CHANGED_ACTION);
intent.putExtra(QBServiceConsts.EXTRA_USER_ID, userId);
intent.putExtra(QBServiceConsts.EXTRA_USER_STATUS, isUserOnline(userId));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
private class ContactListListener implements QBRosterListener {
@Override
public void entriesDeleted(Collection<Integer> userIdsList) {
try {
deleteContacts(userIdsList);
} catch (QBResponseException e) {
Log.e(TAG, ENTRIES_DELETED_ERROR, e);
}
}
@Override
public void entriesAdded(Collection<Integer> userIdsList) {
try {
addContacts(userIdsList);
} catch (QBResponseException e) {
Log.e(TAG, ENTRIES_CREATING_ERROR, e);
}
}
@Override
public void entriesUpdated(Collection<Integer> idsList) {
try {
updateContacts(idsList);
} catch (QBResponseException e) {
Log.e(TAG, ENTRIES_UPDATING_ERROR, e);
}
}
@Override
public void presenceChanged(QBPresence presence) {
notifyUserStatusChanged(presence.getUserId());
}
}
private class SubscriptionListener implements QBSubscriptionListener {
@Override
public void subscriptionRequested(int userId) {
try {
addContact(userId);
} catch (QBResponseException e) {
Log.e(TAG, ENTRIES_CREATING_ERROR, e);
}
}
}
}
|
package org.wyona.yanel.impl.resources.securityapi;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import org.wyona.security.core.api.AccessManagementException;
import org.wyona.security.core.api.Group;
import org.wyona.security.core.api.GroupManager;
import org.wyona.security.core.api.Item;
import org.wyona.security.core.api.PolicyManager;
import org.wyona.security.core.api.User;
import org.wyona.security.core.api.UserManager;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Collections;
import org.apache.log4j.Logger;
/**
* Read and write XML re UserManager
*/
public class UserManagerResource extends BasicXMLResource {
private static Logger log = Logger.getLogger(UserManagerResource.class);
@Override
protected InputStream getContentXML(String viewId) {
if (log.isDebugEnabled()) {
log.debug("requested viewId: " + viewId);
}
StringBuilder sb = new StringBuilder("<?xml version=\"1.0\"?>");
sb.append("<security-api>");
try {
String usecase = getEnvironment().getRequest().getParameter("yanel.usecase");
if (usecase != null) {
log.warn("DEBUG: Yanel usecase: " + usecase);
sb.append("<yanel-usecase>" + usecase + "</yanel-usecase>");
if (usecase.equals("getusers")) {
sb.append(getUsersAsXML());
} else if (usecase.equals("getuser")) {
sb.append(getUserAsXML(getEnvironment().getRequest().getParameter("id")));
} else if (usecase.equals("getgroups")) {
sb.append(getGroupsAsXML());
} else if (usecase.equals("deletepolicy")) {
String path = getParameterAsString("path");
String recursivelyText = getParameterAsString("deep");
boolean recursively = "1".equals(recursivelyText);
deletePolicy(path, recursively);
} else {
sb.append("<no-such-yanel-usecase-implemented>" + usecase + "</no-such-yanel-usecase-implemented>");
}
} else {
sb.append("<no-yanel-usecase/>");
}
} catch(Exception e) {
log.error(e, e);
sb.append("<exception>" + e.getMessage() + "</exception>");
}
sb.append("</security-api>");
return new ByteArrayInputStream(sb.toString().getBytes());
}
@Override
public boolean exists() {
log.warn("TODO: Implementation not finished yet!");
return true;
}
/**
* Get a specific user
* @param id User ID
*/
private StringBuilder getUserAsXML(String id) {
StringBuilder sb = new StringBuilder("<user id=\"" + id + "\">");
sb.append("</user>");
return sb;
}
/**
* Get all groups
*/
private StringBuilder getGroupsAsXML() throws Exception {
GroupManager gm = getRealm().getIdentityManager().getGroupManager();
Group[] groups = gm.getGroups();
Arrays.sort(groups, new ItemIDComparator());
StringBuilder sb = new StringBuilder();
sb.append("<groups");
// INFO: Add custom namespaces
Map<String, String> extraXMLnamespaceDeclarations = getExtraXMLnamespaceDeclarations();
for (Map.Entry<String, String> declaration : extraXMLnamespaceDeclarations.entrySet()) {
sb.append(" xmlns:" + declaration.getKey() + "=\"" + declaration.getValue() + "\"");
}
sb.append(">");
for (int i = 0; i < groups.length; i++) {
sb.append("<group id=\"" + groups[i].getID() + "\"");
// INFO: Add custom properties
SecurityItemExtraPropertiesGetter<Group> itemExtraPropertiesGetter = getGroupExtraPropertiesGetter();
Map<String, String> extraItemProperties = itemExtraPropertiesGetter.getExtraProperties(groups[i]);
for (Map.Entry<String, String> property : extraItemProperties.entrySet()) {
sb.append(" " + property.getKey() + "=\"" + org.wyona.commons.xml.XMLHelper.replaceEntities(property.getValue()) + "\""); //INFO: The name should be safe, so don't escape it
}
sb.append(">" + groups[i].getName() + "</group>");
}
sb.append("</groups>");
return sb;
}
/**
* Deletes a specific policy.
* @param id the policy ID
*/
private void deletePolicy(String path, boolean recursively) throws Exception {
PolicyManager pm = getRealm().getPolicyManager();
if (recursively) {
log.warn("Recursively deletion of policies not yet implemented, only policy "+path+" will be deleted.");
}
pm.removePolicy(path);
}
/**
* Get all users
*/
private StringBuilder getUsersAsXML() throws Exception {
UserManager um = getRealm().getIdentityManager().getUserManager();
boolean refresh = true;
if (getResourceConfigProperty("refresh-users") != null) {
refresh = new Boolean(getResourceConfigProperty("refresh-users")).booleanValue();
} else {
log.warn("No refresh user property set within resource configuration '" + getConfiguration().getNode() + "', hence will use true as default.");
}
User[] users = um.getUsers(refresh);
Arrays.sort(users, new ItemIDComparator());
StringBuilder sb = new StringBuilder();
sb.append("<users");
// INFO: Add custom namespaces
Map<String, String> extraXMLnamespaceDeclarations = getExtraXMLnamespaceDeclarations();
for (Map.Entry<String, String> declaration : extraXMLnamespaceDeclarations.entrySet()) {
sb.append(" xmlns:" + declaration.getKey() + "=\"" + declaration.getValue() + "\"");
}
sb.append(">");
for (int i = 0; i < users.length; i++) {
sb.append("<user id=\"" + users[i].getID() + "\"");
sb.append(" expired=\"" + org.wyona.security.impl.util.UserUtil.isExpired(users[i]) + "\"");
// INFO: Add custom properties
SecurityItemExtraPropertiesGetter<User> itemExtraPropertiesGetter = getUserExtraPropertiesGetter();
Map<String, String> extraItemProperties = itemExtraPropertiesGetter.getExtraProperties(users[i]);
for (Map.Entry<String, String> property : extraItemProperties.entrySet()) {
sb.append(" " + property.getKey() + "=\"" + org.wyona.commons.xml.XMLHelper.replaceEntities(property.getValue()) + "\""); //INFO: The name should be safe, so don't escape it
}
sb.append(">" + users[i].getName() + "</user>");
}
sb.append("</users>");
return sb;
}
public class ItemIDComparator implements Comparator<Item> {
public int compare(Item item1, Item item2) {
try {
String id1 = item1.getID();
String id2 = item2.getID();
return id1.compareToIgnoreCase(id2);
} catch (AccessManagementException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
/**
* Interface/template in order to get custom properties of user or group
*/
public interface SecurityItemExtraPropertiesGetter<I extends Item> {
/**
* Get custom properties
* @param item User, group, host, etc.
*/
Map<String, String> getExtraProperties(I item);
}
/**
* Default implementation of getter for user
*/
protected SecurityItemExtraPropertiesGetter<User> getUserExtraPropertiesGetter() {
return userNoExtraPropertiesGetter;
}
/**
* Default user properties which will be used by default implementation #getUserExtraPropertiesGetter
*/
private static final SecurityItemExtraPropertiesGetter<User> userNoExtraPropertiesGetter = new SecurityItemExtraPropertiesGetter<User>() {
@Override
public Map<String, String> getExtraProperties(User item) {
return Collections.emptyMap();// no extra properties to add for standard Yanel users
}
};
/**
* Default implementation of getter for group
*/
protected SecurityItemExtraPropertiesGetter<Group> getGroupExtraPropertiesGetter() {
return groupNoExtraPropertiesGetter;
}
/**
* Default group properties which will be used by default implementation #getGroupExtraPropertiesGetter
*/
private static final SecurityItemExtraPropertiesGetter<Group> groupNoExtraPropertiesGetter = new SecurityItemExtraPropertiesGetter<Group>() {
@Override
public Map<String, String> getExtraProperties(Group item) {
return Collections.emptyMap();// no extra properties to add for standard Yanel users
}
};
/**
* Overwrite this method in order to insert custom namespaces
*/
protected Map<String, String> getExtraXMLnamespaceDeclarations() throws Exception {
return Collections.emptyMap(); // DEFAULT: No extra XML namespace declarations
}
}
|
package org.rstudio.studio.client.workbench.views.source.editors.text.ace;
import java.util.ArrayList;
import java.util.List;
import org.rstudio.core.client.BrowseCap;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.ListUtil;
import org.rstudio.core.client.MapUtil;
import org.rstudio.core.client.MapUtil.ForEachCommand;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.ListUtil.FilterPredicate;
import org.rstudio.core.client.MouseTracker;
import org.rstudio.core.client.CommandWithArg;
import org.rstudio.core.client.command.KeyboardShortcut;
import org.rstudio.core.client.container.SafeMap;
import org.rstudio.core.client.dom.DomUtils;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.regex.Match;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.filetypes.EditableFileType;
import org.rstudio.studio.client.common.filetypes.FileType;
import org.rstudio.studio.client.common.filetypes.FileTypeRegistry;
import org.rstudio.studio.client.common.filetypes.TextFileType;
import org.rstudio.studio.client.common.filetypes.events.OpenFileInBrowserEvent;
import org.rstudio.studio.client.common.filetypes.model.NavigationMethods;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.workbench.prefs.model.UserPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UserPrefsAccessor;
import org.rstudio.studio.client.workbench.views.files.model.FilesServerOperations;
import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.DocumentChangedEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.EditorModeChangedEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.CommandClickEvent;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.inject.Inject;
import com.google.inject.Provider;
public class AceEditorBackgroundLinkHighlighter
implements
AceClickEvent.Handler,
AttachEvent.Handler,
CommandClickEvent.Handler,
DocumentChangedEvent.Handler,
EditorModeChangedEvent.Handler,
MouseMoveHandler,
MouseUpHandler
{
interface Highlighter
{
void highlight(AceEditor editor, String line, int row);
}
@Inject
private void initialize(GlobalDisplay globalDisplay,
FileTypeRegistry fileTypeRegistry,
EventBus events,
FilesServerOperations server,
MouseTracker mouseTracker,
Provider<UserPrefs> pUserPrefs)
{
globalDisplay_ = globalDisplay;
fileTypeRegistry_ = fileTypeRegistry;
events_ = events;
server_ = server;
mouseTracker_ = mouseTracker;
pUserPrefs_ = pUserPrefs;
}
public AceEditorBackgroundLinkHighlighter(AceEditor editor)
{
RStudioGinjector.INSTANCE.injectMembers(this);
editor_ = editor;
activeMarkers_ = new SafeMap<Integer, List<MarkerRegistration>>();
nextHighlightStart_ = 0;
timer_ = new Timer()
{
@Override
public void run()
{
int n = editor_.getCurrentLineCount();
int startRow = nextHighlightStart_;
int endRow = Math.min(nextHighlightStart_ + N_HIGHLIGHT_ROWS, n);
for (int row = startRow; row < endRow; row++)
highlightRow(row);
nextHighlightStart_ = endRow;
if (endRow != n)
timer_.schedule(5);
}
};
highlighters_ = new ArrayList<Highlighter>();
handlers_ = new ArrayList<HandlerRegistration>();
handlers_.add(editor_.addAceClickHandler(this));
handlers_.add(editor_.addAttachHandler(this));
handlers_.add(editor_.addDocumentChangedHandler(this));
handlers_.add(editor_.addEditorModeChangedHandler(this));
handlers_.add(editor_.addMouseMoveHandler(this));
handlers_.add(editor_.addMouseUpHandler(this));
refreshHighlighters(editor_.getModeId());
}
private void refreshHighlighters(String mode)
{
clearAllMarkers();
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
TextFileType fileType = editor_.getFileType();
highlighters_.clear();
if (pUserPrefs_.get().highlightWebLink().getValue())
{
highlighters_.add(webLinkHighlighter());
}
pUserPrefs_.get().highlightWebLink().bind(
new CommandWithArg<Boolean>() {
public void execute(Boolean arg) {
if (arg)
{
highlighters_.add(webLinkHighlighter());
}
else
{
highlighters_.remove(webLinkHighlighter());
}
}});
if (fileType != null && (fileType.isMarkdown() || fileType.isRmd()))
highlighters_.add(markdownLinkHighlighter());
nextHighlightStart_ = 0;
timer_.schedule(700);
}
});
}
private void highlightRow(int row)
{
for (Highlighter highlighter : highlighters_)
highlighter.highlight(editor_, editor_.getLine(row), row);
}
private void registerActiveMarker(int row,
String id,
int markerId,
final AnchoredRange range)
{
if (!activeMarkers_.containsKey(row))
activeMarkers_.put(row, new ArrayList<MarkerRegistration>());
List<MarkerRegistration> markers = activeMarkers_.get(row);
// if we're adding a marker that subsumes an old one, clear the old marker
List<MarkerRegistration> filtered = ListUtil.filter(markers, new FilterPredicate<MarkerRegistration>()
{
@Override
public boolean test(MarkerRegistration marker)
{
if (range.intersects(marker.getRange()))
{
marker.detach();
return false;
}
return true;
}
});
// add our new marker
filtered.add(new MarkerRegistration(id, markerId, range));
activeMarkers_.put(row, filtered);
}
private boolean isRequiredClickModifier(int modifier)
{
return BrowseCap.isMacintosh()
? modifier == KeyboardShortcut.META
: modifier == KeyboardShortcut.SHIFT;
}
private boolean isRequiredClickModifier(NativeEvent event)
{
return isRequiredClickModifier(KeyboardShortcut.getModifierValue(event));
}
private MarkerRegistration getTargetedMarker(NativeEvent event)
{
int pageX = event.getClientX();
int pageY = event.getClientY();
return getTargetedMarker(pageX, pageY);
}
private MarkerRegistration getTargetedMarker(int pageX, int pageY)
{
Position position = editor_.screenCoordinatesToDocumentPosition(pageX, pageY);
int row = position.getRow();
if (!activeMarkers_.containsKey(row))
return null;
List<MarkerRegistration> markers = activeMarkers_.get(row);
for (MarkerRegistration marker : markers)
if (marker.getRange().contains(position))
return marker;
return null;
}
private void beginDetectClickTarget(int pageX, int pageY, int modifier)
{
if (!isRequiredClickModifier(modifier))
return;
MarkerRegistration activeMarker = getTargetedMarker(pageX, pageY);
if (activeMarker == null)
return;
Element el = DomUtils.elementFromPoint(pageX, pageY);
if (el == null)
return;
// the element might itself be the marker we want to update, or
// it may be the editor instance. handle each case
String id = activeMarker.getId();
Element markerEl = el.hasClassName(id)
? el
: DomUtils.getFirstElementWithClassName(el, id);
if (markerEl == null)
return;
if (activeHighlightMarkerEl_ != null && activeHighlightMarkerEl_ != markerEl)
{
activeHighlightMarkerEl_.addClassName(RES.styles().highlight());
activeHighlightMarkerEl_.removeClassName(RES.styles().hover());
}
markerEl.removeClassName(RES.styles().highlight());
markerEl.addClassName(RES.styles().hover());
activeHighlightMarkerEl_ = markerEl;
}
private void endDetectClickTarget()
{
if (activeHighlightMarkerEl_ == null)
return;
// restore highlight styles
activeHighlightMarkerEl_.addClassName(RES.styles().highlight());
activeHighlightMarkerEl_.removeClassName(RES.styles().hover());
// unset active el
activeHighlightMarkerEl_ = null;
}
private void clearAllMarkers()
{
MapUtil.forEach(activeMarkers_, new ForEachCommand<Integer, List<MarkerRegistration>>()
{
@Override
public void execute(Integer row, List<MarkerRegistration> markers)
{
for (MarkerRegistration marker : markers)
marker.detach();
}
});
activeMarkers_.clear();
}
private void clearMarkers(final Range range)
{
for (int row = range.getStart().getRow();
row <= range.getEnd().getRow();
row++)
{
if (!activeMarkers_.containsKey(row))
continue;
// clear markers that are included within this range
List<MarkerRegistration> markers = activeMarkers_.get(row);
List<MarkerRegistration> filtered = ListUtil.filter(markers, new FilterPredicate<MarkerRegistration>()
{
@Override
public boolean test(MarkerRegistration marker)
{
if (range.contains(marker.getRange()))
{
marker.detach();
return false;
}
return true;
}
});
// update active markers for this row
activeMarkers_.put(row, filtered);
}
}
private void navigateToUrl(String url)
{
// allow web links starting with 'www'
if (url.startsWith("www."))
url = "http://" + url;
// attempt to open web links in a new window
Pattern reWebLink = Pattern.create("^https?:
if (reWebLink.test(url))
{
globalDisplay_.openWindow(url);
return;
}
// handle testthat links
Pattern reSrcRef = Pattern.create("@[^
if (reSrcRef.test(url))
return;
// treat other URLs as paths to files on the server
final String finalUrl = url;
server_.stat(finalUrl, new ServerRequestCallback<FileSystemItem>()
{
@Override
public void onResponseReceived(FileSystemItem file)
{
// inform user when no file found
if (file == null || !file.exists())
{
String message = "No file at path '" + finalUrl + "'.";
String caption = "Error navigating to file";
globalDisplay_.showErrorMessage(caption, message);
return;
}
// if we have a registered filetype for this file, try
// to open it in the IDE; otherwise open in browser
FileType fileType = fileTypeRegistry_.getTypeForFile(file);
if (fileType != null && fileType instanceof EditableFileType)
{
fileType.openFile(file, null, NavigationMethods.DEFAULT, events_);
}
else
{
events_.fireEvent(new OpenFileInBrowserEvent(file));
}
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
private void highlight(final AceEditor editor,
int row,
int startColumn,
int endColumn)
{
// check to see if we already have a marker for this range
Position start = Position.create(row, startColumn);
Position end = Position.create(row, endColumn);
Range range = Range.fromPoints(start, end);
if (activeMarkers_.containsKey(row))
{
List<MarkerRegistration> markers = activeMarkers_.get(row);
for (MarkerRegistration marker : markers)
{
if (marker.getRange().isEqualTo(range))
return;
}
}
// create an anchored range and add a marker for it
final String id = "ace_marker-" + StringUtil.makeRandomId(16);
final String styles = RES.styles().highlight() + " ace_marker " + id;
AnchoredRange anchoredRange = editor.getSession().createAnchoredRange(start, end, true);
final String title = BrowseCap.isMacintosh()
? "Open Link (Command+Click)"
: "Open Link (Shift+Click)";
MarkerRenderer renderer =
MarkerRenderer.create(editor.getWidget().getEditor(), styles, title);
int markerId = editor.getSession().addMarker(anchoredRange, styles, renderer, true);
registerActiveMarker(row, id, markerId, anchoredRange);
}
private Highlighter webLinkHighlighter()
{
return new Highlighter()
{
@Override
public void highlight(AceEditor editor, String line, int row)
{
onWebLinkHighlight(editor, line, row);
}
};
}
private void onWebLinkHighlight(AceEditor editor, String line, int row)
{
// use a regex that captures all non-space characters within
// a web link, and then fix up the captured link by removing
// trailing punctuation, etc. as required
Pattern reWebLink = createWebLinkPattern();
for (Match match = reWebLink.match(line, 0);
match != null;
match = match.nextMatch())
{
// compute start, end index for discovered URL
int startIdx = match.getIndex();
int endIdx = match.getIndex() + match.getValue().length();
// ensure that the discovered url is not within a string
Token token = editor_.getTokenAt(Position.create(row, startIdx));
if (token.hasType("string"))
continue;
String url = match.getValue();
// trim off enclosing brackets
if (!url.matches(reWebLink()))
{
startIdx++;
endIdx
url = url.substring(1, url.length() - 1);
}
// trim off trailing punctuation (characters unlikely
// to be found at the end of a url)
String trimmed = url.replaceAll("[,.?!@
endIdx -= (url.length() - trimmed.length());
url = trimmed;
// perform highlighting
highlight(editor, row, startIdx, endIdx);
}
}
private static String reWebLink()
{
return "(?:\\w+://|www\\.)\\S+";
}
private static Pattern createWebLinkPattern()
{
String rePattern = StringUtil.join(new String[] {
"\\{" + reWebLink() + "?\\}",
"\\(" + reWebLink() + "?\\)",
"\\[" + reWebLink() + "?\\]",
"\\<" + reWebLink() + "?\\>",
"'" + reWebLink() + "'",
"\"" + reWebLink() + "\"",
reWebLink()
}, "|");
return Pattern.create(rePattern);
}
private Highlighter markdownLinkHighlighter()
{
return new Highlighter()
{
@Override
public void highlight(AceEditor editor, String line, int row)
{
onMarkdownLinkHighlight(editor, line, row);
}
};
}
private void onMarkdownLinkHighlight(AceEditor editor,
String line,
int row)
{
Pattern reMarkdownLink = Pattern.create("(\\[[^\\]]+\\])(\\([^\\)]+\\))");
for (Match match = reMarkdownLink.match(line, 0);
match != null;
match = match.nextMatch())
{
int startIdx = match.getIndex() + match.getGroup(1).length() + 1;
int endIdx = match.getIndex() + match.getValue().length() - 1;
highlight(editor, row, startIdx, endIdx);
}
}
@SuppressWarnings("unused")
private Highlighter testthatErrorHighlighter()
{
return new Highlighter()
{
@Override
public void highlight(AceEditor editor, String line, int row)
{
onTestthatErrorHighlight(editor, line, row);
}
};
}
private void onTestthatErrorHighlight(AceEditor editor, String line, int row)
{
Pattern reTestthatError = Pattern.create("\\(@[^
for (Match match = reTestthatError.match(line, 0);
match != null;
match = match.nextMatch())
{
int startIdx = match.getIndex() + 1;
int endIdx = match.getIndex() + match.getValue().length() - 1;
highlight(editor, row, startIdx, endIdx);
}
}
@Override
public void onAttachOrDetach(AttachEvent event)
{
if (event.isAttached())
{
previewHandler_ = Event.addNativePreviewHandler(new NativePreviewHandler()
{
@Override
public void onPreviewNativeEvent(NativePreviewEvent preview)
{
int type = preview.getTypeInt();
if (type == Event.ONKEYDOWN)
{
int modifier = KeyboardShortcut.getModifierValue(preview.getNativeEvent());
beginDetectClickTarget(mouseTracker_.getLastMouseX(), mouseTracker_.getLastMouseY(), modifier);
}
else if (type == Event.ONKEYUP)
{
endDetectClickTarget();
}
}
});
}
else
{
for (HandlerRegistration handler : handlers_)
handler.removeHandler();
handlers_.clear();
if (previewHandler_ != null)
{
previewHandler_.removeHandler();
previewHandler_ = null;
}
}
}
@Override
public void onDocumentChanged(DocumentChangedEvent event)
{
// clear markers within the delete range
clearMarkers(event.getEvent().getRange());
// prepare highlighter
int row = event.getEvent().getRange().getStart().getRow();
nextHighlightStart_ = Math.min(nextHighlightStart_, row);
timer_.schedule(700);
// update marker positions (deferred so that anchors update)
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
final SafeMap<Integer, List<MarkerRegistration>> newMarkers =
new SafeMap<Integer, List<MarkerRegistration>>();
MapUtil.forEach(activeMarkers_, new ForEachCommand<Integer, List<MarkerRegistration>>()
{
@Override
public void execute(Integer oldRow, List<MarkerRegistration> markers)
{
if (markers == null || markers.isEmpty())
return;
// all markers here should have same row
int newRow = markers.get(0).getRange().getStart().getRow();
newMarkers.put(newRow, markers);
}
});
activeMarkers_.clear();
activeMarkers_ = newMarkers;
}
});
}
@Override
public void onEditorModeChanged(EditorModeChangedEvent event)
{
refreshHighlighters(event.getMode());
}
@Override
public void onCommandClick(CommandClickEvent event)
{
Position position = event.getEvent().getDocumentPosition();
int row = position.getRow();
if (!activeMarkers_.containsKey(row))
return;
List<MarkerRegistration> markers = activeMarkers_.get(row);
for (MarkerRegistration registration : markers)
{
if (registration.getRange().contains(position))
{
endDetectClickTarget();
String url = editor_.getTextForRange(registration.getRange());
navigateToUrl(url);
return;
}
}
}
@Override
public void onAceClick(AceClickEvent clickEvent)
{
NativeEvent event = clickEvent.getNativeEvent();
if (!isRequiredClickModifier(event))
return;
MarkerRegistration marker = getTargetedMarker(event);
if (marker == null)
return;
clickEvent.stopPropagation();
clickEvent.preventDefault();
// on OS X, we immediately open the popup as otherwise the link
// will be opened in the background
if (BrowseCap.isMacintosh() && !BrowseCap.isMacintoshDesktop())
{
endDetectClickTarget();
String url = editor_.getTextForRange(marker.getRange());
navigateToUrl(url);
}
}
@Override
public void onMouseUp(MouseUpEvent mouseUpEvent)
{
// clicks handled in 'onAceClick' for OS X web mode
if (BrowseCap.isMacintosh() && !BrowseCap.isMacintoshDesktop())
return;
NativeEvent event = mouseUpEvent.getNativeEvent();
if (!isRequiredClickModifier(event))
return;
MarkerRegistration marker = getTargetedMarker(event);
if (marker == null)
return;
boolean hasMouseMoved =
Math.abs(event.getClientX() - mouseTracker_.getLastMouseX()) >= 2 ||
Math.abs(event.getClientY() - mouseTracker_.getLastMouseY()) >= 2;
if (hasMouseMoved)
return;
event.stopPropagation();
event.preventDefault();
endDetectClickTarget();
String url = editor_.getTextForRange(marker.getRange());
navigateToUrl(url);
}
@Override
public void onMouseMove(MouseMoveEvent event)
{
beginDetectClickTarget(
event.getClientX(),
event.getClientY(),
KeyboardShortcut.getModifierValue(event.getNativeEvent()));
}
interface Resources extends ClientBundle
{
@Source("AceEditorBackgroundLinkHighlighter.css")
Styles styles();
}
interface Styles extends CssResource
{
String highlight();
String hover();
}
public static Resources RES = GWT.create(Resources.class);
static {
RES.styles().ensureInjected();
}
private static class MarkerRenderer extends JavaScriptObject
{
protected MarkerRenderer() {}
public static final native MarkerRenderer create(final AceEditorNative editor,
final String clazz,
final String title)
/*-{
var markerBack = editor.renderer.$markerBack;
return $entry(function(html, range, left, top, config) {
// HACK: we take advantage of an implementation detail of
// Ace's 'drawTextMarker' implementation. Ace constructs
// HTML for the generated markers with code of the form:
//
// html = "<div style='..." + extraStyle + "'>"
//
// We take advantage of this, and inject our 'extraStyle'
// to close the style attribute we were intended to be
// locked in, and instead inject a 'title' attribute instead.
var extra = "' title='" + title;
if (range.isMultiLine())
return markerBack.drawTextMarker(html, range, clazz, config, extra);
else
return markerBack.drawSingleLineMarker(html, range, clazz, config, 0, extra);
});
}-*/;
}
private class MarkerRegistration
{
public MarkerRegistration(String id, int markerId, AnchoredRange range)
{
id_ = id;
markerId_ = markerId;
range_ = range;
}
public void detach()
{
editor_.getSession().removeMarker(getMarkerId());
range_.detach();
}
public String getId()
{
return id_;
}
public int getMarkerId()
{
return markerId_;
}
public AnchoredRange getRange()
{
return range_;
}
private final String id_;
private final int markerId_;
private final AnchoredRange range_;
}
private final AceEditor editor_;
private final List<Highlighter> highlighters_;
private final Timer timer_;
private final List<HandlerRegistration> handlers_;
private SafeMap<Integer, List<MarkerRegistration>> activeMarkers_;
private int nextHighlightStart_;
private static final int N_HIGHLIGHT_ROWS = 200;
private HandlerRegistration previewHandler_;
private Element activeHighlightMarkerEl_;
private GlobalDisplay globalDisplay_;
private FileTypeRegistry fileTypeRegistry_;
private EventBus events_;
private FilesServerOperations server_;
private MouseTracker mouseTracker_;
private Provider<UserPrefs> pUserPrefs_;
}
|
package org.eclipse.birt.integration.wtp.ui.internal.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.integration.wtp.ui.internal.webapplication.ContextParamBean;
import org.eclipse.birt.integration.wtp.ui.internal.webapplication.FilterBean;
import org.eclipse.birt.integration.wtp.ui.internal.webapplication.FilterMappingBean;
import org.eclipse.birt.integration.wtp.ui.internal.webapplication.ListenerBean;
import org.eclipse.birt.integration.wtp.ui.internal.webapplication.ServletBean;
import org.eclipse.birt.integration.wtp.ui.internal.webapplication.ServletMappingBean;
import org.eclipse.birt.integration.wtp.ui.internal.webapplication.TagLibBean;
import org.eclipse.birt.integration.wtp.ui.internal.webapplication.WebAppBean;
import org.eclipse.birt.integration.wtp.ui.internal.wizards.IBirtWizardConstants;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jst.j2ee.common.CommonFactory;
import org.eclipse.jst.j2ee.common.Description;
import org.eclipse.jst.j2ee.common.Listener;
import org.eclipse.jst.j2ee.common.ParamValue;
import org.eclipse.jst.j2ee.jsp.JSPConfig;
import org.eclipse.jst.j2ee.jsp.JspFactory;
import org.eclipse.jst.j2ee.jsp.TagLibRefType;
import org.eclipse.jst.j2ee.web.componentcore.util.WebArtifactEdit;
import org.eclipse.jst.j2ee.webapplication.ContextParam;
import org.eclipse.jst.j2ee.webapplication.Filter;
import org.eclipse.jst.j2ee.webapplication.FilterMapping;
import org.eclipse.jst.j2ee.webapplication.Servlet;
import org.eclipse.jst.j2ee.webapplication.ServletMapping;
import org.eclipse.jst.j2ee.webapplication.ServletType;
import org.eclipse.jst.j2ee.webapplication.TagLibRef;
import org.eclipse.jst.j2ee.webapplication.WebApp;
import org.eclipse.jst.j2ee.webapplication.WebapplicationFactory;
import org.eclipse.ui.dialogs.IOverwriteQuery;
/**
* Birt WebArtifact Utility
*
*/
public class WebArtifactUtil implements IBirtWizardConstants
{
/**
* Configure the web application general descriptions
*
* @param webApp
* @param project
* @param query
* @param monitor
* @throws CoreException
*/
public static void configureWebApp( WebAppBean webAppBean,
IProject project, IOverwriteQuery query, IProgressMonitor monitor )
throws CoreException
{
// cancel progress
if ( monitor.isCanceled( ) )
return;
if ( webAppBean == null || project == null )
{
return;
}
// create WebArtifact
WebArtifactEdit webEdit = WebArtifactEdit
.getWebArtifactEditForWrite( project );
if ( webEdit == null )
return;
try
{
WebApp webapp = (WebApp) webEdit.getDeploymentDescriptorRoot( );
webapp.setDescription( webAppBean.getDescription( ) );
webEdit.saveIfNecessary( monitor );
}
finally
{
webEdit.dispose( );
}
}
/**
* Configure the context param settings
*
* @param map
* @param project
* @param query
* @param monitor
* @throws CoreException
*/
public static void configureContextParam( Map map, IProject project,
IOverwriteQuery query, IProgressMonitor monitor )
throws CoreException
{
// cancel progress
if ( monitor.isCanceled( ) )
return;
if ( map == null || project == null )
{
return;
}
// create WebArtifact
WebArtifactEdit webEdit = WebArtifactEdit
.getWebArtifactEditForWrite( project );
if ( webEdit == null )
return;
try
{
WebApp webapp = (WebApp) webEdit.getDeploymentDescriptorRoot( );
// handle context-param settings
Iterator it = map.keySet( ).iterator( );
while ( it.hasNext( ) )
{
String name = DataUtil.getString( it.next( ), false );
ContextParamBean bean = (ContextParamBean) map.get( name );
if ( bean == null )
continue;
// if contained this param
List list = null;
if ( webapp.getVersionID( ) == 23 )
{
// for servlet 2.3
list = webapp.getContexts( );
}
else
{
// for servlet 2.4
list = webapp.getContextParams( );
}
int index = getContextParamIndexByName( list, name );
if ( index >= 0 )
{
String ret = query
.queryOverwrite( "Context-param '" + name + "'" ); //$NON-NLS-1$ //$NON-NLS-2$
// check overwrite query result
if ( IOverwriteQuery.NO.equalsIgnoreCase( ret ) )
{
continue;
}
if ( IOverwriteQuery.CANCEL.equalsIgnoreCase( ret ) )
{
monitor.setCanceled( true );
return;
}
// remove old item
list.remove( index );
}
String value = bean.getValue( );
String description = bean.getDescription( );
if ( webapp.getVersionID( ) == 23 )
{
// create context-param object
ContextParam param = WebapplicationFactory.eINSTANCE
.createContextParam( );
param.setParamName( name );
param.setParamValue( value );
if ( description != null )
param.setDescription( description );
param.setWebApp( webapp );
}
else
{
// create ParamValue object for servlet 2.4
ParamValue param = CommonFactory.eINSTANCE
.createParamValue( );
param.setName( name );
param.setValue( value );
if ( description != null )
{
Description descriptionObj = CommonFactory.eINSTANCE
.createDescription( );
descriptionObj.setValue( description );
param.getDescriptions( ).add( descriptionObj );
param.setDescription( description );
}
// add into list
webapp.getContextParams( ).add( param );
}
}
webEdit.saveIfNecessary( monitor );
}
finally
{
webEdit.dispose( );
}
}
/**
* get context-param from list by name
*
* @param list
* @param name
* @return
*/
public static Object getContextParamByName( List list, String name )
{
if ( list == null || name == null )
return null;
Iterator it = list.iterator( );
while ( it.hasNext( ) )
{
// get param object
Object paramObj = it.next( );
// for servlet 2.3
if ( paramObj instanceof ContextParam )
{
ContextParam param = (ContextParam) paramObj;
if ( name.equals( param.getParamName( ) ) )
return param;
}
// for servlet 2.4
if ( paramObj instanceof ParamValue )
{
ParamValue param = (ParamValue) paramObj;
if ( name.equals( param.getName( ) ) )
return param;
}
}
return null;
}
/**
* get context-param index from list by name
*
* @param list
* @param name
* @return index
*/
public static int getContextParamIndexByName( List list, String name )
{
if ( list == null || name == null )
return -1;
Iterator it = list.iterator( );
int index = 0;
while ( it.hasNext( ) )
{
// get param object
Object paramObj = it.next( );
// for servlet 2.3
if ( paramObj instanceof ContextParam )
{
ContextParam param = (ContextParam) paramObj;
if ( name.equals( param.getParamName( ) ) )
return index;
}
// for servlet 2.4
if ( paramObj instanceof ParamValue )
{
ParamValue param = (ParamValue) paramObj;
if ( name.equals( param.getName( ) ) )
return index;
}
index++;
}
return -1;
}
/**
* Configure the filter settings
*
* @param map
* @param project
* @param query
* @param monitor
* @throws CoreException
*/
public static void configureFilter( Map map, IProject project,
IOverwriteQuery query, IProgressMonitor monitor )
throws CoreException
{
// cancel progress
if ( monitor.isCanceled( ) )
return;
if ( map == null || project == null )
{
return;
}
// create WebArtifact
WebArtifactEdit webEdit = WebArtifactEdit
.getWebArtifactEditForWrite( project );
if ( webEdit == null )
return;
try
{
WebApp webapp = (WebApp) webEdit.getDeploymentDescriptorRoot( );
// handle filter settings
Iterator it = map.keySet( ).iterator( );
while ( it.hasNext( ) )
{
String name = DataUtil.getString( it.next( ), false );
FilterBean bean = (FilterBean) map.get( name );
if ( bean == null )
continue;
// if contained this filter
Object obj = webapp.getFilterNamed( name );
if ( obj != null )
{
String ret = query.queryOverwrite( "Filter '" + name + "'" ); //$NON-NLS-1$ //$NON-NLS-2$
// check overwrite query result
if ( IOverwriteQuery.NO.equalsIgnoreCase( ret ) )
{
continue;
}
if ( IOverwriteQuery.CANCEL.equalsIgnoreCase( ret ) )
{
monitor.setCanceled( true );
return;
}
// remove old item
webapp.getFilters( ).remove( obj );
}
String className = bean.getClassName( );
String description = bean.getDescription( );
// create filter object
Filter filter = WebapplicationFactory.eINSTANCE.createFilter( );
filter.setName( name );
filter.setFilterClassName( className );
filter.setDescription( description );
webapp.getFilters( ).add( filter );
}
webEdit.saveIfNecessary( monitor );
}
finally
{
webEdit.dispose( );
}
}
/**
* Configure the filter-mapping settings
*
* @param map
* @param project
* @param query
* @param monitor
* @throws CoreException
*/
public static void configureFilterMapping( Map map, IProject project,
IOverwriteQuery query, IProgressMonitor monitor )
throws CoreException
{
// cancel progress
if ( monitor.isCanceled( ) )
return;
if ( map == null || project == null )
{
return;
}
// create WebArtifact
WebArtifactEdit webEdit = WebArtifactEdit
.getWebArtifactEditForWrite( project );
if ( webEdit == null )
return;
try
{
WebApp webapp = (WebApp) webEdit.getDeploymentDescriptorRoot( );
// handle filter-mapping settings
Iterator it = map.keySet( ).iterator( );
while ( it.hasNext( ) )
{
String key = DataUtil.getString( it.next( ), false );
FilterMappingBean bean = (FilterMappingBean) map.get( key );
if ( bean == null )
continue;
// if contained this filter-mapping
Object obj = getFilterMappingByKey(
webapp.getFilterMappings( ), key );
if ( obj != null )
{
String ret = query
.queryOverwrite( "Filter-mapping '" + key + "'" ); //$NON-NLS-1$ //$NON-NLS-2$
// check overwrite query result
if ( IOverwriteQuery.NO.equalsIgnoreCase( ret ) )
{
continue;
}
if ( IOverwriteQuery.CANCEL.equalsIgnoreCase( ret ) )
{
monitor.setCanceled( true );
return;
}
// remove old item
webapp.getFilterMappings( ).remove( obj );
}
// filter name
String name = bean.getName( );
// create FilterMapping object
FilterMapping mapping = WebapplicationFactory.eINSTANCE
.createFilterMapping( );
// get filter by name
Filter filter = webapp.getFilterNamed( name );
if ( filter != null )
{
mapping.setFilter( filter );
mapping.setUrlPattern( bean.getUri( ) );
mapping.setServletName( bean.getServletName( ) );
// get Servlet object
Servlet servlet = webapp.getServletNamed( bean
.getServletName( ) );
mapping.setServlet( servlet );
if ( bean.getUri( ) != null || servlet != null )
webapp.getFilterMappings( ).add( mapping );
}
}
webEdit.saveIfNecessary( monitor );
}
finally
{
webEdit.dispose( );
}
}
/**
* get filter-mapping from list by key String
*
* @param list
* @param name
* @return
*/
public static Object getFilterMappingByKey( List list, String key )
{
if ( list == null || key == null )
return null;
Iterator it = list.iterator( );
while ( it.hasNext( ) )
{
// get filter-mapping object
FilterMapping filterMapping = (FilterMapping) it.next( );
if ( filterMapping != null )
{
String name = filterMapping.getFilter( ).getName( );
String servletName = filterMapping.getServletName( );
String uri = filterMapping.getUrlPattern( );
String curKey = getFilterMappingString( name, servletName, uri );
if ( key.equals( curKey ) )
return filterMapping;
}
}
return null;
}
/**
* Configure the listener settings
*
* @param map
* @param project
* @param query
* @param monitor
* @throws CoreException
*/
public static void configureListener( Map map, IProject project,
IOverwriteQuery query, IProgressMonitor monitor )
throws CoreException
{
// cancel progress
if ( monitor.isCanceled( ) )
return;
if ( map == null || project == null )
{
return;
}
// create WebArtifact
WebArtifactEdit webEdit = WebArtifactEdit
.getWebArtifactEditForWrite( project );
if ( webEdit == null )
return;
try
{
WebApp webapp = (WebApp) webEdit.getDeploymentDescriptorRoot( );
// handle listeners settings
Iterator it = map.keySet( ).iterator( );
while ( it.hasNext( ) )
{
String name = DataUtil.getString( it.next( ), false );
ListenerBean bean = (ListenerBean) map.get( name );
if ( bean == null )
continue;
String className = bean.getClassName( );
String description = bean.getDescription( );
// if listener existed in web.xml, skip it
Object obj = getListenerByClassName( webapp.getListeners( ),
className );
if ( obj != null )
continue;
// create Listener object
Listener listener = CommonFactory.eINSTANCE.createListener( );
listener.setListenerClassName( className );
if ( description != null )
listener.setDescription( description );
webapp.getListeners( ).remove( listener );
webapp.getListeners( ).add( listener );
}
webEdit.saveIfNecessary( monitor );
}
finally
{
webEdit.dispose( );
}
}
/**
* get listener from list by class name
*
* @param list
* @param name
* @return
*/
public static Object getListenerByClassName( List list, String className )
{
if ( list == null || className == null )
return null;
Iterator it = list.iterator( );
while ( it.hasNext( ) )
{
// get listener object
Listener listener = (Listener) it.next( );
if ( listener != null
&& className.equals( listener.getListenerClassName( ) ) )
{
return listener;
}
}
return null;
}
/**
* Configure the servlet settings
*
* @param map
* @param project
* @param query
* @param monitor
* @throws CoreException
*/
public static void configureServlet( Map map, IProject project,
IOverwriteQuery query, IProgressMonitor monitor )
throws CoreException
{
// cancel progress
if ( monitor.isCanceled( ) )
return;
if ( map == null || project == null )
{
return;
}
// create WebArtifact
WebArtifactEdit webEdit = WebArtifactEdit
.getWebArtifactEditForWrite( project );
if ( webEdit == null )
return;
try
{
WebApp webapp = (WebApp) webEdit.getDeploymentDescriptorRoot( );
// handle servlet settings
Iterator it = map.keySet( ).iterator( );
while ( it.hasNext( ) )
{
String name = DataUtil.getString( it.next( ), false );
ServletBean bean = (ServletBean) map.get( name );
if ( bean == null )
continue;
// if contained this servlet
Object obj = webapp.getServletNamed( name );
if ( obj != null )
{
String ret = query
.queryOverwrite( "Servlet '" + name + "'" ); //$NON-NLS-1$ //$NON-NLS-2$
// check overwrite query result
if ( IOverwriteQuery.NO.equalsIgnoreCase( ret ) )
{
continue;
}
if ( IOverwriteQuery.CANCEL.equalsIgnoreCase( ret ) )
{
monitor.setCanceled( true );
return;
}
// remove old item
webapp.getServlets( ).remove( obj );
}
String className = bean.getClassName( );
String description = bean.getDescription( );
// create Servlet Type object
ServletType servletType = WebapplicationFactory.eINSTANCE
.createServletType( );
servletType.setClassName( className );
// create Servlet object
Servlet servlet = WebapplicationFactory.eINSTANCE
.createServlet( );
servlet.setServletName( name );
if ( description != null )
servlet.setDescription( description );
servlet.setWebType( servletType );
servlet.setWebApp( webapp );
}
webEdit.saveIfNecessary( monitor );
}
finally
{
webEdit.dispose( );
}
}
/**
* Configure the servlet-mapping settings
*
* @param map
* @param project
* @param query
* @param monitor
* @throws CoreException
*/
public static void configureServletMapping( Map map, IProject project,
IOverwriteQuery query, IProgressMonitor monitor )
throws CoreException
{
// cancel progress
if ( monitor.isCanceled( ) )
return;
if ( map == null || project == null )
{
return;
}
// create WebArtifact
WebArtifactEdit webEdit = WebArtifactEdit
.getWebArtifactEditForWrite( project );
if ( webEdit == null )
return;
try
{
WebApp webapp = (WebApp) webEdit.getDeploymentDescriptorRoot( );
// handle servlet-mapping settings
Iterator it = map.keySet( ).iterator( );
while ( it.hasNext( ) )
{
String uri = DataUtil.getString( it.next( ), false );
ServletMappingBean bean = (ServletMappingBean) map.get( uri );
if ( bean == null )
continue;
// if contained this servlet-mapping
Object obj = getServletMappingByUri( webapp
.getServletMappings( ), uri );
if ( obj != null )
{
String ret = query
.queryOverwrite( "Servlet-mapping '" + uri + "'" ); //$NON-NLS-1$ //$NON-NLS-2$
// check overwrite query result
if ( IOverwriteQuery.NO.equalsIgnoreCase( ret ) )
{
continue;
}
if ( IOverwriteQuery.CANCEL.equalsIgnoreCase( ret ) )
{
monitor.setCanceled( true );
return;
}
// remove old item
webapp.getServletMappings( ).remove( obj );
}
// servlet name
String name = bean.getName( );
// create ServletMapping object
ServletMapping mapping = WebapplicationFactory.eINSTANCE
.createServletMapping( );
// get servlet by name
Servlet servlet = webapp.getServletNamed( name );
if ( servlet != null )
{
mapping.setServlet( servlet );
mapping.setUrlPattern( uri );
mapping.setWebApp( webapp );
}
}
webEdit.saveIfNecessary( monitor );
}
finally
{
webEdit.dispose( );
}
}
/**
* get servlet mapping from list by uri
*
* @param list
* @param name
* @return
*/
public static Object getServletMappingByUri( List list, String uri )
{
if ( list == null || uri == null )
return null;
Iterator it = list.iterator( );
while ( it.hasNext( ) )
{
// get servlet-mapping object
ServletMapping servletMapping = (ServletMapping) it.next( );
if ( servletMapping != null
&& uri.equals( servletMapping.getUrlPattern( ) ) )
{
return servletMapping;
}
}
return null;
}
/**
* Configure the taglib settings
*
* @param map
* @param project
* @param query
* @param monitor
* @throws CoreException
*/
public static void configureTaglib( Map map, IProject project,
IOverwriteQuery query, IProgressMonitor monitor )
throws CoreException
{
// cancel progress
if ( monitor.isCanceled( ) )
return;
if ( map == null || project == null )
{
return;
}
// create WebArtifact
WebArtifactEdit webEdit = WebArtifactEdit
.getWebArtifactEditForWrite( project );
if ( webEdit == null )
return;
try
{
WebApp webapp = (WebApp) webEdit.getDeploymentDescriptorRoot( );
// handle taglib settings
Iterator it = map.keySet( ).iterator( );
while ( it.hasNext( ) )
{
String uri = DataUtil.getString( it.next( ), false );
TagLibBean bean = (TagLibBean) map.get( uri );
if ( bean == null )
continue;
// if contained this taglib
Object obj = getTagLibByUri( webapp, uri );
if ( obj != null )
{
String ret = query.queryOverwrite( "Taglib '" + uri + "'" ); //$NON-NLS-1$ //$NON-NLS-2$
// check overwrite query result
if ( IOverwriteQuery.NO.equalsIgnoreCase( ret ) )
{
continue;
}
if ( IOverwriteQuery.CANCEL.equalsIgnoreCase( ret ) )
{
monitor.setCanceled( true );
return;
}
// remove old item
if ( obj instanceof TagLibRefType
&& webapp.getJspConfig( ) != null )
{
webapp.getJspConfig( ).getTagLibs( ).remove( obj );
}
else
{
webapp.getTagLibs( ).remove( obj );
}
}
String location = bean.getLocation( );
if ( webapp.getVersionID( ) == 23 )
{
// create TaglibRef object for servlet 2.3
TagLibRef taglib = WebapplicationFactory.eINSTANCE
.createTagLibRef( );
taglib.setTaglibURI( uri );
taglib.setTaglibLocation( location );
webapp.getTagLibs( ).add( taglib );
}
else
{
// for servlet 2.4
JSPConfig jspConfig = JspFactory.eINSTANCE
.createJSPConfig( );
TagLibRefType ref = JspFactory.eINSTANCE
.createTagLibRefType( );
ref.setTaglibURI( uri );
ref.setTaglibLocation( location );
jspConfig.getTagLibs( ).add( ref );
webapp.setJspConfig( jspConfig );
}
}
webEdit.saveIfNecessary( monitor );
}
finally
{
webEdit.dispose( );
}
}
/**
* get servlet mapping from webapp by uri
*
* @param webapp
* @param name
* @return
*/
public static Object getTagLibByUri( WebApp webapp, String uri )
{
if ( webapp == null || uri == null )
return null;
List list = null;
JSPConfig config = webapp.getJspConfig( );
if ( config != null )
{
// for servlet 2.4
list = config.getTagLibs( );
}
else
{
list = webapp.getTagLibs( );
}
Iterator it = list.iterator( );
while ( it.hasNext( ) )
{
Object obj = it.next( );
// for servlet 2.3
if ( obj instanceof TagLibRef )
{
TagLibRef ref = (TagLibRef) obj;
if ( uri.equals( ref.getTaglibURI( ) ) )
return ref;
}
// for servlet 2.4
if ( obj instanceof TagLibRefType )
{
TagLibRefType ref = (TagLibRefType) obj;
if ( uri.equals( ref.getTaglibURI( ) ) )
return ref;
}
}
return null;
}
/**
* returns context-param value
*
* @param map
* @param name
* @return
*/
public static String getContextParamValue( Map map, String name )
{
if ( map == null || name == null )
return null;
ContextParamBean bean = (ContextParamBean) map.get( name );
if ( bean == null )
return null;
return bean.getValue( );
}
/**
* set param value
*
* @param map
* @param name
* @param value
*/
public static void setContextParamValue( Map map, String name, String value )
{
if ( name == null )
return;
if ( map == null )
map = new HashMap( );
// get context-param bean
ContextParamBean bean = (ContextParamBean) map.get( name );
if ( bean == null )
{
bean = new ContextParamBean( name, value );
map.put( name, bean );
return;
}
bean.setValue( value );
}
/**
* Initialize web settings from existed web.xml file
*
* @param map
* @param project
*/
public static void initializeWebapp( Map map, IProject project )
{
if ( project == null )
return;
if ( map == null )
map = new HashMap( );
// create WebArtifact
WebArtifactEdit webEdit = WebArtifactEdit
.getWebArtifactEditForWrite( project );
if ( webEdit == null )
return;
try
{
// get webapp
WebApp webapp = (WebApp) webEdit.getDeploymentDescriptorRoot( );
// context-param
initializeContextParam( map, webapp );
}
finally
{
webEdit.dispose( );
}
}
/**
* Initialize context-param
*
* @param map
* @param webapp
*/
protected static void initializeContextParam( Map map, WebApp webapp )
{
if ( webapp == null )
return;
// get context-param map
Map son = (Map) map.get( EXT_CONTEXT_PARAM );
if ( son == null )
return;
// get param list
List list = null;
if ( webapp.getVersionID( ) == 23 )
{
// for servlet 2.3
list = webapp.getContexts( );
}
else
{
// for servlet 2.4
list = webapp.getContextParams( );
}
// initialzie context-param from web.xml
Iterator it = son.keySet( ).iterator( );
while ( it.hasNext( ) )
{
String name = (String) it.next( );
Object obj = getContextParamByName( list, name );
if ( obj == null )
continue;
String value = null;
String description = null;
if ( obj instanceof ContextParam )
{
// for servlet 2.3
ContextParam param = (ContextParam) obj;
name = param.getParamName( );
value = param.getParamValue( );
description = param.getDescription( );
}
else if ( obj instanceof ParamValue )
{
// for servlet 2.4
ParamValue param = (ParamValue) obj;
name = param.getName( );
value = param.getValue( );
description = param.getDescription( );
if ( description == null )
{
List descList = param.getDescriptions( );
if ( descList != null && descList.size( ) > 0 )
{
Description descObj = (Description) descList.get( 0 );
if ( descObj != null )
description = descObj.getValue( );
}
}
}
// push into map
if ( value != null )
{
ContextParamBean bean = new ContextParamBean( name, value );
bean.setDescription( description );
son.put( name, bean );
}
}
}
/**
* Returns the filter-mapping string
*
* @param name
* @param servletName
* @param uri
* @return
*/
public static String getFilterMappingString( String name,
String servletName, String uri )
{
return ( name != null ? name : "" ) //$NON-NLS-1$
+ ( servletName != null ? servletName : "" ) //$NON-NLS-1$
+ ( uri != null ? uri : "" ); //$NON-NLS-1$
}
}
|
package org.elasticsearch.xpack.watcher.transport.action.activate;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.xpack.core.watcher.client.WatcherClient;
import org.elasticsearch.xpack.core.watcher.execution.ExecutionState;
import org.elasticsearch.xpack.core.watcher.support.xcontent.XContentSource;
import org.elasticsearch.xpack.core.watcher.transport.actions.activate.ActivateWatchResponse;
import org.elasticsearch.xpack.core.watcher.transport.actions.get.GetWatchResponse;
import org.elasticsearch.xpack.core.watcher.transport.actions.stats.WatcherStatsResponse;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.indexAction;
import static org.elasticsearch.xpack.watcher.client.WatchSourceBuilders.watchBuilder;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.simpleInput;
import static org.elasticsearch.xpack.watcher.trigger.TriggerBuilders.schedule;
import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.cron;
import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.interval;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
@TestLogging("org.elasticsearch.xpack.watcher:DEBUG,org.elasticsearch.xpack.core.watcher:DEBUG," +
"org.elasticsearch.xpack.watcher.WatcherIndexingListener:TRACE")
public class ActivateWatchTests extends AbstractWatcherIntegrationTestCase {
@Override
protected boolean timeWarped() {
return false;
}
public void testDeactivateAndActivate() throws Exception {
PutWatchResponse putWatchResponse = watcherClient().preparePutWatch()
.setId("_id")
.setSource(watchBuilder()
.trigger(schedule(interval("1s")))
.input(simpleInput("foo", "bar"))
.addAction("_a1", indexAction("actions"))
.defaultThrottlePeriod(new TimeValue(0, TimeUnit.SECONDS)))
.get();
assertThat(putWatchResponse.isCreated(), is(true));
GetWatchResponse getWatchResponse = watcherClient().prepareGetWatch("_id").get();
assertThat(getWatchResponse, notNullValue());
assertThat(getWatchResponse.getStatus().state().isActive(), is(true));
logger.info("Waiting for watch to be executed at least once");
assertWatchWithMinimumActionsCount("_id", ExecutionState.EXECUTED, 1);
// we now know the watch is executing... lets deactivate it
ActivateWatchResponse activateWatchResponse = watcherClient().prepareActivateWatch("_id", false).get();
assertThat(activateWatchResponse, notNullValue());
assertThat(activateWatchResponse.getStatus().state().isActive(), is(false));
getWatchResponse = watcherClient().prepareGetWatch("_id").get();
assertThat(getWatchResponse, notNullValue());
assertThat(getWatchResponse.getStatus().state().isActive(), is(false));
// wait until no watch is executing
assertBusy(() -> {
WatcherStatsResponse statsResponse = watcherClient().prepareWatcherStats().setIncludeCurrentWatches(true).get();
int sum = statsResponse.getNodes().stream().map(WatcherStatsResponse.Node::getSnapshots).mapToInt(List::size).sum();
assertThat(sum, is(0));
});
logger.info("Ensured no more watches are being executed");
refresh();
long count1 = docCount(".watcher-history*", matchAllQuery());
refresh();
//ensure no new watch history
awaitBusy(() -> count1 != docCount(".watcher-history*", matchAllQuery()), 5, TimeUnit.SECONDS);
// lets activate it again
logger.info("Activating watch again");
activateWatchResponse = watcherClient().prepareActivateWatch("_id", true).get();
assertThat(activateWatchResponse, notNullValue());
assertThat(activateWatchResponse.getStatus().state().isActive(), is(true));
getWatchResponse = watcherClient().prepareGetWatch("_id").get();
assertThat(getWatchResponse, notNullValue());
assertThat(getWatchResponse.getStatus().state().isActive(), is(true));
refresh();
assertBusy(() -> {
long count2 = docCount(".watcher-history*", matchAllQuery());
assertThat(count2, greaterThan(count1));
});
}
public void testLoadWatchWithoutAState() throws Exception {
WatcherClient watcherClient = watcherClient();
PutWatchResponse putWatchResponse = watcherClient.preparePutWatch()
.setId("_id")
.setSource(watchBuilder()
.trigger(schedule(cron("0 0 0 1 1 ? 2050"))) // some time in 2050
.input(simpleInput("foo", "bar"))
.addAction("_a1", indexAction("actions"))
.defaultThrottlePeriod(new TimeValue(0, TimeUnit.SECONDS)))
.get();
assertThat(putWatchResponse.isCreated(), is(true));
GetWatchResponse getWatchResponse = watcherClient.prepareGetWatch("_id").get();
assertThat(getWatchResponse, notNullValue());
assertThat(getWatchResponse.getStatus().state().isActive(), is(true));
GetResponse getResponse = client().prepareGet().setIndex(".watches").setId("_id").get();
XContentSource source = new XContentSource(getResponse.getSourceAsBytesRef(), XContentType.JSON);
Set<String> filters = Sets.newHashSet(
"trigger.**",
"input.**",
"condition.**",
"throttle_period.**",
"transform.**",
"actions.**",
"metadata.**",
"status.version",
"status.last_checked",
"status.last_met_condition",
"status.actions.**");
XContentBuilder builder = new XContentBuilder(XContentType.JSON.xContent(), new BytesStreamOutput(), filters);
source.toXContent(builder, ToXContent.EMPTY_PARAMS);
// now that we filtered out the watch status state, lets put it back in
IndexResponse indexResponse = client().prepareIndex().setIndex(".watches").setId("_id")
.setSource(BytesReference.bytes(builder), XContentType.JSON)
.get();
assertThat(indexResponse.getId(), is("_id"));
// now, let's restart
stopWatcher();
startWatcher();
getWatchResponse = watcherClient.prepareGetWatch("_id").get();
assertThat(getWatchResponse, notNullValue());
assertThat(getWatchResponse.getStatus().state(), notNullValue());
assertThat(getWatchResponse.getStatus().state().isActive(), is(true));
}
}
|
package eu.bcvsolutions.idm.icf.virtual.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import eu.bcvsolutions.idm.icf.api.IcfConnectorConfiguration;
import eu.bcvsolutions.idm.icf.api.IcfConnectorInfo;
import eu.bcvsolutions.idm.icf.api.IcfConnectorKey;
import eu.bcvsolutions.idm.icf.api.IcfSchema;
import eu.bcvsolutions.idm.icf.exception.IcfException;
import eu.bcvsolutions.idm.icf.impl.IcfConfigurationPropertiesImpl;
import eu.bcvsolutions.idm.icf.impl.IcfConfigurationPropertyImpl;
import eu.bcvsolutions.idm.icf.impl.IcfConnectorConfigurationImpl;
import eu.bcvsolutions.idm.icf.impl.IcfConnectorInfoImpl;
import eu.bcvsolutions.idm.icf.impl.IcfConnectorKeyImpl;
import eu.bcvsolutions.idm.icf.service.api.IcfConfigurationFacade;
import eu.bcvsolutions.idm.icf.service.api.IcfConfigurationService;
/**
* Connector framework for virtual account implementation
* @author svandav
*
*/
@Service
public class VirtualIcfConfigurationService implements IcfConfigurationService {
@Autowired
public VirtualIcfConfigurationService(IcfConfigurationFacade icfConfigurationAggregator) {
if (icfConfigurationAggregator.getIcfConfigs() == null) {
throw new IcfException("Map of ICF implementations is not defined!");
}
if (icfConfigurationAggregator.getIcfConfigs().containsKey(this.getIcfType())) {
throw new IcfException("ICF implementation duplicity for key: " + this.getIcfType());
}
// Disable for now
// icfConfigurationAggregator.getIcfConfigs().put(this.getIcfType(), this);
}
/**
* Return key defined ICF implementation
*
* @return
*/
@Override
public String getIcfType() {
return "virtual";
}
/**
* Return available local connectors for this ICF implementation
*
* @return
*/
@Override
public List<IcfConnectorInfo> getAvailableLocalConnectors() {
List<IcfConnectorInfo> localConnectorInfos = new ArrayList<>();
IcfConnectorInfoImpl dto = new IcfConnectorInfoImpl("Testovací konektor", "categori test", new IcfConnectorKeyImpl(getIcfType(), "eu.bcvsolutions.connectors.test", "0.0.1", "Test connector"));
localConnectorInfos.add(dto);
return localConnectorInfos;
}
/**
* Return find connector default configuration by connector key
*
* @param key
* @return
*/
@Override
public IcfConnectorConfiguration getConnectorConfiguration(IcfConnectorKey key) {
Assert.notNull(key);
IcfConnectorConfigurationImpl dto = new IcfConnectorConfigurationImpl();
IcfConfigurationPropertiesImpl propertiesDto = new IcfConfigurationPropertiesImpl();
IcfConfigurationPropertyImpl propertyDto = new IcfConfigurationPropertyImpl();
propertyDto.setConfidential(true);
propertyDto.setDisplayName("First property");
propertyDto.setGroup("test");
propertyDto.setName("first_property");
propertyDto.setRequired(true);
propertyDto.setType(String.class.getName());
propertyDto.setValue("test value");
propertiesDto.getProperties().add(propertyDto);
dto.setConfigurationProperties(propertiesDto);
return dto;
}
@Override
public IcfSchema getSchema(IcfConnectorKey key, IcfConnectorConfiguration connectorConfiguration) {
return null;
}
}
|
package org.eclipse.birt.report.designer.internal.ui.views.actions;
import java.util.logging.Level;
import org.eclipse.birt.report.designer.internal.ui.command.CommandUtils;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.designer.util.DNDUtil;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.core.IDesignElement;
import org.eclipse.gef.ui.actions.Clipboard;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
/**
* Paste action
*/
public class PasteAction extends AbstractViewAction
{
private static final String DEFAULT_TEXT = Messages.getString( "PasteAction.text" ); //$NON-NLS-1$
/**
* Create a new paste action with given selection and default text
*
* @param selectedObject
* the selected object,which cannot be null
*
*/
public PasteAction( Object selectedObject )
{
this( selectedObject, DEFAULT_TEXT );
}
/**
* Create a new paste action with given selection and text
*
* @param selectedObject
* the selected object,which cannot be null
* @param text
* the text of the action
*/
public PasteAction( Object selectedObject, String text )
{
super( selectedObject, text );
ISharedImages shareImages = PlatformUI.getWorkbench( )
.getSharedImages( );
setImageDescriptor( shareImages.getImageDescriptor( ISharedImages.IMG_TOOL_PASTE ) );
setDisabledImageDescriptor( shareImages.getImageDescriptor( ISharedImages.IMG_TOOL_PASTE_DISABLED ) );
setAccelerator( SWT.CTRL | 'V' );
}
/**
* Runs this action. Copies the content. Each action implementation must
* define the steps needed to carry out this action. The default
* implementation of this method in <code>Action</code> does nothing.
*/
public void run( )
{
try
{
CommandUtils.executeCommand( "org.eclipse.birt.report.designer.ui.command.pasteAction", null ); //$NON-NLS-1$
}
catch ( Exception e )
{
// TODO Auto-generated catch block
logger.log( Level.SEVERE, e.getMessage( ), e );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#isEnabled()
*/
public boolean isEnabled( )
{
if ( getSelection( ) instanceof DesignElementHandle )
{
DesignElementHandle elementHandle = (DesignElementHandle) getSelection( );
if ( getClipBoardContents( ) instanceof IDesignElement )
{
IDesignElement content = (IDesignElement) getClipBoardContents( );
try
{
if ( !elementHandle.canPaste( DEUtil.getDefaultContentName( elementHandle ),
content ) )
return false;
}
catch ( SemanticException e )
{
}
}
else if ( getClipBoardContents( ) instanceof Object[] )
{
Object[] array = (Object[]) getClipBoardContents( );
for ( int i = 0; i < array.length; i++ )
{
if ( array[i] instanceof IDesignElement )
{
IDesignElement content = (IDesignElement) array[i];
try
{
if ( !elementHandle.canPaste( DEUtil.getDefaultContentName( elementHandle ),
content ) )
return false;
}
catch ( SemanticException e )
{
}
}
}
}
}
return DNDUtil.handleValidateTargetCanContain( getSelection( ),
getClipBoardContents( ) )
&& DNDUtil.handleValidateTargetCanContainMore( getSelection( ),
DNDUtil.getObjectLength( getClipBoardContents( ) ) );
}
protected Object getClipBoardContents( )
{
return Clipboard.getDefault( ).getContents( );
}
public Object getSelection( )
{
Object selection = super.getSelection( );
if ( selection instanceof StructuredSelection )
{
selection = ( (StructuredSelection) selection ).getFirstElement( );
}
return selection;
}
}
|
package at.ecrit.e4.tools.extension.core;
import org.eclipse.core.databinding.observable.value.WritableValue;
import org.eclipse.core.resources.IProject;
import org.eclipse.e4.tools.emf.ui.common.AbstractElementEditorContribution;
import org.eclipse.e4.ui.model.application.MApplicationElement;
import org.eclipse.emf.databinding.EMFDataBindingContext;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import at.ecrit.e4.tools.extension.core.control.MapEntryEditorComposite;
public class EcritDocumentationElementEditorContribution extends
AbstractElementEditorContribution {
public EcritDocumentationElementEditorContribution() {
// TODO Auto-generated constructor stub
}
@Override
public Class<?> getContributableTo() {
return MApplicationElement.class;
}
@Override
public String getTabLabel() {
return "Documentation";
}
@Override
public void createContributedEditorTab(Composite parent,
EMFDataBindingContext context, final WritableValue master,
final EditingDomain editingDomain, IProject project) {
Composite descEdComp = new MapEntryEditorComposite(parent, SWT.None,
context, master, editingDomain, "description",
Constants.PERSISTENT_STATE_DESCRIPTION);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
descEdComp.setLayoutData(gd);
Composite preCondComp = new MapEntryEditorComposite(parent, SWT.None,
context, master, editingDomain, "precondition",
Constants.PERSISTENT_STATE_PRECONDITION);
preCondComp.setLayoutData(gd);
Composite postCondComp = new MapEntryEditorComposite(parent, SWT.None,
context, master, editingDomain, "postcondition",
Constants.PERSISTENT_STATE_POSTCONDITION);
postCondComp.setLayoutData(gd);
}
}
|
package org.ovirt.engine.core.vdsbroker.vdsbroker;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.network.cluster.ManagementNetworkUtil;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.businessentities.ArchitectureType;
import org.ovirt.engine.core.common.businessentities.AutoNumaBalanceStatus;
import org.ovirt.engine.core.common.businessentities.CpuStatistics;
import org.ovirt.engine.core.common.businessentities.Entities;
import org.ovirt.engine.core.common.businessentities.GraphicsInfo;
import org.ovirt.engine.core.common.businessentities.GraphicsType;
import org.ovirt.engine.core.common.businessentities.HostDevice;
import org.ovirt.engine.core.common.businessentities.KdumpStatus;
import org.ovirt.engine.core.common.businessentities.NumaNodeStatistics;
import org.ovirt.engine.core.common.businessentities.SessionState;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.V2VJobInfo;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSDomainsData;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VdsNumaNode;
import org.ovirt.engine.core.common.businessentities.VdsTransparentHugePagesState;
import org.ovirt.engine.core.common.businessentities.VmBalloonInfo;
import org.ovirt.engine.core.common.businessentities.VmBlockJob;
import org.ovirt.engine.core.common.businessentities.VmBlockJobType;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.businessentities.VmExitReason;
import org.ovirt.engine.core.common.businessentities.VmExitStatus;
import org.ovirt.engine.core.common.businessentities.VmGuestAgentInterface;
import org.ovirt.engine.core.common.businessentities.VmJob;
import org.ovirt.engine.core.common.businessentities.VmJobState;
import org.ovirt.engine.core.common.businessentities.VmJobType;
import org.ovirt.engine.core.common.businessentities.VmNumaNode;
import org.ovirt.engine.core.common.businessentities.VmPauseStatus;
import org.ovirt.engine.core.common.businessentities.VmRngDevice;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmStatistics;
import org.ovirt.engine.core.common.businessentities.network.Bond;
import org.ovirt.engine.core.common.businessentities.network.BondMode;
import org.ovirt.engine.core.common.businessentities.network.HostNetworkQos;
import org.ovirt.engine.core.common.businessentities.network.InterfaceStatus;
import org.ovirt.engine.core.common.businessentities.network.NetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.NetworkStatistics;
import org.ovirt.engine.core.common.businessentities.network.Nic;
import org.ovirt.engine.core.common.businessentities.network.VdsInterfaceType;
import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.VdsNetworkStatistics;
import org.ovirt.engine.core.common.businessentities.network.Vlan;
import org.ovirt.engine.core.common.businessentities.network.VmInterfaceType;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.DiskImageDynamic;
import org.ovirt.engine.core.common.businessentities.storage.DiskInterface;
import org.ovirt.engine.core.common.businessentities.storage.LUNs;
import org.ovirt.engine.core.common.businessentities.storage.StorageType;
import org.ovirt.engine.core.common.businessentities.storage.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.storage.VolumeType;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.utils.EnumUtils;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.utils.SizeConverter;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.RpmVersion;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.di.Injector;
import org.ovirt.engine.core.utils.NetworkUtils;
import org.ovirt.engine.core.utils.NumaUtils;
import org.ovirt.engine.core.utils.SerializationFactory;
import org.ovirt.engine.core.utils.network.predicate.InterfaceByAddressPredicate;
import org.ovirt.engine.core.vdsbroker.NetworkStatisticsBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class encapsulate the knowledge of how to create objects from the VDS RPC protocol response.
* This class has methods that receive XmlRpcStruct and construct the following Classes: VmDynamic VdsDynamic VdsStatic.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class VdsBrokerObjectsBuilder {
private static final Logger log = LoggerFactory.getLogger(VdsBrokerObjectsBuilder.class);
private final static int VNC_START_PORT = 5900;
private final static double NANO_SECONDS = 1000000000;
private static final AuditLogDirector auditLogDirector = new AuditLogDirector();
private static final Comparator<VdsNumaNode> numaNodeComparator = Comparator.comparing(VdsNumaNode::getIndex);
public static VM buildVmsDataFromExternalProvider(Map<String, Object> xmlRpcStruct) {
VmStatic vmStatic = buildVmStaticDataFromExternalProvider(xmlRpcStruct);
if (vmStatic == null) {
return null;
}
VmDynamic vmDynamic = buildVMDynamicDataFromList(xmlRpcStruct);
VM vm = new VM(vmStatic, vmDynamic, new VmStatistics());
for (DiskImage image : vm.getImages()) {
vm.getDiskMap().put(Guid.newGuid(), image);
}
try {
vm.setClusterArch(parseArchitecture(xmlRpcStruct));
} catch (IllegalArgumentException ex) {
log.error("Illegal architecture type: %s, replacing with x86_64", xmlRpcStruct.get(VdsProperties.vm_arch));
vm.setClusterArch(ArchitectureType.x86_64);
}
return vm;
}
/**
* Convert the devices map and make a list of {@linkplain DiskImage}
* Mainly used to import the Hosted Engine Vm disks.
*
* @param vmStruct
* @return A List of Disk Images {@linkplain DiskImage}
*/
public static ArrayList<DiskImage> buildDiskImagesFromDevices(Map<String, Object> vmStruct) {
ArrayList<DiskImage> diskImages = new ArrayList<>();
Object[] devices = (Object[]) vmStruct.get("devices");
if (devices != null) {
for (Object device : devices) {
Map <String, Object> deviceMap = (Map<String, Object>) device;
if (VdsProperties.Disk.equals(deviceMap.get(VdsProperties.Device))) {
DiskImage image = new DiskImage();
image.setDiskAlias((String) deviceMap.get(VdsProperties.Alias));
image.setSize(Long.parseLong((String) deviceMap.get("apparentsize")));
image.setActualSize(Long.parseLong((String) deviceMap.get("truesize")));
image.setId(Guid.newGuid());
image.setvolumeFormat(VolumeFormat.valueOf(((String) deviceMap.get(VdsProperties.Format)).toUpperCase()));
image.setShareable(false);
image.setId(Guid.createGuidFromString((String) deviceMap.get(VdsProperties.DeviceId)));
image.setImageId(Guid.createGuidFromString((String) deviceMap.get(VdsProperties.VolumeId)));
// TODO not sure how to extract that info
image.setVolumeType(VolumeType.Preallocated);
switch ((String) deviceMap.get("iface")) {
case "virtio":
image.setDiskInterface(DiskInterface.VirtIO);
break;
case "iscsi":
image.setDiskInterface(DiskInterface.VirtIO_SCSI);
break;
case "ide":
image.setDiskInterface(DiskInterface.IDE);
break;
}
diskImages.add(image);
}
}
}
return diskImages;
}
/**
* Convert the devices map and make a list of {@linkplain VmNetworkInterface}
* Mainly used to import the Hosted Engine Vm disks.
*
* @param vmStruct
* @return A List of VM network interfaces {@linkplain VmNetworkInterface}
*/
public static ArrayList<VmNetworkInterface> buildVmNetworkInterfacesFromDevices(Map<String, Object> vmStruct) {
ArrayList<VmNetworkInterface> nics = new ArrayList<>();
Object[] devices = (Object[]) vmStruct.get("devices");
if (devices != null) {
for (Object device : devices) {
Map<String, Object> deviceMap = (Map<String, Object>) device;
if (VdsProperties.VM_INTERFACE_DEVICE_TYPE.equals(deviceMap.get(VdsProperties.Type))) {
VmNetworkInterface nic = new VmNetworkInterface();
nic.setMacAddress((String) deviceMap.get(VdsProperties.MAC_ADDR));
nic.setName((String) deviceMap.get(VdsProperties.Name));
// FIXME we can't deduce the network profile by the network name. its many to many.
nic.setNetworkName((String) deviceMap.get(VdsProperties.NETWORK));
nic.setType(VmInterfaceType.valueOf((String) deviceMap.get(VdsProperties.NIC_TYPE)).getValue());
if (deviceMap.containsKey(VdsProperties.Model)) {
String model = (String) deviceMap.get(VdsProperties.Model);
for (VmInterfaceType type : VmInterfaceType.values()) {
if (model.equals(type.getInternalName())) {
nic.setType(type.getValue());
break;
}
}
}
nics.add(nic);
}
}
}
return nics;
}
private static VmStatic buildVmStaticDataFromExternalProvider(Map<String, Object> xmlRpcStruct) {
if (!xmlRpcStruct.containsKey(VdsProperties.vm_guid) || !xmlRpcStruct.containsKey(VdsProperties.vm_name)
|| !xmlRpcStruct.containsKey(VdsProperties.mem_size_mb)
|| !xmlRpcStruct.containsKey(VdsProperties.num_of_cpus)) {
return null;
}
VmStatic vmStatic = new VmStatic();
vmStatic.setId(Guid.createGuidFromString((String) xmlRpcStruct.get(VdsProperties.vm_guid)));
vmStatic.setName((String) xmlRpcStruct.get(VdsProperties.vm_name));
vmStatic.setMemSizeMb(parseIntVdsProperty(xmlRpcStruct.get(VdsProperties.mem_size_mb)));
vmStatic.setNumOfSockets(parseIntVdsProperty(xmlRpcStruct.get(VdsProperties.num_of_cpus)));
vmStatic.setCustomCpuName((String) xmlRpcStruct.get(VdsProperties.cpu_model));
vmStatic.setCustomEmulatedMachine((String) xmlRpcStruct.get(VdsProperties.emulatedMachine));
if (xmlRpcStruct.containsKey(VdsProperties.vm_disks)) {
for (Object disk : (Object[]) xmlRpcStruct.get(VdsProperties.vm_disks)) {
Map<String, Object> diskMap = (Map<String, Object>) disk;
if (VdsProperties.Disk.equals(diskMap.get(VdsProperties.type))) {
DiskImage image = buildDiskImageFromExternalProvider(diskMap);
vmStatic.getImages().add(image);
}
}
}
if (xmlRpcStruct.containsKey(VdsProperties.NETWORKS)) {
int idx = 0;
for (Object networkMap : (Object[]) xmlRpcStruct.get(VdsProperties.NETWORKS)) {
VmNetworkInterface nic = buildNetworkInterfaceFromExternalProvider((Map<String, Object>) networkMap);
nic.setName(String.format("nic%d", ++idx));
nic.setVmName(vmStatic.getName());
nic.setVmId(vmStatic.getId());
vmStatic.getInterfaces().add(nic);
}
}
return vmStatic;
}
private static DiskImage buildDiskImageFromExternalProvider(Map<String, Object> map) {
DiskImage image = new DiskImage();
image.setDiskAlias((String) map.get(VdsProperties.Alias));
image.setSize(Long.parseLong((String) map.get(VdsProperties.DISK_VIRTUAL_SIZE)));
image.setActualSizeInBytes(Long.parseLong((String) map.get(VdsProperties.DISK_ALLOCATION)));
image.setId(Guid.newGuid());
return image;
}
private static VmNetworkInterface buildNetworkInterfaceFromExternalProvider(Map<String, Object> map) {
VmNetworkInterface nic = new VmNetworkInterface();
nic.setMacAddress((String) map.get(VdsProperties.MAC_ADDR));
nic.setRemoteNetworkName((String) map.get(VdsProperties.BRIDGE));
nic.setType(VmInterfaceType.pv.getValue());
if (map.containsKey(VdsProperties.Model)) {
String model = (String) map.get(VdsProperties.Model);
for (VmInterfaceType type : VmInterfaceType.values()) {
if (model.equals(type.getInternalName())) {
nic.setType(type.getValue());
break;
}
}
}
return nic;
}
public static VmDynamic buildVMDynamicDataFromList(Map<String, Object> xmlRpcStruct) {
VmDynamic vmdynamic = new VmDynamic();
if (xmlRpcStruct.containsKey(VdsProperties.vm_guid)) {
vmdynamic.setId(new Guid((String) xmlRpcStruct.get(VdsProperties.vm_guid)));
}
if (xmlRpcStruct.containsKey(VdsProperties.status)) {
vmdynamic.setStatus(convertToVmStatus((String) xmlRpcStruct.get(VdsProperties.status)));
}
return vmdynamic;
}
public static Double getVdsmCallTimestamp(Map<String, Object> xmlRpcStruct) {
if (xmlRpcStruct.containsKey(VdsProperties.statusTime)) {
return assignDoubleValue(xmlRpcStruct, VdsProperties.statusTime);
}
return -1d;
}
public static VmDynamic buildVMDynamicData(Map<String, Object> xmlRpcStruct, VDS host) {
VmDynamic vmdynamic = new VmDynamic();
updateVMDynamicData(vmdynamic, xmlRpcStruct, host);
return vmdynamic;
}
public static StoragePool buildStoragePool(Map<String, Object> xmlRpcStruct) {
StoragePool sPool = new StoragePool();
if (xmlRpcStruct.containsKey("type")) {
sPool.setIsLocal(StorageType.valueOf(xmlRpcStruct.get("type").toString()).isLocal());
}
sPool.setName(assignStringValue(xmlRpcStruct, "name"));
Integer masterVersion = assignIntValue(xmlRpcStruct, "master_ver");
if (masterVersion != null) {
sPool.setMasterDomainVersion(masterVersion);
}
return sPool;
}
public static VmStatistics buildVMStatisticsData(Map<String, Object> xmlRpcStruct) {
VmStatistics vmStatistics = new VmStatistics();
updateVMStatisticsData(vmStatistics, xmlRpcStruct);
return vmStatistics;
}
public static Map<String, LUNs> buildVmLunDisksData(Map<String, Object> xmlRpcStruct) {
Map<String, Object> disks = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.vm_disks);
Map<String, LUNs> lunsMap = new HashMap<>();
if (disks != null) {
for (Object diskAsObj : disks.values()) {
Map<String, Object> disk = (Map<String, Object>) diskAsObj;
String lunGuidString = assignStringValue(disk, VdsProperties.lun_guid);
if (!StringUtils.isEmpty(lunGuidString)) {
LUNs lun = new LUNs();
lun.setLUNId(lunGuidString);
if (disk.containsKey(VdsProperties.disk_true_size)) {
long sizeInBytes = assignLongValue(disk, VdsProperties.disk_true_size);
int sizeInGB = SizeConverter.convert(
sizeInBytes, SizeConverter.SizeUnit.BYTES, SizeConverter.SizeUnit.GiB).intValue();
lun.setDeviceSize(sizeInGB);
}
lunsMap.put(lunGuidString, lun);
}
}
}
return lunsMap;
}
public static void updateVMDynamicData(VmDynamic vm, Map<String, Object> xmlRpcStruct, VDS host) {
if (xmlRpcStruct.containsKey(VdsProperties.vm_guid)) {
vm.setId(new Guid((String) xmlRpcStruct.get(VdsProperties.vm_guid)));
}
if (xmlRpcStruct.containsKey(VdsProperties.session)) {
String session = (String) xmlRpcStruct.get(VdsProperties.session);
try {
vm.setSession(SessionState.valueOf(session));
} catch (Exception e) {
log.error("Illegal vm session '{}'.", session);
}
}
if (xmlRpcStruct.containsKey(VdsProperties.kvmEnable)) {
vm.setKvmEnable(Boolean.parseBoolean((String) xmlRpcStruct.get(VdsProperties.kvmEnable)));
}
if (xmlRpcStruct.containsKey(VdsProperties.acpiEnable)) {
vm.setAcpiEnable(Boolean.parseBoolean((String) xmlRpcStruct.get(VdsProperties.acpiEnable)));
}
if (xmlRpcStruct.containsKey(VdsProperties.win2kHackEnable)) {
vm.setWin2kHackEnable(Boolean.parseBoolean((String) xmlRpcStruct.get(VdsProperties.win2kHackEnable)));
}
if (xmlRpcStruct.containsKey(VdsProperties.status)) {
vm.setStatus(convertToVmStatus((String) xmlRpcStruct.get(VdsProperties.status)));
}
boolean hasGraphicsInfo = updateGraphicsInfo(vm, xmlRpcStruct);
if (!hasGraphicsInfo) {
updateGraphicsInfoFromConf(vm, xmlRpcStruct);
}
adjustDisplayIp(vm.getGraphicsInfos(), host);
if (xmlRpcStruct.containsKey((VdsProperties.utc_diff))) {
String utc_diff = xmlRpcStruct.get(VdsProperties.utc_diff).toString();
if (utc_diff.startsWith("+")) {
utc_diff = utc_diff.substring(1);
}
try {
vm.setUtcDiff(Integer.parseInt(utc_diff));
} catch (NumberFormatException e) {
log.error("Illegal vm offset (utc_diff) '{}'.", utc_diff);
}
}
if (xmlRpcStruct.containsKey(VdsProperties.hash)) {
String hash = (String) xmlRpcStruct.get(VdsProperties.hash);
try {
vm.setHash(hash);
} catch (Exception e) {
log.error("Illegal vm hash '{}'.", hash);
}
}
/**
* vm disks
*/
if (xmlRpcStruct.containsKey(VdsProperties.vm_disks)) {
initDisks(xmlRpcStruct, vm);
}
if (xmlRpcStruct.containsKey(VdsProperties.vm_host)) {
vm.setVmHost(assignStringValue(xmlRpcStruct, VdsProperties.vm_host));
}
if (xmlRpcStruct.containsKey(VdsProperties.guest_cur_user_name)) {
vm.setGuestCurrentUserName(assignStringValue(xmlRpcStruct, VdsProperties.guest_cur_user_name));
}
initAppsList(xmlRpcStruct, vm);
if (xmlRpcStruct.containsKey(VdsProperties.guest_os)) {
vm.setGuestOs(assignStringValue(xmlRpcStruct, VdsProperties.guest_os));
}
if (xmlRpcStruct.containsKey(VdsProperties.VM_FQDN)) {
vm.setVmFQDN(assignStringValue(xmlRpcStruct, VdsProperties.VM_FQDN));
String fqdn = vm.getVmFQDN().trim();
if ("localhost".equalsIgnoreCase(fqdn) || "localhost.localdomain".equalsIgnoreCase(fqdn)) {
vm.setVmFQDN(null);
}
else {
vm.setVmFQDN(fqdn);
}
}
if (xmlRpcStruct.containsKey(VdsProperties.VM_IP)) {
vm.setVmIp(assignStringValue(xmlRpcStruct, VdsProperties.VM_IP));
}
if (vm.getVmIp() != null) {
if (vm.getVmIp().startsWith("127.0.")) {
vm.setVmIp(null);
} else {
vm.setVmIp(vm.getVmIp().trim());
}
}
if (xmlRpcStruct.containsKey(VdsProperties.vm_guest_mem_stats)) {
Map<String, Object> sub = (Map<String, Object>)xmlRpcStruct.get(VdsProperties.vm_guest_mem_stats);
if (sub.containsKey(VdsProperties.vm_guest_mem_buffered)) {
vm.setGuestMemoryBuffered(Long.parseLong(sub.get(VdsProperties.vm_guest_mem_buffered).toString()));
}
if (sub.containsKey(VdsProperties.vm_guest_mem_cached)) {
vm.setGuestMemoryCached(Long.parseLong(sub.get(VdsProperties.vm_guest_mem_cached).toString()));
}
if (sub.containsKey(VdsProperties.vm_guest_mem_free)) {
vm.setGuestMemoryFree(Long.parseLong(sub.get(VdsProperties.vm_guest_mem_free).toString()));
}
}
if (xmlRpcStruct.containsKey(VdsProperties.exit_code)) {
String exitCodeStr = xmlRpcStruct.get(VdsProperties.exit_code).toString();
vm.setExitStatus(VmExitStatus.forValue(Integer.parseInt(exitCodeStr)));
}
if (xmlRpcStruct.containsKey(VdsProperties.exit_message)) {
String exitMsg = (String) xmlRpcStruct.get(VdsProperties.exit_message);
vm.setExitMessage(exitMsg);
}
if (xmlRpcStruct.containsKey(VdsProperties.exit_reason)) {
String exitReasonStr = xmlRpcStruct.get(VdsProperties.exit_reason).toString();
vm.setExitReason(VmExitReason.forValue(Integer.parseInt(exitReasonStr)));
}
// if monitorResponse returns negative it means its erroneous
if (xmlRpcStruct.containsKey(VdsProperties.monitorResponse)) {
int response = Integer.parseInt(xmlRpcStruct.get(VdsProperties.monitorResponse).toString());
if (response < 0) {
vm.setStatus(VMStatus.NotResponding);
}
}
if (xmlRpcStruct.containsKey(VdsProperties.clientIp)) {
vm.setClientIp(xmlRpcStruct.get(VdsProperties.clientIp).toString());
}
if (xmlRpcStruct.containsKey(VdsProperties.pauseCode)) {
String pauseCodeStr = (String) xmlRpcStruct.get(VdsProperties.pauseCode);
try {
vm.setPauseStatus(VmPauseStatus.valueOf(pauseCodeStr));
} catch (IllegalArgumentException ex) {
log.error("Error in parsing vm pause status. Setting value to NONE");
}
}
if (xmlRpcStruct.containsKey(VdsProperties.watchdogEvent)) {
Map<String, Object> watchdogStruct = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.watchdogEvent);
double time = Double.parseDouble(watchdogStruct.get(VdsProperties.time).toString());
String action =
watchdogStruct.containsKey(VdsProperties.action) ? watchdogStruct.get(VdsProperties.action)
.toString() : null;
vm.setLastWatchdogEvent((long) time);
vm.setLastWatchdogAction(action);
}
if (xmlRpcStruct.containsKey(VdsProperties.CDRom)) {
Path fileName = Paths.get((String) xmlRpcStruct.get(VdsProperties.CDRom)).getFileName();
if (fileName != null) {
String isoName = fileName.toString();
vm.setCurrentCd(isoName);
}
}
if (xmlRpcStruct.containsKey(VdsProperties.GUEST_CPU_COUNT)) {
vm.setGuestCpuCount(assignIntValue(xmlRpcStruct, VdsProperties.GUEST_CPU_COUNT));
}
// Guest OS Info
if (xmlRpcStruct.containsKey(VdsProperties.GUEST_OS_INFO)) {
updateGuestOsInfo(vm, xmlRpcStruct);
}
// Guest Timezone
if (xmlRpcStruct.containsKey(VdsProperties.GUEST_TIMEZONE)) {
Map<String, Object> guestTimeZoneStruct =
(Map<String, Object>) xmlRpcStruct.get(VdsProperties.GUEST_TIMEZONE);
vm.setGuestOsTimezoneName(assignStringValue(guestTimeZoneStruct, VdsProperties.GUEST_TIMEZONE_ZONE));
vm.setGuestOsTimezoneOffset(assignIntValue(guestTimeZoneStruct, VdsProperties.GUEST_TIMEZONE_OFFSET));
}
}
/**
* Adjusts displayIp for graphicsInfos:
* - if displayIp is overriden on cluster level then overriden address is used,
* or
* - if current displayIp starts with "0" then host's hostname is used.
*
* @param graphicsInfos - graphicsInfo to adjust
*/
private static void adjustDisplayIp(Map<GraphicsType, GraphicsInfo> graphicsInfos, VDS host) {
if (graphicsInfos == null) {
return;
}
for (GraphicsInfo graphicsInfo : graphicsInfos.values()) {
if (graphicsInfo == null) {
continue;
}
if (host.getConsoleAddress() != null) {
graphicsInfo.setIp(host.getConsoleAddress());
} else if (graphicsInfo.getIp() != null && graphicsInfo.getIp().startsWith("0")) {
graphicsInfo.setIp(host.getHostName());
}
}
}
private static void updateGuestOsInfo(VmDynamic vm, Map<String, Object> xmlRpcStruct) {
Map<String, Object> guestOsInfoStruct = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.GUEST_OS_INFO);
if(guestOsInfoStruct.containsKey(VdsProperties.GUEST_OS_INFO_ARCH)) {
String arch = assignStringValue(guestOsInfoStruct, VdsProperties.GUEST_OS_INFO_ARCH);
try {
vm.setGuestOsArch(arch);
} catch(IllegalArgumentException e) {
log.warn("Invalid or unknown guest architecture type '{}' received from guest agent", arch);
}
}
vm.setGuestOsCodename(assignStringValue(guestOsInfoStruct, VdsProperties.GUEST_OS_INFO_CODENAME));
vm.setGuestOsDistribution(assignStringValue(guestOsInfoStruct, VdsProperties.GUEST_OS_INFO_DISTRIBUTION));
vm.setGuestOsKernelVersion(assignStringValue(guestOsInfoStruct, VdsProperties.GUEST_OS_INFO_KERNEL));
if(guestOsInfoStruct.containsKey(VdsProperties.GUEST_OS_INFO_TYPE)) {
String osType = assignStringValue(guestOsInfoStruct, VdsProperties.GUEST_OS_INFO_TYPE);
try {
vm.setGuestOsType(osType);
} catch(IllegalArgumentException e) {
log.warn("Invalid or unknown guest os type '{}' received from guest agent", osType);
}
} else {
log.warn("Guest OS type not reported by guest agent but expected.");
}
vm.setGuestOsVersion(assignStringValue(guestOsInfoStruct, VdsProperties.GUEST_OS_INFO_VERSION));
}
/**
* Updates graphics runtime information according displayInfo VDSM structure if it exists.
*
* @param vm - VmDynamic to update
* @param xmlRpcStruct - data from VDSM
* @return true if displayInfo exists, false otherwise
*/
private static boolean updateGraphicsInfo(VmDynamic vm, Map<String, Object> xmlRpcStruct) {
Object displayInfo = xmlRpcStruct.get(VdsProperties.displayInfo);
if (displayInfo == null) {
return false;
}
for (Object info : (Object[]) displayInfo) {
Map<String, String> infoMap = (Map<String, String>) info;
GraphicsType graphicsType = GraphicsType.fromString(infoMap.get(VdsProperties.type));
GraphicsInfo graphicsInfo = new GraphicsInfo();
graphicsInfo.setIp(infoMap.get(VdsProperties.ipAddress))
.setPort(parseIntegerOrNull(infoMap.get(VdsProperties.port)))
.setTlsPort(parseIntegerOrNull(infoMap.get(VdsProperties.tlsPort)));
if (graphicsInfo.getPort() != null || graphicsInfo.getTlsPort() != null) {
vm.getGraphicsInfos().put(graphicsType, graphicsInfo);
}
}
return true;
}
/**
* Updates graphics runtime information according to vm.conf vdsm structure. It's used with legacy VDSMs that have
* no notion about graphics device.
* @param vm - VmDynamic to update
* @param xmlRpcStruct - data from VDSM
*/
private static void updateGraphicsInfoFromConf(VmDynamic vm, Map<String, Object> xmlRpcStruct) {
GraphicsType vmGraphicsType = parseGraphicsType(xmlRpcStruct);
if (vmGraphicsType == null) {
log.debug("graphics data missing in XML.");
return;
}
GraphicsInfo graphicsInfo = new GraphicsInfo();
if (xmlRpcStruct.containsKey(VdsProperties.display_port)) {
try {
graphicsInfo.setPort(Integer.parseInt(xmlRpcStruct.get(VdsProperties.display_port).toString()));
} catch (NumberFormatException e) {
log.error("vm display_port value illegal : {0}", xmlRpcStruct.get(VdsProperties.display_port));
}
} else if (xmlRpcStruct.containsKey(VdsProperties.display)) {
try {
graphicsInfo
.setPort(VNC_START_PORT + Integer.parseInt(xmlRpcStruct.get(VdsProperties.display).toString()));
} catch (NumberFormatException e) {
log.error("vm display value illegal : {0}", xmlRpcStruct.get(VdsProperties.display));
}
}
if (xmlRpcStruct.containsKey(VdsProperties.display_secure_port)) {
try {
graphicsInfo
.setTlsPort(Integer.parseInt(xmlRpcStruct.get(VdsProperties.display_secure_port).toString()));
} catch (NumberFormatException e) {
log.error("vm display_secure_port value illegal : {0}",
xmlRpcStruct.get(VdsProperties.display_secure_port));
}
}
if (xmlRpcStruct.containsKey((VdsProperties.displayIp))) {
graphicsInfo.setIp((String) xmlRpcStruct.get(VdsProperties.displayIp));
}
vm.getGraphicsInfos().put(vmGraphicsType, graphicsInfo);
}
/**
* Retrieves graphics type from xml.
* @param xmlRpcStruct
* @return
* - graphics type derived from xml on success
* - null on error
*/
private static GraphicsType parseGraphicsType(Map<String, Object> xmlRpcStruct) {
GraphicsType result = null;
try {
String displayTypeStr = xmlRpcStruct.get(VdsProperties.displayType).toString();
switch (displayTypeStr) {
case VdsProperties.VNC:
result = GraphicsType.VNC;
break;
case VdsProperties.QXL:
result = GraphicsType.SPICE;
break;
}
} catch (Exception e) {
}
return result;
}
private static Integer parseIntegerOrNull(String s) {
try {
return Integer.parseInt(s);
} catch (Exception e) {
return null;
}
}
/**
* Some properties were changed recently from String to Integer
* This method checks what type is the property, and returns int
* @param vdsProperty
* @return
*/
public static int parseIntVdsProperty(Object vdsProperty) {
if (vdsProperty instanceof Integer) {
return (Integer) vdsProperty;
} else {
return Integer.parseInt((String) vdsProperty);
}
}
protected static ArchitectureType parseArchitecture(Map<String, Object> xmlRpcStruct) {
try {
return ArchitectureType.valueOf((String) xmlRpcStruct.get(VdsProperties.vm_arch));
} catch (NullPointerException e) {
return null;
}
}
public static void updateVMStatisticsData(VmStatistics vm, Map<String, Object> xmlRpcStruct) {
if (xmlRpcStruct.containsKey(VdsProperties.vm_guid)) {
vm.setId(new Guid((String) xmlRpcStruct.get(VdsProperties.vm_guid)));
}
vm.setElapsedTime(assignDoubleValue(xmlRpcStruct, VdsProperties.elapsed_time));
if (xmlRpcStruct.containsKey(VdsProperties.VM_NETWORK)) {
Map networkStruct = (Map) xmlRpcStruct.get(VdsProperties.VM_NETWORK);
vm.setInterfaceStatistics(new ArrayList<>());
for (Object tempNic : networkStruct.values()) {
Map nic = (Map) tempNic;
VmNetworkInterface stats = new VmNetworkInterface();
vm.getInterfaceStatistics().add(stats);
if (nic.containsKey(VdsProperties.VM_INTERFACE_NAME)) {
stats.setName((String) ((nic.get(VdsProperties.VM_INTERFACE_NAME) instanceof String) ? nic
.get(VdsProperties.VM_INTERFACE_NAME) : null));
}
extractInterfaceStatistics(nic, stats);
stats.setMacAddress((String) ((nic.get(VdsProperties.MAC_ADDR) instanceof String) ? nic
.get(VdsProperties.MAC_ADDR) : null));
}
}
if (xmlRpcStruct.containsKey(VdsProperties.VM_DISKS_USAGE)) {
initDisksUsage(xmlRpcStruct, vm);
}
vm.setCpuSys(assignDoubleValue(xmlRpcStruct, VdsProperties.cpu_sys));
vm.setCpuUser(assignDoubleValue(xmlRpcStruct, VdsProperties.cpu_user));
vm.setUsageMemPercent(assignIntValue(xmlRpcStruct, VdsProperties.vm_usage_mem_percent));
vm.setVmBalloonInfo(getBalloonInfo(xmlRpcStruct));
Integer migrationProgress = assignIntValue(xmlRpcStruct, VdsProperties.vm_migration_progress_percent);
vm.setMigrationProgressPercent(migrationProgress != null ? migrationProgress : 0);
vm.setVmJobs(getVmJobs(vm.getId(), xmlRpcStruct));
if (xmlRpcStruct.containsKey(VdsProperties.VM_NUMA_NODES_RUNTIME_INFO)) {
updateVmNumaNodesRuntimeInfo(vm, xmlRpcStruct);
}
}
private static VmBalloonInfo getBalloonInfo(Map<String, Object> xmlRpcStruct) {
Map<String, Object> balloonInfo = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.vm_balloonInfo);
VmBalloonInfo vmBalloonInfo = new VmBalloonInfo();
if (balloonInfo != null && balloonInfo.size() > 0) {
vmBalloonInfo.setCurrentMemory(assignLongValue(balloonInfo, VdsProperties.vm_balloon_cur));
vmBalloonInfo.setBalloonMaxMemory(assignLongValue(balloonInfo, VdsProperties.vm_balloon_max));
vmBalloonInfo.setBalloonTargetMemory(assignLongValue(balloonInfo, VdsProperties.vm_balloon_target));
vmBalloonInfo.setBalloonMinMemory(assignLongValue(balloonInfo, VdsProperties.vm_balloon_min));
if (balloonInfo.size() >= 4) { // only if all 4 properties are found the balloon is considered enabled (available from 3.3)
vmBalloonInfo.setBalloonDeviceEnabled(true);
}
} else {
vmBalloonInfo.setBalloonDeviceEnabled(false);
}
return vmBalloonInfo;
}
private static List<VmJob> getVmJobs(Guid vmId, Map<String, Object> xmlRpcStruct) {
if (!xmlRpcStruct.containsKey(VdsProperties.vmJobs)) {
return null;
}
List<VmJob> vmJobs = new ArrayList<>();
for (Object jobMap : ((Map<String, Object>) xmlRpcStruct.get(VdsProperties.vmJobs)).values()) {
VmJob job = buildVmJobData(vmId, (Map<String, Object>) jobMap);
vmJobs.add(job);
}
return vmJobs;
}
private static VmJob buildVmJobData(Guid vmId, Map<String, Object> xmlRpcStruct) {
VmJob ret;
VmJobType jobType = VmJobType.getByName(assignStringValue(xmlRpcStruct, VdsProperties.vmJobType));
if (jobType == null) {
jobType = VmJobType.UNKNOWN;
}
switch (jobType) {
case BLOCK:
VmBlockJob blockJob = new VmBlockJob();
blockJob.setBlockJobType(VmBlockJobType.getByName(assignStringValue(xmlRpcStruct, VdsProperties.vmBlockJobType)));
blockJob.setCursorCur(assignLongValue(xmlRpcStruct, VdsProperties.vmJobCursorCur));
blockJob.setCursorEnd(assignLongValue(xmlRpcStruct, VdsProperties.vmJobCursorEnd));
blockJob.setBandwidth(assignLongValue(xmlRpcStruct, VdsProperties.vmJobBandwidth));
blockJob.setImageGroupId(new Guid(assignStringValue(xmlRpcStruct, VdsProperties.vmJobImageUUID)));
ret = blockJob;
break;
default:
ret = new VmJob();
break;
}
ret.setVmId(vmId);
ret.setId(new Guid(assignStringValue(xmlRpcStruct, VdsProperties.vmJobId)));
ret.setJobState(VmJobState.NORMAL);
ret.setJobType(jobType);
return ret;
}
public static void updateVDSDynamicData(VDS vds, Map<String, Object> xmlRpcStruct) {
vds.setSupportedClusterLevels(assignStringValueFromArray(xmlRpcStruct, VdsProperties.supported_cluster_levels));
updateNetworkData(vds, xmlRpcStruct);
updateNumaNodesData(vds, xmlRpcStruct);
vds.setCpuThreads(assignIntValue(xmlRpcStruct, VdsProperties.cpuThreads));
vds.setCpuCores(assignIntValue(xmlRpcStruct, VdsProperties.cpu_cores));
vds.setCpuSockets(assignIntValue(xmlRpcStruct, VdsProperties.cpu_sockets));
vds.setCpuModel(assignStringValue(xmlRpcStruct, VdsProperties.cpu_model));
vds.setOnlineCpus(assignStringValue(xmlRpcStruct, VdsProperties.online_cpus));
vds.setCpuSpeedMh(assignDoubleValue(xmlRpcStruct, VdsProperties.cpu_speed_mh));
vds.setPhysicalMemMb(assignIntValue(xmlRpcStruct, VdsProperties.physical_mem_mb));
vds.setKvmEnabled(assignBoolValue(xmlRpcStruct, VdsProperties.kvm_enabled));
vds.setReservedMem(assignIntValue(xmlRpcStruct, VdsProperties.reservedMem));
Integer guestOverhead = assignIntValue(xmlRpcStruct, VdsProperties.guestOverhead);
vds.setGuestOverhead(guestOverhead != null ? guestOverhead : 0);
vds.setCpuFlags(assignStringValue(xmlRpcStruct, VdsProperties.cpu_flags));
updatePackagesVersions(vds, xmlRpcStruct);
vds.setSupportedEngines(assignStringValueFromArray(xmlRpcStruct, VdsProperties.supported_engines));
vds.setIScsiInitiatorName(assignStringValue(xmlRpcStruct, VdsProperties.iSCSIInitiatorName));
vds.setSupportedEmulatedMachines(assignStringValueFromArray(xmlRpcStruct, VdsProperties.emulatedMachines));
setRngSupportedSourcesToVds(vds, xmlRpcStruct);
String hooksStr = ""; // default value if hooks is not in the xml rpc struct
if (xmlRpcStruct.containsKey(VdsProperties.hooks)) {
hooksStr = xmlRpcStruct.get(VdsProperties.hooks).toString();
}
vds.setHooksStr(hooksStr);
// parse out the HBAs available in this host
Map<String, List<Map<String, String>>> hbas = new HashMap<>();
for (Map.Entry<String, Object[]> el: ((Map<String, Object[]>)xmlRpcStruct.get(VdsProperties.HBAInventory)).entrySet()) {
List<Map<String, String>> devicesList = new ArrayList<>();
for (Object device: el.getValue()) {
devicesList.add((Map<String, String>)device);
}
hbas.put(el.getKey(), devicesList);
}
vds.setHBAs(hbas);
vds.setBootTime(assignLongValue(xmlRpcStruct, VdsProperties.bootTime));
vds.setKdumpStatus(KdumpStatus.valueOfNumber(assignIntValue(xmlRpcStruct, VdsProperties.KDUMP_STATUS)));
vds.setHostDevicePassthroughEnabled(assignBoolValue(xmlRpcStruct, VdsProperties.HOST_DEVICE_PASSTHROUGH));
Map<String, Object> selinux = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.selinux);
if (selinux != null) {
vds.setSELinuxEnforceMode(assignIntValue(selinux, VdsProperties.selinux_mode));
} else {
vds.setSELinuxEnforceMode(null);
}
if (xmlRpcStruct.containsKey(VdsProperties.liveSnapshotSupport)) {
vds.setLiveSnapshotSupport(assignBoolValue(xmlRpcStruct, VdsProperties.liveSnapshotSupport));
} else {
vds.setLiveSnapshotSupport(true); // for backward compatibility's sake
}
if (xmlRpcStruct.containsKey(VdsProperties.liveMergeSupport)) {
vds.setLiveMergeSupport(assignBoolValue(xmlRpcStruct, VdsProperties.liveMergeSupport));
} else {
vds.setLiveMergeSupport(false);
}
updateAdditionalFeatures(vds, xmlRpcStruct);
}
private static void updateAdditionalFeatures(VDS vds, Map<String, Object> xmlRpcStruct) {
String[] addtionalFeaturesSupportedByHost =
assignStringArrayValue(xmlRpcStruct, VdsProperties.ADDITIONAL_FEATURES);
if (addtionalFeaturesSupportedByHost != null) {
for (String feature : addtionalFeaturesSupportedByHost) {
vds.getAdditionalFeatures().add(feature);
}
}
}
private static void setRngSupportedSourcesToVds(VDS vds, Map<String, Object> xmlRpcStruct) {
vds.getSupportedRngSources().clear();
String rngSourcesFromStruct = assignStringValueFromArray(xmlRpcStruct, VdsProperties.rngSources);
if (rngSourcesFromStruct != null) {
vds.getSupportedRngSources().addAll(VmRngDevice.csvToSourcesSet(rngSourcesFromStruct.toUpperCase()));
}
}
public static void checkTimeDrift(VDS vds, Map<String, Object> xmlRpcStruct) {
Boolean isHostTimeDriftEnabled = Config.getValue(ConfigValues.EnableHostTimeDrift);
if (isHostTimeDriftEnabled) {
Integer maxTimeDriftAllowed = Config.getValue(ConfigValues.HostTimeDriftInSec);
Date hostDate = assignDatetimeValue(xmlRpcStruct, VdsProperties.hostDatetime);
if (hostDate != null) {
Long timeDrift =
TimeUnit.MILLISECONDS.toSeconds(Math.abs(hostDate.getTime() - System.currentTimeMillis()));
if (timeDrift > maxTimeDriftAllowed) {
AuditLogableBase logable = new AuditLogableBase(vds.getId());
logable.addCustomValue("Actual", timeDrift.toString());
logable.addCustomValue("Max", maxTimeDriftAllowed.toString());
auditLogDirector.log(logable, AuditLogType.VDS_TIME_DRIFT_ALERT);
}
} else {
log.error("Time Drift validation: failed to get Host or Engine time.");
}
}
}
private static void initDisksUsage(Map<String, Object> vmStruct, VmStatistics vm) {
Object[] vmDisksUsage = (Object[]) vmStruct.get(VdsProperties.VM_DISKS_USAGE);
if (vmDisksUsage != null) {
ArrayList<Object> disksUsageList = new ArrayList<>(Arrays.asList(vmDisksUsage));
vm.setDisksUsage(SerializationFactory.getSerializer().serializeUnformattedJson(disksUsageList));
}
}
private static void updatePackagesVersions(VDS vds, Map<String, Object> xmlRpcStruct) {
vds.setVersionName(assignStringValue(xmlRpcStruct, VdsProperties.version_name));
vds.setSoftwareVersion(assignStringValue(xmlRpcStruct, VdsProperties.software_version));
vds.setBuildName(assignStringValue(xmlRpcStruct, VdsProperties.build_name));
if (xmlRpcStruct.containsKey(VdsProperties.host_os)) {
vds.setHostOs(getPackageVersionFormated((Map<String, Object>) xmlRpcStruct.get(VdsProperties.host_os),
true));
}
if (xmlRpcStruct.containsKey(VdsProperties.packages)) {
// packages is an array of xmlRpcStruct (that each is a name, ver,
// release.. of a package)
for (Object hostPackageMap : (Object[]) xmlRpcStruct.get(VdsProperties.packages)) {
Map<String, Object> hostPackage = (Map<String, Object>) hostPackageMap;
String packageName = assignStringValue(hostPackage, VdsProperties.package_name);
if (VdsProperties.kvmPackageName.equals(packageName)) {
vds.setKvmVersion(getPackageVersionFormated(hostPackage, false));
} else if (VdsProperties.spicePackageName.equals(packageName)) {
vds.setSpiceVersion(getPackageVersionFormated(hostPackage, false));
} else if (VdsProperties.kernelPackageName.equals(packageName)) {
vds.setKernelVersion(getPackageVersionFormated(hostPackage, false));
}
}
} else if (xmlRpcStruct.containsKey(VdsProperties.packages2)) {
Map<String, Object> packages = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.packages2);
if (packages.containsKey(VdsProperties.vdsmPackageName)) {
Map<String, Object> vdsm = (Map<String, Object>) packages.get(VdsProperties.vdsmPackageName);
vds.setVersion(getPackageRpmVersion("vdsm", vdsm));
}
if (packages.containsKey(VdsProperties.qemuKvmPackageName)) {
Map<String, Object> kvm = (Map<String, Object>) packages.get(VdsProperties.qemuKvmPackageName);
vds.setKvmVersion(getPackageVersionFormated2(kvm));
}
if (packages.containsKey(VdsProperties.libvirtPackageName)) {
Map<String, Object> libvirt = (Map<String, Object>) packages.get(VdsProperties.libvirtPackageName);
vds.setLibvirtVersion(getPackageRpmVersion("libvirt", libvirt));
}
if (packages.containsKey(VdsProperties.librbdPackageName)) {
Map<String, Object> librbd1 = (Map<String, Object>) packages.get(VdsProperties.librbdPackageName);
vds.setLibrbdVersion(getPackageRpmVersion(VdsProperties.librbdPackageName, librbd1));
}
if (packages.containsKey(VdsProperties.glusterfsCliPackageName)) {
Map<String, Object> glusterfsCli = (Map<String, Object>) packages.get(VdsProperties.glusterfsCliPackageName);
vds.setGlusterfsCliVersion(getPackageRpmVersion(VdsProperties.glusterfsCliPackageName, glusterfsCli));
}
if (packages.containsKey(VdsProperties.spiceServerPackageName)) {
Map<String, Object> spice = (Map<String, Object>) packages.get(VdsProperties.spiceServerPackageName);
vds.setSpiceVersion(getPackageVersionFormated2(spice));
}
if (packages.containsKey(VdsProperties.kernelPackageName)) {
Map<String, Object> kernel = (Map<String, Object>) packages.get(VdsProperties.kernelPackageName);
vds.setKernelVersion(getPackageVersionFormated2(kernel));
}
if (packages.containsKey(VdsProperties.GLUSTER_PACKAGE_NAME)) {
Map<String, Object> gluster = (Map<String, Object>) packages.get(VdsProperties.GLUSTER_PACKAGE_NAME);
vds.setGlusterVersion(getPackageRpmVersion("glusterfs", gluster));
}
}
}
// Version 2 of GetPackageVersionFormated2:
// from 2.3 we get dictionary and not a flat list.
// from now the packages names (of spice, kernel, qemu and libvirt) are the same as far as VDSM and ENGINE.
// (VDSM use to report packages name of rpm so in RHEL6 when it change it broke our interface)
private static String getPackageVersionFormated2(Map<String, Object> hostPackage) {
String packageVersion = (hostPackage.get(VdsProperties.package_version) != null) ? (String) hostPackage
.get(VdsProperties.package_version) : null;
String packageRelease = (hostPackage.get(VdsProperties.package_release) != null) ? (String) hostPackage
.get(VdsProperties.package_release) : null;
StringBuilder sb = new StringBuilder();
if (!StringUtils.isEmpty(packageVersion)) {
sb.append(packageVersion);
}
if (!StringUtils.isEmpty(packageRelease)) {
if (sb.length() > 0) {
sb.append(String.format(" - %1$s", packageRelease));
} else {
sb.append(packageRelease);
}
}
return sb.toString();
}
private static RpmVersion getPackageRpmVersion(String packageName, Map<String, Object> hostPackage) {
String packageVersion = (hostPackage.get(VdsProperties.package_version) != null) ? (String) hostPackage
.get(VdsProperties.package_version) : null;
String packageRelease = (hostPackage.get(VdsProperties.package_release) != null) ? (String) hostPackage
.get(VdsProperties.package_release) : null;
StringBuilder sb = new StringBuilder();
if (!StringUtils.isEmpty(packageName)) {
sb.append(packageName);
}
boolean hasPackageVersion = StringUtils.isEmpty(packageVersion);
boolean hasPackageRelease = StringUtils.isEmpty(packageRelease);
if (!hasPackageVersion || !hasPackageRelease) {
sb.append("-");
}
if (!hasPackageVersion) {
sb.append(packageVersion);
}
if (!hasPackageRelease) {
if (sb.length() > 0) {
sb.append(String.format("-%1$s", packageRelease));
} else {
sb.append(packageRelease);
}
}
return new RpmVersion(sb.toString());
}
public static void updateHardwareSystemInformation(Map<String, Object> hwInfo, VDS vds){
vds.setHardwareManufacturer(assignStringValue(hwInfo, VdsProperties.hwManufacturer));
vds.setHardwareProductName(assignStringValue(hwInfo, VdsProperties.hwProductName));
vds.setHardwareVersion(assignStringValue(hwInfo, VdsProperties.hwVersion));
vds.setHardwareSerialNumber(assignStringValue(hwInfo, VdsProperties.hwSerialNumber));
vds.setHardwareUUID(assignStringValue(hwInfo, VdsProperties.hwUUID));
vds.setHardwareFamily(assignStringValue(hwInfo, VdsProperties.hwFamily));
}
private static String getPackageVersionFormated(Map<String, Object> hostPackage, boolean getName) {
String packageName = assignStringValue(hostPackage, VdsProperties.package_name);
String packageVersion = assignStringValue(hostPackage, VdsProperties.package_version);
String packageRelease = assignStringValue(hostPackage, VdsProperties.package_release);
StringBuilder sb = new StringBuilder();
if (!StringUtils.isEmpty(packageName) && getName) {
sb.append(packageName);
}
if (!StringUtils.isEmpty(packageVersion)) {
if (sb.length() > 0) {
sb.append(String.format(" - %1$s", packageVersion));
} else {
sb.append(packageVersion);
}
}
if (!StringUtils.isEmpty(packageRelease)) {
if (sb.length() > 0) {
sb.append(String.format(" - %1$s", packageRelease));
} else {
sb.append(packageRelease);
}
}
return sb.toString();
}
public static void updateVDSStatisticsData(VDS vds, Map<String, Object> xmlRpcStruct) {
vds.setUsageMemPercent(assignIntValue(xmlRpcStruct, VdsProperties.mem_usage));
Map<String, Object> interfaces = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.NETWORK);
if (interfaces != null) {
int networkUsage = 0;
Map<String, VdsNetworkInterface> nicsByName = Entities.entitiesByName(vds.getInterfaces());
NetworkStatisticsBuilder statsBuilder = new NetworkStatisticsBuilder(vds.getVdsGroupCompatibilityVersion());
for (Entry<String, Object> entry : interfaces.entrySet()) {
if (nicsByName.containsKey(entry.getKey())) {
VdsNetworkInterface existingIface = nicsByName.get(entry.getKey());
existingIface.setVdsId(vds.getId());
Map<String, Object> dict = (Map<String, Object>) entry.getValue();
VdsNetworkInterface reportedIface = new VdsNetworkInterface();
extractInterfaceStatistics(dict, reportedIface);
statsBuilder.updateExistingInterfaceStatistics(existingIface, reportedIface);
existingIface.getStatistics()
.setStatus(assignInterfaceStatusValue(dict, VdsProperties.iface_status));
if (!NetworkUtils.isVlan(existingIface) && !existingIface.isPartOfBond()) {
Double ifaceUsage = computeInterfaceUsage(existingIface, statsBuilder.isTotalStatsReported());
if (ifaceUsage != null) {
networkUsage = (int) Math.max(networkUsage, ifaceUsage);
}
}
}
}
vds.setUsageNetworkPercent(networkUsage);
}
vds.setCpuSys(assignDoubleValue(xmlRpcStruct, VdsProperties.cpu_sys));
vds.setCpuUser(assignDoubleValue(xmlRpcStruct, VdsProperties.cpu_user));
if (vds.getCpuSys() != null && vds.getCpuUser() != null) {
vds.setUsageCpuPercent((int) (vds.getCpuSys() + vds.getCpuUser()));
}
// CPU load reported by VDSM is in uptime-style format, i.e. normalized
// to unity, so that say an 8% load is reported as 0.08
Double d = assignDoubleValue(xmlRpcStruct, VdsProperties.cpu_load);
d = (d != null) ? d : 0;
vds.setCpuLoad(d.doubleValue() * 100.0);
vds.setCpuIdle(assignDoubleValue(xmlRpcStruct, VdsProperties.cpu_idle));
vds.setMemAvailable(assignLongValue(xmlRpcStruct, VdsProperties.mem_available));
vds.setMemFree(assignLongValue(xmlRpcStruct, VdsProperties.memFree));
vds.setMemShared(assignLongValue(xmlRpcStruct, VdsProperties.mem_shared));
vds.setSwapFree(assignLongValue(xmlRpcStruct, VdsProperties.swap_free));
vds.setSwapTotal(assignLongValue(xmlRpcStruct, VdsProperties.swap_total));
vds.setKsmCpuPercent(assignIntValue(xmlRpcStruct, VdsProperties.ksm_cpu_percent));
vds.setKsmPages(assignLongValue(xmlRpcStruct, VdsProperties.ksm_pages));
vds.setKsmState(assignBoolValue(xmlRpcStruct, VdsProperties.ksm_state));
// dynamic data got from GetVdsStats
if (xmlRpcStruct.containsKey(VdsProperties.transparent_huge_pages_state)) {
vds.setTransparentHugePagesState(EnumUtils.valueOf(VdsTransparentHugePagesState.class, xmlRpcStruct
.get(VdsProperties.transparent_huge_pages_state).toString(), true));
}
if (xmlRpcStruct.containsKey(VdsProperties.anonymous_transparent_huge_pages)) {
vds.setAnonymousHugePages(assignIntValue(xmlRpcStruct, VdsProperties.anonymous_transparent_huge_pages));
}
vds.setNetConfigDirty(assignBoolValue(xmlRpcStruct, VdsProperties.netConfigDirty));
vds.setImagesLastCheck(assignDoubleValue(xmlRpcStruct, VdsProperties.images_last_check));
vds.setImagesLastDelay(assignDoubleValue(xmlRpcStruct, VdsProperties.images_last_delay));
Integer vm_count = assignIntValue(xmlRpcStruct, VdsProperties.vm_count);
vds.setVmCount(vm_count == null ? 0 : vm_count);
vds.setVmActive(assignIntValue(xmlRpcStruct, VdsProperties.vm_active));
vds.setVmMigrating(assignIntValue(xmlRpcStruct, VdsProperties.vm_migrating));
Integer inOutMigrations;
inOutMigrations = assignIntValue(xmlRpcStruct, VdsProperties.INCOMING_VM_MIGRATIONS);
if (inOutMigrations != null) {
vds.setIncomingMigrations(inOutMigrations);
} else {
// TODO remove in 4.x when all hosts will send in/out migrations separately
vds.setIncomingMigrations(-1);
}
inOutMigrations = assignIntValue(xmlRpcStruct, VdsProperties.OUTGOING_VM_MIGRATIONS);
if (inOutMigrations != null) {
vds.setOutgoingMigrations(inOutMigrations);
} else {
// TODO remove in 4.x when all hosts will send in/out migrations separately
vds.setOutgoingMigrations(-1);
}
updateVDSDomainData(vds, xmlRpcStruct);
updateLocalDisksUsage(vds, xmlRpcStruct);
// hosted engine
Integer haScore = null;
Boolean haIsConfigured = null;
Boolean haIsActive = null;
Boolean haGlobalMaint = null;
Boolean haLocalMaint = null;
if (xmlRpcStruct.containsKey(VdsProperties.ha_stats)) {
Map<String, Object> haStats = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.ha_stats);
if (haStats != null) {
haScore = assignIntValue(haStats, VdsProperties.ha_stats_score);
haIsConfigured = assignBoolValue(haStats, VdsProperties.ha_stats_is_configured);
haIsActive = assignBoolValue(haStats, VdsProperties.ha_stats_is_active);
haGlobalMaint = assignBoolValue(haStats, VdsProperties.ha_stats_global_maintenance);
haLocalMaint = assignBoolValue(haStats, VdsProperties.ha_stats_local_maintenance);
}
} else {
haScore = assignIntValue(xmlRpcStruct, VdsProperties.ha_score);
// prior to 3.4, haScore was returned if ha was installed; assume active if > 0
if (haScore != null) {
haIsConfigured = true;
haIsActive = (haScore > 0);
}
}
vds.setHighlyAvailableScore(haScore != null ? haScore : 0);
vds.setHighlyAvailableIsConfigured(haIsConfigured != null ? haIsConfigured : false);
vds.setHighlyAvailableIsActive(haIsActive != null ? haIsActive : false);
vds.setHighlyAvailableGlobalMaintenance(haGlobalMaint != null ? haGlobalMaint : false);
vds.setHighlyAvailableLocalMaintenance(haLocalMaint != null ? haLocalMaint : false);
vds.setBootTime(assignLongValue(xmlRpcStruct, VdsProperties.bootTime));
updateNumaStatisticsData(vds, xmlRpcStruct);
updateV2VJobs(vds, xmlRpcStruct);
}
private static void extractInterfaceStatistics(Map<String, Object> dict, NetworkInterface<?> iface) {
NetworkStatistics stats = iface.getStatistics();
stats.setReceiveRate(assignDoubleValueWithNullProtection(dict, VdsProperties.rx_rate));
stats.setReceiveDropRate(assignDoubleValueWithNullProtection(dict, VdsProperties.rx_dropped));
stats.setReceivedBytes(assignLongValue(dict, VdsProperties.rx_total));
stats.setTransmitRate(assignDoubleValueWithNullProtection(dict, VdsProperties.tx_rate));
stats.setTransmitDropRate(assignDoubleValueWithNullProtection(dict, VdsProperties.tx_dropped));
stats.setTransmittedBytes(assignLongValue(dict, VdsProperties.tx_total));
stats.setSampleTime(assignDoubleValue(dict, VdsProperties.sample_time));
iface.setSpeed(assignIntValue(dict, VdsProperties.INTERFACE_SPEED));
}
private static Double computeInterfaceUsage(VdsNetworkInterface iface, boolean totalStatsReported) {
Double receiveRate = iface.getStatistics().getReceiveRate();
Double transmitRate = iface.getStatistics().getTransmitRate();
/**
* TODO: only needed if rate reported by vdsm (in which case can't be null) - remove in 4.0 and turn
* NetworkStatisticsBuilder.truncatePercentage() private
*/
if (!totalStatsReported) {
receiveRate = NetworkStatisticsBuilder.truncatePercentage(receiveRate);
transmitRate = NetworkStatisticsBuilder.truncatePercentage(transmitRate);
}
if (receiveRate == null) {
return transmitRate;
} else if (transmitRate == null) {
return receiveRate;
} else {
return Math.max(receiveRate, transmitRate);
}
}
public static void updateNumaStatisticsData(VDS vds, Map<String, Object> xmlRpcStruct) {
List<VdsNumaNode> vdsNumaNodes = new ArrayList<>();
if (vds.getNumaNodeList() != null && !vds.getNumaNodeList().isEmpty()) {
vdsNumaNodes.addAll(vds.getNumaNodeList());
}
List<CpuStatistics> cpuStatsData = new ArrayList<>();
if (xmlRpcStruct.containsKey(VdsProperties.CPU_STATS)) {
Map<String, Map<String, Object>> cpuStats = (Map<String, Map<String, Object>>)
xmlRpcStruct.get(VdsProperties.CPU_STATS);
Map<Integer, List<CpuStatistics>> numaNodeCpuStats = new HashMap<>();
for (Map.Entry<String, Map<String, Object>> item : cpuStats.entrySet()) {
CpuStatistics data = buildVdsCpuStatistics(item);
cpuStatsData.add(data);
int numaNodeIndex = assignIntValue(item.getValue(), VdsProperties.NUMA_NODE_INDEX);
if (!numaNodeCpuStats.containsKey(numaNodeIndex)) {
numaNodeCpuStats.put(numaNodeIndex, new ArrayList<>());
}
numaNodeCpuStats.get(numaNodeIndex).add(data);
}
DecimalFormat percentageFormatter = new DecimalFormat("
for (Map.Entry<Integer, List<CpuStatistics>> item : numaNodeCpuStats.entrySet()) {
VdsNumaNode nodeWithStatistics = buildVdsNumaNodeStatistics(percentageFormatter, item);
if (vdsNumaNodes.isEmpty()) {
vdsNumaNodes.add(nodeWithStatistics);
} else {
boolean foundNumaNode = false;
// append the statistics to the correct numaNode (search by its Index.)
for (VdsNumaNode currNumaNode : vdsNumaNodes) {
if (currNumaNode.getIndex() == nodeWithStatistics.getIndex()) {
currNumaNode.setNumaNodeStatistics(nodeWithStatistics.getNumaNodeStatistics());
foundNumaNode = true;
break;
}
}
// append new numaNode (contains only statistics) if not found existing
if (!foundNumaNode) {
vdsNumaNodes.add(nodeWithStatistics);
}
}
}
}
if (xmlRpcStruct.containsKey(VdsProperties.NUMA_NODE_FREE_MEM_STAT)) {
Map<String, Map<String, Object>> memStats = (Map<String, Map<String, Object>>)
xmlRpcStruct.get(VdsProperties.NUMA_NODE_FREE_MEM_STAT);
for (Map.Entry<String, Map<String, Object>> item : memStats.entrySet()) {
VdsNumaNode node = NumaUtils.getVdsNumaNodeByIndex(vdsNumaNodes, Integer.parseInt(item.getKey()));
if (node != null && node.getNumaNodeStatistics() != null) {
node.getNumaNodeStatistics().setMemFree(assignLongValue(item.getValue(),
VdsProperties.NUMA_NODE_FREE_MEM));
node.getNumaNodeStatistics().setMemUsagePercent(assignIntValue(item.getValue(),
VdsProperties.NUMA_NODE_MEM_PERCENT));
}
}
}
vds.getNumaNodeList().clear();
vds.getNumaNodeList().addAll(vdsNumaNodes);
vds.getStatisticsData().getCpuCoreStatistics().clear();
vds.getStatisticsData().getCpuCoreStatistics().addAll(cpuStatsData);
}
private static VdsNumaNode buildVdsNumaNodeStatistics(DecimalFormat percentageFormatter,
Map.Entry<Integer, List<CpuStatistics>> item) {
VdsNumaNode node = new VdsNumaNode();
NumaNodeStatistics nodeStat = new NumaNodeStatistics();
double nodeCpuUser = 0.0;
double nodeCpuSys = 0.0;
double nodeCpuIdle = 0.0;
for (CpuStatistics cpuStat : item.getValue()) {
nodeCpuUser += cpuStat.getCpuUser();
nodeCpuSys += cpuStat.getCpuSys();
nodeCpuIdle += cpuStat.getCpuIdle();
}
nodeStat.setCpuUser(Double.parseDouble(percentageFormatter.format(nodeCpuUser / item.getValue().size())));
nodeStat.setCpuSys(Double.parseDouble(percentageFormatter.format(nodeCpuSys / item.getValue().size())));
nodeStat.setCpuIdle(Double.parseDouble(percentageFormatter.format(nodeCpuIdle / item.getValue().size())));
nodeStat.setCpuUsagePercent((int) (nodeStat.getCpuSys() + nodeStat.getCpuUser()));
node.setIndex(item.getKey());
node.setNumaNodeStatistics(nodeStat);
return node;
}
private static CpuStatistics buildVdsCpuStatistics(Map.Entry<String, Map<String, Object>> item) {
CpuStatistics data = new CpuStatistics();
data.setCpuId(Integer.parseInt(item.getKey()));
data.setCpuUser(assignDoubleValue(item.getValue(), VdsProperties.NUMA_CPU_USER));
data.setCpuSys(assignDoubleValue(item.getValue(), VdsProperties.NUMA_CPU_SYS));
data.setCpuIdle(assignDoubleValue(item.getValue(), VdsProperties.NUMA_CPU_IDLE));
data.setCpuUsagePercent((int) (data.getCpuSys() + data.getCpuUser()));
return data;
}
/**
* Update {@link VDS#setLocalDisksUsage(Map)} with map of paths usage extracted from the returned returned value. The
* usage is reported in MB.
*
* @param vds
* The VDS object to update.
* @param xmlRpcStruct
* The XML/RPC to extract the usage from.
*/
protected static void updateLocalDisksUsage(VDS vds, Map<String, Object> xmlRpcStruct) {
if (xmlRpcStruct.containsKey(VdsProperties.DISK_STATS)) {
Map<String, Object> diskStatsStruct = (Map<String, Object>) xmlRpcStruct.get(VdsProperties.DISK_STATS);
Map<String, Long> diskStats = new HashMap<>();
vds.setLocalDisksUsage(diskStats);
for (Entry<String, Object> entry : diskStatsStruct.entrySet()) {
Map<String, Object> pathStatsStruct = (Map<String, Object>) entry.getValue();
diskStats.put(entry.getKey(), assignLongValue(pathStatsStruct, VdsProperties.DISK_STATS_FREE));
}
}
}
private static void updateVDSDomainData(VDS vds, Map<String, Object> xmlRpcStruct) {
if (xmlRpcStruct.containsKey(VdsProperties.domains)) {
Map<String, Object> domains = (Map<String, Object>)
xmlRpcStruct.get(VdsProperties.domains);
ArrayList<VDSDomainsData> domainsData = new ArrayList<>();
for (Map.Entry<String, ?> value : domains.entrySet()) {
try {
VDSDomainsData data = new VDSDomainsData();
data.setDomainId(new Guid(value.getKey().toString()));
Map<String, Object> internalValue = (Map<String, Object>) value.getValue();
double lastCheck = 0;
data.setCode((Integer) (internalValue).get(VdsProperties.code));
if (internalValue.containsKey(VdsProperties.lastCheck)) {
lastCheck = Double.parseDouble((String) internalValue.get(VdsProperties.lastCheck));
}
data.setLastCheck(lastCheck);
double delay = 0;
if (internalValue.containsKey(VdsProperties.delay)) {
delay = Double.parseDouble((String) internalValue.get(VdsProperties.delay));
}
data.setDelay(delay);
Boolean actual = Boolean.TRUE;
if (internalValue.containsKey(VdsProperties.actual)) {
actual = (Boolean)internalValue.get(VdsProperties.actual);
}
data.setActual(actual);
domainsData.add(data);
} catch (Exception e) {
log.error("failed building domains: {}", e.getMessage());
log.debug("Exception", e);
}
}
vds.setDomains(domainsData);
}
}
private static InterfaceStatus assignInterfaceStatusValue(Map<String, Object> input, String name) {
InterfaceStatus ifaceStatus = InterfaceStatus.NONE;
if (input.containsKey(name)) {
String stringValue = (String) ((input.get(name) instanceof String) ? input.get(name) : null);
if (!StringUtils.isEmpty(stringValue)) {
if (stringValue.toLowerCase().trim().equals("up")) {
ifaceStatus = InterfaceStatus.UP;
} else {
ifaceStatus = InterfaceStatus.DOWN;
}
}
}
return ifaceStatus;
}
private static Double assignDoubleValue(Map<String, Object> input, String name) {
Object value = input.get(name);
if (value instanceof Double) {
return (Double) value;
} else if (value instanceof String) {
return Double.parseDouble((String) value);
}
return null;
}
/**
* Do the same logic as assignDoubleValue does, but instead, in case of null we return 0.
* @param input - the Input xml
* @param name - The name of the field we want to cast it to double.
* @return - the double value.
*/
private static Double assignDoubleValueWithNullProtection(Map<String, Object> input, String name) {
Double doubleValue = assignDoubleValue(input, name);
return (doubleValue == null ? Double.valueOf(0.0) : doubleValue);
}
private static Integer assignIntValue(Map input, String name) {
if (input.containsKey(name)) {
if (input.get(name) instanceof Integer) {
return (Integer) input.get(name);
}
String stringValue = (String) input.get(name);
if (StringUtils.isNotEmpty(stringValue)) { // in case the input
// is decimal and we
// need int.
stringValue = stringValue.split("[.]", -1)[0];
}
try {
int intValue = Integer.parseInt(stringValue);
return intValue;
} catch (NumberFormatException nfe) {
log.error("Failed to parse '{}' value '{}' to integer: {}", name, stringValue, nfe.getMessage());
}
}
return null;
}
private static Long assignLongValue(Map<String, Object> input, String name) {
if (input.containsKey(name)) {
if (input.get(name) instanceof Long || input.get(name) instanceof Integer) {
return Long.parseLong(input.get(name).toString());
}
String stringValue = (String) ((input.get(name) instanceof String) ? input.get(name) : null);
if (!StringUtils.isEmpty(stringValue)) { // in case the input
// is decimal and we
// need int.
stringValue = stringValue.split("[.]", -1)[0];
}
try {
return Long.parseLong(stringValue);
} catch (NumberFormatException e) {
log.error("Failed to parse '{}' value '{}' to long: {}", name, stringValue, e.getMessage());
}
}
return null;
}
private static String assignStringValue(Map<String, Object> input, String name) {
if (input.containsKey(name)) {
return (String) ((input.get(name) instanceof String) ? input.get(name) : null);
}
return null;
}
private static String[] assignStringArrayValue(Map<String, Object> input, String name) {
String[] array = null;
if (input.containsKey(name)) {
array = (String[]) ((input.get(name) instanceof String[]) ? input.get(name) : null);
if (array == null) {
Object[] arr2 = (Object[]) ((input.get(name) instanceof Object[]) ? input.get(name) : null);
if (arr2 != null) {
array = new String[arr2.length];
for (int i = 0; i < arr2.length; i++)
array[i] = arr2[i].toString();
}
}
}
return array;
}
private static String assignStringValueFromArray(Map<String, Object> input, String name) {
String[] arr = assignStringArrayValue(input, name);
if (arr != null) {
return StringUtils.join(arr, ',');
}
return null;
}
private static Date assignDateTImeFromEpoch(Map<String, Object> input, String name) {
Date retval = null;
try {
if (input.containsKey(name)) {
Double secsSinceEpoch = (Double) input.get(name);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(secsSinceEpoch.longValue());
retval = calendar.getTime();
}
} catch (RuntimeException ex) {
log.warn("VdsBroker::assignDateTImeFromEpoch - failed to convert field '{}' to dateTime: {}",
name, ex.getMessage());
log.debug("Exception", ex);
retval = null;
}
return retval;
}
private static Date assignDatetimeValue(Map<String, Object> input, String name) {
if (input.containsKey(name)) {
if (input.get(name) instanceof Date) {
return (Date) input.get(name);
}
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
try {
String dateStr = input.get(name).toString().replaceFirst("T", " ").trim();
return formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
private static Boolean assignBoolValue(Map<String, Object> input, String name) {
if (input.containsKey(name)) {
if (input.get(name) instanceof Boolean) {
return (Boolean) input.get(name);
}
return Boolean.parseBoolean(input.get(name).toString());
}
return Boolean.FALSE;
}
private static void initDisks(Map<String, Object> vmStruct, VmDynamic vm) {
Map<String, Object> disks = (Map<String, Object>) vmStruct.get(VdsProperties.vm_disks);
ArrayList<DiskImageDynamic> disksData = new ArrayList<>();
for (Object diskAsObj : disks.values()) {
Map<String, Object> disk = (Map<String, Object>) diskAsObj;
DiskImageDynamic diskData = new DiskImageDynamic();
String imageGroupIdString = assignStringValue(disk, VdsProperties.image_group_id);
if (!StringUtils.isEmpty(imageGroupIdString)) {
Guid imageGroupIdGuid = new Guid(imageGroupIdString);
diskData.setId(imageGroupIdGuid);
diskData.setReadRate(assignIntValue(disk, VdsProperties.vm_disk_read_rate));
diskData.setWriteRate(assignIntValue(disk, VdsProperties.vm_disk_write_rate));
if (disk.containsKey(VdsProperties.disk_actual_size)) {
Long size = assignLongValue(disk, VdsProperties.disk_actual_size);
diskData.setActualSize(size != null ? size * 512 : 0);
} else if (disk.containsKey(VdsProperties.disk_true_size)) {
Long size = assignLongValue(disk, VdsProperties.disk_true_size);
diskData.setActualSize(size != null ? size : 0);
}
if (disk.containsKey(VdsProperties.vm_disk_read_latency)) {
diskData.setReadLatency(assignDoubleValueWithNullProtection(disk,
VdsProperties.vm_disk_read_latency) / NANO_SECONDS);
}
if (disk.containsKey(VdsProperties.vm_disk_write_latency)) {
diskData.setWriteLatency(assignDoubleValueWithNullProtection(disk,
VdsProperties.vm_disk_write_latency) / NANO_SECONDS);
}
if (disk.containsKey(VdsProperties.vm_disk_flush_latency)) {
diskData.setFlushLatency(assignDoubleValueWithNullProtection(disk,
VdsProperties.vm_disk_flush_latency) / NANO_SECONDS);
}
disksData.add(diskData);
}
}
vm.setDisks(disksData);
}
private static void initAppsList(Map<String, Object> vmStruct, VmDynamic vm) {
if (vmStruct.containsKey(VdsProperties.app_list)) {
Object tempAppsList = vmStruct.get(VdsProperties.app_list);
if (tempAppsList instanceof Object[]) {
Object[] apps = (Object[]) tempAppsList;
StringBuilder builder = new StringBuilder();
boolean firstTime = true;
for (Object app : apps) {
String appString = (String) ((app instanceof String) ? app : null);
if (app == null) {
log.warn("Failed to convert app: [null] to string");
continue; // Don't process this
}
if(appString == null) {
// Note: app cannot be null here anymore
log.warn("Failed to convert app: [" + app.getClass().getName() + "] is not a string");
continue; // Don't process this
}
if (!firstTime) {
builder.append(",");
} else {
firstTime = false;
}
builder.append(appString);
}
vm.setAppList(builder.toString());
} else {
vm.setAppList("");
}
}
}
public static VMStatus convertToVmStatus(String statusName) {
VMStatus status = VMStatus.Unassigned;
// TODO: The following condition should deleted as soon as we drop compatibility with 3.3 since "Running" state
// will be replaced "Up" state and "Unknown" will exist no more. The "Up" state will be processed by
// EnumUtils as other states below.
if ("Running".equals(statusName) || "Unknown".equals(statusName)) {
status = VMStatus.Up;
}
else if ("Migration Source".equals(statusName)) {
status = VMStatus.MigratingFrom;
}
else if ("Migration Destination".equals(statusName)) {
status = VMStatus.MigratingTo;
} else {
try {
statusName = statusName.replace(" ", "");
status = EnumUtils.valueOf(VMStatus.class, statusName, true);
} catch (Exception e) {
log.error("Illegal Vm status: '{}'.", statusName);
}
}
return status;
}
/**
* Updates the host network data with the network data reported by the host
*
* @param vds
* The host to update
* @param xmlRpcStruct
* A nested map contains network interfaces data
*/
public static void updateNetworkData(VDS vds, Map<String, Object> xmlRpcStruct) {
List<VdsNetworkInterface> oldInterfaces =
DbFacade.getInstance().getInterfaceDao().getAllInterfacesForVds(vds.getId());
vds.getInterfaces().clear();
addHostNetworkInterfaces(vds, xmlRpcStruct);
addHostVlanDevices(vds, xmlRpcStruct);
addHostBondDevices(vds, xmlRpcStruct);
addHostNetworksAndUpdateInterfaces(vds, xmlRpcStruct);
// set bonding options
setBondingOptions(vds, oldInterfaces);
// This information was added in 3.1, so don't use it if it's not there.
if (xmlRpcStruct.containsKey(VdsProperties.netConfigDirty)) {
vds.setNetConfigDirty(assignBoolValue(xmlRpcStruct, VdsProperties.netConfigDirty));
}
}
/***
* resolve the the host's interface that is being used to communicate with engine.
*
* @param host
* @return host's interface that being used to communicate with engine, null otherwise
*/
private static VdsNetworkInterface resolveActiveNic(VDS host, String hostIp) {
if (hostIp == null) {
return null;
}
final String managementAddress = hostIp;
VdsNetworkInterface activeIface = host.getInterfaces().stream()
.filter(new InterfaceByAddressPredicate(managementAddress)).findFirst().orElse(null);
return activeIface;
}
private static void addHostNetworksAndUpdateInterfaces(VDS host, Map<String, Object> xmlRpcStruct) {
Map<String, Map<String, Object>> bridges =
(Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORK_BRIDGES);
final String hostActiveNicName = findActiveNicName(host, bridges);
host.setActiveNic(hostActiveNicName);
// Networks collection (name point to list of nics or bonds)
Map<String, Map<String, Object>> networks =
(Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORKS);
Map<String, VdsNetworkInterface> vdsInterfaces = Entities.entitiesByName(host.getInterfaces());
boolean bridgesReported = FeatureSupported.bridgesReportByVdsm(host.getVdsGroupCompatibilityVersion());
if (networks != null) {
host.getNetworkNames().clear();
for (Entry<String, Map<String, Object>> entry : networks.entrySet()) {
Map<String, Object> networkProperties = entry.getValue();
String networkName = entry.getKey();
if (networkProperties != null) {
String interfaceName = (String) networkProperties.get(VdsProperties.INTERFACE);
Map<String, Object> bridgeProperties = (bridges == null) ? null : bridges.get(interfaceName);
boolean bridgedNetwork = isBridgedNetwork(networkProperties);
HostNetworkQos qos = new HostNetworkQosMapper(networkProperties).deserialize();
/**
* TODO: remove overly-defensive code in 4.0 - IP address, subnet, gateway and boot protocol should
* only be extracted for bridged networks and from bridge entries (not network entries)
**/
Map<String, Object> effectiveProperties =
(bridgesReported && bridgedNetwork && bridgeProperties != null) ? bridgeProperties
: networkProperties;
String addr = extractAddress(effectiveProperties);
String subnet = extractSubnet(effectiveProperties);
String gateway = (String) effectiveProperties.get(VdsProperties.GLOBAL_GATEWAY);
List<VdsNetworkInterface> interfaces =
bridgesReported ? findNetworkInterfaces(vdsInterfaces, interfaceName, bridgeProperties)
: findBridgedNetworkInterfaces(networkProperties, vdsInterfaces);
for (VdsNetworkInterface iface : interfaces) {
iface.setNetworkName(networkName);
iface.setAddress(addr);
iface.setSubnet(subnet);
iface.setBridged(bridgedNetwork);
iface.setQos(qos);
// set the management ip
if (getManagementNetworkUtil().isManagementNetwork(iface.getNetworkName(), host.getVdsGroupId())) {
iface.setType(iface.getType() | VdsInterfaceType.MANAGEMENT.getValue());
}
setGatewayIfNecessary(iface, host, gateway);
if (bridgedNetwork) {
addBootProtocol(effectiveProperties, host, iface);
}
}
host.getNetworkNames().add(networkName);
reportInvalidInterfacesForNetwork(interfaces, networkName, host);
}
}
}
}
private static String findActiveNicName(VDS vds, Map<String, Map<String, Object>> bridges) {
final String hostIp = NetworkUtils.getHostByIp(vds);
final String activeBridge = findActiveBridge(hostIp, bridges);
if (activeBridge != null) {
return activeBridge;
}
// by now, if the host is communicating with engine over a valid interface,
// the interface will have the host's engine IP
final VdsNetworkInterface activeIface = resolveActiveNic(vds, hostIp);
String hostActiveNic = (activeIface == null) ? null : activeIface.getName();
return hostActiveNic;
}
/***
*
* @param ipAddress
* @param bridges
* @return the name of the bridge obtaining ipAddress, null in case no such exist
*/
private static String findActiveBridge(String ipAddress, Map<String, Map<String, Object>> bridges) {
String activeBridge = null;
if (bridges != null) {
for (Entry<String, Map<String, Object>> entry : bridges.entrySet()) {
Map<String, Object> bridgeProperties = entry.getValue();
String bridgeName = entry.getKey();
if (bridgeProperties != null) {
String bridgeAddress = (String) bridgeProperties.get("addr");
// in case host is communicating with engine over a bridge
if (bridgeAddress != null && bridgeAddress.equals(ipAddress)) {
activeBridge = bridgeName;
}
}
}
}
return activeBridge;
}
/**
* Reports a warning to the audit log if a bridge is connected to more than one interface which is considered bad
* configuration.
*
* @param interfaces
* The network's interfaces
* @param network
* The network to report for
* @param vds
* The host in which the network is defined
*/
private static void reportInvalidInterfacesForNetwork(List<VdsNetworkInterface> interfaces, String networkName, VDS vds) {
if (interfaces.isEmpty()) {
auditLogDirector.log(createHostNetworkAuditLog(networkName, vds), AuditLogType.NETWORK_WITHOUT_INTERFACES);
} else if (interfaces.size() > 1) {
AuditLogableBase logable = createHostNetworkAuditLog(networkName, vds);
logable.addCustomValue("Interfaces", StringUtils.join(Entities.objectNames(interfaces), ","));
auditLogDirector.log(logable, AuditLogType.BRIDGED_NETWORK_OVER_MULTIPLE_INTERFACES);
}
}
protected static AuditLogableBase createHostNetworkAuditLog(String networkName, VDS vds) {
AuditLogableBase logable = new AuditLogableBase(vds.getId());
logable.addCustomValue("NetworkName", networkName);
return logable;
}
private static List<VdsNetworkInterface> findNetworkInterfaces(Map<String, VdsNetworkInterface> vdsInterfaces,
String interfaceName,
Map<String, Object> bridgeProperties) {
List<VdsNetworkInterface> interfaces = new ArrayList<>();
VdsNetworkInterface iface = vdsInterfaces.get(interfaceName);
if (iface == null) {
if (bridgeProperties != null) {
interfaces.addAll(findBridgedNetworkInterfaces(bridgeProperties, vdsInterfaces));
}
} else {
interfaces.add(iface);
}
return interfaces;
}
private static List<VdsNetworkInterface> findBridgedNetworkInterfaces(Map<String, Object> bridge,
Map<String, VdsNetworkInterface> vdsInterfaces) {
List<VdsNetworkInterface> interfaces = new ArrayList<>();
Object[] ports = (Object[]) bridge.get("ports");
if (ports != null) {
for (Object port : ports) {
if (vdsInterfaces.containsKey(port.toString())) {
interfaces.add(vdsInterfaces.get(port.toString()));
}
}
}
return interfaces;
}
private static void addHostBondDevices(VDS vds, Map<String, Object> xmlRpcStruct) {
Map<String, Map<String, Object>> bonds =
(Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORK_BONDINGS);
if (bonds != null) {
boolean cfgEntriesDeprecated = FeatureSupported.cfgEntriesDeprecated(vds.getVdsGroupCompatibilityVersion());
for (Entry<String, Map<String, Object>> entry : bonds.entrySet()) {
VdsNetworkInterface bond = new Bond();
updateCommonInterfaceData(bond, vds, entry);
bond.setBonded(true);
Map<String, Object> bondProperties = entry.getValue();
if (bondProperties != null) {
bond.setMacAddress((String) bondProperties.get("hwaddr"));
if (bondProperties.get("slaves") != null) {
addBondDeviceToHost(vds, bond, (Object[]) bondProperties.get("slaves"));
}
Object bondOptions = null;
if (cfgEntriesDeprecated) {
Map<String, Object> bondOptionsMap = new HashMap<>();
Map<String, Object> bondOpts = (Map<String, Object>) bondProperties.get("opts");
if (bondOpts != null) {
bondOptionsMap.putAll(bondOpts);
}
String bondOptionsString = "";
String mode = (String) bondOptionsMap.get("mode");
String miimon = (String) bondOptionsMap.get("miimon");
if (mode != null && miimon != null) {
bondOptionsString = String.format("mode=%s miimon=%s", mode, miimon);
bondOptionsMap.remove("mode");
bondOptionsMap.remove("miimon");
}
for (Map.Entry<String, Object> optionEntry : bondOptionsMap.entrySet()) {
bondOptionsString =
String.format("%s %s=%s",
bondOptionsString,
optionEntry.getKey(),
optionEntry.getValue());
}
bondOptions = bondOptionsString.isEmpty() ? null : bondOptionsString;
} else {
Map<String, Object> config = (Map<String, Object>) bondProperties.get("cfg");
bondOptions = (config == null) ? null : config.get("BONDING_OPTS");
}
if (bondOptions != null) {
bondOptions = normalizeBondOptions(bondOptions.toString());
bond.setBondOptions(bondOptions.toString());
}
}
}
}
}
private static String normalizeBondOptions(String bondOptions){
Matcher matcher = Pattern.compile("mode=([\\w-\\.]+)").matcher(bondOptions);
if (!matcher.find()) {
return bondOptions;
}
BondMode bondMode = BondMode.getBondMode(matcher.group(1));
if (bondMode != null) {
return matcher.replaceAll("mode=" + bondMode.getValue());
}
return bondOptions;
}
/**
* Updates the host interfaces list with vlan devices
*
* @param vds
* The host to update
* @param xmlRpcStruct
* a map contains pairs of vlan device name and vlan data
*/
private static void addHostVlanDevices(VDS vds, Map<String, Object> xmlRpcStruct) {
// vlans
Map<String, Map<String, Object>> vlans = (Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORK_VLANS);
if (vlans != null) {
for (Entry<String, Map<String, Object>> entry : vlans.entrySet()) {
VdsNetworkInterface vlan = new Vlan();
updateCommonInterfaceData(vlan, vds, entry);
String vlanDeviceName = entry.getKey();
Map<String, Object> vlanProperties = entry.getValue();
if (vlanProperties.get(VdsProperties.VLAN_ID) != null && vlanProperties.get(VdsProperties.BASE_INTERFACE) != null) {
vlan.setVlanId((Integer) vlanProperties.get(VdsProperties.VLAN_ID));
vlan.setBaseInterface((String) vlanProperties.get(VdsProperties.BASE_INTERFACE));
} else if (vlanDeviceName.contains(".")) {
String[] names = vlanDeviceName.split("[.]", -1);
String vlanId = names[1];
vlan.setVlanId(Integer.parseInt(vlanId));
vlan.setBaseInterface(names[0]);
}
vds.getInterfaces().add(vlan);
}
}
}
/**
* Updates the host network interfaces with the collected data from the host
*
* @param vds
* The host to update its interfaces
* @param xmlRpcStruct
* A nested map contains network interfaces data
*/
private static void addHostNetworkInterfaces(VDS vds, Map<String, Object> xmlRpcStruct) {
Map<String, Map<String, Object>> nics =
(Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NETWORK_NICS);
if (nics != null) {
for (Entry<String, Map<String, Object>> entry : nics.entrySet()) {
VdsNetworkInterface nic = new Nic();
updateCommonInterfaceData(nic, vds, entry);
Map<String, Object> nicProperties = entry.getValue();
if (nicProperties != null) {
if (nicProperties.get("speed") != null) {
Object speed = nicProperties.get("speed");
nic.setSpeed((Integer) speed);
}
nic.setMacAddress((String) nicProperties.get("hwaddr"));
// if we get "permhwaddr", we are a part of a bond and we use that as the mac address
String mac = (String) nicProperties.get("permhwaddr");
if (mac != null) {
//TODO remove when the minimal supported vdsm version is >=3.6
// in older VDSM version, slave's Mac is in upper case
nic.setMacAddress(mac.toLowerCase());
}
}
vds.getInterfaces().add(nic);
}
}
}
/**
* Updates a given interface (be it physical, bond or VLAN) by data as collected from the host.
*
* @param iface
* The interface to update
* @param host
* The host to which the interface belongs.
* @param ifaceEntry
* A pair whose key is the interface's name, and whose value it a map of the interface properties.
*/
private static void updateCommonInterfaceData(VdsNetworkInterface iface,
VDS host,
Entry<String, Map<String, Object>> ifaceEntry) {
iface.setName(ifaceEntry.getKey());
iface.setId(Guid.newGuid());
iface.setVdsId(host.getId());
VdsNetworkStatistics iStats = new VdsNetworkStatistics();
iStats.setId(iface.getId());
iStats.setVdsId(host.getId());
iface.setStatistics(iStats);
Map<String, Object> nicProperties = ifaceEntry.getValue();
if (nicProperties != null) {
iface.setAddress(extractAddress(nicProperties));
iface.setSubnet(extractSubnet(nicProperties));
final Integer mtu = assignIntValue(nicProperties, VdsProperties.MTU);
if (mtu != null) {
iface.setMtu(mtu);
}
addBootProtocol(nicProperties, host, iface);
}
}
private static String extractAddress(Map<String, Object> properties) {
return (String) properties.get("addr");
}
private static String extractSubnet(Map<String, Object> properties) {
return (String) properties.get("netmask");
}
/**
* Returns true if vdsm doesn't report the 'bridged' attribute or if reported - its actual value.<br>
* The assumption is bridge-less network isn't supported if the 'bridged' attribute wasn't reported.<br>
* Bridge-less networks must report 'false' for this property.
*
* @param network
* The network to evaluate its bridge attribute
* @return true is no attribute is reported or its actual value
*/
private static boolean isBridgedNetwork(Map<String, Object> network) {
return network.get("bridged") == null || Boolean.parseBoolean(network.get("bridged").toString());
}
// we check for old bonding options,
// if we had value for the bonding options, i.e. the user set it by the UI
// and we have host that is not returning it's bonding options(host below 2.2.4) we override
// the "new" bonding options with the old one only if we have the new one as null and the old one is not
private static void setBondingOptions(VDS vds, List<VdsNetworkInterface> oldInterfaces) {
for (VdsNetworkInterface iface : oldInterfaces) {
if (iface.getBondOptions() != null) {
for (VdsNetworkInterface newIface : vds.getInterfaces()) {
if (iface.getName().equals(newIface.getName()) && newIface.getBondOptions() == null) {
newIface.setBondOptions(iface.getBondOptions());
break;
}
}
}
}
}
private static void addBootProtocol(Map<String, Object> entry, VDS host, VdsNetworkInterface iface) {
BootProtocolResolver resolver =
FeatureSupported.cfgEntriesDeprecated(host.getVdsGroupCompatibilityVersion())
? new NoCfgBootProtocolResolver(entry, iface, host)
: new CfgBootProtocolResolver(entry, iface, host);
resolver.resolve();
}
private static void addBondDeviceToHost(VDS vds, VdsNetworkInterface iface, Object[] interfaces) {
vds.getInterfaces().add(iface);
if (interfaces != null) {
for (Object name : interfaces) {
for (VdsNetworkInterface tempInterface : vds.getInterfaces()) {
if (tempInterface.getName().equals(name.toString())) {
tempInterface.setBondName(iface.getName());
break;
}
}
}
}
}
/**
* Store the gateway for either of these cases:
* 1. any host network, in a cluster that supports multiple gateways
* 2. management network, no matter the cluster compatibility version
* 3. the active interface (could happen when there is no management network yet)
* If gateway was provided for non-management network when multiple gateways aren't supported, its value should be ignored.
*
* @param iface
* the host network interface
* @param host
* the host whose interfaces are being edited
* @param gateway
* the gateway value to be set
*/
public static void setGatewayIfNecessary(VdsNetworkInterface iface, VDS host, String gateway) {
final ManagementNetworkUtil managementNetworkUtil = getManagementNetworkUtil();
if (FeatureSupported.multipleGatewaysSupported(host.getVdsGroupCompatibilityVersion())
|| managementNetworkUtil.isManagementNetwork(iface.getNetworkName(), host.getVdsGroupId())
|| iface.getName().equals(host.getActiveNic())) {
iface.setGateway(gateway);
}
}
private static ManagementNetworkUtil getManagementNetworkUtil() {
final ManagementNetworkUtil managementNetworkUtil = Injector.get(ManagementNetworkUtil.class);
return managementNetworkUtil;
}
/**
* Creates a list of {@link VmGuestAgentInterface} from the {@link VdsProperties.GuestNetworkInterfaces}
*
* @param vmId
* the Vm's ID which contains the interfaces
*
* @param xmlRpcStruct
* the xml structure that describes the VM as reported by VDSM
* @return a list of {@link VmGuestAgentInterface} or null if no guest vNics were reported
*/
public static List<VmGuestAgentInterface> buildVmGuestAgentInterfacesData(Guid vmId, Map<String, Object> xmlRpcStruct) {
if (!xmlRpcStruct.containsKey(VdsProperties.VM_NETWORK_INTERFACES)) {
return null;
}
List<VmGuestAgentInterface> interfaces = new ArrayList<>();
for (Object ifaceStruct : (Object[]) xmlRpcStruct.get(VdsProperties.VM_NETWORK_INTERFACES)) {
VmGuestAgentInterface nic = new VmGuestAgentInterface();
Map ifaceMap = (Map) ifaceStruct;
nic.setInterfaceName(assignStringValue(ifaceMap, VdsProperties.VM_INTERFACE_NAME));
nic.setMacAddress(getMacAddress(ifaceMap));
nic.setIpv4Addresses(extracStringtList(ifaceMap, VdsProperties.VM_IPV4_ADDRESSES));
nic.setIpv6Addresses(extracStringtList(ifaceMap, VdsProperties.VM_IPV6_ADDRESSES));
nic.setVmId(vmId);
interfaces.add(nic);
}
return interfaces;
}
private static String getMacAddress(Map<String, Object> ifaceMap) {
String macAddress = assignStringValue(ifaceMap, VdsProperties.VM_INTERFACE_MAC_ADDRESS);
return macAddress != null ? macAddress.replace('-', ':') : null;
}
/**
* Build through the received NUMA nodes information
* @param vds
* @param xmlRpcStruct
*/
private static void updateNumaNodesData(VDS vds, Map<String, Object> xmlRpcStruct) {
if (xmlRpcStruct.containsKey(VdsProperties.AUTO_NUMA)) {
vds.getDynamicData().setAutoNumaBalancing(AutoNumaBalanceStatus.forValue(
assignIntValue(xmlRpcStruct, VdsProperties.AUTO_NUMA)));
}
if (xmlRpcStruct.containsKey(VdsProperties.NUMA_NODES)) {
Map<String, Map<String, Object>> numaNodeMap =
(Map<String, Map<String, Object>>) xmlRpcStruct.get(VdsProperties.NUMA_NODES);
Map<String, Object> numaNodeDistanceMap =
(Map<String, Object>) xmlRpcStruct.get(VdsProperties.NUMA_NODE_DISTANCE);
List<VdsNumaNode> newNumaNodeList = new ArrayList<>(numaNodeMap.size());
for (Map.Entry<String, Map<String, Object>> item : numaNodeMap.entrySet()) {
int index = Integer.parseInt(item.getKey());
Map<String, Object> itemMap = item.getValue();
List<Integer> cpuIds = extractIntegerList(itemMap, VdsProperties.NUMA_NODE_CPU_LIST);
long memTotal = assignLongValue(itemMap, VdsProperties.NUMA_NODE_TOTAL_MEM);
VdsNumaNode numaNode = new VdsNumaNode();
numaNode.setIndex(index);
if (cpuIds != null) {
numaNode.setCpuIds(cpuIds);
}
numaNode.setMemTotal(memTotal);
newNumaNodeList.add(numaNode);
}
Collections.sort(newNumaNodeList, numaNodeComparator);
for (VdsNumaNode vdsNumaNode : newNumaNodeList) {
int index = vdsNumaNode.getIndex();
Map<Integer, Integer> distanceMap = new HashMap<>();
List<Integer> distances = Collections.emptyList();
if (numaNodeDistanceMap != null) {
// Save the received NUMA node distances
distances = extractIntegerList(numaNodeDistanceMap, String.valueOf(index));
for (int i = 0; i < distances.size(); i++) {
distanceMap.put(newNumaNodeList.get(i).getIndex(), distances.get(i));
}
}
if (distances.isEmpty()) {
// Save faked distances
for (VdsNumaNode otherNumaNode : newNumaNodeList) {
// There is no distance if the node is the same one
if (otherNumaNode.getIndex() == vdsNumaNode.getIndex()) {
continue;
}
distanceMap.put(otherNumaNode.getIndex(), 0);
}
}
VdsNumaNode newNumaNode = NumaUtils.getVdsNumaNodeByIndex(newNumaNodeList, index);
if (newNumaNode != null) {
newNumaNode.setNumaNodeDistances(distanceMap);
}
}
vds.getDynamicData().setNumaNodeList(newNumaNodeList);
vds.setNumaSupport(newNumaNodeList.size() > 1);
}
}
/**
* Build through the received vm NUMA nodes runtime information
* @param vm
* @param xmlRpcStruct
*/
private static void updateVmNumaNodesRuntimeInfo(VmStatistics vm, Map<String, Object> xmlRpcStruct) {
Map<String, Object[]> vNodesRunInfo = (Map<String, Object[]>)xmlRpcStruct.get(
VdsProperties.VM_NUMA_NODES_RUNTIME_INFO);
for (Map.Entry<String, Object[]> item : vNodesRunInfo.entrySet()) {
VmNumaNode vNode = new VmNumaNode();
vNode.setIndex(Integer.parseInt(item.getKey()));
for (Object pNodeIndex : item.getValue()) {
vNode.getVdsNumaNodeList().add(new Pair<>(
Guid.Empty, new Pair<>(false, (Integer)pNodeIndex)));
}
vm.getvNumaNodeStatisticsList().add(vNode);
}
}
private static List<String> extracStringtList(Map<String, Object> xmlRpcStruct, String propertyName) {
if (!xmlRpcStruct.containsKey(propertyName)){
return null;
}
Object[] items = (Object[]) xmlRpcStruct.get(propertyName);
if (items.length == 0) {
return null;
}
List<String> list = new ArrayList<>();
for (Object item : items) {
list.add((String) item);
}
return list;
}
private static List<Integer> extractIntegerList(Map<String, Object> xmlRpcStruct, String propertyName) {
if (!xmlRpcStruct.containsKey(propertyName)){
return Collections.emptyList();
}
Object[] items = (Object[]) xmlRpcStruct.get(propertyName);
if (items.length == 0) {
return Collections.emptyList();
}
List<Integer> list = new ArrayList<>();
for (Object item : items) {
list.add((Integer) item);
}
return list;
}
/**
* Parse Host Device Information in the form of
*
* {
* 'computer': {
* 'params': {'capability': 'system', 'product': 'ProLiant DL160 G6 '}
* },
* 'pci_0000_00_1d_2': {
* 'params': {
* 'capability': 'pci',
* 'iommu_group': '9',
* 'parent': 'computer',
* 'product': '82801JI (ICH10 Family) USB UHCI Controller #3',
* 'product_id': '0x3a36',
* 'vendor': 'Intel Corporation',
* 'vendor_id': '0x8086'
* }
* },
* 'pci_0000_00_1d_1': {
* ...
* }
* }
*/
public static List<HostDevice> buildHostDevices(Map<String, Map<String, Map<String, Object>>> deviceList) {
List<HostDevice> devices = new ArrayList<>();
for (Entry<String, Map<String, Map<String, Object>>> entry : deviceList.entrySet()) {
Map<String, Object> params = entry.getValue().get(VdsProperties.PARAMS);
String deviceName = entry.getKey();
HostDevice device = new HostDevice();
device.setDeviceName(entry.getKey());
device.setCapability(params.get(VdsProperties.CAPABILITY).toString());
// special case for root device "computer"
if (VdsProperties.ROOT_HOST_DEVICE.equals(deviceName)) {
device.setParentDeviceName(VdsProperties.ROOT_HOST_DEVICE); // set parent to self, for DB integrity
} else {
device.setParentDeviceName(params.get(VdsProperties.PARENT_NAME).toString());
}
if (params.containsKey(VdsProperties.IOMMU_GROUP)) {
device.setIommuGroup(Integer.parseInt(params.get(VdsProperties.IOMMU_GROUP).toString()));
}
if (params.containsKey(VdsProperties.PRODUCT_ID)) {
device.setProductId(params.get(VdsProperties.PRODUCT_ID).toString());
}
if (params.containsKey(VdsProperties.PRODUCT_NAME)) {
device.setProductName(params.get(VdsProperties.PRODUCT_NAME).toString());
}
if (params.containsKey(VdsProperties.VENDOR_NAME)) {
device.setVendorName(params.get(VdsProperties.VENDOR_NAME).toString());
}
if (params.containsKey(VdsProperties.VENDOR_ID)) {
device.setVendorId(params.get(VdsProperties.VENDOR_ID).toString());
}
if (params.containsKey(VdsProperties.PHYSICAL_FUNCTION)) {
device.setParentPhysicalFunction(params.get(VdsProperties.PHYSICAL_FUNCTION).toString());
}
if (params.containsKey(VdsProperties.TOTAL_VFS)) {
device.setTotalVirtualFunctions(Integer.parseInt(params.get(VdsProperties.TOTAL_VFS).toString()));
}
if (params.containsKey(VdsProperties.NET_INTERFACE_NAME)) {
device.setNetworkInterfaceName(params.get(VdsProperties.NET_INTERFACE_NAME).toString());
}
devices.add(device);
}
return devices;
}
private static void updateV2VJobs(VDS vds, Map<String, Object> xmlRpcStruct) {
if (!xmlRpcStruct.containsKey(VdsProperties.v2vJobs)) {
return;
}
List<V2VJobInfo> v2vJobs = new ArrayList<>();
for (Entry<String, Object> job : ((Map<String, Object>) xmlRpcStruct.get(VdsProperties.v2vJobs)).entrySet()) {
v2vJobs.add(buildV2VJobData(job.getKey(), (Map<String, Object>) job.getValue()));
}
vds.getStatisticsData().setV2VJobs(v2vJobs);
}
private static V2VJobInfo buildV2VJobData(String jobId, Map<String, Object> xmlRpcStruct) {
V2VJobInfo job = new V2VJobInfo();
job.setId(Guid.createGuidFromString(jobId));
job.setStatus(getV2VJobStatusValue(xmlRpcStruct));
job.setDescription(assignStringValue(xmlRpcStruct, VdsProperties.v2vDescription));
job.setProgress(assignIntValue(xmlRpcStruct, VdsProperties.v2vProgress));
return job;
}
private static V2VJobInfo.JobStatus getV2VJobStatusValue(Map<String, Object> input) {
String status = (String) input.get(VdsProperties.v2vJobStatus);
try {
return V2VJobInfo.JobStatus.valueOf(status.toUpperCase());
} catch (Exception e) {
log.warn("Got invalid status for virt-v2v job: {}", status);
return V2VJobInfo.JobStatus.UNKNOWN;
}
}
public static Double removeNotifyTimeFromVmStatusEvent(Map<String, Object> xmlRpcStruct) {
Object notifyTime = xmlRpcStruct.remove(VdsProperties.notify_time);
if (Long.class.isInstance(notifyTime)) {
return ((Long) notifyTime).doubleValue();
}
return null;
}
}
|
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// File created: 2011-06-14 13:38:57
package fi.tkk.ics.hadoop.bam.cli.plugins;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.Path;
import net.sf.samtools.SAMFormatException;
import net.sf.samtools.SAMFileReader.ValidationStringency;
import net.sf.samtools.util.SeekableStream;
import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMFileHeader;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMFileReader;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecord;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecordIterator;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMSequenceRecord;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMTextWriter;
import fi.tkk.ics.hadoop.bam.cli.CLIPlugin;
import fi.tkk.ics.hadoop.bam.util.Pair;
import fi.tkk.ics.hadoop.bam.util.WrapSeekable;
import static fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.*;
public final class View extends CLIPlugin {
private static final List<Pair<CmdLineParser.Option, String>> optionDescs
= new ArrayList<Pair<CmdLineParser.Option, String>>();
private static final CmdLineParser.Option
headerOnlyOpt = new BooleanOption('H', "header-only");
public View() {
super("view", "BAM viewing", "1.0", "PATH [regions...]", optionDescs,
"Reads the BAM file in PATH and, by default, outputs it in SAM "+
"format. If any number of regions is given, only the alignments "+
"overlapping with those regions are output. Then an index is also "+
"required, expected at PATH.bai by default."+
"\n\n"+
"Regions can be given as only reference sequence names or indices "+
"like 'chr1', or with position ranges as well like 'chr1:100-200'. "+
"These coordinates are 1-based, with 0 representing the start or "+
"end of the sequence.");
}
static {
optionDescs.add(new Pair<CmdLineParser.Option, String>(
headerOnlyOpt, "print header only"));
}
@Override protected int run(CmdLineParser parser) {
final List<String> args = parser.getRemainingArgs();
if (args.isEmpty()) {
System.err.println("view :: PATH not given.");
return 3;
}
final String path = args.get(0);
final List<String> regions = args.subList(1, args.size());
final boolean headerOnly = parser.getBoolean(headerOnlyOpt);
final SAMFileReader reader;
try {
final Path p = new Path(path);
SeekableStream idx;
try {
idx = WrapSeekable.openPath(getConf(), p.suffix(".bai"));
} catch (Exception e) {
idx = null;
}
final SeekableStream sam = WrapSeekable.openPath(getConf(), p);
reader = idx == null ? new SAMFileReader(sam, false)
: new SAMFileReader(sam, idx, false);
} catch (Exception e) {
System.err.printf("view :: Could not open '%s': %s\n",
path, e.getMessage());
return 4;
}
reader.setValidationStringency(ValidationStringency.SILENT);
final SAMTextWriter writer = new SAMTextWriter(System.out);
final SAMFileHeader header;
try {
header = reader.getFileHeader();
} catch (SAMFormatException e) {
System.err.printf("view :: Could not parse '%s': %s\n",
path, e.getMessage());
return 4;
}
if (regions.isEmpty() || headerOnly) {
writer.setSortOrder(header.getSortOrder(), true);
writer.setHeader(header);
if (!headerOnly)
if (!writeIterator(writer, reader.iterator(), path))
return 4;
writer.close();
return 0;
}
if (!reader.isBinary()) {
System.err.println("view :: Cannot output regions from SAM file");
return 4;
}
if (!reader.hasIndex()) {
System.err.println(
"view :: Cannot output regions from BAM file lacking an index");
return 4;
}
reader.enableIndexCaching(true);
boolean errors = false;
for (final String region : regions) {
final StringTokenizer st = new StringTokenizer(region, ":-");
final String refStr = st.nextToken();
final int beg, end;
if (st.hasMoreTokens()) {
beg = parseCoordinate(st.nextToken());
end = st.hasMoreTokens() ? parseCoordinate(st.nextToken()) : -1;
if (beg < 0 || end < 0) {
errors = true;
continue;
}
if (end < beg) {
System.err.printf(
"view :: Invalid range, cannot end before start: '%d-%d'\n",
beg, end);
errors = true;
continue;
}
} else
beg = end = 0;
SAMSequenceRecord ref = header.getSequence(refStr);
if (ref == null) try {
ref = header.getSequence(Integer.parseInt(refStr));
} catch (NumberFormatException e) {}
if (ref == null) {
System.err.printf(
"view :: Not a valid sequence name or index: '%s'\n", refStr);
errors = true;
continue;
}
final SAMRecordIterator it =
reader.queryOverlapping(ref.getSequenceName(), beg, end);
if (!writeIterator(writer, it, path))
return 4;
}
writer.close();
return errors ? 5 : 0;
}
private boolean writeIterator(
SAMTextWriter writer, SAMRecordIterator it, String path)
{
try {
while (it.hasNext())
writer.writeAlignment(it.next());
return true;
} catch (SAMFormatException e) {
writer.close();
System.err.printf("view :: Could not parse '%s': %s\n",
path, e.getMessage());
return false;
}
}
private int parseCoordinate(String s) {
int c;
try {
c = Integer.parseInt(s);
} catch (NumberFormatException e) {
c = -1;
}
if (c < 0)
System.err.printf("view :: Not a valid coordinate: '%s'\n", s);
return c;
}
}
|
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// File created: 2011-06-14 13:38:57
package fi.tkk.ics.hadoop.bam.cli.plugins;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.hadoop.fs.Path;
import net.sf.samtools.SAMFormatException;
import net.sf.samtools.SAMFileReader.ValidationStringency;
import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser;
import fi.tkk.ics.hadoop.bam.custom.samtools.BAMIndex;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMFileHeader;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMFileReader;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMFileSpan;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecord;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecordIterator;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMTextWriter;
import fi.tkk.ics.hadoop.bam.cli.CLIPlugin;
import fi.tkk.ics.hadoop.bam.util.Pair;
import fi.tkk.ics.hadoop.bam.util.WrapSeekable;
import static fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.*;
public final class View extends CLIPlugin {
private static final List<Pair<CmdLineParser.Option, String>> optionDescs
= new ArrayList<Pair<CmdLineParser.Option, String>>();
private static final CmdLineParser.Option
localFilesystemOpt = new BooleanOption('L', "--local-filesystem"),
headerOnlyOpt = new BooleanOption('H', "--header-only");
public View() {
super("view", "BAM viewing", "1.0", "PATH [regions...]", optionDescs,
"Reads the BAM file in PATH and, by default, outputs it in SAM "+
"format. If any number of regions is given, only the alignments "+
"overlapping with those regions are output. Then an index is also "+
"required, expected at PATH.bai by default."+
"\n\n"+
"By default, PATH is treated as a local file path if run outside "+
"Hadoop and an HDFS path if run within it."+
"\n\n"+
"Regions can be given as only reference sequence names or indices "+
"like 'chr1', or with position ranges as well like 'chr1:100-200'.");
}
static {
optionDescs.add(new Pair<CmdLineParser.Option, String>(
localFilesystemOpt, "force use of the local FS instead of HDFS"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
headerOnlyOpt, "print header only"));
}
@Override protected int run(CmdLineParser parser) {
final List<String> args = parser.getRemainingArgs();
if (args.isEmpty()) {
System.err.println("view :: PATH not given.");
return 3;
}
final String path = args.get(0);
final List<String> regions = args.subList(1, args.size());
final boolean
localFilesystem = parser.getBoolean(localFilesystemOpt),
headerOnly = parser.getBoolean(headerOnlyOpt);
final SAMFileReader reader;
try {
if (localFilesystem)
reader = new SAMFileReader(
new File(path), new File(path + ".bai"), false);
else {
final Path p = new Path(path);
reader = new SAMFileReader(
WrapSeekable.openPath(getConf(), p),
WrapSeekable.openPath(getConf(), p.suffix(".bai")),
false);
}
} catch (Exception e) {
System.err.printf("view :: Could not open '%s': %s\n",
path, e.getMessage());
return 4;
}
// We'd rather get an exception than have Picard barf all the errors it
// finds without us knowing about it.
reader.setValidationStringency(ValidationStringency.STRICT);
final SAMTextWriter writer = new SAMTextWriter(System.out);
final SAMFileHeader header;
try {
header = reader.getFileHeader();
} catch (SAMFormatException e) {
System.err.printf("view :: Could not parse '%s': %s\n",
path, e.getMessage());
return 4;
}
if (regions.isEmpty() || headerOnly) {
writer.setSortOrder(header.getSortOrder(), true);
writer.setHeader(header);
if (!headerOnly) try {
final SAMRecordIterator it = reader.iterator();
while (it.hasNext())
writer.writeAlignment(it.next());
} catch (SAMFormatException e) {
writer.close();
System.err.printf("view :: Could not parse '%s': %s\n",
path, e.getMessage());
return 4;
}
writer.close();
return 0;
}
if (!reader.hasIndex()) {
System.err.println(
"view :: Cannot output regions from BAM file lacking an index");
return 4;
}
reader.enableIndexCaching(true);
final BAMIndex index = reader.getIndex();
boolean errors = false;
for (final String region : regions) {
final StringTokenizer st = new StringTokenizer(region, ":-");
final String refStr = st.nextToken();
final int beg, end;
if (st.hasMoreTokens()) {
beg = parseCoordinate(st.nextToken());
end = st.hasMoreTokens() ? parseCoordinate(st.nextToken()) : -1;
if (beg < 0 || end < 0) {
errors = true;
continue;
}
if (end < beg) {
System.err.printf(
"view :: Invalid range, cannot end before start: '%d-%d'\n",
beg, end);
errors = true;
continue;
}
} else {
beg = 0;
end = SAMRecord.MAX_INSERT_SIZE;
}
int ref = header.getSequenceIndex(refStr);
if (ref == -1) try {
ref = Integer.parseInt(refStr);
} catch (NumberFormatException e) {
System.err.printf(
"view :: Not a valid sequence name or index: '%s'\n", refStr);
errors = true;
continue;
}
final SAMFileSpan span = index.getSpanOverlapping(ref, beg, end);
if (span == null)
continue;
try {
final SAMRecordIterator it = reader.iterator(span);
// This containment checking seems like something that should be
// handled by the SAMFileSpan, but no such luck...
// Because they're in order, we can get by without doing the full
// two-comparison containment check on each record: loop until a
// record in range is found and then loop until one out of range is
// found.
while (it.hasNext()) {
final SAMRecord rec = it.next();
if (rec.getAlignmentEnd() >= beg) {
if (rec.getAlignmentStart() <= end)
writer.writeAlignment(rec);
break;
}
}
while (it.hasNext()) {
final SAMRecord rec = it.next();
if (rec.getAlignmentStart() <= end)
writer.writeAlignment(rec);
else
break;
}
} catch (SAMFormatException e) {
writer.close();
System.err.printf("view :: Could not parse '%s': %s\n",
path, e.getMessage());
return 4;
}
}
writer.close();
return errors ? 5 : 0;
}
private int parseCoordinate(String s) {
int c;
try {
c = Integer.parseInt(s);
} catch (NumberFormatException e) {
c = -1;
}
if (c < 0)
System.err.printf("view :: Not a valid coordinate: '%s'\n", s);
return c;
}
}
|
package ch.elexis.core.importer.div.tasks.internal;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.slf4j.Logger;
import ch.elexis.core.importer.div.importers.DefaultPersistenceHandler;
import ch.elexis.core.importer.div.importers.HL7Parser;
import ch.elexis.core.importer.div.importers.ILabImportUtil;
import ch.elexis.core.importer.div.importers.ImportHandler;
import ch.elexis.core.importer.div.importers.TransientLabResult;
import ch.elexis.core.importer.div.importers.multifile.MultiFileParser;
import ch.elexis.core.importer.div.importers.multifile.strategy.IFileImportStrategyFactory;
import ch.elexis.core.model.ILabResult;
import ch.elexis.core.model.IPatient;
import ch.elexis.core.model.tasks.IIdentifiedRunnable;
import ch.elexis.core.model.tasks.TaskException;
import ch.elexis.core.services.IModelService;
import ch.elexis.core.services.IVirtualFilesystemService;
import ch.elexis.core.services.IVirtualFilesystemService.IVirtualFilesystemHandle;
import ch.rgw.tools.Result;
/**
*
* @see ch.elexis.laborimport.hl7.automatic.AutomaticImportService
*/
public class HL7ImporterIIdentifiedRunnable implements IIdentifiedRunnable {
public static final String RUNNABLE_ID = "hl7importer";
public static final String DESCRIPTION = "Import a single hl7 file from a given url";
/**
* run parameter: the laboratory name to use, defaults to: "myLab"
*/
public static final String RCP_STRING_IMPORTER_LABNAME = "labName";
/**
* run parameter: create patient if not exists, default: <code>false</code>
*/
public static final String RCP_BOOLEAN_CREATE_PATIENT_IF_NOT_EXISTS = "createPatientIfNotExists";
/**
* run parameter: create laboratory if not exists, default: <code>false</code>
*/
public static final String RCP_BOOLEAN_CREATE_LABORATORY_IF_NOT_EXISTS = "createLaboratoryIfNotExists";
/**
* run parameter: move hl7 file after successful import, default:
* <code>true</code>
*/
public static final String RCP_BOOLEAN_MOVE_FILE_AFTER_IMPORT = "moveFile";
private ILabImportUtil labimportUtil;
private IModelService coreModelService;
private IVirtualFilesystemService vfsService;
public HL7ImporterIIdentifiedRunnable(IModelService coreModelService, ILabImportUtil labimportUtil,
IVirtualFilesystemService vfsService) {
this.coreModelService = coreModelService;
this.labimportUtil = labimportUtil;
this.vfsService = vfsService;
}
@Override
public String getId() {
return RUNNABLE_ID;
}
@Override
public String getLocalizedDescription() {
return DESCRIPTION;
}
@Override
public Map<String, String> getDefaultRunContext() {
Map<String, String> defaultRunContext = new HashMap<>();
defaultRunContext.put(RunContextParameter.STRING_URL, RunContextParameter.VALUE_MISSING_REQUIRED);
defaultRunContext.put(RCP_BOOLEAN_CREATE_PATIENT_IF_NOT_EXISTS, Boolean.toString(false));
defaultRunContext.put(RCP_BOOLEAN_CREATE_LABORATORY_IF_NOT_EXISTS, Boolean.toString(true));
defaultRunContext.put(RCP_BOOLEAN_MOVE_FILE_AFTER_IMPORT, Boolean.toString(true));
defaultRunContext.put(RCP_STRING_IMPORTER_LABNAME, "myLab");
return defaultRunContext;
}
@Override
public Map<String, Serializable> run(Map<String, Serializable> context, IProgressMonitor progressMonitor,
Logger logger) throws TaskException {
boolean bCreateLaboratoryIfNotExists = Boolean.valueOf((String) context.get(RCP_BOOLEAN_CREATE_LABORATORY_IF_NOT_EXISTS));
boolean bMoveFile = Boolean.valueOf((String) context.get(RCP_BOOLEAN_MOVE_FILE_AFTER_IMPORT));
String urlString = (String) context.get(RunContextParameter.STRING_URL);
String labName = (String) context.get(RCP_STRING_IMPORTER_LABNAME);
// TODO make configurable
final boolean CFG_IMPORT_ENCDATA = false;
MyImportHandler myImportHandler = new MyImportHandler();
HL7ImporterLabContactResolver labContactResolver = new HL7ImporterLabContactResolver(coreModelService, logger,
bCreateLaboratoryIfNotExists);
IFileImportStrategyFactory importStrategyFactory = new HL7ImportStrategyFactory(logger, myImportHandler)
.setMoveAfterImport(bMoveFile).setLabContactResolver(labContactResolver);
MultiFileParser multiFileParser = new MultiFileParser(labName);
HL7Parser hl7Parser = new HL7Parser(labName, new HL7ImporterPatientResolver(coreModelService, logger),
labimportUtil, myImportHandler, labContactResolver, CFG_IMPORT_ENCDATA);
IVirtualFilesystemHandle fileHandle;
try {
fileHandle = vfsService.of(urlString);
Result<?> result = multiFileParser.importFromHandle(fileHandle, importStrategyFactory, hl7Parser,
new DefaultPersistenceHandler());
if(!result.isOK()) {
throw new TaskException(TaskException.EXECUTION_ERROR, result.toString());
}
return Collections.singletonMap(IIdentifiedRunnable.ReturnParameter.RESULT_DATA, result.toString());
} catch (IOException e) {
throw new TaskException(TaskException.EXECUTION_ERROR, e);
}
}
private class MyImportHandler extends ImportHandler {
@Override
public OverwriteState askOverwrite(IPatient patient, ILabResult oldResult, TransientLabResult newResult) {
// TODO make configurable
return null;
}
}
}
|
package fitnesse.html.template;
import fitnesse.wikitext.Utils;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import java.io.IOException;
import java.io.Writer;
public class EscapeDirective extends Directive {
@Override
public String getName() {
return "escape";
}
@Override
public int getType() {
return LINE;
}
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
Object value = node.jjtGetChild(0).value(context);
if (value != null) {
String text = Utils.escapeHTML(String.valueOf(value));
writer.write(text);
}
return true;
}
}
|
package com.codeaffine.extras.imageviewer.internal;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.ide.IDE;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
@RunWith( value = Parameterized.class )
public class ContentTypeExtensionPDETest {
@Parameters(name = "{0}")
public static Collection<Object[]> parameters() {
return asList(
new Object[] { "gif" },
new Object[] { "jpg" },
new Object[] { "jpeg" },
new Object[] { "png" },
new Object[] { "bmp" },
new Object[] { "ico" },
new Object[] { "tiff" }
);
}
@Parameter
public String fileExtension;
private String fileName;
@Before
public void setUp() {
fileName = "image." + fileExtension;
}
@Test
public void testContentTypes() {
IContentType contentType = Platform.getContentTypeManager().findContentTypeFor( fileName );
assertThat( contentType.getId() ).isEqualTo( ImageViewerPlugin.IMAGE_CONTENT_TYPE_ID );
}
@SuppressWarnings("deprecation")
@Test
public void testDefaultEditorBinding() throws Exception {
IEditorDescriptor editorDescriptor = IDE.getEditorDescriptor( fileName, true );
assertThat( editorDescriptor.getId() ).isEqualTo( ImageViewerEditor.ID );
}
}
|
package de.itemis.xtext.utils.jface.viewers;
import java.util.List;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.source.AnnotationModel;
import org.eclipse.jface.text.source.ICharacterPairMatcher;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.editors.text.EditorsPlugin;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess;
import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.xtext.Constants;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.ui.editor.XtextSourceViewer;
import org.eclipse.xtext.ui.editor.XtextSourceViewer.Factory;
import org.eclipse.xtext.ui.editor.XtextSourceViewerConfiguration;
import org.eclipse.xtext.ui.editor.bracketmatching.BracketMatchingPreferencesInitializer;
import org.eclipse.xtext.ui.editor.model.XtextDocument;
import org.eclipse.xtext.ui.editor.preferences.IPreferenceStoreAccess;
import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionProvider;
import org.eclipse.xtext.ui.editor.validation.AnnotationIssueProcessor;
import org.eclipse.xtext.ui.editor.validation.ValidationJob;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.eclipse.xtext.validation.CheckMode;
import org.eclipse.xtext.validation.IResourceValidator;
import org.eclipse.xtext.validation.Issue;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
/**
* This class integrates xText Features into a {@link CellEditor} and can be
* used i.E. in jface {@link StructuredViewer}s or in GMF EditParts via
* DirectEditManager.
*
* The current implementation supports, code completion, syntax highlighting and
* validation
*
* Some code is initially copied from xText.
*
* @author andreas.muelder@itemis.de
* @author alexander.nyssen@itemis.de
*/
// TODO: Check if we can use the XTextDocumentProvider instead of creating own
// XTextDocument + setup
@SuppressWarnings("restriction")
public class XtextCellEditor extends StyledTextCellEditor {
/**
* Key listener executed content assist operation on CTRL+Space
*/
private final KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
XtextCellEditor.this.valueChanged(true, true);
// CONTENTASSIST_PROPOSALS
if ((e.keyCode == 32) && ((e.stateMask & SWT.CTRL) != 0)) {
BusyIndicator.showWhile(Display.getDefault(), new Runnable() {
public void run() {
sourceviewer
.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
}
});
}
}
public void keyReleased(KeyEvent e) {
}
};
/**
* The sourceViewer, that provides additional functions to the styled text
* widget
*/
private XtextSourceViewer sourceviewer;
private ValidationJob validationJob;
private IssueResolutionProvider resolutionProvider = new IssueResolutionProvider.NullImpl();
@Inject
private IPreferenceStoreAccess preferenceStoreAccess;
@Inject
private ICharacterPairMatcher characterPairMatcher;
@Inject
private XtextSourceViewerConfiguration configuration;
@Inject
private Factory sourceViewerFactory;
@Inject
private XtextResource resource;
@Inject
private IResourceValidator validator;
@Inject
private Provider<IDocumentPartitioner> documentPartitioner;
@Inject
private @Named(Constants.FILE_EXTENSIONS)
String fileExtension;
@Inject
private XtextDocument document;
private Resource context;
/**
* C'tor to create a new Instance.
*
*/
public XtextCellEditor(int style) {
setStyle(style);
}
/**
* Creates an {@link SourceViewer} and returns the {@link StyledText} widget
* of the viewer as the cell editors control. Some code is copied from
* {@link XtextEditor}.
*/
@Override
protected Control createControl(Composite parent) {
sourceviewer = sourceViewerFactory.createSourceViewer(parent, null,
null, false, getStyle());
sourceviewer.configure(configuration);
createResourceSet();
setResourceUri(resource);
document.setInput(resource);
IDocumentPartitioner partitioner = documentPartitioner.get();
partitioner.connect(document);
document.setDocumentPartitioner(partitioner);
sourceviewer.setDocument(document, new AnnotationModel());
SourceViewerDecorationSupport support = new SourceViewerDecorationSupport(
sourceviewer, null, new DefaultMarkerAnnotationAccess(),
EditorsPlugin.getDefault().getSharedTextColors());
configureSourceViewerDecorationSupport(support);
validationJob = createValidationJob();
document.setValidationJob(validationJob);
text = sourceviewer.getTextWidget();
text.addKeyListener(keyListener);
text.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
XtextCellEditor.this.focusLost();
}
});
text.setFont(parent.getFont());
text.setBackground(parent.getBackground());
text.setText("");
return text;
}
private XtextResourceSet createResourceSet() {
XtextResourceSet resourceSet = new XtextResourceSet();
resourceSet.getResources().add(resource);
if (context != null) {
Resource contextResource = resourceSet.createResource(context
.getURI());
contextResource.getContents().addAll(
EcoreUtil.copyAll(context.getContents()));
resourceSet.getResources().add(contextResource);
}
return resourceSet;
}
@Override
protected StyledText createStyledText(Composite parent) {
sourceviewer = sourceViewerFactory.createSourceViewer(parent, null,
null, false, getStyle());
sourceviewer.configure(configuration);
sourceviewer.setDocument(document, new AnnotationModel());
SourceViewerDecorationSupport support = new SourceViewerDecorationSupport(
sourceviewer, null, new DefaultMarkerAnnotationAccess(),
EditorsPlugin.getDefault().getSharedTextColors());
configureSourceViewerDecorationSupport(support);
validationJob = createValidationJob();
document.setValidationJob(validationJob);
return sourceviewer.getTextWidget();
}
private ValidationJob createValidationJob() {
return new ValidationJob(validator, document,
new AnnotationIssueProcessor(document, sourceviewer
.getAnnotationModel(), resolutionProvider),
CheckMode.ALL);
}
/**
* Creates decoration support for the sourceViewer. code is entirely copied
* from {@link XtextEditor} and its super class
* {@link AbstractDecoratedTextEditor}.
*
*/
private void configureSourceViewerDecorationSupport(
SourceViewerDecorationSupport support) {
MarkerAnnotationPreferences annotationPreferences = new MarkerAnnotationPreferences();
@SuppressWarnings("unchecked")
List<AnnotationPreference> prefs = annotationPreferences
.getAnnotationPreferences();
for (AnnotationPreference annotationPreference : prefs) {
support.setAnnotationPreference(annotationPreference);
}
support.setCharacterPairMatcher(characterPairMatcher);
support.setMatchingCharacterPainterPreferenceKeys(
BracketMatchingPreferencesInitializer.IS_ACTIVE_KEY,
BracketMatchingPreferencesInitializer.COLOR_KEY);
support.install(preferenceStoreAccess.getPreferenceStore());
}
/**
* Sets the resource uri. From the resource uris project name the global
* scope is determined.
*
* @param resource
*/
protected void setResourceUri(final XtextResource resource) {
// TODO: This should be moved outside the CellEditor
// TODO: Remove dependency to IFileEditorInput
Display.getDefault().syncExec(new Runnable() {
public void run() {
IWorkbenchWindow activeWorkbenchWindow = PlatformUI
.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage activePage = activeWorkbenchWindow
.getActivePage();
if (activePage != null) {
IEditorInput editorInput = activePage.getActiveEditor()
.getEditorInput();
if (editorInput instanceof IFileEditorInput) {
IFileEditorInput input = (IFileEditorInput) editorInput;
String activeProject = input.getFile().getProject()
.getName();
resource.setURI(URI.createURI("platform:/resource/"
+ activeProject + "/embedded." + fileExtension));
}
}
}
});
}
public IParseResult getParseResult() {
return document
.readOnly(new IUnitOfWork<IParseResult, XtextResource>() {
public IParseResult exec(XtextResource state)
throws Exception {
return state.getParseResult();
}
});
}
public List<Issue> getIssues() {
return validationJob.createIssues(new NullProgressMonitor());
}
@Override
public void dispose() {
text.removeKeyListener(keyListener);
document.disposeInput();
super.dispose();
}
public Resource getContext() {
return context;
}
public void setContext(Resource context) {
this.context = context;
}
}
|
package org.hisp.dhis.trackedentity;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.time.DateUtils;
import org.hisp.dhis.DhisSpringTest;
import org.hisp.dhis.common.AssignedUserSelectionMode;
import org.hisp.dhis.common.IllegalQueryException;
import org.hisp.dhis.common.OrganisationUnitSelectionMode;
import org.hisp.dhis.common.QueryOperator;
import org.hisp.dhis.event.EventStatus;
import org.hisp.dhis.mock.MockCurrentUserService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramInstance;
import org.hisp.dhis.program.ProgramInstanceService;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.program.ProgramStageInstance;
import org.hisp.dhis.program.ProgramStageInstanceService;
import org.hisp.dhis.program.ProgramStageService;
import org.hisp.dhis.program.ProgramStatus;
import org.hisp.dhis.security.acl.AccessStringHelper;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.User;
import org.hisp.dhis.user.UserService;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.util.ReflectionTestUtils;
import com.google.common.collect.Sets;
/**
* @author Chau Thu Tran
*/
public class TrackedEntityInstanceServiceTest
extends
DhisSpringTest
{
@Autowired
private TrackedEntityInstanceService entityInstanceService;
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
private ProgramService programService;
@Autowired
private ProgramStageService programStageService;
@Autowired
private ProgramStageInstanceService programStageInstanceService;
@Autowired
private ProgramInstanceService programInstanceService;
@Autowired
private TrackedEntityAttributeService attributeService;
@Autowired
private UserService userService;
@Autowired
private TrackedEntityTypeService trackedEntityTypeService;
private ProgramStageInstance programStageInstanceA;
private ProgramInstance programInstanceA;
private Program programA;
private TrackedEntityInstance entityInstanceA1;
private TrackedEntityInstance entityInstanceB1;
private TrackedEntityAttribute entityInstanceAttribute;
private OrganisationUnit organisationUnit;
private TrackedEntityType trackedEntityTypeA = createTrackedEntityType( 'A' );
private TrackedEntityAttribute attrD = createTrackedEntityAttribute( 'D' );
private TrackedEntityAttribute attrE = createTrackedEntityAttribute( 'E' );
private TrackedEntityAttribute filtF = createTrackedEntityAttribute( 'F' );
private TrackedEntityAttribute filtG = createTrackedEntityAttribute( 'G' );
@Rule
public ExpectedException exception = ExpectedException.none();
@Override
public void setUpTest()
{
organisationUnit = createOrganisationUnit( 'A' );
organisationUnitService.addOrganisationUnit( organisationUnit );
OrganisationUnit organisationUnitB = createOrganisationUnit( 'B' );
organisationUnitService.addOrganisationUnit( organisationUnitB );
entityInstanceAttribute = createTrackedEntityAttribute( 'A' );
attributeService.addTrackedEntityAttribute( entityInstanceAttribute );
entityInstanceA1 = createTrackedEntityInstance( organisationUnit );
entityInstanceB1 = createTrackedEntityInstance( organisationUnit );
entityInstanceB1.setUid( "UID-B1" );
programA = createProgram( 'A', new HashSet<>(), organisationUnit );
programService.addProgram( programA );
ProgramStage stageA = createProgramStage( 'A', programA );
stageA.setSortOrder( 1 );
programStageService.saveProgramStage( stageA );
Set<ProgramStage> programStages = new HashSet<>();
programStages.add( stageA );
programA.setProgramStages( programStages );
programService.updateProgram( programA );
DateTime enrollmentDate = DateTime.now();
enrollmentDate.withTimeAtStartOfDay();
enrollmentDate = enrollmentDate.minusDays( 70 );
DateTime incidenDate = DateTime.now();
incidenDate.withTimeAtStartOfDay();
programInstanceA = new ProgramInstance( enrollmentDate.toDate(), incidenDate.toDate(), entityInstanceA1,
programA );
programInstanceA.setUid( "UID-A" );
programInstanceA.setOrganisationUnit( organisationUnit );
programStageInstanceA = new ProgramStageInstance( programInstanceA, stageA );
programInstanceA.setUid( "UID-PSI-A" );
programInstanceA.setOrganisationUnit( organisationUnit );
trackedEntityTypeA.setPublicAccess( AccessStringHelper.FULL );
trackedEntityTypeService.addTrackedEntityType( trackedEntityTypeA );
attributeService.addTrackedEntityAttribute( attrD );
attributeService.addTrackedEntityAttribute( attrE );
attributeService.addTrackedEntityAttribute( filtF );
attributeService.addTrackedEntityAttribute( filtG );
super.userService = this.userService;
User user = createUser( "testUser" );
user.setTeiSearchOrganisationUnits( Sets.newHashSet( organisationUnit ) );
CurrentUserService currentUserService = new MockCurrentUserService( user );
ReflectionTestUtils.setField( entityInstanceService, "currentUserService", currentUserService );
}
@Test
public void testSaveTrackedEntityInstance()
{
long idA = entityInstanceService.addTrackedEntityInstance( entityInstanceA1 );
long idB = entityInstanceService.addTrackedEntityInstance( entityInstanceB1 );
assertNotNull( entityInstanceService.getTrackedEntityInstance( idA ) );
assertNotNull( entityInstanceService.getTrackedEntityInstance( idB ) );
}
@Test
public void testDeleteTrackedEntityInstance()
{
long idA = entityInstanceService.addTrackedEntityInstance( entityInstanceA1 );
long idB = entityInstanceService.addTrackedEntityInstance( entityInstanceB1 );
TrackedEntityInstance teiA = entityInstanceService.getTrackedEntityInstance( idA );
TrackedEntityInstance teiB = entityInstanceService.getTrackedEntityInstance( idB );
assertNotNull( teiA );
assertNotNull( teiB );
entityInstanceService.deleteTrackedEntityInstance( entityInstanceA1 );
assertNull( entityInstanceService.getTrackedEntityInstance( teiA.getUid() ) );
assertNotNull( entityInstanceService.getTrackedEntityInstance( teiB.getUid() ) );
entityInstanceService.deleteTrackedEntityInstance( entityInstanceB1 );
assertNull( entityInstanceService.getTrackedEntityInstance( teiA.getUid() ) );
assertNull( entityInstanceService.getTrackedEntityInstance( teiB.getUid() ) );
}
@Test
public void testDeleteTrackedEntityInstanceAndLinkedEnrollmentsAndEvents()
{
long idA = entityInstanceService.addTrackedEntityInstance( entityInstanceA1 );
long psIdA = programInstanceService.addProgramInstance( programInstanceA );
long psiIdA = programStageInstanceService.addProgramStageInstance( programStageInstanceA );
programInstanceA.setProgramStageInstances( newHashSet( programStageInstanceA ) );
entityInstanceA1.setProgramInstances( newHashSet( programInstanceA ) );
programInstanceService.updateProgramInstance( programInstanceA );
entityInstanceService.updateTrackedEntityInstance( entityInstanceA1 );
TrackedEntityInstance teiA = entityInstanceService.getTrackedEntityInstance( idA );
ProgramInstance psA = programInstanceService.getProgramInstance( psIdA );
ProgramStageInstance psiA = programStageInstanceService.getProgramStageInstance( psiIdA );
assertNotNull( teiA );
assertNotNull( psA );
assertNotNull( psiA );
entityInstanceService.deleteTrackedEntityInstance( entityInstanceA1 );
assertNull( entityInstanceService.getTrackedEntityInstance( teiA.getUid() ) );
assertNull( programInstanceService.getProgramInstance( psIdA ) );
assertNull( programStageInstanceService.getProgramStageInstance( psiIdA ) );
}
@Test
public void testUpdateTrackedEntityInstance()
{
long idA = entityInstanceService.addTrackedEntityInstance( entityInstanceA1 );
assertNotNull( entityInstanceService.getTrackedEntityInstance( idA ) );
entityInstanceA1.setName( "B" );
entityInstanceService.updateTrackedEntityInstance( entityInstanceA1 );
assertEquals( "B", entityInstanceService.getTrackedEntityInstance( idA ).getName() );
}
@Test
public void testGetTrackedEntityInstanceById()
{
long idA = entityInstanceService.addTrackedEntityInstance( entityInstanceA1 );
long idB = entityInstanceService.addTrackedEntityInstance( entityInstanceB1 );
assertEquals( entityInstanceA1, entityInstanceService.getTrackedEntityInstance( idA ) );
assertEquals( entityInstanceB1, entityInstanceService.getTrackedEntityInstance( idB ) );
}
@Test
public void testGetTrackedEntityInstanceByUid()
{
entityInstanceA1.setUid( "A1" );
entityInstanceB1.setUid( "B1" );
entityInstanceService.addTrackedEntityInstance( entityInstanceA1 );
entityInstanceService.addTrackedEntityInstance( entityInstanceB1 );
assertEquals( entityInstanceA1, entityInstanceService.getTrackedEntityInstance( "A1" ) );
assertEquals( entityInstanceB1, entityInstanceService.getTrackedEntityInstance( "B1" ) );
}
@Test
public void testStoredByColumnForTrackedEntityInstance()
{
entityInstanceA1.setStoredBy( "test" );
entityInstanceService.addTrackedEntityInstance( entityInstanceA1 );
TrackedEntityInstance tei = entityInstanceService.getTrackedEntityInstance( entityInstanceA1.getUid() );
assertEquals( "test", tei.getStoredBy() );
}
@Test
public void testGetFromUrl()
{
final TrackedEntityInstanceQueryParams queryParams = entityInstanceService.getFromUrl(
"query-test",
newHashSet( attrD.getUid(), attrE.getUid() ),
newHashSet( filtF.getUid(), filtG.getUid() ),
newHashSet( organisationUnit.getUid() ),
OrganisationUnitSelectionMode.DESCENDANTS,
programA.getUid(),
ProgramStatus.ACTIVE,
false,
getDate( 2019, 1, 1 ),
getDate( 2020, 1, 1 ),
"20",
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
getDate( 2019, 8, 5 ),
getDate( 2020, 8, 5 ),
trackedEntityTypeA.getUid(),
EventStatus.COMPLETED,
getDate( 2019, 7, 7 ),
getDate( 2020, 7, 7 ),
AssignedUserSelectionMode.PROVIDED,
newHashSet( "user-1", "user-2" ),
true,
1,
50,
false,
false,
true,
false,
newArrayList( "order-1" ) );
assertThat( queryParams.getQuery().getFilter(), is( "query-test" ) );
assertThat( queryParams.getQuery().getOperator(), is( QueryOperator.EQ ) );
assertThat( queryParams.getProgram(), is( programA ) );
assertThat( queryParams.getTrackedEntityType(), is( trackedEntityTypeA ) );
assertThat( queryParams.getOrganisationUnits(), hasSize( 1 ) );
assertThat( queryParams.getOrganisationUnits().iterator().next(), is( organisationUnit ) );
assertThat( queryParams.getAttributes(), hasSize( 2 ) );
assertTrue(
queryParams.getAttributes().stream().anyMatch( a -> a.getItem().getUid().equals( attrD.getUid() ) ) );
assertTrue(
queryParams.getAttributes().stream().anyMatch( a -> a.getItem().getUid().equals( attrE.getUid() ) ) );
assertThat( queryParams.getFilters(), hasSize( 2 ) );
assertTrue( queryParams.getFilters().stream().anyMatch( a -> a.getItem().getUid().equals( filtF.getUid() ) ) );
assertTrue( queryParams.getFilters().stream().anyMatch( a -> a.getItem().getUid().equals( filtG.getUid() ) ) );
assertThat( queryParams.getPageSizeWithDefault(), is( 50 ) );
assertThat( queryParams.getPageSize(), is( 50 ) );
assertThat( queryParams.getPage(), is( 1 ) );
assertThat( queryParams.isTotalPages(), is( false ) );
assertThat( queryParams.getProgramStatus(), is( ProgramStatus.ACTIVE ) );
assertThat( queryParams.getFollowUp(), is( false ) );
assertThat( queryParams.getLastUpdatedStartDate(), is( getDate( 2019, 1, 1 ) ) );
assertThat( queryParams.getLastUpdatedEndDate(), is( getDate( 2020, 1, 1 ) ) );
assertThat( queryParams.getProgramEnrollmentStartDate(), is( getDate( 2019, 5, 5 ) ) );
assertThat( queryParams.getProgramEnrollmentEndDate(), is( DateUtils.addDays( getDate( 2020, 5, 5 ), 1 ) ) );
assertThat( queryParams.getProgramIncidentStartDate(), is( getDate( 2019, 8, 5 ) ) );
assertThat( queryParams.getProgramIncidentEndDate(), is( DateUtils.addDays( getDate( 2020, 8, 5 ), 1 ) ) );
assertThat( queryParams.getEventStatus(), is( EventStatus.COMPLETED ) );
assertThat( queryParams.getEventStartDate(), is( getDate( 2019, 7, 7 ) ) );
assertThat( queryParams.getEventEndDate(), is( getDate( 2020, 7, 7 ) ) );
assertThat( queryParams.getAssignedUserSelectionMode(), is( AssignedUserSelectionMode.PROVIDED ) );
assertTrue( queryParams.getAssignedUsers().stream().anyMatch( u -> u.equals( "user-1" ) ) );
assertTrue( queryParams.getAssignedUsers().stream().anyMatch( u -> u.equals( "user-2" ) ) );
assertThat( queryParams.isIncludeDeleted(), is( true ) );
assertThat( queryParams.isIncludeAllAttributes(), is( false ) );
assertTrue( queryParams.getOrders().stream().anyMatch( o -> o.equals( "order-1" ) ) );
}
@Test
public void testGetFromUrlFailOnMissingAttribute()
{
exception.expect( IllegalQueryException.class );
exception.expectMessage( "Attribute does not exist: missing" );
entityInstanceService.getFromUrl(
"query-test",
newHashSet( attrD.getUid(), attrE.getUid(), "missing" ),
newHashSet( filtF.getUid(), filtG.getUid() ),
newHashSet( organisationUnit.getUid() ),
OrganisationUnitSelectionMode.DESCENDANTS,
programA.getUid(),
ProgramStatus.ACTIVE,
false,
getDate( 2019, 1, 1 ),
getDate( 2020, 1, 1 ),
"20",
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
trackedEntityTypeA.getUid(),
EventStatus.COMPLETED,
getDate( 2019, 7, 7 ),
getDate( 2020, 7, 7 ),
AssignedUserSelectionMode.PROVIDED,
newHashSet( "user-1", "user-2" ),
true,
1,
50,
false,
false,
true,
false,
newArrayList( "order-1" ) );
}
@Test
public void testGetFromUrlFailOnMissingFilter()
{
exception.expect( IllegalQueryException.class );
exception.expectMessage( "Attribute does not exist: missing" );
entityInstanceService.getFromUrl(
"query-test",
newHashSet( attrD.getUid(), attrE.getUid() ),
newHashSet( filtF.getUid(), filtG.getUid(), "missing" ),
newHashSet( organisationUnit.getUid() ),
OrganisationUnitSelectionMode.DESCENDANTS,
programA.getUid(),
ProgramStatus.ACTIVE,
false,
getDate( 2019, 1, 1 ),
getDate( 2020, 1, 1 ),
"20",
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
trackedEntityTypeA.getUid(),
EventStatus.COMPLETED,
getDate( 2019, 7, 7 ),
getDate( 2020, 7, 7 ),
AssignedUserSelectionMode.PROVIDED,
newHashSet( "user-1", "user-2" ),
true,
1,
50,
false,
false,
true,
false,
newArrayList( "order-1" ) );
}
@Test
public void testGetFromUrlFailOnMissingProgram()
{
exception.expect( IllegalQueryException.class );
exception.expectMessage( "Program does not exist: " + programA.getUid() + "A" );
entityInstanceService.getFromUrl(
"query-test",
newHashSet( attrD.getUid(), attrE.getUid() ),
newHashSet( filtF.getUid(), filtG.getUid() ),
newHashSet( organisationUnit.getUid() ),
OrganisationUnitSelectionMode.DESCENDANTS,
programA.getUid() + "A",
ProgramStatus.ACTIVE,
false,
getDate( 2019, 1, 1 ),
getDate( 2020, 1, 1 ),
"20",
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
trackedEntityTypeA.getUid(),
EventStatus.COMPLETED,
getDate( 2019, 7, 7 ),
getDate( 2020, 7, 7 ),
AssignedUserSelectionMode.PROVIDED,
newHashSet( "user-1", "user-2" ),
true,
1,
50,
false,
false,
true,
false,
newArrayList( "order-1" ) );
}
@Test
public void testGetFromUrlFailOnMissingTrackerEntityType()
{
exception.expect( IllegalQueryException.class );
exception.expectMessage( "Tracked entity type does not exist: " + trackedEntityTypeA.getUid() + "A" );
entityInstanceService.getFromUrl(
"query-test",
newHashSet( attrD.getUid(), attrE.getUid() ),
newHashSet( filtF.getUid(), filtG.getUid() ),
newHashSet( organisationUnit.getUid() ),
OrganisationUnitSelectionMode.DESCENDANTS,
programA.getUid(),
ProgramStatus.ACTIVE,
false,
getDate( 2019, 1, 1 ),
getDate( 2020, 1, 1 ),
"20",
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
trackedEntityTypeA.getUid() + "A",
EventStatus.COMPLETED,
getDate( 2019, 7, 7 ),
getDate( 2020, 7, 7 ),
AssignedUserSelectionMode.PROVIDED,
newHashSet( "user-1", "user-2" ),
true,
1,
50,
false,
false,
true,
false,
newArrayList( "order-1" ) );
}
@Test
public void testGetFromUrlFailOnMissingOrgUnit()
{
exception.expect( IllegalQueryException.class );
exception.expectMessage( "Organisation unit does not exist: " + organisationUnit.getUid() + "A" );
entityInstanceService.getFromUrl(
"query-test",
newHashSet( attrD.getUid(), attrE.getUid() ),
newHashSet( filtF.getUid(), filtG.getUid() ),
newHashSet( organisationUnit.getUid() + "A" ),
OrganisationUnitSelectionMode.DESCENDANTS,
programA.getUid(),
ProgramStatus.ACTIVE,
false,
getDate( 2019, 1, 1 ),
getDate( 2020, 1, 1 ),
"20",
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
trackedEntityTypeA.getUid(),
EventStatus.COMPLETED,
getDate( 2019, 7, 7 ),
getDate( 2020, 7, 7 ),
AssignedUserSelectionMode.PROVIDED,
newHashSet( "user-1", "user-2" ),
true,
1,
50,
false,
false,
true,
false,
newArrayList( "order-1" ) );
}
@Test
public void testGetFromUrlFailOnUserNonInOuHierarchy()
{
exception.expect( IllegalQueryException.class );
exception.expectMessage( "Organisation unit is not part of the search scope: " + organisationUnit.getUid() );
// Force Current User Service to return a User without search org unit
ReflectionTestUtils.setField( entityInstanceService, "currentUserService",
new MockCurrentUserService( createUser( "testUser2" ) ) );
entityInstanceService.getFromUrl(
"query-test",
newHashSet( attrD.getUid(), attrE.getUid() ),
newHashSet( filtF.getUid(), filtG.getUid() ),
newHashSet( organisationUnit.getUid() ),
OrganisationUnitSelectionMode.DESCENDANTS,
programA.getUid(),
ProgramStatus.ACTIVE,
false,
getDate( 2019, 1, 1 ),
getDate( 2020, 1, 1 ),
"20",
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
trackedEntityTypeA.getUid(),
EventStatus.COMPLETED,
getDate( 2019, 7, 7 ),
getDate( 2020, 7, 7 ),
AssignedUserSelectionMode.PROVIDED,
newHashSet( "user-1", "user-2" ),
true,
1,
50,
false,
false,
true,
false,
newArrayList( "order-1" ) );
}
@Test
public void testGetFromUrlFailOnNonProvidedAndAssignedUsers()
{
exception.expect( IllegalQueryException.class );
exception.expectMessage( "Assigned User uid(s) cannot be specified if selectionMode is not PROVIDED" );
entityInstanceService.getFromUrl(
"query-test",
newHashSet( attrD.getUid(), attrE.getUid() ),
newHashSet( filtF.getUid(), filtG.getUid() ),
newHashSet( organisationUnit.getUid() ),
OrganisationUnitSelectionMode.DESCENDANTS,
programA.getUid(),
ProgramStatus.ACTIVE,
false,
getDate( 2019, 1, 1 ),
getDate( 2020, 1, 1 ),
"20",
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
getDate( 2019, 5, 5 ),
getDate( 2020, 5, 5 ),
trackedEntityTypeA.getUid(),
EventStatus.COMPLETED,
getDate( 2019, 7, 7 ),
getDate( 2020, 7, 7 ),
AssignedUserSelectionMode.CURRENT,
newHashSet( "user-1", "user-2" ),
true,
1,
50,
false,
false,
true,
false,
newArrayList( "order-1" ) );
}
}
|
package agentgui.core.project.transfer;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.agentgui.gui.ProjectNewOpenDialog;
import org.agentgui.gui.ProjectNewOpenDialog.ProjectAction;
import org.agentgui.gui.UiBridge;
import agentgui.core.application.Application;
import agentgui.core.application.Language;
import agentgui.core.common.CommonComponentFactory;
import agentgui.core.project.Project;
import agentgui.core.project.setup.SimulationSetup;
import agentgui.core.project.transfer.gui.ProjectExportDialog;
import de.enflexit.common.swing.ProgressMonitor;
import de.enflexit.common.transfer.ArchiveFileHandler;
import de.enflexit.common.transfer.RecursiveFolderCopier;
import de.enflexit.common.transfer.RecursiveFolderDeleter;
/**
* This class is responsible for exporting projects from AgentWorkbench.
*
* @author Nils Loose - DAWIS - ICB - University of Duisburg - Essen
*/
public class ProjectExportController {
private static final String FILE_NAME_FOR_INSTALLATION_PACKAGE = "agentgui";
private ProjectExportDialog projectExportDialog;
private Project project;
private ProjectExportSettings exportSettings;
private Path tempExportFolderPath;
private ProgressMonitor progressMonitor;
/**
* Constructor
*
* @param project The project to be exported
*/
public ProjectExportController(Project project) {
this.project = project;
}
/**
* Exports the current project. The export settings are requested from the user.
*/
public void exportProject() {
if (this.project == null) {
this.project = selectProjectForExport();
if (this.project == null) {
return;
}
}
this.projectExportDialog = new ProjectExportDialog(project);
if (projectExportDialog.isCanceled() == false) {
ProjectExportSettings exportSettings = projectExportDialog.getExportSettings();
JFileChooser chooser = this.getJFileChooser();
if (chooser.showSaveDialog(Application.getMainWindow()) == JFileChooser.APPROVE_OPTION) {
File targetFile = chooser.getSelectedFile();
Application.getGlobalInfo().setLastSelectedFolder(targetFile.getParentFile());
if (targetFile.exists() == true) {
String optionTitle = targetFile.getName() + ": " + Language.translate("Datei überschreiben?");
String optionMsg = Language.translate("Die Datei existiert bereits. Wollen Sie diese Datei überschreiben?");
int answer = JOptionPane.showConfirmDialog(Application.getMainWindow(), optionMsg, optionTitle, JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
targetFile.delete();
} else {
return;
}
}
this.exportSettings.setTargetFile(targetFile);
this.exportProject(exportSettings);
}
}
}
/**
* Exports the current project using the provided {@link ProjectExportSettings}
*
* @param exportSettings The {@link ProjectExportSettings}
*/
public void exportProject(ProjectExportSettings exportSettings) {
this.exportSettings = exportSettings;
ProjectExportThread exportThread = new ProjectExportThread();
exportThread.start();
}
/**
* Shows a dialog for project selection, loads the selected project
*
* @return the selected project
*/
private Project selectProjectForExport() {
String actionTitle = Language.translate("Projekt zum Export auswählen");
ProjectNewOpenDialog newProDia = UiBridge.getInstance().getProjectNewOpenDialog(Application.getGlobalInfo().getApplicationTitle() + ": " + actionTitle, ProjectAction.ExportProject);
newProDia.setVisible(true);
if (newProDia.isCanceled() == true) {
return null;
} else {
String projectSubFolder = newProDia.getProjectDirectory();
newProDia.close();
newProDia = null;
String projectFolderFullPath = Application.getGlobalInfo().getPathProjects() + projectSubFolder;
return Project.load(new File(projectFolderFullPath), false);
}
}
/**
* Creates and initialized a {@link JFileChooser} for selecting the export
* target
*
* @return the {@link JFileChooser}
*/
private JFileChooser getJFileChooser() {
String projectFileSuffix = Application.getGlobalInfo().getFileEndProjectZip();
FileNameExtensionFilter projectFileFilter = new FileNameExtensionFilter(Language.translate("Agent.GUI Projekt-Datei") + " (*." + projectFileSuffix + ")", projectFileSuffix);
FileNameExtensionFilter zipFileFilter = new FileNameExtensionFilter(Language.translate("Zip-Datei") + " (*.zip)", "zip");
FileNameExtensionFilter tarGzFileFilter = new FileNameExtensionFilter(Language.translate("Tar.gz-Datei") + " (*.tar.gz)", "tar.gz");
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.addChoosableFileFilter(projectFileFilter);
jFileChooser.addChoosableFileFilter(zipFileFilter);
jFileChooser.addChoosableFileFilter(tarGzFileFilter);
jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
jFileChooser.setMultiSelectionEnabled(false);
jFileChooser.setAcceptAllFileFilterUsed(false);
StringBuffer proposedFileName = new StringBuffer();
proposedFileName.append(Application.getGlobalInfo().getLastSelectedFolderAsString());
if (this.exportSettings.isIncludeInstallationPackage() == true) {
proposedFileName.append(FILE_NAME_FOR_INSTALLATION_PACKAGE);
if (this.exportSettings.getInstallationPackage().getPacakgeFile().getName().endsWith(".zip")) {
proposedFileName.append(".zip");
jFileChooser.setFileFilter(zipFileFilter);
} else {
proposedFileName.append(".tar.gz");
jFileChooser.setFileFilter(tarGzFileFilter);
}
} else {
proposedFileName.append(project.getProjectFolder() + '.' + Application.getGlobalInfo().getFileEndProjectZip());
jFileChooser.setFileFilter(projectFileFilter);
}
File proposedFile = new File(proposedFileName.toString());
jFileChooser.setSelectedFile(proposedFile);
jFileChooser.setCurrentDirectory(proposedFile);
return jFileChooser;
}
/**
* Copies all required project data to a temporary folder next to the selected
*
* @return Copying successful?
*/
private boolean copyProjectDataToTempFolder() {
Path sourcePath = new File(project.getProjectFolderFullPath()).toPath();
List<Path> skipList = new ArrayList<>();
skipList.add(sourcePath.resolve("~tmp"));
if (this.exportSettings.isIncludeAllSetups() == false) {
skipList.add(sourcePath.resolve("setups"));
skipList.add(sourcePath.resolve("setupsEnv"));
}
try {
Files.createDirectories(this.getTempExportFolderPath());
RecursiveFolderCopier rfc = CommonComponentFactory.getNewRecursiveFolderCopier();
rfc.copyFolder(sourcePath, this.getTempExportFolderPath(), skipList);
} catch (IOException e) {
System.err.println("Error copying project data!");
e.printStackTrace();
return false;
}
return true;
}
/**
* Copies the required files for the selected simulation setups. Based on a
* negative list approach, i.e. all files from the setup folders except those of
* the setups not being exported will be copied.
*
* @return Copying successful?
*/
private boolean copyRequiredSimulationSetupFiles() {
Path setupsSubFolderSourcePath = new File(project.getSubFolder4Setups(true)).toPath();
Path setupEnvironmentsSubFolderSourcePath = new File(project.getProjectFolder()).toPath().resolve(project.getEnvSetupPath());
Path setupsSubFolderTargetPath = this.getTempExportFolderPath().resolve(project.getSubFolder4Setups(false));
Path setupEnvironmentsSubFolderTargetPath = this.getTempExportFolderPath().resolve(project.getEnvSetupPath(false));
try {
if (setupsSubFolderTargetPath.toFile().exists() == false) {
Files.createDirectory(setupsSubFolderTargetPath);
}
if (setupEnvironmentsSubFolderTargetPath.toFile().exists() == false) {
Files.createDirectory(setupEnvironmentsSubFolderTargetPath);
}
} catch (IOException e) {
System.err.println("Error creating supfolders for simulation setups!");
e.printStackTrace();
return false;
}
List<String> setupsNegativeList = new ArrayList<>(this.project.getSimulationSetups().keySet());
setupsNegativeList.removeAll(this.exportSettings.getSimSetups());
List<String> setupFilesNegativeList = new ArrayList<>();
List<String> environmentFilesNegativeList = new ArrayList<>();
for (String excludedSetupName : setupsNegativeList) {
SimulationSetup excludedSetup = null;
try {
excludedSetup = this.loadSimSetup(excludedSetupName);
} catch (JAXBException | IOException e) {
System.err.println("Error loading simulation setup data!");
e.printStackTrace();
return false;
}
if (excludedSetup != null) {
String setupFileName = this.project.getSimulationSetups().get(excludedSetupName);
String setupFileBaseName = setupFileName.substring(0, setupFileName.lastIndexOf('.'));
setupFilesNegativeList.add(setupFileBaseName);
String envFileName = excludedSetup.getEnvironmentFileName();
String setupEnvironmentFileBaseName = envFileName.substring(0, envFileName.lastIndexOf('.'));
environmentFilesNegativeList.add(setupEnvironmentFileBaseName);
}
}
try {
FileBaseNameNegativeListFilter setupFilesNegativeListFilter = new FileBaseNameNegativeListFilter(setupFilesNegativeList);
DirectoryStream<Path> setupDirectoryStream = Files.newDirectoryStream(setupsSubFolderSourcePath, setupFilesNegativeListFilter);
for (Path sourcePath : setupDirectoryStream) {
Path targetPath = setupsSubFolderTargetPath.resolve(sourcePath.getFileName());
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
}
FileBaseNameNegativeListFilter environmentFIlesNegativeListFilter = new FileBaseNameNegativeListFilter(environmentFilesNegativeList);
DirectoryStream<Path> setupEnvironmentDirectoryStream = Files.newDirectoryStream(setupEnvironmentsSubFolderSourcePath, environmentFIlesNegativeListFilter);
for (Path sourcePath : setupEnvironmentDirectoryStream) {
Path targetPath = setupEnvironmentsSubFolderTargetPath.resolve(sourcePath.getFileName());
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
System.err.println("Error copying simulation setup files");
e.printStackTrace();
return false;
}
return true;
}
/**
* Loads the simulation setup with the specified name
*
* @param setupName The setup to be loaded
* @return The setup
* @throws JAXBException Parsing the setup file failed
* @throws IOException Reading the setup file failed
*/
private SimulationSetup loadSimSetup(String setupName) throws JAXBException, IOException {
String setupFileName = this.project.getSimulationSetups().get(setupName);
String setupFileFullPath = this.project.getSubFolder4Setups(true) + File.separator + setupFileName;
File setupFile = new File(setupFileFullPath);
JAXBContext pc;
SimulationSetup simSetup = null;
pc = JAXBContext.newInstance(this.project.getSimulationSetups().getCurrSimSetup().getClass());
Unmarshaller um = pc.createUnmarshaller();
FileReader fr = new FileReader(setupFile);
simSetup = (SimulationSetup) um.unmarshal(fr);
fr.close();
return simSetup;
}
/**
* Removes all setups that are not selected for export from the setup list
*/
private void removeUnexportedSetupsFromList() {
Project exportedProject = Project.load(this.tempExportFolderPath.toFile(), false);
Set<String> setupNames = new HashSet<>(exportedProject.getSimulationSetups().keySet());
for (String setupName : setupNames) {
if (exportSettings.getSimSetups().contains(setupName) == false) {
exportedProject.getSimulationSetups().remove(setupName);
}
}
if (this.exportSettings.getSimSetups().contains(exportedProject.getSimulationSetupCurrent()) == false) {
exportedProject.setSimulationSetupCurrent(this.exportSettings.getSimSetups().get(0));
}
exportedProject.save(this.tempExportFolderPath.toFile(), false);
}
/**
* Gets the temporary export folder path
*
* @return the temporary export folder path
*/
private Path getTempExportFolderPath() {
if (tempExportFolderPath == null) {
File targetFile = this.exportSettings.getTargetFile();
Path containingFolder = targetFile.getParentFile().toPath();
tempExportFolderPath = containingFolder.resolve(project.getProjectFolder());
}
return this.tempExportFolderPath;
}
/**
*
* @return
*/
private boolean integrateProjectIntoInstallationPackage() {
File installationPackageFile = this.exportSettings.getInstallationPackage().getPacakgeFile();
try {
ArchiveFileHandler newZipper = new ArchiveFileHandler();
newZipper.appendFolderToArchive(tempExportFolderPath.toFile(), installationPackageFile, exportSettings.getTargetFile(), "agentgui/projects");
} catch (IOException e) {
System.err.println("Error integrating project into installation package!");
e.printStackTrace();
return false;
}
return true;
}
/**
* Gets the progress monitor.
*
* @return the progress monitor
*/
private ProgressMonitor getProgressMonitor() {
if (this.progressMonitor == null) {
String title = Language.translate("Projekt-Export");
String header = Language.translate("Exportiere Projekt") + " " + project.getProjectName();
String progress = Language.translate("Exportiere") + "...";
this.progressMonitor = CommonComponentFactory.getNewProgressMonitor(title, header, progress);
}
return this.progressMonitor;
}
/**
* Updates the progress monitor.
*
* @param currentProgress the current progress
*/
private void updateProgressMonitor(int currentProgress) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
getProgressMonitor().setProgress(currentProgress);
if (getProgressMonitor().isVisible() == false) {
getProgressMonitor().setVisible(true);
getProgressMonitor().validate();
getProgressMonitor().repaint();
}
}
});
}
/**
* Disposes the progress monitor.
*/
private void disposeProgressMonitor() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
getProgressMonitor().setVisible(false);
getProgressMonitor().dispose();
}
});
}
/**
* This {@link DirectoryStream.Filter} implementation matches all directory
* entries whose file base name (without extension) is not contained in a
* negative list.
*
* @author Nils Loose - DAWIS - ICB - University of Duisburg - Essen
*/
private class FileBaseNameNegativeListFilter implements DirectoryStream.Filter<Path> {
private List<String> negativeList;
/**
* Constructor
*
* @param negativeList the negative list
*/
public FileBaseNameNegativeListFilter(List<String> negativeList) {
this.negativeList = negativeList;
}
@Override
public boolean accept(Path entry) throws IOException {
String fileBaseName = entry.toFile().getName().substring(0, entry.toFile().getName().lastIndexOf('.'));
if (negativeList.contains(fileBaseName)) {
return false;
} else {
return true;
}
}
}
/**
* This Thread does the actual export.
*
* @author Nils Loose - DAWIS - ICB - University of Duisburg - Essen
*/
private class ProjectExportThread extends Thread {
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
ProjectExportController.this.updateProgressMonitor(0);
boolean success = ProjectExportController.this.copyProjectDataToTempFolder();
ProjectExportController.this.updateProgressMonitor(10);
if (success == true) {
if (ProjectExportController.this.exportSettings.isIncludeAllSetups() == false) {
success = ProjectExportController.this.copyRequiredSimulationSetupFiles();
if (success == true) {
ProjectExportController.this.removeUnexportedSetupsFromList();
}
}
ProjectExportController.this.updateProgressMonitor(30);
if (ProjectExportController.this.exportSettings.isIncludeInstallationPackage()) {
success = ProjectExportController.this.integrateProjectIntoInstallationPackage();
} else {
ArchiveFileHandler newZipper = new ArchiveFileHandler();
success = newZipper.compressFolder(tempExportFolderPath.toFile(), ProjectExportController.this.exportSettings.getTargetFile());
}
ProjectExportController.this.updateProgressMonitor(80);
try {
RecursiveFolderDeleter folderDeleter = CommonComponentFactory.getNewRecursiveFolderDeleter();
folderDeleter.deleteFolder(tempExportFolderPath);
} catch (IOException e) {
System.err.println("Error deleting temoprary export folder");
e.printStackTrace();
}
ProjectExportController.this.updateProgressMonitor(100);
ProjectExportController.this.disposeProgressMonitor();
if (success == true) {
System.out.println("Project " + project.getProjectName() + " export successful!");
String messageTitle = Language.translate("Export erfolgreich");
String messageContent = Language.translate("Projekt") + " " + project.getProjectName() + " " + Language.translate("erfolgreich exportiert!");
JOptionPane.showMessageDialog(null, messageContent, messageTitle, JOptionPane.INFORMATION_MESSAGE);
} else {
System.err.println("Project " + project.getProjectName() + " export failed!");
String message = Language.translate("Export fehlgeschlagen");
JOptionPane.showMessageDialog(null, message, message, JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
|
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.psi.*;
import com.intellij.psi.filters.*;
import com.intellij.psi.filters.classes.*;
import com.intellij.psi.filters.element.ExcludeDeclaredFilter;
import com.intellij.psi.filters.element.ModifierFilter;
import com.intellij.psi.filters.element.ReferenceOnFilter;
import com.intellij.psi.filters.getters.UpWalkGetter;
import com.intellij.psi.filters.position.*;
import com.intellij.psi.filters.types.TypeCodeFragmentIsVoidEnabledFilter;
import com.intellij.psi.impl.source.jsp.jspJava.JspClass;
import com.intellij.psi.jsp.JspElementType;
public class JavaCompletionData extends CompletionData{
protected static final String[] MODIFIERS_LIST = {
"public", "protected", "private",
"static", "final", "native",
"abstract", "synchronized", "volatile", "transient"
};
private static final String[] ourBlockFinalizers = {"{", "}", ";", ":", "else"};
public JavaCompletionData(){
declareCompletionSpaces();
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, TrueFilter.INSTANCE);
variant.includeScopeClass(PsiVariable.class);
variant.includeScopeClass(PsiClass.class);
variant.includeScopeClass(PsiFile.class);
variant.addCompletion(new ModifierChooser());
registerVariant(variant);
initVariantsInFileScope();
initVariantsInClassScope();
initVariantsInMethodScope();
initVariantsInFieldScope();
defineScopeEquivalence(PsiMethod.class, PsiClassInitializer.class);
defineScopeEquivalence(PsiMethod.class, PsiCodeFragment.class);
}
private void declareCompletionSpaces() {
declareFinalScope(PsiFile.class);
{
// Class body
final CompletionVariant variant = new CompletionVariant(CLASS_BODY);
variant.includeScopeClass(PsiClass.class, true);
this.registerVariant(variant);
}
{
// Method body
final CompletionVariant variant = new CompletionVariant(new InsideElementFilter(new ClassFilter(PsiCodeBlock.class)));
variant.includeScopeClass(PsiMethod.class, true);
variant.includeScopeClass(PsiClassInitializer.class, true);
this.registerVariant(variant);
}
{
// Field initializer
final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("=")));
variant.includeScopeClass(PsiField.class, true);
this.registerVariant(variant);
}
declareFinalScope(PsiLiteralExpression.class);
declareFinalScope(PsiComment.class);
}
protected void initVariantsInFileScope(){
// package keyword completion
{
final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new StartElementFilter());
variant.addCompletion(PsiKeyword.PACKAGE);
this.registerVariant(variant);
}
// import keyword completion
{
final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, new OrFilter(
new StartElementFilter(),
END_OF_BLOCK
));
variant.addCompletion(PsiKeyword.IMPORT);
this.registerVariant(variant);
}
// other in file scope
{
final ElementFilter position = new OrFilter(new ElementFilter[]{
END_OF_BLOCK,
new LeftNeighbour(new OrFilter(new SuperParentFilter(new ClassFilter(PsiAnnotation.class)),
new TextFilter(MODIFIERS_LIST))),
new StartElementFilter()
});
final CompletionVariant variant = new CompletionVariant(PsiJavaFile.class, position);
variant.includeScopeClass(PsiClass.class);
variant.addCompletion(PsiKeyword.CLASS);
variant.addCompletion(PsiKeyword.INTERFACE);
registerVariant(variant);
}
{
final CompletionVariant variant = new CompletionVariant(PsiTypeCodeFragment.class, new StartElementFilter());
addPrimitiveTypes(variant, TailType.NONE);
final CompletionVariant variant1 = new CompletionVariant(PsiTypeCodeFragment.class,
new AndFilter(
new StartElementFilter(),
new TypeCodeFragmentIsVoidEnabledFilter()
)
);
variant1.addCompletion(PsiKeyword.VOID, TailType.NONE);
registerVariant(variant);
registerVariant(variant1);
}
}
/**
* aClass == null for JspDeclaration scope
*/
protected void initVariantsInClassScope() {
// Completion for extends keyword
// position
{
final ElementFilter position = new AndFilter(new ElementFilter[]{
new NotFilter(CLASS_BODY),
new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))),
new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))),
new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))),
new NotFilter(new ScopeFilter(new EnumFilter())),
new LeftNeighbour(new OrFilter(
new ClassFilter(PsiIdentifier.class),
new TextFilter(">"))),
});
// completion
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiClass.class, true);
variant.addCompletion(PsiKeyword.EXTENDS);
variant.excludeScopeClass(PsiAnonymousClass.class);
variant.excludeScopeClass(PsiTypeParameter.class);
this.registerVariant(variant);
}
// Completion for implements keyword
// position
{
final ElementFilter position = new AndFilter(new ElementFilter[]{
new NotFilter(CLASS_BODY),
new NotFilter(new BeforeElementFilter(new ContentFilter(new TextFilter(PsiKeyword.EXTENDS)))),
new NotFilter(new AfterElementFilter(new ContentFilter(new TextFilter(PsiKeyword.IMPLEMENTS)))),
new NotFilter(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ",")))),
new LeftNeighbour(new OrFilter(
new ClassFilter(PsiIdentifier.class),
new TextFilter(">"))),
new NotFilter(new ScopeFilter(new InterfaceFilter()))
});
// completion
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiClass.class, true);
variant.addCompletion(PsiKeyword.IMPLEMENTS);
variant.excludeScopeClass(PsiAnonymousClass.class);
this.registerVariant(variant);
}
// Completion after extends in interface, type parameter and implements in class
// position
{
final ElementFilter position = new AndFilter(
new NotFilter(CLASS_BODY),
new OrFilter( new ElementFilter [] {
new AndFilter(
new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, ",")),
new ScopeFilter(new InterfaceFilter())
),
new AndFilter(
new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS, "&")),
new ScopeFilter(new ClassFilter(PsiTypeParameter.class))
),
new LeftNeighbour(new TextFilter(PsiKeyword.IMPLEMENTS, ","))
}
)
);
// completion
final OrFilter flags = new OrFilter();
flags.addFilter(new ThisOrAnyInnerFilter(
new AndFilter(new ElementFilter[]{
new ClassFilter(PsiClass.class),
new NotFilter(new AssignableFromContextFilter()),
new InterfaceFilter()
})
));
flags.addFilter(new ClassFilter(PsiPackage.class));
CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiClass.class, true);
variant.excludeScopeClass(PsiAnonymousClass.class);
variant.addCompletionFilterOnElement(flags);
this.registerVariant(variant);
}
// Completion for classes in class extends
// position
{
final ElementFilter position = new AndFilter(
new NotFilter(CLASS_BODY),
new AndFilter(new ElementFilter[]{
new LeftNeighbour(new TextFilter(PsiKeyword.EXTENDS)),
new ScopeFilter(new NotFilter(new InterfaceFilter()))
})
);
// completion
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiClass.class, true);
variant.excludeScopeClass(PsiAnonymousClass.class);
variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(
new AndFilter(new ElementFilter[]{
new ClassFilter(PsiClass.class),
new NotFilter(new AssignableFromContextFilter()),
new NotFilter(new InterfaceFilter()),
new ModifierFilter(PsiModifier.FINAL, false)
})
));
variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class));
this.registerVariant(variant);
}
{
// declaration start
// position
final CompletionVariant variant = new CompletionVariant(PsiClass.class, new AndFilter(
CLASS_BODY,
new OrFilter(
END_OF_BLOCK,
new LeftNeighbour(new OrFilter(
new TextFilter(MODIFIERS_LIST),
new SuperParentFilter(new ClassFilter(PsiAnnotation.class)),
new TokenTypeFilter(JavaTokenType.GT)))
)));
// completion
addPrimitiveTypes(variant);
variant.addCompletion(PsiKeyword.VOID);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class));
this.registerVariant(variant);
}
{
final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new LeftNeighbour(new TextFilter("<", ","))));
variant.includeScopeClass(PsiClass.class, true);
variant.addCompletion(PsiKeyword.EXTENDS, TailType.SPACE);
this.registerVariant(variant);
}
}
private void initVariantsInMethodScope() {
{
// parameters list completion
final CompletionVariant variant = new CompletionVariant(
new LeftNeighbour(new OrFilter(new TextFilter(new String[]{"(", ",", "final"}),
new SuperParentFilter(new ClassFilter(PsiAnnotation.class)))));
variant.includeScopeClass(PsiParameterList.class, true);
addPrimitiveTypes(variant);
variant.addCompletion(PsiKeyword.FINAL);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
this.registerVariant(variant);
}
// Completion for classes in method throws section
// position
{
final ElementFilter position = new LeftNeighbour(new AndFilter(
new TextFilter(")"),
new ParentElementFilter(new ClassFilter(PsiParameterList.class))));
// completion
CompletionVariant variant = new CompletionVariant(PsiMethod.class, position);
variant.addCompletion(PsiKeyword.THROWS);
this.registerVariant(variant);
//in annotation methods
variant = new CompletionVariant(PsiAnnotationMethod.class, position);
variant.addCompletion(PsiKeyword.DEFAULT);
this.registerVariant(variant);
}
{
// Completion for classes in method throws section
// position
final ElementFilter position = new AndFilter(
new LeftNeighbour(new TextFilter(PsiKeyword.THROWS, ",")),
new InsideElementFilter(new ClassFilter(PsiReferenceList.class))
);
// completion
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiMethod.class, true);
variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable")));
variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class));
this.registerVariant(variant);
}
{
// completion for declarations
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new OrFilter(END_OF_BLOCK, new LeftNeighbour(new TextFilter("final"))));
addPrimitiveTypes(variant);
variant.addCompletion(PsiKeyword.CLASS);
this.registerVariant(variant);
}
// Completion in cast expressions
{
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new AndFilter(
new TextFilter("("),
new ParentElementFilter(new OrFilter(
new ClassFilter(PsiParenthesizedExpression.class),
new ClassFilter(PsiTypeCastExpression.class))))));
addPrimitiveTypes(variant);
this.registerVariant(variant);
}
{
// instanceof keyword
final ElementFilter position = new LeftNeighbour(new OrFilter(new ElementFilter[]{
new ReferenceOnFilter(new ClassFilter(PsiVariable.class)),
new TextFilter("this"),
new AndFilter(new TextFilter(")"), new ParentElementFilter(new AndFilter(
new ClassFilter(PsiTypeCastExpression.class, false),
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiExpression.class)),
new ClassFilter(PsiExpression.class))))),
new AndFilter(new TextFilter("]"), new ParentElementFilter(new ClassFilter(PsiArrayAccessExpression.class)))
}));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiExpression.class, true);
variant.includeScopeClass(PsiMethod.class);
variant.addCompletionFilter(new FalseFilter());
variant.addCompletion(PsiKeyword.INSTANCEOF);
this.registerVariant(variant);
}
{
// after instanceof keyword
final ElementFilter position = new PreviousElementFilter(new TextFilter(PsiKeyword.INSTANCEOF));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiExpression.class, true);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
this.registerVariant(variant);
}
{
// after final keyword
final ElementFilter position = new AndFilter(new SuperParentFilter(new ClassFilter(PsiCodeBlock.class)),
new LeftNeighbour(new TextFilter(PsiKeyword.FINAL)));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiDeclarationStatement.class, true);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
addPrimitiveTypes(variant);
this.registerVariant(variant);
}
{
// Keyword completion in start of declaration
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, END_OF_BLOCK);
variant.addCompletion(PsiKeyword.THIS, TailType.NONE);
variant.addCompletion(PsiKeyword.SUPER, TailType.NONE);
addKeywords(variant);
this.registerVariant(variant);
}
{
// Keyword completion in returns
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(new TextFilter("return")));
variant.addCompletion(PsiKeyword.THIS, TailType.NONE);
variant.addCompletion(PsiKeyword.SUPER, TailType.NONE);
this.registerVariant(variant);
}
// Catch/Finnaly completion
{
final ElementFilter position = new LeftNeighbour(new AndFilter(
new TextFilter("}"),
new ParentElementFilter(new AndFilter(
new LeftNeighbour(new TextFilter("try")),
new ParentElementFilter(new ClassFilter(PsiTryStatement.class))))));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiCodeBlock.class, true);
variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.FINALLY, '{');
variant.addCompletionFilter(new FalseFilter());
this.registerVariant(variant);
}
// Catch/Finnaly completion
{
final ElementFilter position = new LeftNeighbour(new AndFilter(
new TextFilter("}"),
new ParentElementFilter(new AndFilter(
new LeftNeighbour(new NotFilter(new TextFilter("try"))),
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiTryStatement.class)),
new ParentElementFilter(new ClassFilter(PsiCatchSection.class)))
))));
final CompletionVariant variant = new CompletionVariant(position);
variant.includeScopeClass(PsiCodeBlock.class, false);
variant.addCompletion(PsiKeyword.CATCH, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.FINALLY, '{');
//variant.addCompletionFilter(new FalseFilter());
this.registerVariant(variant);
}
{
// Completion for catches
final CompletionVariant variant = new CompletionVariant(PsiTryStatement.class, new PreviousElementFilter(new AndFilter(
new ParentElementFilter(new ClassFilter(PsiTryStatement.class)),
new TextFilter("(")
)));
variant.includeScopeClass(PsiParameter.class);
variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable")));
variant.addCompletionFilterOnElement(new ClassFilter(PsiPackage.class));
this.registerVariant(variant);
}
// Completion for else expression
// completion
{
final ElementFilter position = new LeftNeighbour(
new OrFilter(
new AndFilter(new TextFilter("}"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 3)),
new AndFilter(new TextFilter(";"),new ParentElementFilter(new ClassFilter(PsiIfStatement.class), 2))
));
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position);
variant.addCompletion(PsiKeyword.ELSE);
this.registerVariant(variant);
}
{
// Super/This keyword completion
final ElementFilter position =
new LeftNeighbour(
new AndFilter(
new TextFilter("."),
new LeftNeighbour(
new ReferenceOnFilter(new GeneratorFilter(EqualsFilter.class, new UpWalkGetter(new ClassFilter(PsiClass.class))))
)));
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, position);
variant.includeScopeClass(PsiVariable.class);
variant.addCompletion(PsiKeyword.SUPER, TailType.DOT);
variant.addCompletion(PsiKeyword.THIS, TailType.DOT);
this.registerVariant(variant);
}
{
// Class field completion
final CompletionVariant variant = new CompletionVariant(PsiMethod.class, new LeftNeighbour(
new AndFilter(new TextFilter("."), new LeftNeighbour(new OrFilter(new ElementFilter[]{
new ReferenceOnFilter(new ClassFilter(PsiClass.class)),
new TextFilter(PRIMITIVE_TYPES),
new TextFilter("]")
})))));
variant.includeScopeClass(PsiVariable.class);
variant.addCompletion(PsiKeyword.CLASS, TailType.NONE);
this.registerVariant(variant);
}
{
// break completion
final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new OrFilter(
new ScopeFilter(new ClassFilter(PsiSwitchStatement.class)),
new InsideElementFilter(new ClassFilter(PsiBlockStatement.class)))));
variant.includeScopeClass(PsiForStatement.class, false);
variant.includeScopeClass(PsiForeachStatement.class, false);
variant.includeScopeClass(PsiWhileStatement.class, false);
variant.includeScopeClass(PsiDoWhileStatement.class, false);
variant.includeScopeClass(PsiSwitchStatement.class, false);
variant.addCompletion(PsiKeyword.BREAK);
this.registerVariant(variant);
}
{
// continue completion
final CompletionVariant variant = new CompletionVariant(new AndFilter(END_OF_BLOCK, new InsideElementFilter(new ClassFilter(PsiBlockStatement.class))));
variant.includeScopeClass(PsiForeachStatement.class, false);
variant.includeScopeClass(PsiForStatement.class, false);
variant.includeScopeClass(PsiWhileStatement.class, false);
variant.includeScopeClass(PsiDoWhileStatement.class, false);
variant.addCompletion(PsiKeyword.CONTINUE);
this.registerVariant(variant);
}
{
final CompletionVariant variant = new CompletionVariant(
new AndFilter(
END_OF_BLOCK,
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiSwitchLabelStatement.class)),
new LeftNeighbour(new OrFilter(
new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 2),
new AndFilter(new TextFilter(";", "}"),new ParentElementFilter(new ClassFilter(PsiSwitchStatement.class), 3)
))))));
variant.includeScopeClass(PsiSwitchStatement.class, true);
variant.addCompletion(PsiKeyword.CASE, TailType.SPACE);
variant.addCompletion(PsiKeyword.DEFAULT, ':');
this.registerVariant(variant);
}
{
// primitive arrays after new
final CompletionVariant variant = new CompletionVariant(PsiExpression.class, new LeftNeighbour(
new AndFilter(new TextFilter("new"), new LeftNeighbour(new NotFilter(new TextFilter(".", "throw")))))
);
variant.includeScopeClass(PsiNewExpression.class, true);
addPrimitiveTypes(variant);
variant.setItemProperty(LookupItem.BRACKETS_COUNT_ATTR, new Integer(1));
this.registerVariant(variant);
}
{
// after new
final CompletionVariant variant = new CompletionVariant(new LeftNeighbour(new TextFilter("new")));
variant.includeScopeClass(PsiNewExpression.class, true);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
this.registerVariant(variant);
}
{
final CompletionVariant variant = new CompletionVariant(new AndFilter(
new ScopeFilter(new ParentElementFilter(new ClassFilter(PsiThrowStatement.class))),
new ParentElementFilter(new ClassFilter(PsiNewExpression.class)))
);
variant.includeScopeClass(PsiNewExpression.class, false);
variant.addCompletionFilterOnElement(new ThisOrAnyInnerFilter(new InheritorFilter("java.lang.Throwable")));
this.registerVariant(variant);
}
{
// completion in reference parameters
final CompletionVariant variant = new CompletionVariant(TrueFilter.INSTANCE);
variant.includeScopeClass(PsiReferenceParameterList.class, true);
variant.addCompletionFilterOnElement(new ClassFilter(PsiClass.class));
this.registerVariant(variant);
}
{
// null completion
final CompletionVariant variant = new CompletionVariant(new NotFilter(new LeftNeighbour(new TextFilter("."))));
variant.addCompletion("null",TailType.NONE);
variant.includeScopeClass(PsiExpressionList.class);
this.registerVariant(variant);
}
}
private void initVariantsInFieldScope() {
{
// completion in initializer
final CompletionVariant variant = new CompletionVariant(new AfterElementFilter(new TextFilter("=")));
variant.includeScopeClass(PsiVariable.class, false);
variant.addCompletionFilterOnElement(new OrFilter(
new ClassFilter(PsiVariable.class, false),
new ExcludeDeclaredFilter(new ClassFilter(PsiVariable.class))
));
this.registerVariant(variant);
}
}
private static void addPrimitiveTypes(CompletionVariant variant){
addPrimitiveTypes(variant, CompletionVariant.DEFAULT_TAIL_TYPE);
}
private static void addPrimitiveTypes(CompletionVariant variant, int tailType){
variant.addCompletion(new String[]{
PsiKeyword.SHORT, PsiKeyword.BOOLEAN,
PsiKeyword.DOUBLE, PsiKeyword.LONG,
PsiKeyword.INT, PsiKeyword.FLOAT, PsiKeyword.CHAR
}, tailType);
}
private static void addKeywords(CompletionVariant variant){
variant.addCompletion(PsiKeyword.SWITCH, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.WHILE, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.FOR, TailType.LPARENTH);
variant.addCompletion(PsiKeyword.TRY, '{');
variant.addCompletion(PsiKeyword.THROW, TailType.SPACE);
variant.addCompletion(PsiKeyword.RETURN, TailType.SPACE);
variant.addCompletion(PsiKeyword.NEW, TailType.SPACE);
variant.addCompletion(PsiKeyword.ASSERT, TailType.SPACE);
}
static final AndFilter START_OF_CODE_FRAGMENT = new AndFilter(
new ScopeFilter(new AndFilter(
new ClassFilter(PsiCodeFragment.class),
new ClassFilter(PsiExpressionCodeFragment.class, false)
)),
new StartElementFilter()
);
static final ElementFilter END_OF_BLOCK = new OrFilter(
new AndFilter(
new LeftNeighbour(new OrFilter(new ElementFilter[]{
new TextFilter(ourBlockFinalizers),
new TextFilter("*/"),
new TokenTypeFilter(JspElementType.HOLDER_TEMPLATE_DATA),
new AndFilter(
new TextFilter(")"),
new NotFilter(
new OrFilter(
new ParentElementFilter(new ClassFilter(PsiExpressionList.class)),
new ParentElementFilter(new ClassFilter(PsiParameterList.class))
)
)
),
})),
new NotFilter(new TextFilter("."))
),
START_OF_CODE_FRAGMENT
);
private static final String[] PRIMITIVE_TYPES = new String[]{
PsiKeyword.SHORT, PsiKeyword.BOOLEAN,
PsiKeyword.DOUBLE, PsiKeyword.LONG,
PsiKeyword.INT, PsiKeyword.FLOAT,
PsiKeyword.VOID, PsiKeyword.CHAR, PsiKeyword.BYTE
};
private final static ElementFilter CLASS_BODY = new OrFilter(
new AfterElementFilter(new TextFilter("{")),
new ScopeFilter(new ClassFilter(JspClass.class)));
}
|
package com.intellij.openapi.vcs.changes;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diff.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.changes.ui.ChangeListChooser;
import com.intellij.openapi.vcs.changes.ui.ChangesListView;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.peer.PeerFactory;
import com.intellij.util.Alarm;
import com.intellij.util.IncorrectOperationException;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author max
*/
public class ChangeListManagerImpl extends ChangeListManager implements ProjectComponent, ChangeListOwner, JDOMExternalizable {
private Project myProject;
private final ProjectLevelVcsManager myVcsManager;
private static final String TOOLWINDOW_ID = "Changes";
private Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.OWN_THREAD);
private Alarm myRepaintAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
private boolean myInitilized = false;
private boolean myDisposed = false;
private final UnversionedFilesHolder myUnversionedFilesHolder = new UnversionedFilesHolder();
private final List<ChangeList> myChangeLists = new ArrayList<ChangeList>();
private ChangeList myDefaultChangelist;
private ChangesListView myView;
private JLabel myProgressLabel;
public ChangeListManagerImpl(final Project project, ProjectLevelVcsManager vcsManager) {
myProject = project;
myVcsManager = vcsManager;
myView = new ChangesListView(project);
}
public void projectOpened() {
if (myChangeLists.isEmpty()) {
final ChangeList list = ChangeList.createEmptyChangeList("Default");
myChangeLists.add(list);
setDefaultChangeList(list);
}
if (ApplicationManagerEx.getApplicationEx().isInternal()) {
StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() {
public void run() {
ToolWindowManager.getInstance(myProject).registerToolWindow(TOOLWINDOW_ID, createChangeViewComponent(), ToolWindowAnchor.BOTTOM);
myInitilized = true;
}
});
}
}
public void projectClosed() {
if (ApplicationManagerEx.getApplicationEx().isInternal()) {
myDisposed = true;
myUpdateAlarm.cancelAllRequests();
myRepaintAlarm.cancelAllRequests();
ToolWindowManager.getInstance(myProject).unregisterToolWindow(TOOLWINDOW_ID);
myView.dispose();
}
}
@NonNls
public String getComponentName() {
return "ChangeListManager";
}
public void initComponent() {
}
public void disposeComponent() {
}
private JComponent createChangeViewComponent() {
JPanel panel = new JPanel(new BorderLayout());
DefaultActionGroup group = new DefaultActionGroup();
RefreshAction refreshAction = new RefreshAction();
refreshAction.registerCustomShortcutSet(CommonShortcuts.getRerun(), panel);
AddChangeListAction newChangeListAction = new AddChangeListAction();
newChangeListAction.registerCustomShortcutSet(CommonShortcuts.getNew(), panel);
final RemoveChangeListAction removeChangeListAction = new RemoveChangeListAction();
removeChangeListAction.registerCustomShortcutSet(CommonShortcuts.DELETE, panel);
final ShowDiffAction diffAction = new ShowDiffAction();
diffAction.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_D,
SystemInfo.isMac
? KeyEvent.META_DOWN_MASK
: KeyEvent.CTRL_DOWN_MASK)),
panel);
final MoveChangesToAnotherListAction toAnotherListAction = new MoveChangesToAnotherListAction();
toAnotherListAction.registerCustomShortcutSet(CommonShortcuts.getMove(), panel);
group.add(refreshAction);
group.add(newChangeListAction);
group.add(removeChangeListAction);
group.add(new SetDefaultChangeListAction());
group.add(toAnotherListAction);
group.add(diffAction);
final ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("ChangeView", group, false);
panel.add(toolbar.getComponent(), BorderLayout.WEST);
panel.add(new JScrollPane(myView), BorderLayout.CENTER);
myProgressLabel = new JLabel();
panel.add(myProgressLabel, BorderLayout.NORTH);
myView.installDndSupport(this);
return panel;
}
private void updateProgressText(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myProgressLabel.setText(text);
}
});
}
public void scheduleUpdate() {
myUpdateAlarm.cancelAllRequests();
myUpdateAlarm.addRequest(new Runnable() {
public void run() {
if (myDisposed) return;
if (!myInitilized) {
scheduleUpdate();
return;
}
final List<VcsDirtyScope> scopes = ((VcsDirtyScopeManagerImpl)VcsDirtyScopeManager.getInstance(myProject)).retreiveScopes();
for (final VcsDirtyScope scope : scopes) {
updateProgressText(" Updating: " + scope.getScopeRoot().getPresentableUrl());
for (ChangeList list : getChangeLists()) {
if (myDisposed) return;
list.removeChangesInScope(scope);
}
myUnversionedFilesHolder.cleanScope(scope);
scheduleRefresh();
final AbstractVcs vcs = myVcsManager.getVcsFor(scope.getScopeRoot());
if (vcs != null) {
final ChangeProvider changeProvider = vcs.getChangeProvider();
if (changeProvider != null) {
changeProvider.getChanges(scope, new ChangelistBuilder() {
public void processChange(Change change) {
if (isUnder(change, scope)) {
try {
synchronized (myChangeLists) {
for (ChangeList list : myChangeLists) {
if (list == myDefaultChangelist) continue;
if (list.processChange(change)) return;
}
myDefaultChangelist.processChange(change);
}
}
finally {
scheduleRefresh();
}
}
}
public void processUnversionedFile(VirtualFile file) {
if (scope.belongsTo(PeerFactory.getInstance().getVcsContextFactory().createFilePathOn(file))) {
myUnversionedFilesHolder.addFile(file);
scheduleRefresh();
}
}
}, null); // TODO: make real indicator
}
}
}
updateProgressText("");
}
private boolean isUnder(final Change change, final VcsDirtyScope scope) {
final ContentRevision before = change.getBeforeRevision();
final ContentRevision after = change.getAfterRevision();
return before != null && scope.belongsTo(before.getFile()) || after != null && scope.belongsTo(after.getFile());
}
}, 300);
}
private void scheduleRefresh() {
myRepaintAlarm.cancelAllRequests();
myRepaintAlarm.addRequest(new Runnable() {
public void run() {
if (myDisposed) return;
myView.updateModel(getChangeLists(), new ArrayList<VirtualFile>(myUnversionedFilesHolder.getFiles()));
}
}, 100, ModalityState.NON_MMODAL);
}
@NotNull
public List<ChangeList> getChangeLists() {
synchronized (myChangeLists) {
return myChangeLists;
}
}
public ChangeList addChangeList(String name) {
synchronized (myChangeLists) {
final ChangeList list = ChangeList.createEmptyChangeList(name);
myChangeLists.add(list);
scheduleRefresh();
return list;
}
}
public void removeChangeList(ChangeList list) {
synchronized (myChangeLists) {
if (list.isDefault()) throw new RuntimeException(new IncorrectOperationException("Cannot remove default changelist"));
final Collection<Change> changes = list.getChanges();
for (Change change : changes) {
myDefaultChangelist.addChange(change);
}
myChangeLists.remove(list);
scheduleRefresh();
}
}
public void setDefaultChangeList(ChangeList list) {
synchronized (myChangeLists) {
if (myDefaultChangelist != null) myDefaultChangelist.setDefault(false);
list.setDefault(true);
myDefaultChangelist = list;
scheduleRefresh();
}
}
public class RefreshAction extends AnAction {
public RefreshAction() {
super("Refresh", "Refresh VCS changes", IconLoader.getIcon("/actions/sync.png"));
}
public void actionPerformed(AnActionEvent e) {
VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
}
}
public class AddChangeListAction extends AnAction {
public AddChangeListAction() {
super("New ChangeList", "Create new changelist", IconLoader.getIcon("/actions/include.png"));
}
public void actionPerformed(AnActionEvent e) {
String rc = Messages.showInputDialog(myProject, "Enter new changelist name", "New ChangeList", Messages.getQuestionIcon());
if (rc != null) {
if (rc.length() == 0) {
rc = getUniqueName();
}
addChangeList(rc);
}
}
private String getUniqueName() {
int unnamedcount = 0;
for (ChangeList list : getChangeLists()) {
if (list.getDescription().startsWith("Unnamed")) {
unnamedcount++;
}
}
return unnamedcount == 0 ? "Unnamed" : "Unnamed (" + unnamedcount + ")";
}
}
public class SetDefaultChangeListAction extends AnAction {
public SetDefaultChangeListAction() {
super("Set Default", "Set default changelist", IconLoader.getIcon("/actions/submit1.png"));
}
public void update(AnActionEvent e) {
ChangeList[] lists = (ChangeList[])e.getDataContext().getData(DataConstants.CHANGE_LISTS);
e.getPresentation().setEnabled(lists != null && lists.length == 1 && !lists[0].isDefault());
}
public void actionPerformed(AnActionEvent e) {
setDefaultChangeList(((ChangeList[])e.getDataContext().getData(DataConstants.CHANGE_LISTS))[0]);
}
}
public class RemoveChangeListAction extends AnAction {
public RemoveChangeListAction() {
super("Remove Changelist", "Remove changelist and move all changes to default", IconLoader.getIcon("/actions/exclude.png"));
}
public void update(AnActionEvent e) {
ChangeList[] lists = (ChangeList[])e.getDataContext().getData(DataConstants.CHANGE_LISTS);
e.getPresentation().setEnabled(lists != null && lists.length == 1 && !lists[0].isDefault());
}
public void actionPerformed(AnActionEvent e) {
final ChangeList list = ((ChangeList[])e.getDataContext().getData(DataConstants.CHANGE_LISTS))[0];
int rc = list.getChanges().size() == 0 ? DialogWrapper.OK_EXIT_CODE :
Messages.showYesNoDialog(myProject,
"Are you sure want to remove changelist '" + list.getDescription() + "'?\n" +
"All changes will be moved to default changelist.",
"Remove Change List",
Messages.getQuestionIcon());
if (rc == DialogWrapper.OK_EXIT_CODE) {
removeChangeList(list);
}
}
}
public class MoveChangesToAnotherListAction extends AnAction {
public MoveChangesToAnotherListAction() {
super("Move to another list", "Move selected changes to another changelist", IconLoader.getIcon("/actions/fileStatus.png"));
}
public void update(AnActionEvent e) {
Change[] changes = (Change[])e.getDataContext().getData(DataConstants.CHANGES);
e.getPresentation().setEnabled(changes != null && changes.length > 0);
}
public void actionPerformed(AnActionEvent e) {
Change[] changes = (Change[])e.getDataContext().getData(DataConstants.CHANGES);
if (changes == null) return;
ChangeListChooser chooser = new ChangeListChooser(myProject, getChangeLists(), null);
chooser.show();
ChangeList resultList = chooser.getSelectedList();
if (resultList != null) {
moveChangesTo(resultList, changes);
}
}
}
public class ShowDiffAction extends AnAction {
public ShowDiffAction() {
super("Show Diff", "Show diff for selected change", IconLoader.getIcon("/actions/diff.png"));
}
public void update(AnActionEvent e) {
Change[] changes = (Change[])e.getDataContext().getData(DataConstants.CHANGES);
e.getPresentation().setEnabled(changes != null && changes.length == 1);
}
public void actionPerformed(AnActionEvent e) {
Change[] changes = (Change[])e.getDataContext().getData(DataConstants.CHANGES);
if (changes == null) return;
Change change = changes[0];
final DiffTool tool = DiffManager.getInstance().getDiffTool();
final ContentRevision bRev = change.getBeforeRevision();
final ContentRevision aRev = change.getAfterRevision();
if (bRev != null && bRev.getFile().getFileType().isBinary() || aRev != null && aRev.getFile().getFileType().isBinary()) {
return;
}
String title = bRev != null ? bRev.getFile().getPath() : aRev != null ? aRev.getFile().getPath() : "Unknown diff";
final SimpleDiffRequest diffReq = new SimpleDiffRequest(myProject, title);
diffReq.setContents(createContent(bRev), createContent(aRev));
diffReq.setContentTitles("Base version", "Your version");
tool.show(diffReq);
}
private DiffContent createContent(ContentRevision revision) {
if (revision == null) return new SimpleContent("");
if (revision instanceof CurrentContentRevision) {
final CurrentContentRevision current = (CurrentContentRevision)revision;
final VirtualFile vFile = current.getVirtualFile();
return vFile != null ? new FileContent(myProject, vFile) : new SimpleContent("");
}
SimpleContent content = new SimpleContent(revision.getContent(), revision.getFile().getFileType());
content.setReadOnly(true);
return content;
}
}
public void moveChangesTo(final ChangeList list, final Change[] changes) {
for (ChangeList existingList : getChangeLists()) {
for (Change change : changes) {
existingList.removeChange(change);
}
}
for (Change change : changes) {
list.addChange(change);
}
scheduleRefresh();
}
@SuppressWarnings({"unchecked"})
public void readExternal(Element element) throws InvalidDataException {
final List<Element> listNodes = (List<Element>)element.getChildren("list");
for (Element listNode : listNodes) {
ChangeList list = addChangeList(listNode.getAttributeValue("name"));
final List<Element> changeNodes = (List<Element>)listNode.getChildren("change");
for (Element changeNode : changeNodes) {
try {
list.addChange(readChange(changeNode));
}
catch (OutdatedFakeRevisionException e) {
// Do nothing. Just skip adding outdated revisions to the list.
}
}
if ("true".equals(listNode.getAttributeValue("default"))) {
setDefaultChangeList(list);
}
}
if (myChangeLists.size() > 0 && myDefaultChangelist == null) {
setDefaultChangeList(myChangeLists.get(0));
}
}
public void writeExternal(Element element) throws WriteExternalException {
for (ChangeList list : getChangeLists()) {
Element listNode = new Element("list");
element.addContent(listNode);
if (list.isDefault()) {
listNode.setAttribute("default", "true");
}
listNode.setAttribute("name", list.getDescription());
for (Change change : list.getChanges()) {
writeChange(listNode, change);
}
}
}
private void writeChange(final Element listNode, final Change change) {
Element changeNode = new Element("change");
listNode.addContent(changeNode);
changeNode.setAttribute("type", change.getType().name());
final ContentRevision bRev = change.getBeforeRevision();
final ContentRevision aRev = change.getAfterRevision();
changeNode.setAttribute("beforePath", bRev != null ? bRev.getFile().getPath() : "");
changeNode.setAttribute("afterPath", aRev != null ? aRev.getFile().getPath() : "");
}
private Change readChange(Element changeNode) throws OutdatedFakeRevisionException {
String bRev = changeNode.getAttributeValue("beforePath");
String aRev = changeNode.getAttributeValue("afterPath");
return new Change(StringUtil.isEmpty(bRev) ? null : new FakeRevision(bRev), StringUtil.isEmpty(aRev) ? null : new FakeRevision(aRev));
}
private static final class OutdatedFakeRevisionException extends Exception {}
private static class FakeRevision implements ContentRevision {
private final FilePath myFile;
public FakeRevision(String path) throws OutdatedFakeRevisionException {
final FilePath file = PeerFactory.getInstance().getVcsContextFactory().createFilePathOn(new File(path));
if (file == null) throw new OutdatedFakeRevisionException();
myFile = file;
}
@Nullable
public String getContent() { return null; }
@NotNull
public FilePath getFile() {
return myFile;
}
}
}
|
package es.um.nosql.schemainference.json2dbschema.process;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.PrimitiveIterator.OfInt;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang3.tuple.Pair;
import es.um.nosql.schemainference.NoSQLSchema.Aggregate;
import es.um.nosql.schemainference.NoSQLSchema.Attribute;
import es.um.nosql.schemainference.NoSQLSchema.NoSQLSchemaFactory;
import es.um.nosql.schemainference.NoSQLSchema.Entity;
import es.um.nosql.schemainference.NoSQLSchema.EntityVersion;
import es.um.nosql.schemainference.NoSQLSchema.NoSQLSchema;
import es.um.nosql.schemainference.NoSQLSchema.PrimitiveType;
import es.um.nosql.schemainference.NoSQLSchema.Property;
import es.um.nosql.schemainference.NoSQLSchema.Reference;
import es.um.nosql.schemainference.NoSQLSchema.Tuple;
import es.um.nosql.schemainference.NoSQLSchema.Type;
import es.um.nosql.schemainference.json2dbschema.intermediate.raw.ArraySC;
import es.um.nosql.schemainference.json2dbschema.intermediate.raw.BooleanSC;
import es.um.nosql.schemainference.json2dbschema.intermediate.raw.NullSC;
import es.um.nosql.schemainference.json2dbschema.intermediate.raw.NumberSC;
import es.um.nosql.schemainference.json2dbschema.intermediate.raw.ObjectSC;
import es.um.nosql.schemainference.json2dbschema.intermediate.raw.SchemaComponent;
import es.um.nosql.schemainference.json2dbschema.intermediate.raw.StringSC;
import es.um.nosql.schemainference.json2dbschema.process.util.ReferenceMatcher;
import es.um.nosql.schemainference.json2dbschema.util.inflector.Inflector;
/**
* @author dsevilla
*
*/
public class NoSQLModelBuilder
{
private NoSQLSchemaFactory factory;
// Reverse indexes for finding EntityVersions
private Map<SchemaComponent, EntityVersion> mEntityVersions;
// List of Entities
private List<Entity> mEntities;
// Reference matcher
ReferenceMatcher<Entity> rm;
private String name;
public NoSQLModelBuilder(NoSQLSchemaFactory factory2, String name2)
{
factory = factory2;
name = name2;
mEntities = new ArrayList<Entity>(20);
mEntityVersions = new HashMap<SchemaComponent, EntityVersion>();
}
public NoSQLSchema build(Map<String, List<SchemaComponent>> rawEntities)
{
// TODO: Identify objects that are references in the form of MongoDB
// references: https://docs.mongodb.org/manual/reference/database-references/#dbrefs
// { "$ref" : <type>, "$id" : <value>, "$db" : <value> }
// Build reverse indices & Create Entities & Populate with EntityVersions
rawEntities.forEach((entityName, schemas) -> {
// Entity creation
Entity e = factory.createEntity();
e.setName(entityName);
mEntities.add(e);
OfInt n = IntStream.iterate(1, i -> i+1).iterator();
schemas.forEach(schema -> {
EntityVersion theEV = factory.createEntityVersion();
theEV.setVersionId(n.next());
// Set the root flag. It is needed to know which
// entities can be destination of a reference
ObjectSC obj = (ObjectSC)schema;
theEV.setRoot(obj.isRoot);
e.getEntityversions().add(theEV);
mEntityVersions.put(schema, theEV);
});
});
// Consider as reference matcher only those Entities of which
// at least one version is root
rm = createReferenceMatcher();
// Populate empty EntityVersions
mEntityVersions.forEach((schema, ev) -> fillEV(schema, ev));
// Opposite references
mEntities.forEach(eFrom -> {
eFrom.getEntityversions().forEach(ev -> {
ev.getProperties().stream().filter(p -> p instanceof Reference).forEach(r -> {
Reference ref = (Reference)r;
Entity eTo = ref.getRefTo();
// Find a EntityVersion of eTo that has a reference to the
// current Entity eFrom
Optional<Property> refTo =
eTo.getEntityversions().stream().flatMap(evTo ->
evTo.getProperties().stream().filter(pTo -> pTo instanceof Reference))
.filter(rTo -> ((Reference)rTo).getRefTo() == eFrom).findFirst();
refTo.ifPresent(r_ -> ref.setOpposite((Reference)r_));
});
});
});
NoSQLSchema finalSchema = factory.createNoSQLSchema();
finalSchema.setName(name);
finalSchema.getEntities().addAll(mEntities);
return finalSchema;
}
private ReferenceMatcher<Entity> createReferenceMatcher()
{
return
new ReferenceMatcher<Entity>(mEntities.stream()
.filter(e -> e.getEntityversions().stream().anyMatch(EntityVersion::isRoot))
.map(e ->
Pair.of(Arrays.stream(new String[]{
e.getName(),
Inflector.getInstance().pluralize(e.getName()),
Inflector.getInstance().singularize(e.getName())
}, e)));
}
private void fillEV(SchemaComponent schema, EntityVersion ev)
{
assert(schema instanceof ObjectSC);
ObjectSC obj = (ObjectSC)schema;
// Set properties
ev.getProperties().addAll(obj.getInners().stream()
.map(p -> propertyFromSchemaComponent(p.getLeft(), p.getRight())).collect(Collectors.toList()));
}
private Property propertyFromSchemaComponent(String en, SchemaComponent sc)
{
if (sc instanceof ObjectSC)
return propertyFromSchemaComponent(en, (ObjectSC)sc);
if (sc instanceof ArraySC)
return propertyFromSchemaComponent(en, (ArraySC)sc);
if (sc instanceof BooleanSC)
return propertyFromSchemaComponent(en, (BooleanSC)sc);
if (sc instanceof NumberSC)
return propertyFromSchemaComponent(en, (NumberSC)sc);
if (sc instanceof NullSC)
return propertyFromSchemaComponent(en, (NullSC)sc);
if (sc instanceof StringSC)
return propertyFromSchemaComponent(en, (StringSC)sc);
return null;
}
private Property propertyFromSchemaComponent(String en, ObjectSC sc)
{
// TODO: Check for complex DBRef references
// Note that at this point, there is no need to recursively explore inner objects
// as they have been all put at the root level in the previous phase.
Aggregate a = factory.createAggregate();
a.setName(en);
a.setLowerBound(1);
a.setUpperBound(1);
a.getRefTo().add(mEntityVersions.get(sc));
return a;
}
private Property propertyFromSchemaComponent(String en, ArraySC sc)
{
if (sc.isHomogeneous())
{
// If it is empty or it is NOT an Object (it is a simple type),
// then it may be a reference
if (sc.size() == 0 || !(sc.getInners().get(0) instanceof ObjectSC))
{
return maybeReference(Inflector.getInstance().singularize(en), sc).map(p -> {
Reference ref = (Reference)p;
ref.setName(en);
// All arrays that come from a real array are signaled by a 0 lower bound
//ref.setLowerBound(sc.getLowerBounds() == 1 ? 0 : sc.getLowerBounds());
//ref.setUpperBound(sc.getUpperBounds() > 1 ? -1 : sc.getUpperBounds());
ref.setLowerBound(0);
ref.setUpperBound(-1);
return p;
}).orElseGet(() -> {
// Or else build a tuple with the correct types
Attribute a = factory.createAttribute();
a.setName(en);
a.setType(tupleForArray(sc));
return a;
});
}
else
{
// size is not 0 and the homogeneous type is an object
Aggregate a = factory.createAggregate();
a.setName(en);
a.setLowerBound(sc.getLowerBounds() == 1 ? 0 : sc.getLowerBounds());
a.setUpperBound(sc.getUpperBounds() > 1 ? -1 : sc.getUpperBounds());
a.getRefTo().add(mEntityVersions.get(sc.getInners().get(0)));
return a;
}
}
// Non-homogeneous array. If all elements are objects, then
// create an aggregate. If not, create a tuple
EntityVersion ev = mEntityVersions.get(sc.getInners().get(0));
if (ev != null)
{
Aggregate a = factory.createAggregate();
a.setName(en);
a.setLowerBound(0);
a.setUpperBound(sc.getUpperBounds() > 1 ? -1 : sc.getUpperBounds());
a.getRefTo().addAll(sc.getInners().stream()
.map(mEntityVersions::get)
.collect(Collectors.toList()));
return a;
}
else
{
// Or else build a tuple with the correct types
Attribute a = factory.createAttribute();
a.setName(en);
a.setType(tupleForArray(sc));
return a;
}
}
private Type tupleForArray(ArraySC sc) {
Tuple t = factory.createTuple();
if (sc.size() == 0)
return t;
Stream<SchemaComponent> ssc;
if (sc.isHomogeneous())
ssc = Collections.nCopies(sc.size(), sc.getInners().get(0)).stream();
else
ssc = sc.getInners().stream();
t.getElements().addAll(
ssc.map(_sc -> {
// Recursive
if (_sc instanceof ArraySC)
return tupleForArray((ArraySC)_sc);
String primType = "";
// TODO: Consider Objects?
if (_sc instanceof BooleanSC)
primType = "Boolean";
if (_sc instanceof NumberSC)
primType = "Number";
if (_sc instanceof StringSC)
primType = "String";
PrimitiveType pt = factory.createPrimitiveType();
pt.setName(primType);
return pt;
}).collect(Collectors.toList()));
return t;
}
private Property propertyFromSchemaComponent(String en, NullSC sc)
{
return propertyFromPrimitive(en, sc, "Null");
}
private Property propertyFromSchemaComponent(String en, NumberSC sc)
{
return propertyFromPrimitive(en, sc, "Number");
}
private Property propertyFromSchemaComponent(String en, StringSC sc)
{
return propertyFromPrimitive(en, sc, "String");
}
private Optional<Entity> idReferencesEntity(String id)
{
return rm.maybeMatch(id);
}
private Optional<Property> maybeReference(String en, SchemaComponent sc)
{
return idReferencesEntity(en).map(e -> {
Reference r = factory.createReference();
r.setName(en);
r.setRefTo(e);
r.setLowerBound(1);
r.setUpperBound(1);
return r;
});
}
private Property propertyFromSchemaComponent(String en, BooleanSC sc)
{
Attribute p = factory.createAttribute();
p.setName(en);
PrimitiveType pt = factory.createPrimitiveType();
pt.setName("Boolean");
p.setType(pt);
return p;
}
private Property propertyFromPrimitive(String en, SchemaComponent sc, String primitiveName)
{
return maybeReference(en, sc).orElseGet(() -> {
Attribute a = factory.createAttribute();
a.setName(en);
PrimitiveType pt = factory.createPrimitiveType();
pt.setName(primitiveName);
a.setType(pt);
return a;
});
}
}
|
package symboltable;
enum typeClass {
ENUM('e'),
VARIABLE('v'),
TYPE('t'),
FUNCTION('f');
char firstChar;
typeClass(char firstChar) {
this.firstChar = firstChar;
}
}
public class Symbol { // A generic programming language symbol
String identifier; // All symbols at least have a name
typeClass type;
typeClass[] arguments;
Scope scope; // All symbols know what scope contains them.
public static String generateSignature(String identifier, typeClass type, typeClass[] arguments) {
StringBuilder sb = new StringBuilder(type.firstChar);
sb.append(' ');
sb.append(identifier);
for (int i = 0; arguments != null && i < arguments.length; i++) {
sb.append(' ');
sb.append(arguments[i]);
}
return sb.toString();
}
public Symbol(String identifier, typeClass type, typeClass[] arguments) {
this.identifier = identifier;
this.type = type;
this.arguments = arguments;
}
public Symbol(String identifier, typeClass type) {
this(identifier, type, null);
}
public String getIdentifier() {
return this.identifier;
}
public typeClass getType() {
return this.type;
}
/**
* Deze moet uniek zijn voor twee verschillende functies/variables/enums/...
*/
public String toString() {
return Symbol.generateSignature(this.identifier, this.type, this.arguments);
}
}
|
package org.cagrid.redcap.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import gov.nih.nci.cagrid.cqlquery.Association;
import gov.nih.nci.cagrid.cqlquery.Attribute;
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.cqlquery.Group;
import gov.nih.nci.cagrid.cqlquery.LogicalOperator;
import gov.nih.nci.cagrid.cqlquery.Object;
import gov.nih.nci.cagrid.cqlquery.Predicate;
import gov.nih.nci.cagrid.cqlquery.QueryModifier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.cql.translator.cql1.hql320ga.ParameterizedHqlQuery;
import org.cagrid.cql.translator.cql1.hql320ga.QueryTranslationException;
import org.cagrid.cql.translator.cql1.hql320ga.TypesInformationException;
import org.cagrid.cql.translator.cql1.hql320ga.TypesInformationResolver;
/**
* CqlToHqlConverter
* Converter utility to turn CQL into HQL using positional parameters
* compatible with Hibernate 3.2.0ga
*
*/
public class CqlToHqlConverter{
public static final String TARGET_ALIAS = "__TargetAlias__";
private static Log LOG = LogFactory.getLog(CqlToHqlConverter.class);
// maps a CQL predicate to its HQL string representation
private Map<Predicate, String> predicateValues = null;
private TypesInformationResolver typesInformationResolver = null;
private boolean caseInsensitive;
public CqlToHqlConverter(TypesInformationResolver typesInfoResolver, boolean caseInsensitive) {
this.typesInformationResolver = typesInfoResolver;
this.caseInsensitive = caseInsensitive;
initPredicateValues();
}
private void initPredicateValues() {
predicateValues = new HashMap<Predicate, String>();
predicateValues.put(Predicate.EQUAL_TO, "=");
predicateValues.put(Predicate.GREATER_THAN, ">");
predicateValues.put(Predicate.GREATER_THAN_EQUAL_TO, ">=");
predicateValues.put(Predicate.LESS_THAN, "<");
predicateValues.put(Predicate.LESS_THAN_EQUAL_TO, "<=");
predicateValues.put(Predicate.LIKE, "LIKE");
predicateValues.put(Predicate.NOT_EQUAL_TO, "!=");
predicateValues.put(Predicate.IS_NOT_NULL, "is not null");
predicateValues.put(Predicate.IS_NULL, "is null");
}
/**
* Converts CQL to parameterized HQL suitable for use with
* Hibernate v3.2.0ga
*
* @param query
* The query to convert
* @return
* A parameterized HQL Query representing the CQL query
* @throws QueryTranslationException
*/
public ParameterizedHqlQuery convertToHql(CQLQuery query) throws QueryTranslationException {
// create a string builder to build up the HQL
StringBuilder rawHql = new StringBuilder();
// create the list in which parameters will be placed
List<java.lang.Object> parameters = new LinkedList<java.lang.Object>();
// determine if the target has subclasses
boolean hasSubclasses = false;
try {
hasSubclasses = typesInformationResolver.classHasSubclasses(query.getTarget().getName());
} catch (TypesInformationException ex) {
throw new QueryTranslationException(ex.getMessage(), ex);
}
LOG.debug(query.getTarget().getName()
+ (hasSubclasses ? " has subclasses" : " has no subclasse"));
// begin processing at the target level
processTarget(query.getTarget(), rawHql, parameters, hasSubclasses);
// apply query modifiers
if (query.getQueryModifier() != null) {
handleQueryModifier(query.getQueryModifier(), rawHql);
} else {
// select only unique objects
rawHql.insert(0, "Select distinct (" + TARGET_ALIAS + ") ");
}
// build the final query object
ParameterizedHqlQuery hqlQuery = new ParameterizedHqlQuery(rawHql.toString(), parameters);
return hqlQuery;
}
/**
* Applies query modifiers to the HQL query
*
* @param mods
* The modifiers to apply
* @param hql
* The HQL to apply the modifications to
*/
private void handleQueryModifier(QueryModifier mods, StringBuilder hql) {
StringBuilder prepend = new StringBuilder();
if (mods.isCountOnly()) {
prepend.append("select count(");
if (mods.getDistinctAttribute() != null) {
prepend.append("distinct ").append(TARGET_ALIAS).append(".")
.append(mods.getDistinctAttribute());
} else {
prepend.append("distinct " + TARGET_ALIAS + ".id");
}
prepend.append(')');
} else {
// select distinct tuples
prepend.append("select distinct ");
//REDCAP query modifier association query
prepend.append(TARGET_ALIAS);
prepend.append(".");
if (mods.getDistinctAttribute() != null) {
prepend.append(mods.getDistinctAttribute());
} else {
for (int i = 0; i < mods.getAttributeNames().length; i++) {
prepend.append(mods.getAttributeNames(i));
if (i + 1 < mods.getAttributeNames().length) {
prepend.append(", ");
prepend.append(TARGET_ALIAS);
prepend.append(".");
}
}
}
}
prepend.append(' ');
hql.insert(0, prepend.toString());
}
/**
* Processes the target object of a CQL query
*
* @param target
* The target of a CQL query
* @param hql
* The hql string builder to append to
* @param parameters
* The list of positional parameter values
* @param avoidSubclasses
* A flag to indicate the target has subclasses, which we should not return
* @throws QueryTranslationException
*/
private void processTarget(Object target, StringBuilder hql, List<java.lang.Object> parameters,
boolean avoidSubclasses) throws QueryTranslationException {
LOG.debug("Processing target " + target.getName());
// the stack of associations processed at the current depth of the query
Stack<Association> associationStack = new Stack<Association>();
// start the query
hql.append("From ").append(target.getName()).append(" as ").append(TARGET_ALIAS).append(' ');
if (target.getAssociation() != null) {
processAssociation(target.getAssociation(), hql, parameters, associationStack, target, TARGET_ALIAS);
}
if (target.getAttribute() != null) {
hql.append("where ");
processAttribute(target.getAttribute(), hql, parameters, target, TARGET_ALIAS);
}
if (target.getGroup() != null) {
if(target.getGroup().getAssociation()==null){
hql.append(" where ");
}
processGroup(target.getGroup(), hql, parameters, associationStack, target, TARGET_ALIAS);
}
if (avoidSubclasses) {
boolean mustAddWhereClause =
target.getAssociation() == null
&& target.getAttribute() == null
&& target.getGroup() == null;
if (mustAddWhereClause) {
hql.append(" where ");
} else {
hql.append(" and ");
}
hql.append(TARGET_ALIAS).append(".class = ?");
java.lang.Object classDiscriminatorInstance = null;
try {
classDiscriminatorInstance = typesInformationResolver.getClassDiscriminatorValue(target.getName());
} catch (TypesInformationException ex) {
String message = "Error determining class discriminator for " + target.getName() + ": " + ex.getMessage();
LOG.error(message, ex);
throw new QueryTranslationException(message, ex);
}
parameters.add(classDiscriminatorInstance);
}
}
/**
* Processes a CQL query attribute into HQL
*
* @param attribute
* The CQL attribute
* @param hql
* The HQL statement fragment
* @param parameters
* The positional parameters list
* @param associationTrace
* The trace of associations
* @param objectClassName
* The class name of the object to which this association belongs
* @throws QueryTranslationException
*/
private void processAttribute(Attribute attribute, StringBuilder hql,
List<java.lang.Object> parameters, Object queryObject, String queryObjectAlias) throws QueryTranslationException {
LOG.debug("Processing attribute " + queryObject.getName() + "." + attribute.getName());
// get the predicate, check for a default value
Predicate predicate = attribute.getPredicate();
if (predicate == null) {
predicate = Predicate.EQUAL_TO;
}
// determine if the predicate is unary
boolean unaryPredicate = predicate.equals(Predicate.IS_NOT_NULL)
|| predicate.equals(Predicate.IS_NULL);
// construct the query fragment
if (caseInsensitive) {
hql.append("lower(");
}
// append the path to the attribute itself
hql.append(queryObjectAlias).append('.').append(attribute.getName());
// close up case insensitivity
if (caseInsensitive) {
hql.append(')');
}
// append the predicate
hql.append(' ');
String predicateAsString = predicateValues.get(predicate);
if (!unaryPredicate) {
hql.append(predicateAsString).append(' ');
// add a placeholder parameter to the HQL query
hql.append('?');
// convert the attribute value to the specific data type of the attribute
Class<?> attributeType = null;
try {
attributeType = typesInformationResolver.getJavaDataType(queryObject.getName(), attribute.getName());
} catch (TypesInformationException ex) {
throw new QueryTranslationException(ex.getMessage(), ex);
}
if (attributeType == null) {
throw new QueryTranslationException("No type could be determined for attribute "
+ queryObject.getName() + "." + attribute.getName());
}
java.lang.Object value = valueToObject(attributeType,
caseInsensitive ? attribute.getValue().toLowerCase() : attribute.getValue());
// add a positional parameter value to the list
parameters.add(value);
} else {
// binary predicates just get appended w/o values associated with them
hql.append(predicateAsString);
}
}
/**
* Processes CQL associations into HQL
*
* @param association
* The CQL association
* @param hql
* The HQL fragment which will be edited
* @param parameters
* The positional HQL query parameters
* @param associationTrace
* The trace of associations
* @param sourceClassName
* The class name of the type to which this association belongs
* @throws QueryTranslationException
*/
private void processAssociation(Association association, StringBuilder hql, List<java.lang.Object> parameters,
Stack<Association> associationStack, Object sourceQueryObject, String sourceAlias) throws QueryTranslationException {
LOG.debug("Processing association " + sourceQueryObject.getName() + " to " + association.getName());
// get the association's role name
String roleName = null;
try {
roleName = typesInformationResolver.getRoleName(sourceQueryObject.getName(), association.getName());
} catch (TypesInformationException ex) {
throw new QueryTranslationException(ex.getMessage(), ex);
}
if (roleName == null) {
// still null?? no association to the object!
throw new QueryTranslationException("Association from type " + sourceQueryObject.getName() +
" to type " + association.getName() + " does not exist. Use only direct associations");
}
LOG.debug("Role name determined to be " + roleName);
// determine the alias for this association
String alias = getAssociationAlias(sourceQueryObject.getName(), association.getName(), roleName);
LOG.debug("Association alias determined to be " + alias);
// add this association to the stack
associationStack.push(association);
// flag indicates the query is only verifying the association is populated
boolean simpleNullCheck = true;
if (association.getAssociation() != null) {
simpleNullCheck = false;
hql.append(" join ");
// add clause to select things from this association
hql.append(sourceAlias).append('.').append(roleName);
hql.append(" as ");
hql.append("_").append(roleName).append("_");
hql.append(" where ");
hql.append("_").append(roleName).append("_");
hql.append(".id in (select ").append(alias).append(".id from ");
hql.append(association.getName()).append(" as ").append(alias);
processAssociation(association.getAssociation(), hql, parameters, associationStack, association, alias);
hql.append(") ");
}
if (association.getAttribute() != null) {
simpleNullCheck = false;
//REDCAP
hql.append(" join ");
hql.append(sourceAlias).append('.').append(roleName);
hql.append(" as ");
hql.append("_").append(roleName).append("_");
hql.append(" where ");
hql.append("_").append(roleName).append("_");
hql.append(".id in (select ").append(alias).append(".id from ");
hql.append(association.getName()).append(" as ").append(alias).append(" where ");
processAttribute(association.getAttribute(), hql, parameters, association, alias);
hql.append(") ");
}
if (association.getGroup() != null) {
hql.append(" join ");
simpleNullCheck = false;
hql.append(sourceAlias).append('.').append(roleName);
//REDCAP
hql.append(" as ").append(" b ");
hql.append(" where ").append(" b ");
hql.append(".id in (select ").append(alias).append(".id from ");
hql.append(association.getName()).append(" as ").append(alias);
//REDCAP
if(association.getGroup().getAssociation()==null){
hql.append(" where ");
}
hql.append(" ");
processGroup(association.getGroup(), hql, parameters, associationStack, association, alias);
hql.append(") ");
}
if (simpleNullCheck) {
// query is checking for the association to exist and be non-null
hql.append(" where ");
hql.append(sourceAlias).append('.').append(roleName).append(".id is not null ");
}
// pop this association off the stack
associationStack.pop();
LOG.debug(associationStack.size() + " associations remain on the stack");
}
/**
* Processes a CQL group into HQL
*
* @param group
* The CQL Group
* @param hql
* The HQL fragment which will be edited
* @param parameters
* The positional HQL query parameters
* @param associationTrace
* The trace of associations
* @param sourceClassName
* The class to which this group belongs
* @throws QueryTranslationException
*/
private void processGroup(Group group, StringBuilder hql, List<java.lang.Object> parameters,
Stack<Association> associationStack, Object sourceQueryObject, String sourceAlias) throws QueryTranslationException {
LOG.debug("Processing group on " + sourceQueryObject.getName());
String logic = convertLogicalOperator(group.getLogicRelation());
boolean mustAddLogic = false;
if (group.getAssociation() != null) {
boolean nestedAssociation = false;
//groups having multiple associations
LOG.debug("group association length"+group.getAssociation().length);
if(group.getAssociation().length>1){
for(int i=0;i<group.getAssociation().length;i++){
LOG.debug("Processing group association " + sourceQueryObject.getName() + " to " + group.getAssociation(i).getName());
// get the association's role name
String roleName = null;
try {
roleName = typesInformationResolver.getRoleName(sourceQueryObject.getName(), group.getAssociation(i).getName());
} catch (TypesInformationException ex) {
throw new QueryTranslationException(ex.getMessage(), ex);
}
if (roleName == null) {
// still null?? no association to the object!
throw new QueryTranslationException("Association from type " + sourceQueryObject.getName() +
" to type " + group.getAssociation(i).getName() + " does not exist. Use only direct associations");
}
LOG.debug("Role name determined to be " + roleName);
// determine the alias for this association
String alias = getAssociationAlias(sourceQueryObject.getName(), group.getAssociation(i).getName(), roleName);
LOG.debug("Association alias determined to be " + alias);
if(group.getAssociation(i).getAssociation()!=null){
nestedAssociation=true;
}
hql.append(" join ");
hql.append(sourceAlias).append('.').append(roleName);
hql.append(" as ");
hql.append(sourceAlias).append("_").append(roleName).append("_");
}
hql.append(" where ");
for(int i=0;i<group.getAssociation().length;i++){
mustAddLogic = true;
processGroupAssociations(group,group.getAssociation(i), hql, parameters, associationStack, sourceQueryObject, sourceAlias);
if (i + 1 < group.getAssociation().length) {
hql.append(' ').append(logic).append(' ');
}
}
}else{
//until here
for (int i = 0; i < group.getAssociation().length; i++) {
mustAddLogic = true;
processAssociation(group.getAssociation(i), hql, parameters, associationStack, sourceQueryObject, sourceAlias);
if (i + 1 < group.getAssociation().length) {
hql.append(' ').append(logic).append(' ');
}
}
}
}
if (group.getAttribute() != null) {
if (mustAddLogic) {
hql.append(' ').append(logic).append(' ');
}
for (int i = 0; i < group.getAttribute().length; i++) {
mustAddLogic = true;
processAttribute(group.getAttribute(i), hql, parameters, sourceQueryObject, sourceAlias);
if (i + 1 < group.getAttribute().length) {
hql.append(' ').append(logic).append(' ');
}
}
}
if (group.getGroup() != null) {
//hql.append(" join ");
if (mustAddLogic) {
hql.append(' ').append(logic).append(' ');
}
for (int i = 0; i < group.getGroup().length; i++) {
processGroup(group.getGroup(i), hql, parameters, associationStack, sourceQueryObject, sourceAlias);
if (i + 1 < group.getGroup().length) {
hql.append(' ').append(logic).append(' ');
}
}
}
}
/**
* Converts a logical operator to its HQL string equivalent.
*
* @param op
* The logical operator to convert
* @return
* The CQL logical operator as HQL
*/
private String convertLogicalOperator(LogicalOperator op) throws QueryTranslationException {
if (op.getValue().equals(LogicalOperator._AND)) {
return "AND";
} else if (op.getValue().equals(LogicalOperator._OR)) {
return "OR";
}
throw new QueryTranslationException("Logical operator '" + op.getValue() + "' is not recognized.");
}
// uses the class type to convert the value to a typed object
private java.lang.Object valueToObject(Class<?> fieldType, String value) throws QueryTranslationException {
LOG.debug("Converting \"" + value + "\" to object of type " + fieldType.getName());
if (String.class.equals(fieldType)) {
return value;
}
if (Integer.class.equals(fieldType)) {
return Integer.valueOf(value);
}
if (Long.class.equals(fieldType)) {
return Long.valueOf(value);
}
if (Double.class.equals(fieldType)) {
return Double.valueOf(value);
}
if (Float.class.equals(fieldType)) {
return Float.valueOf(value);
}
if (Boolean.class.equals(fieldType)) {
return Boolean.valueOf(value);
}
if (Character.class.equals(fieldType)) {
if (value.length() == 1) {
return Character.valueOf(value.charAt(0));
} else {
throw new QueryTranslationException("The value \"" + value + "\" of length "
+ value.length() + " is not a valid character");
}
}
if (Date.class.equals(fieldType)) {
// try time, then dateTime, then just date
List<SimpleDateFormat> formats = new ArrayList<SimpleDateFormat>(3);
formats.add(new SimpleDateFormat("HH:mm:ss"));
formats.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
formats.add(new SimpleDateFormat("yyyy-MM-dd"));
Date date = null;
Iterator<SimpleDateFormat> formatIter = formats.iterator();
while (date == null && formatIter.hasNext()) {
SimpleDateFormat formatter = formatIter.next();
try {
date = formatter.parse(value);
} catch (ParseException ex) {
LOG.debug(value + " was not parsable by pattern " + formatter.toPattern());
}
}
if (date == null) {
throw new QueryTranslationException("Unable to parse date value \"" + value + "\"");
}
return date;
}
throw new QueryTranslationException("No conversion for type " + fieldType != null ? fieldType.getName() : "null");
}
private String getAssociationAlias(String parentClassName, String associationClassName, String roleName) {
int dotIndex = parentClassName.lastIndexOf('.');
String parentShortName = dotIndex != -1 ? parentClassName.substring(dotIndex + 1) : parentClassName;
dotIndex = associationClassName.lastIndexOf('.');
String associationShortName = dotIndex != -1 ? associationClassName.substring(dotIndex + 1) : associationClassName;
String alias = "__" + parentShortName + "_" + associationShortName + "_" + roleName;
return alias;
}
//Groups having multiple associtations
private void processGroupAssociations(Group group, Association association, StringBuilder hql, List<java.lang.Object> parameters,
Stack<Association> associationStack, Object sourceQueryObject, String sourceAlias) throws QueryTranslationException {
LOG.debug("Processing group association " + sourceQueryObject.getName() + " to " + association.getName());
// get the association's role name
String roleName = null;
try {
roleName = typesInformationResolver.getRoleName(sourceQueryObject.getName(), association.getName());
} catch (TypesInformationException ex) {
throw new QueryTranslationException(ex.getMessage(), ex);
}
if (roleName == null) {
// still null?? no association to the object!
throw new QueryTranslationException("Association from type " + sourceQueryObject.getName() +
" to type " + association.getName() + " does not exist. Use only direct associations");
}
LOG.debug("Role name determined to be " + roleName);
// determine the alias for this association
String alias = getAssociationAlias(sourceQueryObject.getName(), association.getName(), roleName);
LOG.debug("Association alias determined to be " + alias);
// add this association to the stack
associationStack.push(association);
// flag indicates the query is only verifying the association is populated
boolean simpleNullCheck = true;
if (association.getAssociation() != null) {
simpleNullCheck = false;
hql.append(sourceAlias).append("_");
hql.append(roleName).append("_");
hql.append(".id in (select ").append(alias).append(".id from ");
hql.append(association.getName()).append(" as ").append(alias);//.append(" where ");
processAssociation(association.getAssociation(), hql, parameters, associationStack, association, alias);
hql.append(") ");
}
if (association.getAttribute() != null) {
simpleNullCheck = false;
hql.append(sourceAlias).append("_");
hql.append(roleName).append("_");
hql.append(".id in (select ").append(alias).append(".id from ");
hql.append(association.getName()).append(" as ").append(alias).append(" where ");
processAttribute(association.getAttribute(), hql, parameters, association, alias);
hql.append(") ");
}
if (association.getGroup() != null) {
// hql.append(" join ");
simpleNullCheck = false;
// hql.append(sourceAlias).append('.').append(roleName);
// //REDCAP
// hql.append(" as ").append(" b ");
// hql.append(" where ").append(" b ");
hql.append(sourceAlias).append("_");
hql.append(roleName).append("_");
hql.append(".id in (select ").append(alias).append(".id from ");
hql.append(association.getName()).append(" as ").append(alias);
if(association.getGroup().getAssociation()==null){
hql.append(" where ");
}
hql.append(" ");
processGroup(association.getGroup(), hql, parameters, associationStack, association, alias);
hql.append(") ");
}
if (simpleNullCheck) {
// query is checking for the association to exist and be non-null
hql.append(" where ");
hql.append(sourceAlias).append('.').append(roleName).append(".id is not null ");
}
// pop this association off the stack
associationStack.pop();
LOG.debug(associationStack.size() + " associations remain on the stack");
}
}
|
package org.innovateuk.ifs.glustermigration.service;
import org.innovateuk.ifs.commons.security.NotSecured;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.schedule.transactional.ScheduleResponse;
import java.io.IOException;
public interface GlusterMigrationService {
@NotSecured(value = "Gluster migration scheduler")
ServiceResult<ScheduleResponse> processGlusterFiles() throws IOException;
}
|
package com.worth.ifs.project.viewmodel;
import com.worth.ifs.competition.resource.CompetitionResource;
import com.worth.ifs.project.resource.MonitoringOfficerResource;
import com.worth.ifs.project.resource.ProjectResource;
import java.util.Optional;
/**
* A view model that backs the Project Status page
*/
public class ProjectSetupStatusViewModel {
private Long projectId;
private String projectName;
private Long applicationId;
private String competitionName;
private boolean projectDetailsSubmitted;
private boolean monitoringOfficerAssigned;
private String monitoringOfficerName;
public ProjectSetupStatusViewModel(ProjectResource project, CompetitionResource competition, Optional<MonitoringOfficerResource> monitoringOfficerResource) {
this.projectId = project.getId();
this.projectName = project.getName();
this.applicationId = project.getApplication();
this.competitionName = competition.getName();
this.projectDetailsSubmitted = project.isProjectDetailsSubmitted();
this.monitoringOfficerAssigned = monitoringOfficerResource.isPresent();
this.monitoringOfficerName = monitoringOfficerResource.map(mo -> mo.getFullName()).orElse("");
}
public Long getProjectId() {
return projectId;
}
public String getProjectName() {
return projectName;
}
public Long getApplicationId() {
return applicationId;
}
public String getCompetitionName() {
return competitionName;
}
public boolean isProjectDetailsSubmitted() {
return projectDetailsSubmitted;
}
public boolean isMonitoringOfficerAssigned() {
return monitoringOfficerAssigned;
}
public String getMonitoringOfficerName() {
return monitoringOfficerName;
}
}
|
// SimplePoolTest.java
package ed.util;
import org.testng.annotations.Test;
public class SimplePoolTest extends ed.TestCase {
class MyPool extends SimplePool<Integer> {
MyPool( int maxToKeep , int maxTotal ){
super( "blah" , maxToKeep , maxTotal );
}
public Integer createNew(){
return _num++;
}
int _num = 0;
}
@Test
public void testBasic1(){
MyPool p = new MyPool( 10 , 10 );
int a = p.get();
assertEquals( 0 , a );
int b = p.get();
assertEquals( 1 , b );
p.done( a );
a = p.get();
assertEquals( 0 , a );
}
@Test
public void testBasic2(){
MyPool p = new MyPool( 0 , 0 );
int a = p.get();
assertEquals( 0 , a );
int b = p.get();
assertEquals( 1 , b );
p.done( a );
a = p.get();
assertEquals( 2 , a );
}
@Test
public void testMax1(){
MyPool p = new MyPool( 10 , 2 );
int a = p.get();
assertEquals( 0 , a );
int b = p.get();
assertEquals( 1 , b );
assertNull( p.get( 0 ) );
}
@Test
public void testMax2(){
MyPool p = new MyPool( 10 , 3 );
int a = p.get();
assertEquals( 0 , a );
int b = p.get();
assertEquals( 1 , b );
assertEquals( 2 , (int)p.get( -1 ) );
}
@Test
public void testMax3(){
MyPool p = new MyPool( 10 , 3 );
int a = p.get();
assertEquals( 0 , a );
int b = p.get();
assertEquals( 1 , b );
assertEquals( 2 , (int)p.get( 1 ) );
}
public static void main( String args[] ){
SimplePoolTest t = new SimplePoolTest();
t.runConsole();
}
}
|
package common;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.Ignore;
import de.ust.skill.common.java.api.Access;
import de.ust.skill.common.java.api.FieldDeclaration;
import de.ust.skill.common.java.api.FieldType;
import de.ust.skill.common.java.api.GeneralAccess;
import de.ust.skill.common.java.api.SkillException;
import de.ust.skill.common.java.api.SkillFile;
import de.ust.skill.common.java.internal.SkillObject;
import de.ust.skill.common.java.internal.fieldDeclarations.AutoField;
import de.ust.skill.common.java.internal.fieldDeclarations.InterfaceField;
import de.ust.skill.common.java.internal.fieldTypes.ConstantIntegerType;
import de.ust.skill.common.java.internal.fieldTypes.ConstantLengthArray;
import de.ust.skill.common.java.internal.fieldTypes.SingleArgumentType;
/**
* Some test code commonly used by all tests.
*
* @author Timm Felden
*/
@Ignore
abstract public class CommonTest {
/**
* This constant is used to guide reflective init
*/
private static final int reflectiveInitSize = 10;
public CommonTest() {
super();
}
/**
* TODO move to common tests
*/
protected static Path tmpFile(String string) throws Exception {
File r = File.createTempFile(string, ".sf");
// r.deleteOnExit();
return r.toPath();
}
/**
* TODO move to common tests
*/
protected final static String sha256(String name) throws Exception {
return sha256(new File("src/test/resources/" + name).toPath());
}
/**
* TODO move to common tests
*/
protected final static String sha256(Path path) throws Exception {
byte[] bytes = Files.readAllBytes(path);
StringBuilder sb = new StringBuilder();
for (byte b : MessageDigest.getInstance("SHA-256").digest(bytes))
sb.append(String.format("%02X", b));
return sb.toString();
}
protected static void reflectiveInit(SkillFile sf) {
// create instances
sf.allTypesStream().parallel().forEach(t -> {
try {
for (int i = reflectiveInitSize; i != 0; i
t.make();
} catch (@SuppressWarnings("unused") SkillException e) {
// the type can not have more instances
}
});
// set fields
sf.allTypesStream().parallel().forEach(t -> {
for (SkillObject o : t) {
Iterator<? extends FieldDeclaration<?>> it = t.fields();
while (it.hasNext()) {
final FieldDeclaration<?> f = it.next();
if (!(f instanceof AutoField) && !(f.type() instanceof ConstantIntegerType<?>)
&& !(f instanceof InterfaceField))
set(sf, o, f);
}
}
});
}
private static <T, Obj extends SkillObject> void set(SkillFile sf, Obj o, FieldDeclaration<T> f) {
T v = value(sf, f.type());
// System.out.printf("%s#%d.%s = %s\n", o.getClass().getName(),
// o.getSkillID(), f.name(), v.toString());
o.set(f, v);
}
/**
* unchecked, because the insane amount of casts is necessary to reflect the
* implicit value based type system
*/
@SuppressWarnings("unchecked")
private static <T> T value(SkillFile sf, FieldType<T> type) {
if (type instanceof GeneralAccess<?>) {
// get a random object
Iterator<T> is = (Iterator<T>) ((GeneralAccess<?>) type).iterator();
for (int i = ThreadLocalRandom.current().nextInt(reflectiveInitSize) % 200; i != 0; i
is.next();
return is.next();
}
switch (type.typeID()) {
case 5:
// random type
Iterator<? extends Access<? extends SkillObject>> ts = sf.allTypes().iterator();
Access<? extends SkillObject> t = ts.next();
for (int i = ThreadLocalRandom.current().nextInt(200); i != 0 && ts.hasNext(); i
t = ts.next();
// random object
Iterator<? extends SkillObject> is = t.iterator();
for (int i = ThreadLocalRandom.current().nextInt(Math.min(200, reflectiveInitSize)); i != 0; i
is.next();
return (T) is.next();
case 6:
return (T) (Boolean) ThreadLocalRandom.current().nextBoolean();
case 7:
return (T) (Byte) (byte) ThreadLocalRandom.current().nextInt(reflectiveInitSize);
case 8:
return (T) (Short) (short) ThreadLocalRandom.current().nextInt(reflectiveInitSize);
case 9:
return (T) (Integer) ThreadLocalRandom.current().nextInt(reflectiveInitSize);
case 10:
case 11:
return (T) (Long) (ThreadLocalRandom.current().nextLong() % reflectiveInitSize);
case 12:
return (T) (Float) ThreadLocalRandom.current().nextFloat();
case 13:
return (T) (Double) ThreadLocalRandom.current().nextDouble();
case 14:
return (T) "";
case 15: {
ConstantLengthArray<T> cla = (ConstantLengthArray<T>) type;
ArrayList<Object> rval = new ArrayList<>((int) cla.length);
for (int i = (int) cla.length; i != 0; i
rval.add(value(sf, cla.groundType));
return (T) rval;
}
case 17: {
SingleArgumentType<?, ?> cla = (SingleArgumentType<?, ?>) type;
int length = (int) Math.sqrt(reflectiveInitSize);
ArrayList<Object> rval = new ArrayList<>(length);
while (0 != length
rval.add(value(sf, cla.groundType));
return (T) rval;
}
case 18: {
SingleArgumentType<?, ?> cla = (SingleArgumentType<?, ?>) type;
int length = (int) Math.sqrt(reflectiveInitSize);
LinkedList<Object> rval = new LinkedList<>();
while (0 != length
rval.add(value(sf, cla.groundType));
return (T) rval;
}
case 19: {
SingleArgumentType<?, ?> cla = (SingleArgumentType<?, ?>) type;
int length = (int) Math.sqrt(reflectiveInitSize);
HashSet<Object> rval = new HashSet<>();
while (0 != length
rval.add(value(sf, cla.groundType));
return (T) rval;
}
case 20:
return (T) new HashMap<Object, Object>();
default:
throw new IllegalStateException();
}
}
protected static <T, U> de.ust.skill.common.java.api.FieldDeclaration<T> cast(
de.ust.skill.common.java.api.FieldDeclaration<U> arg) {
return (de.ust.skill.common.java.api.FieldDeclaration<T>) arg;
}
protected static String getProperCollectionType(String type) {
if (type.contains("list")) {
return "java.util.LinkedList";
} else if (type.contains("set")) {
return "java.util.HashSet";
} else if (type.contains("[]")) {
return "java.util.ArrayList";
} else {
throw new IllegalArgumentException("Could not parse provided SKilL collection type.\n" + "Type was: " + type
+ "\n" + "Expected one of { 'list', 'set', 'array' }");
}
}
protected static Object wrapPrimitveTypes(long value,
de.ust.skill.common.java.api.FieldDeclaration<?> declaration) {
if (declaration.toString().contains("i8")) {
return new Byte((byte) value);
} else if (declaration.toString().contains("i16")) {
return new Short((short) value);
} else if (declaration.toString().contains("i32")) {
return new Integer((int) value);
} else if (declaration.toString().contains("i64") || declaration.toString().contains("v64")) {
return new Long(value);
} else {
throw new IllegalArgumentException(
"The given fieldDeclaration is not supported.\n" + "Declaration was: " + declaration.toString()
+ "\n" + "But should contain one of the following : {'i8','i16','i32','i64'}");
}
}
protected static Object wrapPrimitveTypes(double value,
de.ust.skill.common.java.api.FieldDeclaration<?> declaration) {
if (declaration.toString().contains("f32")) {
return new Float((float) value);
} else if (declaration.toString().contains("f64")) {
return new Double(value);
}
if (declaration.toString().contains("i8")) {
return new Byte((byte) value);
} else if (declaration.toString().contains("i16")) {
return new Short((short) value);
} else if (declaration.toString().contains("i32")) {
return new Integer((int) value);
} else if (declaration.toString().contains("i64") || declaration.toString().contains("v64")) {
return new Long((long) value);
} else {
throw new IllegalArgumentException("The given fieldDeclaration is not supported.\n" + "Declaration was: "
+ declaration.toString() + "\n" + "But should contain one of the following : {'i8','i16','i32','i64,'f32','f64'}");
}
}
}
|
// M a i n //
// Contact author at herve.bitteur@laposte.net to report bugs & suggestions. //
package omr;
import omr.constant.Constant;
import omr.constant.ConstantSet;
import omr.score.visitor.ScoreExporter;
import omr.script.Script;
import omr.script.ScriptManager;
import omr.step.Step;
import omr.ui.MainGui;
import omr.ui.util.UILookAndFeel;
import omr.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import javax.swing.*;
/**
* Class <code>Main</code> is the main class for OMR application. It deals with
* the main routine and its command line parameters. It launches the User
* Interface, unless a batch mode is selected.
*
* <p> The command line parameters can be (order not relevant) : <dl>
*
* <dt> <b>-help</b> </dt> <dd> to print a quick usage help and leave the
* application. </dd>
*
* <dt> <b>-batch</b> </dt> <dd> to run in batch mode, with no user
* interface. </dd>
*
* <dt> <b>-write</b> </dt> <dd> to specify that the resulting score has to be
* written down once the specified step has been reached. This feature is
* available in batch mode only. </dd>
*
* <dt> <b>-save SAVEPATH</b> </dt> <dd> to specify the directory where score
* output files are saved. This is meant for batch mode, since in interactive
* mode, the user is presented a file chooser dialog.</dd>
*
* <dt> <b>-sheet (SHEETNAME | @SHEETLIST)+</b> </dt> <dd> to specify some
* sheets to be read, either by naming the image file or by referencing (flagged
* by a @ sign) a file that lists image files (or even other files list
* recursively). A list file is a simple text file, with one image file name per
* line.</dd>
*
* <dt> <b>-script (SCRIPTNAME | @SCRIPTLIST)+</b> </dt> <dd> to specify some
* scripts to be read, using the same mechanism than sheets. These script files
* contain tasks saved during a previous run.</dd>
*
* <dt> <b>-step STEPNAME</b> </dt> <dd> to run till the specified
* step. 'STEPNAME' can be any one of the step names (the case is irrelevant) as
* defined in the {@link omr.step.Step} class.
*
* </dd> </dl>
*
* @author Hervé Bitteur
* @version $Id$
*/
public class Main
{
static {
// Time stamps
Clock.resetTime();
}
/** Usual logger utility */
private static final Logger logger = Logger.getLogger(Main.class);
/** Specific application parameters */
private static final Constants constants = new Constants();
/** Installation container and folder */
private static File container;
/** Installation container and folder */
private static File homeFolder;
/** Singleton */
private static Main INSTANCE;
/** Specific folder name for icons */
public static final String ICONS_NAME = "icons";
/** Tells if using Mac OS X for special GUI functionality */
public static final boolean MAC_OS_X =
System.getProperty("os.name").toLowerCase().
startsWith("mac os x");
/** Build reference of the application as displayed to the user */
private final String toolBuild;
/** Name of the application as displayed to the user */
private final String toolName;
/** Version of the application as displayed to the user */
private final String toolVersion;
/** Master View */
private MainGui gui;
/** List of script file names to process */
private List<String> scriptNames = new ArrayList<String>();
/** List of sheet file names to process */
private List<String> sheetNames = new ArrayList<String>();
/** Target step, LOAD by default */
private Step targetStep = Step.LOAD;
/** Batch mode if any */
private boolean batchMode = false;
/** Request to write score if any */
private boolean writeScore = false;
// Main //
private Main (String[] args,
Class caller)
{
// Locale to be used in the whole application ?
checkLocale();
// Tool name
final Package thisPackage = Main.class.getPackage();
final String name = thisPackage.getSpecificationTitle();
if (name != null) {
toolName = name;
constants.toolName.setValue(name);
} else {
toolName = constants.toolName.getValue();
}
// Tool version
final String version = thisPackage.getSpecificationVersion();
if (version != null) {
toolVersion = version;
constants.toolVersion.setValue(version);
} else {
toolVersion = constants.toolVersion.getValue();
}
// Tool build
toolBuild = thisPackage.getImplementationVersion();
// Remember installation home
container = new File(
caller.getProtectionDomain().getCodeSource().getLocation().getFile());
// Home Folder
// .../build/classes
// .../dist/audiveris.jar
homeFolder = container.getParentFile()
.getParentFile();
}
// getConfigFolder //
/**
* Report the folder where config parameters are stored
*
* @return the directory for configuration files
*/
public static File getConfigFolder ()
{
return new File(getHomeFolder(), "config");
}
// getGui //
/**
* Points to the single instance of the User Interface, if any.
*
* @return MainGui instance, which may be null
*/
public static MainGui getGui ()
{
if (INSTANCE == null) {
return null;
} else {
return INSTANCE.gui;
}
}
// getIconsFolder //
/**
* Report the folder where custom-defined icons are stored
*
* @return the directory for icon files
*/
public static File getIconsFolder ()
{
return new File(getHomeFolder(), ICONS_NAME);
}
// setOutputFolder //
/**
* Set the folder defined for output/saved files
*
* @param saveDir the directory for output
*/
public static void setOutputFolder (String saveDir)
{
constants.savePath.setValue(saveDir);
}
// getOutputFolder //
/**
* Report the folder defined for output/saved files
*
* @return the directory for output
*/
public static String getOutputFolder ()
{
return constants.savePath.getValue();
}
// getToolBuild //
/**
* Report the build reference of the application as displayed to the user
*
* @return Build reference of the application
*/
public static String getToolBuild ()
{
return INSTANCE.toolBuild;
}
// getToolName //
/**
* Report the name of the application as displayed to the user
*
* @return Name of the application
*/
public static String getToolName ()
{
return INSTANCE.toolName;
}
// getToolVersion //
/**
* Report the version of the application as displayed to the user
*
* @return version of the application
*/
public static String getToolVersion ()
{
return INSTANCE.toolVersion;
}
// getTrainFolder //
/**
* Report the folder defined for training files
*
* @return the directory for training material
*/
public static File getTrainFolder ()
{
return new File(getHomeFolder(), "train");
}
// main //
/**
* Specific starting method for the application.
*
* @param args the command line parameters
* @param caller the precise class of the caller
*
* @see omr.Main the possible command line parameters
*/
public static void main (String[] args,
Class caller)
{
// Problem, from Emacs all args are passed in one string sequence. We
// recognize this by detecting a single argument starting with '-'
if ((args.length == 1) && (args[0].startsWith("-"))) {
// Redispatch the real args
StringTokenizer st = new StringTokenizer(args[0]);
int argNb = 0;
// First just count the number of real arguments
while (st.hasMoreTokens()) {
argNb++;
st.nextToken();
}
String[] newArgs = new String[argNb];
// Second copy all real arguments into newly
// allocated array
argNb = 0;
st = new StringTokenizer(args[0]);
while (st.hasMoreTokens()) {
newArgs[argNb++] = st.nextToken();
}
// Fake the args
args = newArgs;
}
// Launch the processing
INSTANCE = new Main(args, caller);
if (logger.isFineEnabled()) {
logger.fine("homeFolder=" + homeFolder);
logger.fine("container=" + container);
logger.fine("isDirectory=" + container.isDirectory());
}
try {
INSTANCE.process(args);
} catch (Main.StopRequired ex) {
logger.info("Exiting.");
}
}
// getHomeFolder //
private static File getHomeFolder ()
{
return homeFolder;
}
// addRef //
private void addRef (String ref,
List<String> list)
{
// The ref may be a plain file name or the name of a pack that lists
// ref(s). This is signalled by a starting '@' character in ref
if (ref.startsWith("@")) {
// File with other refs inside
String pack = ref.substring(1);
try {
BufferedReader br = new BufferedReader(new FileReader(pack));
String newRef;
try {
while ((newRef = br.readLine()) != null) {
addRef(newRef.trim(), list);
}
br.close();
} catch (IOException ex) {
logger.warning(
"IO error while reading file '" + pack + "'");
}
} catch (FileNotFoundException ex) {
logger.warning("Cannot find file '" + pack + "'");
}
} else
// Plain file name
if (ref.length() > 0) {
list.add(ref);
}
}
// browse //
private void browse ()
{
// Browse desired sheets in parallel
for (String name : sheetNames) {
File file = new File(name);
// We do not register the sheet target, since there may be several
// in a row. But we perform all steps through the desired step
targetStep.performParallel(null, file);
// // Batch part?
// if (batchMode) {
// // Do we have to write down the score?
// if (writeScore) {
// ScoreManager.getInstance()
// .exportAll();
// // Dispose allocated stuff
// SheetManager.getInstance()
// .closeAll();
// ScoreManager.getInstance()
// .closeAll();
}
// Browse desired scripts in parallel
for (String name : scriptNames) {
// Run each script in parallel
final String scriptName = name;
OmrExecutors.getLowExecutor()
.execute(
new Runnable() {
public void run ()
{
long start = System.currentTimeMillis();
File file = new File(scriptName);
logger.info("Loading script file " + file + " ...");
try {
final Script script = ScriptManager.getInstance()
.load(
new FileInputStream(file));
script.dump();
script.run();
} catch (FileNotFoundException ex) {
logger.warning(
"Cannot find script file " + file);
}
long stop = System.currentTimeMillis();
logger.info(
"Script file " + file + " run in " +
(stop - start) + " ms");
}
});
}
}
// checkLocale //
private void checkLocale ()
{
final String country = constants.localeCountry.getValue();
if (!country.equals("")) {
for (Locale locale : Locale.getAvailableLocales()) {
if (locale.getCountry()
.equals(country)) {
Locale.setDefault(locale);
return;
}
}
logger.info("Cannot set locale country to " + country);
}
}
// parseArguments //
private void parseArguments (final String[] args)
throws StopRequired
{
// Status of the finite state machine
final int STEP = 0;
final int SHEET = 1;
final int SCRIPT = 2;
final int SAVE = 3;
boolean paramNeeded = false; // Are we expecting a param?
int status = SHEET; // By default
String currentCommand = null;
// Parse all arguments from command line
for (int i = 0; i < args.length; i++) {
String token = args[i];
if (token.startsWith("-")) {
// This is a command
// Check that we were not expecting param(s)
if (paramNeeded) {
printCommandLine(args);
stopUsage(
"Found no parameter after command '" + currentCommand +
"'");
}
if (token.equalsIgnoreCase("-help")) {
stopUsage(null);
} else if (token.equalsIgnoreCase("-batch")) {
batchMode = true;
paramNeeded = false;
} else if (token.equalsIgnoreCase("-write")) {
writeScore = true;
paramNeeded = false;
} else if (token.equalsIgnoreCase("-step")) {
status = STEP;
paramNeeded = true;
} else if (token.equalsIgnoreCase("-sheet")) {
status = SHEET;
paramNeeded = true;
} else if (token.equalsIgnoreCase("-script")) {
status = SCRIPT;
paramNeeded = true;
} else if (token.equalsIgnoreCase("-save")) {
status = SAVE;
paramNeeded = true;
} else {
printCommandLine(args);
stopUsage("Unknown command '" + token + "'");
}
// Remember the current command
currentCommand = token;
} else {
// This is a parameter
switch (status) {
case STEP :
// Read a step name
targetStep = null;
for (Step step : Step.values()) {
if (token.equalsIgnoreCase(step.toString())) {
targetStep = step;
break;
}
}
if (targetStep == null) {
printCommandLine(args);
stopUsage(
"Step name expected, found '" + token +
"' instead");
}
// By default, sheets are now expected
status = SHEET;
paramNeeded = false;
break;
case SHEET :
addRef(token, sheetNames);
paramNeeded = false;
break;
case SCRIPT :
addRef(token, scriptNames);
paramNeeded = false;
break;
case SAVE :
// Make sure that it ends with proper separator
if (!(token.endsWith("\\") || token.endsWith("/"))) {
token = token + "/";
}
constants.savePath.setValue(token);
// By default, sheets are now expected
status = SHEET;
paramNeeded = false;
break;
}
}
}
// Additional error checking
if (paramNeeded) {
printCommandLine(args);
stopUsage(
"Expecting a parameter after command '" + currentCommand + "'");
}
// Results
if (logger.isFineEnabled()) {
logger.fine("batchMode=" + batchMode);
logger.fine("writeScore=" + writeScore);
logger.fine("savePath=" + constants.savePath.getValue());
logger.fine("targetStep=" + targetStep);
logger.fine("sheetNames=" + sheetNames);
logger.fine("scriptNames=" + scriptNames);
}
}
// printCommandLine //
private void printCommandLine (String[] args)
{
System.out.println("\nCommandParameters:");
for (String arg : args) {
System.out.print(" " + arg);
}
System.out.println();
}
// process //
private void process (String[] args)
throws StopRequired
{
// First parse the provided arguments if any
parseArguments(args);
// Then, preload the JAI class so image operations are ready
JaiLoader.preload();
// Interactive or Batch mode ?
if (!batchMode) {
logger.fine("Interactive processing");
// UI Look and Feel
UILookAndFeel.setUI(null);
// Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
// Launch the GUI
gui = new MainGui();
// Background task : JaxbContext
OmrExecutors.getLowExecutor()
.execute(
new Runnable() {
@Implement(Runnable.class)
public void run ()
{
ScoreExporter.preloadJaxbContext();
}
});
// Do we have sheet or script actions specified?
if ((sheetNames.size() > 0) || (scriptNames.size() > 0)) {
browse();
}
} else {
logger.info("Batch processing");
browse();
}
}
// stopUsage //
private void stopUsage (String msg)
throws StopRequired
{
// Print message if any
if (msg != null) {
logger.warning(msg);
}
StringBuffer buf = new StringBuffer(1024);
// Print standard command line syntax
buf.append("usage: java ")
.append(getToolName())
.append(" [-help]")
.append(" [-batch]")
.append(" [-write]")
.append(" [-save SAVEPATH]")
.append(" [-step STEPNAME]")
.append(" [-sheet (SHEETNAME|@SHEETLIST)+]")
.append(" [-script (SCRIPTNAME|@SCRIPTLIST)+]");
// Print all allowed step names
buf.append("\n Known step names are in order")
.append(" (non case-sensitive) :");
for (Step step : Step.values()) {
buf.append(
String.format(
"%n%-17s : %s",
step.toString().toUpperCase(),
step.getDescription()));
}
logger.info(buf.toString());
// Stop application immediately
throw new StopRequired();
}
// Constants //
private static final class Constants
extends ConstantSet
{
/** Selection of locale country code (2 letters), or empty */
Constant.String localeCountry = new Constant.String(
"US",
"Locale country to be used in the whole application (US, FR, ...)");
/** Directory for saved files, defaulted to 'save' audiveris subdir */
Constant.String savePath = new Constant.String(
"",
"Directory for saved files");
/** Utility constant */
Constant.String toolName = new Constant.String(
"Audiveris",
"* DO NOT EDIT * - Name of this application");
/** Utility constant */
Constant.String toolVersion = new Constant.String(
"",
"* DO NOT EDIT * - Version of this application");
}
// StopRequired //
private static class StopRequired
extends Exception
{
}
}
|
package org.safehaus.subutai.ui.cassandra.manager;
import com.vaadin.data.Property;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.server.Sizeable;
import com.vaadin.server.ThemeResource;
import com.vaadin.ui.*;
import org.safehaus.subutai.api.cassandra.Config;
import org.safehaus.subutai.server.ui.component.ConfirmationDialog;
import org.safehaus.subutai.server.ui.component.ProgressWindow;
import org.safehaus.subutai.server.ui.component.TerminalWindow;
import org.safehaus.subutai.shared.protocol.Agent;
import org.safehaus.subutai.shared.protocol.Util;
import org.safehaus.subutai.ui.cassandra.CassandraUI;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* @author dilshat
*/
public class Manager {
private final Table nodesTable;
private GridLayout contentRoot;
private ComboBox clusterCombo;
private HorizontalLayout controlsContent;
private Config config;
public Manager() {
contentRoot = new GridLayout();
contentRoot.setSpacing(true);
contentRoot.setSizeFull();
contentRoot.setRows(5);
contentRoot.setColumns(1);
//tables go here
nodesTable = createTableTemplate("Cluster nodes");
controlsContent = new HorizontalLayout();
controlsContent.setSpacing(true);
getClusterNameLabel();
getClusterCombo();
getRefreshClusterButton();
getCheckAllButton();
getStartAllButton();
getStopAllButton();
getDestroyClusterButton();
contentRoot.addComponent(controlsContent, 0, 0);
contentRoot.addComponent(nodesTable, 0, 1, 0, 4);
}
private Table createTableTemplate(String caption) {
final Table table = new Table(caption);
table.addContainerProperty("Host", String.class, null);
table.addContainerProperty("Status", Embedded.class, null);
table.setPageLength(10);
table.setSelectable(false);
table.setImmediate(true);
table.addItemClickListener(new ItemClickEvent.ItemClickListener() {
@Override
public void itemClick(ItemClickEvent event) {
if (event.isDoubleClick()) {
String lxcHostname = (String) table.getItem(event.getItemId()).getItemProperty("Host").getValue();
Agent lxcAgent = CassandraUI.getAgentManager().getAgentByHostname(lxcHostname);
if (lxcAgent != null) {
TerminalWindow terminal = new TerminalWindow(Util.wrapAgentToSet(lxcAgent), CassandraUI.getExecutor(), CassandraUI.getCommandRunner(), CassandraUI.getAgentManager());
contentRoot.getUI().addWindow(terminal.getWindow());
} else {
show("Agent is not connected");
}
}
}
});
return table;
}
private void getClusterNameLabel() {
Label clusterNameLabel = new Label("Select the cluster");
controlsContent.addComponent(clusterNameLabel);
}
private void getClusterCombo() {
clusterCombo = new ComboBox();
clusterCombo.setImmediate(true);
clusterCombo.setTextInputAllowed(false);
clusterCombo.setWidth(200, Sizeable.Unit.PIXELS);
clusterCombo.addValueChangeListener(new Property.ValueChangeListener() {
@Override
public void valueChange(Property.ValueChangeEvent event) {
config = (Config) event.getProperty().getValue();
refreshUI();
}
});
controlsContent.addComponent(clusterCombo);
}
private void getRefreshClusterButton() {
Button refreshClustersBtn = new Button("Refresh clusters");
refreshClustersBtn.addStyleName("default");
refreshClustersBtn.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
refreshClustersInfo();
}
});
controlsContent.addComponent(refreshClustersBtn);
}
private void getCheckAllButton() {
Button checkAllBtn = new Button("Check all");
checkAllBtn.addStyleName("default");
checkAllBtn.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
UUID trackID = CassandraUI.getCassandraManager().checkAllNodes(config.getClusterName());
ProgressWindow window = new ProgressWindow(CassandraUI.getExecutor(), CassandraUI.getTracker(), trackID, Config.PRODUCT_KEY);
window.getWindow().addCloseListener(new Window.CloseListener() {
@Override
public void windowClose(Window.CloseEvent closeEvent) {
refreshClustersInfo();
}
});
contentRoot.getUI().addWindow(window.getWindow());
}
});
controlsContent.addComponent(checkAllBtn);
}
private void getStartAllButton() {
Button startAllBtn = new Button("Start all");
startAllBtn.addStyleName("default");
startAllBtn.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
UUID trackID = CassandraUI.getCassandraManager().startAllNodes(config.getClusterName());
ProgressWindow window = new ProgressWindow(CassandraUI.getExecutor(), CassandraUI.getTracker(), trackID, Config.PRODUCT_KEY);
window.getWindow().addCloseListener(new Window.CloseListener() {
@Override
public void windowClose(Window.CloseEvent closeEvent) {
refreshClustersInfo();
}
});
contentRoot.getUI().addWindow(window.getWindow());
}
});
controlsContent.addComponent(startAllBtn);
}
private void getStopAllButton() {
Button stopAllBtn = new Button("Stop all");
stopAllBtn.addStyleName("default");
stopAllBtn.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
UUID trackID = CassandraUI.getCassandraManager().stopAllNodes(config.getClusterName());
ProgressWindow window = new ProgressWindow(CassandraUI.getExecutor(), CassandraUI.getTracker(), trackID, Config.PRODUCT_KEY);
window.getWindow().addCloseListener(new Window.CloseListener() {
@Override
public void windowClose(Window.CloseEvent closeEvent) {
refreshClustersInfo();
}
});
contentRoot.getUI().addWindow(window.getWindow());
}
});
controlsContent.addComponent(stopAllBtn);
}
private void getDestroyClusterButton() {
Button destroyClusterBtn = new Button("Destroy cluster");
destroyClusterBtn.addStyleName("default");
destroyClusterBtn.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
if (config != null) {
ConfirmationDialog alert = new ConfirmationDialog(String.format("Do you want to destroy the %s cluster?", config.getClusterName()),
"Yes", "No");
alert.getOk().addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent clickEvent) {
UUID trackID = CassandraUI.getCassandraManager()
.uninstallCluster(config.getClusterName());
ProgressWindow window = new ProgressWindow(CassandraUI.getExecutor(), CassandraUI.getTracker(), trackID, Config.PRODUCT_KEY);
window.getWindow().addCloseListener(new Window.CloseListener() {
@Override
public void windowClose(Window.CloseEvent closeEvent) {
refreshClustersInfo();
}
});
contentRoot.getUI().addWindow(window.getWindow());
}
});
contentRoot.getUI().addWindow(alert.getAlert());
} else {
show("Please, select cluster");
}
}
});
controlsContent.addComponent(destroyClusterBtn);
}
private void show(String notification) {
Notification.show(notification);
}
private void refreshUI() {
if (config != null) {
populateTable(nodesTable, config.getNodes());
} else {
nodesTable.removeAllItems();
}
}
public void refreshClustersInfo() {
List<Config> info = CassandraUI.getCassandraManager().getClusters();
Config clusterInfo = (Config) clusterCombo.getValue();
clusterCombo.removeAllItems();
if (info != null && info.size() > 0) {
for (Config mongoInfo : info) {
clusterCombo.addItem(mongoInfo);
clusterCombo.setItemCaption(mongoInfo,
mongoInfo.getClusterName());
}
if (clusterInfo != null) {
for (Config cassandraInfo : info) {
if (cassandraInfo.getClusterName().equals(clusterInfo.getClusterName())) {
clusterCombo.setValue(cassandraInfo);
return;
}
}
} else {
clusterCombo.setValue(info.iterator().next());
}
}
}
private void populateTable(final Table table, Set<Agent> agents) {
table.removeAllItems();
for (Iterator it = agents.iterator(); it.hasNext(); ) {
final Agent agent = (Agent) it.next();
final Embedded progressIcon = new Embedded("",
new ThemeResource("img/spinner.gif"));
progressIcon.setVisible(false);
final Object rowId = table.addItem(new Object[] {
agent.getHostname(),
progressIcon},
null
);
}
}
public Component getContent() {
return contentRoot;
}
}
|
package org.topcased.requirement.document.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EModelElement;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.ui.IImportWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.uml2.uml.DataType;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.topcased.doc2model.parser.Doc2ModelParser;
import org.topcased.doc2model.parser.ProgressionObserver;
import org.topcased.requirement.RequirementFactory;
import org.topcased.requirement.RequirementProject;
import org.topcased.requirement.core.RequirementCorePlugin;
import org.topcased.requirement.core.preferences.CurrentPreferenceHelper;
import org.topcased.requirement.core.preferences.RequirementPreferenceConstants;
import org.topcased.requirement.document.Activator;
import org.topcased.requirement.document.checker.AbstractDescriptionChecker;
import org.topcased.requirement.document.doc2model.Doc2ModelCreator;
import org.topcased.requirement.document.elements.Attribute;
import org.topcased.requirement.document.elements.Mapping;
import org.topcased.requirement.document.elements.PageController;
import org.topcased.requirement.document.elements.RecognizedElement;
import org.topcased.requirement.document.elements.RecognizedTree;
import org.topcased.requirement.document.elements.Regex;
import org.topcased.requirement.document.elements.Style;
import org.topcased.requirement.document.utils.Constants;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import doc2modelMapping.doc2model;
/**
* The Class ImportRequirementWizard.
*/
public class ImportRequirementWizard extends Wizard implements IImportWizard
{
private static final String CONSTANT_DEBUG = "ADMIN_DOC_MAPPING";
/** The current file. */
private IFile currentFile;
/** The stereotype. */
private Stereotype stereotype;
/** The stereotypes collection. */
private Collection<Stereotype> stereotypes;
/** The tree. */
private RecognizedTree tree = new RecognizedTree();
/** The list attributes. */
private Collection<Attribute> listAttributes = new LinkedList<Attribute>();
/** The file */
private File currentFileSystem;
/** the controller */
private PageController pageController;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench,
* org.eclipse.jface.viewers.IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection selection)
{
setWindowTitle("File Import Wizard");
setNeedsProgressMonitor(true);
String valueForInput = null;
if (selection.getFirstElement() instanceof IFile)
{
currentFile = (IFile) selection.getFirstElement();
if ("docx".equals(currentFile.getLocation().getFileExtension().toLowerCase()) || "csv".equals(currentFile.getLocation().getFileExtension().toLowerCase())
|| "xlsx".equals(currentFile.getLocation().getFileExtension().toLowerCase()) || "odt".equals(currentFile.getLocation().getFileExtension().toLowerCase())
|| "ods".equals(currentFile.getLocation().getFileExtension().toLowerCase()))
{
valueForInput = currentFile.getLocationURI().toString();
}
}
pageController = new PageController(this);
List<WizardPage> pages = pageController.createPages(valueForInput, currentFile != null ? currentFile.getLocation().toFile() : null, tree, listAttributes);
for (WizardPage wizardPage : pages) {
addPage(wizardPage);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
@Override
public boolean performFinish()
{
String pathForDebug = getPathForDebug(pageController.getLevel());
if (pageController.getDescriptionState())
{
if (pageController.isDescriptionText())
{
AbstractDescriptionChecker.setEndText(pageController.getDescriptionEndText());
}
if (pageController.isDescriptionRegex())
{
AbstractDescriptionChecker.setRegDescription(pageController.getDescriptionRegex());
}
if (Constants.UML_EXTENSION.equals(pageController.getModelType()) || Constants.SYSML_EXTENSION.equals(pageController.getModelType()))
{
AbstractDescriptionChecker.setStereotypeAttribute(pageController.getDescriptionAttribute());
}
}
RecognizedElement id = pageController.getIdentification();
if (id instanceof Style)
{
AbstractDescriptionChecker.setStyleIdent(((Style) id).getStyle());
String regex = ((Style) id).getRegex();
if (regex != null)
{
AbstractDescriptionChecker.setReqIdent(regex);
}
}
else if (id instanceof Regex)
{
AbstractDescriptionChecker.setReqIdent(((Regex) id).getRegex());
}
String uris = "";
Collection<String> profilesUris = new ArrayList<String>();
if(pageController.getStereotypes() != null)
{
for(Stereotype stereotype:pageController.getStereotypes())
{
if(stereotype.getProfile() != null && stereotype.getProfile().eResource() != null && stereotype.getProfile().eResource().getURI() != null)
{
profilesUris.add(stereotype.getProfile().eResource().getURI().toString());
}
}
}
if (profilesUris != null && !profilesUris.isEmpty())
{
uris = Joiner.on(";").join(Iterables.transform(profilesUris, new Function<String, String>()
{
public String apply(String from)
{
return from;
}
}));
}
/** Process **/
Doc2ModelCreator d2mc = new Doc2ModelCreator(pageController.getListMapping(), pageController.getModelType(), pageController.isSpreadsheet(), uris, pageController.getStereotypes(),
pageController.isHierarchical(), pageController.getIdentification(), pathForDebug);
final doc2model model = d2mc.createDoc2Model();
if (model != null)
{
try
{
getContainer().run(false, true, new IRunnableWithProgress()
{
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
{
try
{
final IProgressMonitor myMonitor = monitor;
Doc2ModelParser parser = new Doc2ModelParser(currentFileSystem.getAbsolutePath(), model, pageController.getOutputModel(), null, false);
EObject result = parser.parse(new ProgressionObserver()
{
public void worked(int i)
{
myMonitor.worked(i);
}
public void warningOrErrorsOccurs()
{
}
public void setMax(int max)
{
myMonitor.beginTask("Import", max);
}
public void notifyNoElementsFounded()
{
}
public boolean isCanceled()
{
return myMonitor.isCanceled();
}
});
// post processes
assignLevel(myMonitor, result);
if (Constants.REQUIREMENT_EXTENSION.equals(pageController.getModelType()))
{
assignAttributeConfiguration(myMonitor, result);
}
IFile file = getFile(pageController.getOutputModel());
if (file != null && file.exists())
{
try
{
file.getParent().refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
}
catch (CoreException e)
{
}
}
if (pageController.isAttachRequirement())
{
myMonitor.beginTask("Attaching requirement", 3);
if (!getPageController().attachRequirement(myMonitor).get())
{
throw new InvocationTargetException(new Exception("Action Cancelled"));
}
}
myMonitor.done();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
AbstractDescriptionChecker.rollback();
}
}
/**
* Assign attribute configuration. for attribute type
*
* @param myMonitor the my monitor
* @param result the result
*/
private void assignAttributeConfiguration(IProgressMonitor myMonitor, EObject result)
{
if (result instanceof RequirementProject)
{
myMonitor.beginTask("Load attribute configuration", 1);
RequirementProject project = (RequirementProject) result;
project.setAttributeConfiguration(CurrentPreferenceHelper.getConfigurationInWorkspace());
project.getChapter().add(RequirementFactory.eINSTANCE.createProblemChapter());
project.getChapter().add(RequirementFactory.eINSTANCE.createTrashChapter());
project.getChapter().add(RequirementFactory.eINSTANCE.createUntracedChapter());
try
{
result.eResource().save(Collections.EMPTY_MAP);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* Assign level.
*
* @param myMonitor the my monitor
* @param result the result
*/
private void assignLevel(final IProgressMonitor myMonitor, EObject result)
{
// sysml or uml so we apply eannotations
if (result != null)
{
if (pageController.getLevel() != null && pageController.getLevel().length() > 0)
{
myMonitor.beginTask("Assign level", 1);
Resource r = result.eResource();
for (Iterator<EObject> i = r.getAllContents(); i.hasNext();)
{
EObject tmp = i.next();
if (tmp instanceof EModelElement)
{
EModelElement element = (EModelElement) tmp;
EAnnotation annotation = EcoreFactory.eINSTANCE.createEAnnotation();
annotation.setSource("http:
element.getEAnnotations().add(annotation);
annotation.getDetails().put("author", pageController.getLevel());
}
}
try
{
r.save(Collections.EMPTY_MAP);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
});
}
catch (InvocationTargetException e)
{
e.printStackTrace();
return false;
}
catch (InterruptedException e)
{
e.printStackTrace();
return false;
}
}
// re fill lists
for (Mapping m : pageController.getListMapping())
{
m.getElement().setSelected(false);
pageController.getListAttributes().add(m.getAttribute());
}
/** Save preferences **/
// Pref from the first page
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectDocument.PREFERENCE_FOR_INPUT_DOC, pageController.getInputDocument());
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectDocument.PREFERENCE_FOR_OUTPUT_MODEL, pageController.getOutputModel());
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectDocument.PREFERENCE_FOR_LEVEL, pageController.getLevel());
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectDocument.PREFERENCE_FOR_MODEL_TYPE, pageController.getModelType());
// Saving profile and stereotypes
String stereoPref = "";
if(pageController.getStereotypes() != null)
{
for(Stereotype stereotype:pageController.getStereotypes())
{
if(stereotype.getProfile() != null && stereotype.getProfile().eResource() != null && stereotype.getProfile().eResource().getURI() != null)
{
stereoPref += stereotype.eResource().getURI().toString()+"#"+stereotype.eResource().getURIFragment(stereotype)+";";
}
}
}
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectDocument.PREFERENCE_FOR_STEREO, stereoPref);
// Pref from the second page
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectFormat.PREFERENCE_FOR_CHAPTER, pageController.isHierarchical());
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectFormat.PREFERENCE_FOR_VALUE_TO_RECOGNIZE_REQ, pageController.getValueToRecognizeReq());
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectFormat.PREFERENCE_FOR_LIST_RECOGNIZED_ELEMENT, pageController.getListAttributesPref());
boolean descriptionState = pageController.getDescriptionState();
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectFormat.PREFERENCE_FOR_DESCRIPTION, descriptionState);
if (descriptionState)
{
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectFormat.PREFERENCE_FOR_DESCRIPTION_ENDLABEL, pageController.getDescriptionEndText());
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectFormat.PREFERENCE_FOR_DESCRIPTION_REGEX, pageController.getDescriptionRegex());
}
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageSelectFormat.PREFERENCE_FOR_DESCRIPTION_ATTRIBUTE, pageController.getStereotypeDescriptionAttributeSelectedIndex());
// Pref from the third page
// Save only if it is requirement model
if (Constants.REQUIREMENT_EXTENSION.equals(pageController.getModelType()))
{
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageMapping.PREFERENCE_FOR_LIST_ATTRIBUT, pageController.getListAttributesPref());
}
Activator.getDefault().getPluginPreferences().setValue(ImportRequirementWizardPageMapping.PREFERENCE_FOR_LIST_MAPPING, pageController.getListMappingPref());
IPreferenceStore preferenceStorePlugIn = RequirementCorePlugin.getDefault().getPreferenceStore();
if (!preferenceStorePlugIn.getBoolean(RequirementPreferenceConstants.IMPORT_REQUIREMENT_WITHOUT_DIALOG))
{
MessageDialog dialog = new MessageDialog(getShell(), "Information", null, "The .requirement file is generated in : " + pageController.getOutputModel(), MessageDialog.INFORMATION,
new String[] {IDialogConstants.OK_LABEL}, Window.OK);
dialog.open();
}
return true;
}
/**
* Transforms an String path to IFile
*
* @return
*/
public static IFile getFile(String argPath)
{
URI uri = URI.createURI(argPath);
String path = null;
if (uri.isFile())
{
path = "/" + uri.deresolve(URI.createURI(EcorePlugin.getWorkspaceRoot().getLocationURI().toString() + "/"), false, false, true).toString();
}
else
{
path = uri.toString();
}
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path));
return file;
}
private String getPathForDebug(String level)
{
String result = null;
Pattern p = Pattern.compile(CONSTANT_DEBUG + " (.*)");
Matcher m = p.matcher(level);
if (m.matches())
{
result = m.group(1);
}
return result;
}
/**
* Gets the stereotype.
*
* Use getStereotypes() instead
*
* @return the stereotype
*/
@Deprecated
public Stereotype getStereotype()
{
return stereotype;
}
/**
* Gets the stereotypes collection.
*
*
* @return the stereotypes collection
*/
public Collection<Stereotype> getStereotypes()
{
return stereotypes;
}
/**
* Sets the stereotype.
*
* Use addStereotypes instead
*
* @param stereotype the new stereotype
*/
@Deprecated
public void setStereotype(Stereotype stereotype)
{
this.stereotype = stereotype;
}
/**
* Adds a Stereotype to the stereotypes collection
*
* @param stereotype
*/
public void addStereotype(Stereotype stereotype)
{
this.stereotypes.add(stereotype);
}
/**
* Remove all stereotypes
*
* @param stereotype
*/
public void clearStereotypes()
{
this.stereotypes.clear();
}
/**
* Checks if is ref.
*
* @param next the next
*
* @return true, if is ref
*/
public static boolean isRef(Property next)
{
boolean isRef = next.getType() != null && !(next.getType() instanceof DataType);
return isRef;
}
/**
* Contains.
*
* @param listAttributes the list attributes
* @param att the att
*
* @return true, if successful
*/
public static boolean contains(Collection<Attribute> listAttributes, Attribute att)
{
for (Attribute a : listAttributes)
{
if (a.getName() != null && a.getName().equals(att.getName()) && a.getSource() != null && a.getSource().equals(att.getSource()) && a.getOriginalName() != null
&& a.getOriginalName().equals(att.getOriginalName()))
{
return true;
}
}
return false;
}
/**
* Gets the page Controller
*
* @return
*/
public PageController getPageController()
{
return pageController;
}
/**
* The current File System Variable
*
* @param currentFileSystem
*/
public void setCurrentFileSystem(File currentFileSystem)
{
this.currentFileSystem = currentFileSystem;
pageController.setDocumentFile(currentFileSystem);
}
/**
* Sets the current File Variable
*
* @param currentFile
*/
public void setCurrentFile(IFile currentFile)
{
this.currentFile = currentFile;
}
}
|
package com.opengamma.financial.analytics.model.trs;
import static com.opengamma.engine.value.ValuePropertyNames.CURRENCY;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_EXPOSURES;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_SENSITIVITY_CURRENCY;
import static com.opengamma.engine.value.ValueRequirementNames.PV01;
import static com.opengamma.financial.analytics.model.curve.CurveCalculationPropertyNamesAndValues.DISCOUNTING;
import static com.opengamma.financial.analytics.model.curve.CurveCalculationPropertyNamesAndValues.PROPERTY_CURVE_TYPE;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.threeten.bp.Instant;
import com.google.common.collect.Iterables;
import com.opengamma.analytics.financial.equity.EquityTrsDataBundle;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.provider.calculator.discounting.PV01CurveParametersCalculator;
import com.opengamma.analytics.financial.provider.calculator.equity.PresentValueCurveSensitivityEquityDiscountingCalculator;
import com.opengamma.analytics.util.amount.ReferenceAmount;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.CompiledFunctionDefinition;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.util.money.Currency;
import com.opengamma.util.tuple.Pair;
/**
* Calculates the PV01 of an equity total return swap security.
*/
public class EquityTotalReturnSwapPV01Function extends EquityTotalReturnSwapFunction {
/** The calculator */
private static final PV01CurveParametersCalculator<EquityTrsDataBundle> CALCULATOR =
new PV01CurveParametersCalculator<>(PresentValueCurveSensitivityEquityDiscountingCalculator.getInstance());
/**
* Sets the value requirement to {@link ValueRequirementNames#PV01}.
*/
public EquityTotalReturnSwapPV01Function() {
super(PV01);
}
@Override
public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) {
return new EquityTotalReturnSwapCompiledFunction(getTargetToDefinitionConverter(context), getDefinitionToDerivativeConverter(context), true) {
@SuppressWarnings("synthetic-access")
@Override
protected Set<ComputedValue> getValues(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
final Set<ValueRequirement> desiredValues, final InstrumentDerivative derivative, final FXMatrix fxMatrix) {
final ValueProperties properties = Iterables.getOnlyElement(desiredValues).getConstraints().copy().get();
final EquityTrsDataBundle data = getDataBundle(inputs, fxMatrix);
final String desiredCurveName = properties.getStrictValue(CURVE);
final ReferenceAmount<Pair<String, Currency>> pv01 = derivative.accept(CALCULATOR, data);
final Set<ComputedValue> results = new HashSet<>();
boolean curveNameFound = false;
for (final Map.Entry<Pair<String, Currency>, Double> entry : pv01.getMap().entrySet()) {
final String curveName = entry.getKey().getFirst();
if (desiredCurveName.equals(curveName)) {
curveNameFound = true;
}
final ValueProperties curveSpecificProperties = properties.copy()
.withoutAny(CURVE)
.with(CURVE, curveName)
.get();
final ValueSpecification spec = new ValueSpecification(PV01, target.toSpecification(), curveSpecificProperties);
results.add(new ComputedValue(spec, entry.getValue()));
}
if (!curveNameFound) {
final ValueSpecification spec = new ValueSpecification(PV01, target.toSpecification(), properties.copy().with(CURVE, desiredCurveName).get());
return Collections.singleton(new ComputedValue(spec, 0.));
}
return results;
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext compilationContext, final ComputationTarget target, final ValueRequirement desiredValue) {
final Set<String> curveNames = desiredValue.getConstraints().getValues(CURVE);
if (curveNames == null || curveNames.size() != 1) {
return null;
}
return super.getRequirements(context, target, desiredValue);
}
@SuppressWarnings("synthetic-access")
@Override
protected Collection<ValueProperties.Builder> getResultProperties(final FunctionCompilationContext compilationContext, final ComputationTarget target) {
final ValueProperties.Builder properties = createValueProperties()
.with(PROPERTY_CURVE_TYPE, DISCOUNTING)
.withAny(CURVE_EXPOSURES)
.withAny(CURVE_SENSITIVITY_CURRENCY)
.withoutAny(CURRENCY)
.withAny(CURRENCY)
.withAny(CURVE);
return Collections.singleton(properties);
}
};
}
}
|
package org.sagebionetworks.repo.manager.table;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.sagebionetworks.common.util.progress.ProgressCallback;
import org.sagebionetworks.common.util.progress.ProgressingCallable;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.dbo.dao.table.MaterializedViewDao;
import org.sagebionetworks.repo.model.dbo.dao.table.TableModelTestUtils;
import org.sagebionetworks.repo.model.entity.IdAndVersion;
import org.sagebionetworks.repo.model.message.ChangeMessage;
import org.sagebionetworks.repo.model.message.ChangeType;
import org.sagebionetworks.repo.model.message.TransactionalMessenger;
import org.sagebionetworks.repo.model.table.ColumnModel;
import org.sagebionetworks.repo.model.table.ColumnType;
import org.sagebionetworks.repo.model.table.MaterializedView;
import org.sagebionetworks.repo.model.table.TableState;
import org.sagebionetworks.repo.model.table.TableStatus;
import org.sagebionetworks.table.cluster.SqlQuery;
import org.sagebionetworks.table.cluster.description.IndexDescription;
import org.sagebionetworks.table.cluster.description.MaterializedViewIndexDescription;
import org.sagebionetworks.table.cluster.description.TableIndexDescription;
import org.sagebionetworks.table.query.ParseException;
import org.sagebionetworks.table.query.model.QuerySpecification;
import org.sagebionetworks.workers.util.aws.message.RecoverableMessageException;
import com.google.common.collect.ImmutableSet;
@ExtendWith(MockitoExtension.class)
public class MaterializedViewManagerImplTest {
@Mock
private ColumnModelManager mockColumnModelManager;
@Mock
private TableManagerSupport mockTableManagerSupport;
@Mock
private ProgressCallback mockProgressCallback;
@Mock
private TableIndexConnectionFactory mockConnectionFactory;
@Mock
private TableIndexManager mockTableIndexManager;
@Mock
private MaterializedViewDao mockMaterializedViewDao;
@Mock
private TransactionalMessenger mockMessagePublisher;
@InjectMocks
private MaterializedViewManagerImpl manager;
private MaterializedViewManagerImpl managerSpy;
@Mock
private MaterializedView mockView;
private IdAndVersion idAndVersion = IdAndVersion.parse("syn123.1");
private List<ColumnModel> syn123Schema;
@BeforeEach
public void before() {
syn123Schema = Arrays.asList(TableModelTestUtils.createColumn(111L, "foo", ColumnType.INTEGER),
TableModelTestUtils.createColumn(222L, "bar", ColumnType.STRING));
managerSpy = Mockito.spy(manager);
}
@Test
public void testValidate() {
String sql = "SELECT * FROM syn123";
when(mockView.getDefiningSQL()).thenReturn(sql);
// Call under test
manager.validate(mockView);
verify(mockView, atLeastOnce()).getDefiningSQL();
}
@Test
public void testValidateWithNullSQL() {
String sql = null;
when(mockView.getDefiningSQL()).thenReturn(sql);
String message = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.validate(mockView);
}).getMessage();
assertEquals("The definingSQL of the materialized view is required and must not be the empty string.", message);
verify(mockView, atLeastOnce()).getDefiningSQL();
}
@Test
public void testValidateWithEmptySQL() {
String sql = "";
when(mockView.getDefiningSQL()).thenReturn(sql);
String message = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.validate(mockView);
}).getMessage();
assertEquals("The definingSQL of the materialized view is required and must not be the empty string.", message);
verify(mockView, atLeastOnce()).getDefiningSQL();
}
@Test
public void testValidateWithBlankSQL() {
String sql = " ";
when(mockView.getDefiningSQL()).thenReturn(sql);
String message = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.validate(mockView);
}).getMessage();
assertEquals("The definingSQL of the materialized view is required and must not be a blank string.", message);
verify(mockView, atLeastOnce()).getDefiningSQL();
}
@Test
public void testValidateWithInvalidSQL() {
String sql = "invalid SQL";
when(mockView.getDefiningSQL()).thenReturn(sql);
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.validate(mockView);
});
assertTrue(ex.getCause() instanceof ParseException);
assertTrue(ex.getMessage().startsWith("Encountered \" <regular_identifier> \"invalid"));
verify(mockView, atLeastOnce()).getDefiningSQL();
}
@Test
public void testValidateWithWithNoTable() {
String sql = "SELECT foo";
when(mockView.getDefiningSQL()).thenReturn(sql);
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.validate(mockView);
});
assertTrue(ex.getCause() instanceof ParseException);
assertTrue(ex.getMessage().startsWith("Encountered \"<EOF>\" at line 1, column 10."));
verify(mockView, atLeastOnce()).getDefiningSQL();
}
@Test
public void testValidateWithWithUnsupportedJoin() {
String sql = "SELECT * FROM table1 JOIN table2";
when(mockView.getDefiningSQL()).thenReturn(sql);
String message = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.validate(mockView);
}).getMessage();
assertEquals("The JOIN keyword is not supported in this context", message);
verify(mockView, atLeastOnce()).getDefiningSQL();
}
@Test
public void testRegisterSourceTables() {
Set<IdAndVersion> currentSourceTables = Collections.emptySet();
String sql = "SELECT * FROM syn123";
Set<IdAndVersion> expectedDeletes = Collections.emptySet();
Set<IdAndVersion> expectedSources = ImmutableSet.of(IdAndVersion.parse("syn123"));
when(mockMaterializedViewDao.getSourceTablesIds(any())).thenReturn(currentSourceTables);
doNothing().when(managerSpy).bindSchemaToView(any(), any(QuerySpecification.class));
// Call under test
managerSpy.registerSourceTables(idAndVersion, sql);
verify(mockMaterializedViewDao).getSourceTablesIds(idAndVersion);
verify(mockMaterializedViewDao).deleteSourceTablesIds(idAndVersion, expectedDeletes);
verify(mockMaterializedViewDao).addSourceTablesIds(idAndVersion, expectedSources);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(QuerySpecification.class));
verify(mockTableManagerSupport).setTableToProcessingAndTriggerUpdate(idAndVersion);
}
@Test
public void testRegisterSourceTablesWithNonOverlappingAssociations() {
Set<IdAndVersion> currentSourceTables = ImmutableSet.of(IdAndVersion.parse("syn456"));
String sql = "SELECT * FROM syn123";
Set<IdAndVersion> expectedDeletes = currentSourceTables;
Set<IdAndVersion> expectedSources = ImmutableSet.of(IdAndVersion.parse("syn123"));
when(mockMaterializedViewDao.getSourceTablesIds(any())).thenReturn(currentSourceTables);
doNothing().when(managerSpy).bindSchemaToView(any(), any(QuerySpecification.class));
// Call under test
managerSpy.registerSourceTables(idAndVersion, sql);
verify(mockMaterializedViewDao).getSourceTablesIds(idAndVersion);
verify(mockMaterializedViewDao).deleteSourceTablesIds(idAndVersion, expectedDeletes);
verify(mockMaterializedViewDao).addSourceTablesIds(idAndVersion, expectedSources);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(QuerySpecification.class));
verify(mockTableManagerSupport).setTableToProcessingAndTriggerUpdate(idAndVersion);
}
@Test
public void testRegisterSourceTablesWithOverlappingAssociations() {
Set<IdAndVersion> currentSourceTables = ImmutableSet.of(IdAndVersion.parse("syn123"),
IdAndVersion.parse("syn456"));
String sql = "SELECT * FROM syn123";
Set<IdAndVersion> expectedDeletes = ImmutableSet.of(IdAndVersion.parse("syn456"));
Set<IdAndVersion> expectedSources = ImmutableSet.of(IdAndVersion.parse("syn123"));
when(mockMaterializedViewDao.getSourceTablesIds(any())).thenReturn(currentSourceTables);
doNothing().when(managerSpy).bindSchemaToView(any(), any(QuerySpecification.class));
// Call under test
managerSpy.registerSourceTables(idAndVersion, sql);
verify(mockMaterializedViewDao).getSourceTablesIds(idAndVersion);
verify(mockMaterializedViewDao).deleteSourceTablesIds(idAndVersion, expectedDeletes);
verify(mockMaterializedViewDao).addSourceTablesIds(idAndVersion, expectedSources);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(QuerySpecification.class));
verify(mockTableManagerSupport).setTableToProcessingAndTriggerUpdate(idAndVersion);
}
@Test
public void testRegisterSourceTablesWithNoChanges() {
Set<IdAndVersion> currentSourceTables = ImmutableSet.of(IdAndVersion.parse("syn123"));
String sql = "SELECT * FROM syn123";
when(mockMaterializedViewDao.getSourceTablesIds(any())).thenReturn(currentSourceTables);
doNothing().when(managerSpy).bindSchemaToView(any(), any(QuerySpecification.class));
// Call under test
managerSpy.registerSourceTables(idAndVersion, sql);
verify(mockMaterializedViewDao).getSourceTablesIds(idAndVersion);
verifyNoMoreInteractions(mockMaterializedViewDao);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(QuerySpecification.class));
verify(mockTableManagerSupport).setTableToProcessingAndTriggerUpdate(idAndVersion);
}
@Test
public void testRegisterSourceTablesWithMultipleTables() {
Set<IdAndVersion> currentSourceTables = Collections.emptySet();
String sql = "SELECT * FROM syn123 JOIN syn456";
Set<IdAndVersion> expectedDeletes = Collections.emptySet();
Set<IdAndVersion> expectedSources = ImmutableSet.of(IdAndVersion.parse("syn123"), IdAndVersion.parse("syn456"));
when(mockMaterializedViewDao.getSourceTablesIds(any())).thenReturn(currentSourceTables);
doNothing().when(managerSpy).bindSchemaToView(any(), any(QuerySpecification.class));
// Call under test
managerSpy.registerSourceTables(idAndVersion, sql);
verify(mockMaterializedViewDao).getSourceTablesIds(idAndVersion);
verify(mockMaterializedViewDao).deleteSourceTablesIds(idAndVersion, expectedDeletes);
verify(mockMaterializedViewDao).addSourceTablesIds(idAndVersion, expectedSources);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(QuerySpecification.class));
verify(mockTableManagerSupport).setTableToProcessingAndTriggerUpdate(idAndVersion);
}
@Test
public void testRegisterSourceTablesWithMultipleTablesWithNonOverlappingAssociations() {
Set<IdAndVersion> currentSourceTables = ImmutableSet.of(IdAndVersion.parse("syn789"),
IdAndVersion.parse("syn101112"));
String sql = "SELECT * FROM syn123 JOIN syn456";
Set<IdAndVersion> expectedDeletes = currentSourceTables;
Set<IdAndVersion> expectedSources = ImmutableSet.of(IdAndVersion.parse("syn123"), IdAndVersion.parse("syn456"));
when(mockMaterializedViewDao.getSourceTablesIds(any())).thenReturn(currentSourceTables);
doNothing().when(managerSpy).bindSchemaToView(any(), any(QuerySpecification.class));
// Call under test
managerSpy.registerSourceTables(idAndVersion, sql);
verify(mockMaterializedViewDao).getSourceTablesIds(idAndVersion);
verify(mockMaterializedViewDao).deleteSourceTablesIds(idAndVersion, expectedDeletes);
verify(mockMaterializedViewDao).addSourceTablesIds(idAndVersion, expectedSources);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(QuerySpecification.class));
verify(mockTableManagerSupport).setTableToProcessingAndTriggerUpdate(idAndVersion);
}
@Test
public void testRegisterSourceTablesWithMultipleTablesWithOverlappingAssociations() {
Set<IdAndVersion> currentSourceTables = ImmutableSet.of(IdAndVersion.parse("syn456"),
IdAndVersion.parse("syn789"), IdAndVersion.parse("syn101112"));
String sql = "SELECT * FROM syn123 JOIN syn456";
Set<IdAndVersion> expectedDeletes = ImmutableSet.of(IdAndVersion.parse("syn789"),
IdAndVersion.parse("syn101112"));
Set<IdAndVersion> expectedSources = ImmutableSet.of(IdAndVersion.parse("syn123"), IdAndVersion.parse("syn456"));
when(mockMaterializedViewDao.getSourceTablesIds(any())).thenReturn(currentSourceTables);
doNothing().when(managerSpy).bindSchemaToView(any(), any(QuerySpecification.class));
// Call under test
managerSpy.registerSourceTables(idAndVersion, sql);
verify(mockMaterializedViewDao).getSourceTablesIds(idAndVersion);
verify(mockMaterializedViewDao).deleteSourceTablesIds(idAndVersion, expectedDeletes);
verify(mockMaterializedViewDao).addSourceTablesIds(idAndVersion, expectedSources);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(QuerySpecification.class));
verify(mockTableManagerSupport).setTableToProcessingAndTriggerUpdate(idAndVersion);
}
@Test
public void testRegisterSourceTablesWithMultipleTablesAndNoChanges() {
Set<IdAndVersion> currentSourceTables = ImmutableSet.of(IdAndVersion.parse("syn456"),
IdAndVersion.parse("syn123"));
String sql = "SELECT * FROM syn123 JOIN syn456";
when(mockMaterializedViewDao.getSourceTablesIds(any())).thenReturn(currentSourceTables);
doNothing().when(managerSpy).bindSchemaToView(any(), any(QuerySpecification.class));
// Call under test
managerSpy.registerSourceTables(idAndVersion, sql);
verify(mockMaterializedViewDao).getSourceTablesIds(idAndVersion);
verifyNoMoreInteractions(mockMaterializedViewDao);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(QuerySpecification.class));
verify(mockTableManagerSupport).setTableToProcessingAndTriggerUpdate(idAndVersion);
}
@Test
public void testRegisterSourceTablesWithVersions() {
Set<IdAndVersion> currentSourceTables = ImmutableSet.of(IdAndVersion.parse("syn456"),
IdAndVersion.parse("syn123.2"));
String sql = "SELECT * FROM syn123.3 JOIN syn456";
Set<IdAndVersion> expectedDeletes = ImmutableSet.of(IdAndVersion.parse("syn123.2"));
Set<IdAndVersion> expectedSources = ImmutableSet.of(IdAndVersion.parse("syn123.3"),
IdAndVersion.parse("syn456"));
when(mockMaterializedViewDao.getSourceTablesIds(any())).thenReturn(currentSourceTables);
doNothing().when(managerSpy).bindSchemaToView(any(), any(QuerySpecification.class));
// Call under test
managerSpy.registerSourceTables(idAndVersion, sql);
verify(mockMaterializedViewDao).getSourceTablesIds(idAndVersion);
verify(mockMaterializedViewDao).deleteSourceTablesIds(idAndVersion, expectedDeletes);
verify(mockMaterializedViewDao).addSourceTablesIds(idAndVersion, expectedSources);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(QuerySpecification.class));
verify(mockTableManagerSupport).setTableToProcessingAndTriggerUpdate(idAndVersion);
}
@Test
public void testRegisterSourceTablesWithNoIdAndVersion() {
idAndVersion = null;
String sql = "SELECT * FROM syn123";
String message = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.registerSourceTables(idAndVersion, sql);
}).getMessage();
assertEquals("The id of the materialized view is required.", message);
verifyZeroInteractions(mockMaterializedViewDao);
}
@Test
public void testRegisterSourceTablesWithNoSql() {
String sql = null;
String message = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.registerSourceTables(idAndVersion, sql);
}).getMessage();
assertEquals("The definingSQL of the materialized view is required and must not be the empty string.", message);
verifyZeroInteractions(mockMaterializedViewDao);
}
@Test
public void testRegisterSourceTablesWithEmptySql() {
String sql = "";
String message = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.registerSourceTables(idAndVersion, sql);
}).getMessage();
assertEquals("The definingSQL of the materialized view is required and must not be the empty string.", message);
verifyZeroInteractions(mockMaterializedViewDao);
}
@Test
public void testRegisterSourceTablesWithBlankSql() {
String sql = " ";
String message = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.registerSourceTables(idAndVersion, sql);
}).getMessage();
assertEquals("The definingSQL of the materialized view is required and must not be a blank string.", message);
verifyZeroInteractions(mockMaterializedViewDao);
}
@Test
public void testGetQuerySpecification() {
String sql = "SELECT * FROM syn123";
QuerySpecification result = MaterializedViewManagerImpl.getQuerySpecification(sql);
assertNotNull(result);
}
@Test
public void testGetQuerySpecificationWithParingException() {
String sql = "invalid query";
String message = assertThrows(IllegalArgumentException.class, () -> {
MaterializedViewManagerImpl.getQuerySpecification(sql);
}).getMessage();
assertTrue(message.startsWith("Encountered \" <regular_identifier>"));
}
@Test
public void testGetQuerySpecificationWithNullQuery() {
String sql = null;
String message = assertThrows(IllegalArgumentException.class, () -> {
MaterializedViewManagerImpl.getQuerySpecification(sql);
}).getMessage();
assertEquals("The definingSQL of the materialized view is required and must not be the empty string.", message);
}
@Test
public void testGetQuerySpecificationWithEmptyQuery() {
String sql = "";
String message = assertThrows(IllegalArgumentException.class, () -> {
MaterializedViewManagerImpl.getQuerySpecification(sql);
}).getMessage();
assertEquals("The definingSQL of the materialized view is required and must not be the empty string.", message);
}
@Test
public void testGetQuerySpecificationWithBlankQuery() {
String sql = " ";
String message = assertThrows(IllegalArgumentException.class, () -> {
MaterializedViewManagerImpl.getQuerySpecification(sql);
}).getMessage();
assertEquals("The definingSQL of the materialized view is required and must not be a blank string.", message);
}
@Test
public void testGetSourceTableIds() {
QuerySpecification query = MaterializedViewManagerImpl.getQuerySpecification("SELECT * FROM syn123");
Set<IdAndVersion> expected = ImmutableSet.of(IdAndVersion.parse("syn123"));
Set<IdAndVersion> result = MaterializedViewManagerImpl.getSourceTableIds(query);
assertEquals(expected, result);
}
@Test
public void testGetSourceTableIdsWithVersion() {
QuerySpecification query = MaterializedViewManagerImpl.getQuerySpecification("SELECT * FROM syn123.1");
Set<IdAndVersion> expected = ImmutableSet.of(IdAndVersion.parse("syn123.1"));
Set<IdAndVersion> result = MaterializedViewManagerImpl.getSourceTableIds(query);
assertEquals(expected, result);
}
@Test
public void testGetSourceTableIdsWithMultiple() {
QuerySpecification query = MaterializedViewManagerImpl
.getQuerySpecification("SELECT * FROM syn123.1 JOIN syn456 JOIN syn123");
Set<IdAndVersion> expected = ImmutableSet.of(IdAndVersion.parse("syn123"), IdAndVersion.parse("syn123.1"),
IdAndVersion.parse("456"));
Set<IdAndVersion> result = MaterializedViewManagerImpl.getSourceTableIds(query);
assertEquals(expected, result);
}
@Test
public void testBindSchemaToView() {
when(mockColumnModelManager.getTableSchema(any())).thenReturn(syn123Schema);
when(mockColumnModelManager.createColumnModel(any())).thenReturn(
TableModelTestUtils.createColumn(333L, "foo", ColumnType.INTEGER),
TableModelTestUtils.createColumn(444L, "bar", ColumnType.STRING));
IdAndVersion idAndVersion = IdAndVersion.parse("syn123");
QuerySpecification query = MaterializedViewManagerImpl.getQuerySpecification("SELECT * FROM syn123");
when(mockTableManagerSupport.getIndexDescription(any())).thenReturn(new MaterializedViewIndexDescription(
idAndVersion, Arrays.asList(new TableIndexDescription(IdAndVersion.parse("syn1")))));
// call under test
manager.bindSchemaToView(idAndVersion, query);
verify(mockColumnModelManager).getTableSchema(idAndVersion);
verify(mockColumnModelManager)
.createColumnModel(new ColumnModel().setName("foo").setColumnType(ColumnType.INTEGER).setId(null));
verify(mockColumnModelManager).createColumnModel(
new ColumnModel().setName("bar").setColumnType(ColumnType.STRING).setMaximumSize(50L).setId(null));
verify(mockColumnModelManager).bindColumnsToVersionOfObject(Arrays.asList("333", "444"), idAndVersion);
verify(mockTableManagerSupport).getIndexDescription(idAndVersion);
}
@Test
public void testRefreshDependentMaterializedViews() {
List<IdAndVersion> dependencies = Arrays.asList(
IdAndVersion.parse("syn123"),
IdAndVersion.parse("234"),
IdAndVersion.parse("syn456.2")
);
// The second return must be an empty list because of the PaginationIterator that performs an additional call to check if there are more results
when(mockMaterializedViewDao.getMaterializedViewIdsPage(any(), anyLong(), anyLong())).thenReturn(dependencies, Collections.emptyList());
List<ChangeMessage> expectedMessages = Arrays.asList(
new ChangeMessage().setObjectType(ObjectType.MATERIALIZED_VIEW).setObjectId("123").setChangeType(ChangeType.UPDATE),
new ChangeMessage().setObjectType(ObjectType.MATERIALIZED_VIEW).setObjectId("234").setChangeType(ChangeType.UPDATE),
new ChangeMessage().setObjectType(ObjectType.MATERIALIZED_VIEW).setObjectId("456").setObjectVersion(2L).setChangeType(ChangeType.UPDATE)
);
// Call under test
manager.refreshDependentMaterializedViews(idAndVersion);
for (ChangeMessage change : expectedMessages) {
verify(mockMessagePublisher).sendMessageAfterCommit(change);
}
verifyNoMoreInteractions(mockMessagePublisher);
}
@Test
public void testRefreshDependentMaterializedViewsWithNoIdAndVersion() {
String message = assertThrows(IllegalArgumentException.class, () -> {
// Call under test
manager.refreshDependentMaterializedViews(null);
}).getMessage();
assertEquals("The tableId is required.", message);
verifyZeroInteractions(mockMaterializedViewDao);
verifyZeroInteractions(mockMessagePublisher);
}
@Test
public void testDeleteViewIndex() {
when(mockConnectionFactory.connectToTableIndex(any())).thenReturn(mockTableIndexManager);
// call under test
manager.deleteViewIndex(idAndVersion);
verify(mockConnectionFactory).connectToTableIndex(idAndVersion);
verify(mockTableIndexManager).deleteTableIndex(idAndVersion);
}
@Test
public void testCreateOrUpdateViewIndex() throws Exception {
doAnswer(invocation -> {
ProgressCallback callback = (ProgressCallback) invocation.getArguments()[0];
ProgressingCallable runner = (ProgressingCallable) invocation.getArguments()[2];
runner.call(callback);
return null;
}).when(mockTableManagerSupport).tryRunWithTableExclusiveLock(any(), any(IdAndVersion.class), any());
doNothing().when(managerSpy).createOrRebuildViewHoldingExclusiveLock(any(), any());
// call under test
managerSpy.createOrUpdateViewIndex(mockProgressCallback, idAndVersion);
verify(mockTableManagerSupport).tryRunWithTableExclusiveLock(eq(mockProgressCallback), eq(idAndVersion), any());
verify(managerSpy).createOrRebuildViewHoldingExclusiveLock(mockProgressCallback, idAndVersion);
}
@Test
public void testCreateOrRebuildViewHoldingExclusiveLock() throws Exception {
idAndVersion = IdAndVersion.parse("syn123");
doAnswer(invocation -> {
ProgressCallback callback = (ProgressCallback) invocation.getArguments()[0];
ProgressingCallable runner = (ProgressingCallable) invocation.getArguments()[1];
runner.call(callback);
return null;
}).when(mockTableManagerSupport).tryRunWithTableNonexclusiveLock(any(), any(), any());
when(mockMaterializedViewDao.getMaterializedViewDefiningSql(any())).thenReturn(Optional.of("select * from syn456"));
when(mockColumnModelManager.getTableSchema(any())).thenReturn(syn123Schema);
IndexDescription indexDescription = new MaterializedViewIndexDescription(idAndVersion, Collections.emptyList());
when(mockTableManagerSupport.getIndexDescription(any())).thenReturn(indexDescription);
when(mockTableManagerSupport.getTableStatusOrCreateIfNotExists(any())).thenReturn(new TableStatus().setState(TableState.AVAILABLE));
doNothing().when(managerSpy).bindSchemaToView(any(), any(SqlQuery.class));
IdAndVersion dependentIdAndVersion = IdAndVersion.parse("syn456");
// call under test
managerSpy.createOrRebuildViewHoldingExclusiveLock(mockProgressCallback, idAndVersion);
verify(mockMaterializedViewDao).getMaterializedViewDefiningSql(idAndVersion);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(SqlQuery.class));
verify(mockTableManagerSupport).getTableStatusOrCreateIfNotExists(dependentIdAndVersion);
verify(mockTableManagerSupport).tryRunWithTableNonexclusiveLock(eq(mockProgressCallback), any(), eq( dependentIdAndVersion));
verify(managerSpy).createOrRebuildViewHoldingWriteLockAndAllDependentReadLocks(eq(idAndVersion), any());
}
@Test
public void testCreateOrRebuildViewHoldingExclusiveLockWithSnapshot() throws Exception {
idAndVersion = IdAndVersion.parse("syn123.1");
doAnswer(invocation -> {
ProgressCallback callback = (ProgressCallback) invocation.getArguments()[0];
ProgressingCallable runner = (ProgressingCallable) invocation.getArguments()[1];
runner.call(callback);
return null;
}).when(mockTableManagerSupport).tryRunWithTableNonexclusiveLock(any(), any(), any());
IndexDescription indexDescription = new MaterializedViewIndexDescription(idAndVersion, Collections.emptyList());
when(mockTableManagerSupport.getIndexDescription(any())).thenReturn(indexDescription);
when(mockMaterializedViewDao.getMaterializedViewDefiningSql(any())).thenReturn(Optional.of("select * from syn456"));
when(mockTableManagerSupport.getTableStatusOrCreateIfNotExists(any())).thenReturn(new TableStatus().setState(TableState.AVAILABLE));
when(mockColumnModelManager.getTableSchema(any())).thenReturn(syn123Schema);
IdAndVersion dependentIdAndVersion = IdAndVersion.parse("syn456");
// call under test
managerSpy.createOrRebuildViewHoldingExclusiveLock(mockProgressCallback, idAndVersion);
verify(mockTableManagerSupport).getIndexDescription(idAndVersion);
verify(mockMaterializedViewDao).getMaterializedViewDefiningSql(idAndVersion);
verify(mockColumnModelManager, never()).bindColumnsToVersionOfObject(any(), any());
verify(mockTableManagerSupport).getTableStatusOrCreateIfNotExists(dependentIdAndVersion);
verify(mockTableManagerSupport).tryRunWithTableNonexclusiveLock(eq(mockProgressCallback), any(), eq( dependentIdAndVersion));
verify(managerSpy).createOrRebuildViewHoldingWriteLockAndAllDependentReadLocks(eq(idAndVersion), any());
}
@Test
public void testCreateOrRebuildViewHoldingExclusiveLockWithMultipleDependencies() throws Exception {
idAndVersion = IdAndVersion.parse("syn123");
doAnswer(invocation -> {
ProgressCallback callback = (ProgressCallback) invocation.getArguments()[0];
ProgressingCallable runner = (ProgressingCallable) invocation.getArguments()[1];
runner.call(callback);
return null;
}).when(mockTableManagerSupport).tryRunWithTableNonexclusiveLock(any(), any(), any());
when(mockMaterializedViewDao.getMaterializedViewDefiningSql(any()))
.thenReturn(Optional.of("select * from syn456 join syn789"));
IndexDescription indexDescription = new MaterializedViewIndexDescription(idAndVersion, Collections.emptyList());
when(mockTableManagerSupport.getIndexDescription(any())).thenReturn(indexDescription);
when(mockColumnModelManager.getTableSchema(any())).thenReturn(syn123Schema);
when(mockTableManagerSupport.getTableStatusOrCreateIfNotExists(any())).thenReturn(new TableStatus().setState(TableState.AVAILABLE));
doNothing().when(managerSpy).bindSchemaToView(any(), any(SqlQuery.class));
IdAndVersion[] dependentIdAndVersions = new IdAndVersion[] { IdAndVersion.parse("syn456"),
IdAndVersion.parse("syn789") };
// call under test
managerSpy.createOrRebuildViewHoldingExclusiveLock(mockProgressCallback, idAndVersion);
verify(mockMaterializedViewDao).getMaterializedViewDefiningSql(idAndVersion);
verify(mockTableManagerSupport).getIndexDescription(idAndVersion);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(SqlQuery.class));
verify(mockTableManagerSupport).getTableStatusOrCreateIfNotExists(dependentIdAndVersions[0]);
verify(mockTableManagerSupport).getTableStatusOrCreateIfNotExists(dependentIdAndVersions[1]);
verify(mockTableManagerSupport).tryRunWithTableNonexclusiveLock(eq(mockProgressCallback), any(),
eq(dependentIdAndVersions[0]), eq(dependentIdAndVersions[1]));
verify(managerSpy).createOrRebuildViewHoldingWriteLockAndAllDependentReadLocks(eq(idAndVersion), any());
}
@Test
public void testCreateOrRebuildViewHoldingExclusiveLockWithMultipleDependenciesWithUnavailable() throws Exception {
idAndVersion = IdAndVersion.parse("syn123");
when(mockMaterializedViewDao.getMaterializedViewDefiningSql(any()))
.thenReturn(Optional.of("select * from syn456 join syn789"));
when(mockColumnModelManager.getTableSchema(any())).thenReturn(syn123Schema);
IndexDescription indexDescription = new MaterializedViewIndexDescription(idAndVersion, Collections.emptyList());
when(mockTableManagerSupport.getIndexDescription(any())).thenReturn(indexDescription);
when(mockTableManagerSupport.getTableStatusOrCreateIfNotExists(any())).thenReturn(new TableStatus().setState(TableState.AVAILABLE),
new TableStatus().setState(TableState.PROCESSING));
doNothing().when(managerSpy).bindSchemaToView(any(), any(SqlQuery.class));
IdAndVersion[] dependentIdAndVersions = new IdAndVersion[] { IdAndVersion.parse("syn456"),
IdAndVersion.parse("syn789") };
assertThrows(RecoverableMessageException.class, ()->{
// call under test
managerSpy.createOrRebuildViewHoldingExclusiveLock(mockProgressCallback, idAndVersion);
});
verify(mockMaterializedViewDao).getMaterializedViewDefiningSql(idAndVersion);
verify(managerSpy).bindSchemaToView(eq(idAndVersion), any(SqlQuery.class));
verify(mockTableManagerSupport).getTableStatusOrCreateIfNotExists(dependentIdAndVersions[0]);
verify(mockTableManagerSupport).getTableStatusOrCreateIfNotExists(dependentIdAndVersions[1]);
verify(mockTableManagerSupport, never()).tryRunWithTableNonexclusiveLock(any(), any());
verify(managerSpy, never()).createOrRebuildViewHoldingWriteLockAndAllDependentReadLocks(any(), any());
}
@Test
public void testCreateOrRebuildViewHoldingExclusiveLockWithNoDefiningSql() throws Exception {
when(mockMaterializedViewDao.getMaterializedViewDefiningSql(any())).thenReturn(Optional.empty());
String message = assertThrows(IllegalArgumentException.class, ()->{
// call under test
managerSpy.createOrRebuildViewHoldingExclusiveLock(mockProgressCallback, idAndVersion);
}).getMessage();
assertEquals("No defining SQL for: syn123.1", message);
verify(mockMaterializedViewDao).getMaterializedViewDefiningSql(any());
verify(mockColumnModelManager, never()).bindColumnsToVersionOfObject(any(), any());
verify(mockTableManagerSupport, never()).tryRunWithTableNonexclusiveLock(any(), any(), any());
verify(managerSpy, never()).createOrRebuildViewHoldingWriteLockAndAllDependentReadLocks(eq(idAndVersion), any());
}
}
|
package tools.vitruv.framework.tests.vsum;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.UMLFactory;
import org.junit.Test;
import pcm_mockup.Component;
import pcm_mockup.Repository;
import tools.vitruv.framework.tuid.AttributeTUIDCalculatorAndResolver;
import tools.vitruv.framework.tuid.TUID;
import tools.vitruv.framework.tuid.TUIDCalculatorAndResolver;
import tools.vitruv.framework.util.datatypes.ModelInstance;
import tools.vitruv.framework.util.datatypes.VURI;
import tools.vitruv.framework.vsum.InternalVirtualModel;
public class DefaultTUIDCalculatorTest extends VSUMTest {
@Test
public void testAll() {
InternalVirtualModel vsum = createMetaRepositoryVSUMAndModelInstances();
VURI model1URI = VURI.getInstance(getDefaultPCMInstanceURI());
ModelInstance model1 = vsum.getModelInstance(model1URI);
Repository pcmRoot = (Repository) model1.getResource().getContents().get(0);
String expectedTUID = pcmRoot.getId();
EObject resolvedEObject = testTUIDCalculator(PCM_MM_URI, pcmRoot, pcmRoot, expectedTUID, "id");
assertEquals(resolvedEObject, pcmRoot);
Component pcmComponent = (Component) pcmRoot.eContents().get(1);
expectedTUID = pcmComponent.getId();
resolvedEObject = testTUIDCalculator(PCM_MM_URI, pcmRoot, pcmComponent, expectedTUID, "id");
assertEquals(resolvedEObject, pcmComponent);
}
@Test
public void testTUIDCalculationAndResolutionForUnsettedElement() {
// create UML class with empty Property
Property umlProperty = createUmlModelWithProperty();
String expectedTUID = "name";
String umlPrefix = umlProperty.eClass().getEPackage().getNsPrefix();
EObject resolvedEObject = testTUIDCalculator(umlPrefix, umlProperty.getClass_().getPackage(), umlProperty,
expectedTUID, "name");
assertEquals("UAttribute could not be correctly resolved", resolvedEObject, umlProperty);
}
private Property createUmlModelWithProperty() {
Package umlPackage = UMLFactory.eINSTANCE.createPackage();
Class umlClass = UMLFactory.eINSTANCE.createClass();
umlPackage.getPackagedElements().add(umlClass);
Property umlProperty = UMLFactory.eINSTANCE.createProperty();
umlClass.getOwnedAttributes().add(umlProperty);
return umlProperty;
}
private EObject testTUIDCalculator(final String tuidPrefix, final EObject rootEObject, final EObject eObject,
final String expectedTUID, final String... attributeNames) {
TUIDCalculatorAndResolver defaultTUIDCalculatorAndResolver = new AttributeTUIDCalculatorAndResolver(tuidPrefix,
attributeNames);
boolean hasTUID = defaultTUIDCalculatorAndResolver.calculateTUIDFromEObject(eObject) != null;
assertTrue("TUID Calculator is not able to calculate TUID for EObject " + eObject, hasTUID);
String calculatedTuid = defaultTUIDCalculatorAndResolver.calculateTUIDFromEObject(eObject);
// Calculated TUID contains more than just the UUID itself. It also contains the resource
// and the class name that was used to create the TUID. Hence, we just compare with contains
// instead of equals
assertNotNull("Calculated TUID is null", calculatedTuid);
assertTrue("Calculated TUID does not contain expected TUID", calculatedTuid.contains(expectedTUID));
TUID tuid = TUID.getInstance(calculatedTuid);
String tuidString = tuid.toString();
assertNotNull("TUID string is null", tuidString);
EObject resolvedEObject = defaultTUIDCalculatorAndResolver.resolveEObjectFromRootAndFullTUID(rootEObject,
tuidString);
assertNotNull(resolvedEObject);
return resolvedEObject;
}
}
|
package org.eclipse.ice.viz.service.visit.test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.ice.client.widgets.test.utils.AbstractSWTTester;
import org.eclipse.ice.viz.service.visit.widgets.TimeSliderComposite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotScale;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotText;
import org.junit.Test;
/**
* This tester applies SWTBot tests to the {@link TimeSliderComposite}. It tests
* the default values, selection listeners, and setting the range of time values
* for the underlying scale, spinner, and text widgets.
*
* @author Jordan
*
*/
public class TimeSliderCompositeTester extends AbstractSWTTester {
/**
* The time widget that will be tested. This gets initialized before and
* disposed after each test.
*/
private TimeSliderComposite timeComposite;
/**
* A list of test times. This includes the values -1.0, 0.0, null, -2.0,
* 42.0, null, 0.0 (again) and 1337.1337. It should be able to be passed to
* the {@link #timeComposite}.
*/
private List<Double> testTimes;
/**
* A list of the complete test times, ordered, and without nulls or
* duplicates.
*/
private SortedSet<Double> orderedTimes;
/**
* The expected size of {@link #testTimes}.
*/
private int testTimesSize;
/**
* The string used in the time text widget when no times are available.
*/
private static final String NO_TIMES = "N/A";
/**
* A fake listener to listen to selection events. Its notified flag is reset
* before each test.
*/
private FakeListener fakeListener1;
/**
* A second fake listener to listen to selection events. Its notified flag
* is reset before each test.
*/
private FakeListener fakeListener2;
/**
* The error of margin for double comparisons.
*/
private final static double epsilon = 1e-5;
/*
* Overrides a method from AbstractSWTTester.
*/
@Override
public void beforeEachTest() {
super.beforeEachTest();
// Initialize the list of times.
testTimes = new ArrayList<Double>();
testTimes.add(-1.0);
testTimes.add(0.0);
testTimes.add(null);
testTimes.add(-2.0);
testTimes.add(42.0);
testTimes.add(null);
testTimes.add(0.0);
testTimes.add(1337.1337);
testTimesSize = testTimes.size();
// Create an ordered set of the times, and remove nulls. We expect the
// time widget to effectively traverse across this set.
Set<Double> hashedTimes = new HashSet<Double>(testTimes);
hashedTimes.remove(null);
orderedTimes = new TreeSet<Double>(hashedTimes);
// Create the two fake listeners.
fakeListener1 = new FakeListener();
fakeListener2 = new FakeListener();
// Initialize the time Composite, set its timesteps, and register the
// first fake listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite = new TimeSliderComposite(getShell(), SWT.NONE);
timeComposite.setTimes(testTimes);
timeComposite.addSelectionListener(fakeListener1);
// Refresh the shell's layout so screenshots will show changes.
getShell().layout();
}
});
// Reset the time.
SWTBotScale scale = getTimeScale();
scale.setValue(scale.getMinimum());
// Reset the listeners.
fakeListener1.wasNotified.set(false);
fakeListener2.wasNotified.set(false);
// Unregister the second fake listener in case one of the listener tests
// failed.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.removeSelectionListener(fakeListener2);
}
});
return;
}
/*
* Overrides a method from AbstractSWTTester.
*/
@Override
public void afterEachTest() {
// Dispose the time widget. The UI thread can do this whenever it gets a
// chance.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.dispose();
timeComposite = null;
// Refresh the shell's layout so screenshots will show changes.
getShell().layout();
}
});
// Empty out the list of times.
testTimes.clear();
testTimes = null;
super.afterEachTest();
}
/**
* Checks the default values for the time widget.
*/
@Test
public void checkDefaults() {
final AtomicInteger timestep = new AtomicInteger();
final AtomicReference<Double> time = new AtomicReference<Double>();
// Create a temporary, blank test Composite, pull off its default
// values, and dispose it.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
TimeSliderComposite c = new TimeSliderComposite(getShell(), SWT.NONE);
timestep.set(c.getTimestep());
time.set(c.getTime());
c.dispose();
}
});
// Check the two getters.
assertEquals(-1, timestep.get());
assertEquals(0.0, time.get(), epsilon);
return;
}
/**
* Checks that the time steps can be set and fetched.
*/
@Test
public void checkSetTimeSteps() {
final AtomicInteger timestep = new AtomicInteger();
final AtomicReference<Double> time = new AtomicReference<Double>();
final List<Double> emptyList = new ArrayList<Double>();
final List<Double> nullList = null;
// Get a copy of the ordered times.
SortedSet<Double> orderedTimes = new TreeSet<Double>(this.orderedTimes);
// Get the time scale widget.
SWTBotScale widget = getTimeScale();
SWTBotScale scale = getTimeScale();
// Check that the list of times sent to the widget was not modified.
assertEquals(
"TimeSliderComposite failure: The collection passed into " + "setTimes(...) should not be modified!",
testTimesSize, testTimes.size());
// Get the timestep and time from the time widget, and check its values
// match.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timestep.set(timeComposite.getTimestep());
time.set(timeComposite.getTime());
}
});
// The timestep should be the first timestep (index 0), while the time
// should be the lowest value.
assertEquals(0, timestep.get());
assertEquals(orderedTimes.first(), time.get(), epsilon);
// Check the scale's min, max, and increment. Each timestep should have
// a tick on the scale.
assertEquals(0, scale.getMinimum());
assertEquals(orderedTimes.size() - 1, scale.getMaximum());
assertEquals(1, scale.getIncrement());
// Set the time widget to the last time.
widget.setValue(orderedTimes.size() - 1);
// Get the timestep and time from the time widget, and check its values
// match.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timestep.set(timeComposite.getTimestep());
time.set(timeComposite.getTime());
}
});
// The timestep should be the last timestep, while the time should be
// the highest value.
assertEquals(orderedTimes.size() - 1, timestep.get());
assertEquals(orderedTimes.last(), time.get(), epsilon);
// Set new times on the widget and get each one from the widget.
orderedTimes.remove(42.0);
orderedTimes.remove(0.0);
final List<Double> newTimes = new ArrayList<Double>(orderedTimes);
// Update the times for the widget and get the default values.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
// Update the times and get the default values.
timeComposite.setTimes(newTimes);
timestep.set(timeComposite.getTimestep());
time.set(timeComposite.getTime());
}
});
assertEquals(0, timestep.get());
assertEquals(orderedTimes.first(), time.get(), epsilon);
// Check all of the times.
for (int i = 0; i < newTimes.size(); i++) {
// Increment the widget.
widget.setValue(i);
// Get the time widget's time and timestep, and compare them.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timestep.set(timeComposite.getTimestep());
time.set(timeComposite.getTime());
}
});
assertEquals(i, timestep.get());
assertEquals(newTimes.get(i), time.get(), epsilon);
}
// We should be able to set to an empty list, in which case the timestep
// switches to -1 and the time to 0.0 (the defaults).
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
// Update the times and get the default values.
timeComposite.setTimes(emptyList);
timestep.set(timeComposite.getTimestep());
time.set(timeComposite.getTime());
}
});
assertEquals(-1, timestep.get());
assertEquals(0.0, time.get(), epsilon);
// Make sure an exception is thrown when the argument is null.
SWTException e = catchSWTException(new Runnable() {
@Override
public void run() {
timeComposite.setTimes(nullList);
}
});
assertNotNull("TimeSliderComposite failure: Null argument exception "
+ "not thrown for setTimes(List<Double>) when passed a " + "null list.", e);
assertEquals(SWT.ERROR_NULL_ARGUMENT, e.code);
// Restore the original times.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.setTimes(testTimes);
}
});
return;
}
/**
* Checks that the widgets are enabled when they should be (when there is
* more than 1 time to pick from) and disabled otherwise.
*/
@Test
public void checkWidgetsEnabled() {
SWTBotScale scale = getTimeScale();
SWTBotButton nextButton = getNextButton();
SWTBotButton prevButton = getPrevButton();
SWTBotButton playButton = getPlayPauseButton();
SWTBotText text = getTimeText();
final List<Double> goodTimes = new ArrayList<Double>();
goodTimes.add(1.0);
goodTimes.add(2.0);
final List<Double> badTimes = new ArrayList<Double>();
badTimes.add(1.0);
// For a new time widget, all sub-widgets should be disabled (no times
// have been set).
final AtomicReference<TimeSliderComposite> testWidget;
testWidget = new AtomicReference<TimeSliderComposite>();
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
testWidget.set(new TimeSliderComposite(getShell(), SWT.NONE));
}
});
// None of them should be enabled. Also, the text widget should say N/A.
SWTBot testBot = new SWTBot(testWidget.get());
assertNotEnabled(testBot.scale());
assertNotEnabled(testBot.button(0));
assertNotEnabled(testBot.button(1));
assertNotEnabled(testBot.button(2));
assertNotEnabled(testBot.text());
assertEquals(NO_TIMES, testBot.text().getText());
// Dispose the temporary test widget.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
testWidget.get().dispose();
}
});
// Initially, the test time widget's sub-widgets are enabled because the
// times have been set.
assertEnabled(scale);
assertEnabled(nextButton);
assertEnabled(prevButton);
assertEnabled(playButton);
assertEnabled(text);
// Setting the times to something with 1 value should disable them.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.setTimes(badTimes);
}
});
assertNotEnabled(scale);
assertNotEnabled(nextButton);
assertNotEnabled(prevButton);
assertNotEnabled(playButton);
assertNotEnabled(text);
// The text widget's text should be set to the current value.
assertEquals(badTimes.get(0).toString(), text.getText());
// Setting the times to something with 2 values should enable them.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.setTimes(goodTimes);
}
});
assertEnabled(scale);
assertEnabled(nextButton);
assertEnabled(prevButton);
assertEnabled(playButton);
assertEnabled(text);
// Setting the times to something with 0 values should also disable
// them.
badTimes.clear();
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.setTimes(badTimes);
}
});
assertNotEnabled(scale);
assertNotEnabled(nextButton);
assertNotEnabled(prevButton);
assertNotEnabled(playButton);
assertNotEnabled(text);
// The text widget's text should be set to N/A.
assertEquals(NO_TIMES, text.getText());
// Restore the times.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.setTimes(testTimes);
}
});
return;
}
/**
* Checks that you cannot add null selection listeners to the time widget.
*/
@Test
public void checkNullSelectionListenerExceptions() {
// Set up the helpful test failure message used if the exception is not
// thrown.
final String missedExceptionFormat = "TimeSliderComposite failure: "
+ "Null argument exception not thrown for %s when passed a " + "null selection listener.";
final SelectionListener nullListener = null;
SWTException e;
// Check addSelectionListener(SelectionListener).
e = catchSWTException(new Runnable() {
@Override
public void run() {
timeComposite.addSelectionListener(nullListener);
}
});
assertNotNull(String.format(missedExceptionFormat, "addSelectionListener(SelectionListener)"), e);
assertEquals(SWT.ERROR_NULL_ARGUMENT, e.code);
// Check removeSelectionListener(SelectionListener).
e = catchSWTException(new Runnable() {
@Override
public void run() {
timeComposite.removeSelectionListener(nullListener);
}
});
assertNotNull(String.format(missedExceptionFormat, "removeSelectionListener(SelectionListener)"), e);
assertEquals(SWT.ERROR_NULL_ARGUMENT, e.code);
return;
}
/**
* Checks that listeners are updated when the scale widget changes.
*/
@Test
public void checkSelectionListenersByScale() {
// Get the specific widget that will be used to set the time.
SWTBotScale widget = getTimeScale();
// Register the second fake listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.addSelectionListener(fakeListener2);
}
});
// They should both be notified when the widget is used to change the
// values.
widget.setValue(widget.getValue() + widget.getIncrement());
assertTrue(fakeListener1.wasNotified());
assertTrue(fakeListener2.wasNotified());
// Unregister this listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.removeSelectionListener(fakeListener2);
}
});
// It should not be notified when the widget changes, but the other
// should still be notified.
widget.setValue(widget.getValue() - widget.getIncrement());
assertFalse(fakeListener2.wasNotified()); // Test this one first!
assertTrue(fakeListener1.wasNotified());
return;
}
/**
* Checks that listeners are updated when the spinner widget changes.
* <p>
* The times should also loop between last and first when the next/previous
* button is clicked.
* </p>
*/
@Test
public void checkSelectionListenersBySpinner() {
// Get the specific widget that will be used to set the time.
SWTBotButton nextButton = getNextButton();
SWTBotButton prevButton = getPrevButton();
final FakeListener loopListener = new FakeListener();
// Register the second fake listener and the test listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.addSelectionListener(loopListener);
timeComposite.addSelectionListener(fakeListener2);
}
});
// They should both be notified when the widget is used to change the
// values.
prevButton.click();
assertTrue(fakeListener1.wasNotified());
assertTrue(fakeListener2.wasNotified());
assertTrue(loopListener.wasNotified());
// The previous button should have looped around to the last time.
assertEquals(orderedTimes.last(), loopListener.notificationTimes.poll(), epsilon);
// Unregister the second fake listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.removeSelectionListener(fakeListener2);
}
});
// It should not be notified when the widget changes, but the other
// should still be notified.
nextButton.click();
assertFalse(fakeListener2.wasNotified()); // Test this one first!
assertTrue(fakeListener1.wasNotified());
assertTrue(loopListener.wasNotified());
// The next button should have looped around to the first time.
assertEquals(orderedTimes.first(), loopListener.notificationTimes.poll(), epsilon);
// Unregister the loop listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.removeSelectionListener(loopListener);
}
});
return;
}
/**
* Checks that listeners are periodically updated when the play button is
* clicked, and that notifications stop when the same (pause) button is
* clicked.
* <p>
* The times should also loop from last to first when the play button is
* clicked.
* </p>
*/
@Test
public void checkSelectionListenersByPlayButton() {
// Get the specific widget that will be used to set the time.
SWTBotButton widget = getPlayPauseButton();
// Set the time to the last timestep. This will ensure the play action
// hits the last timestep, then loops back around to the first.
getTimeScale().setValue(orderedTimes.size() - 2);
// Add a new test listener.
final FakeListener listener = new FakeListener();
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.addSelectionListener(listener);
}
});
// Play for two seconds, then pause. Use a buffer of a half second in
// case the SWTBot click beats the display thread scheduling.
widget.click();
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
fail("TimeSliderCompositeTester error: " + "Thread interrupted while testing play button.");
}
widget.click();
// The listener should have been notified twice: two timesteps were
// traversed while playing.
assertTrue(listener.wasNotified(2, FakeListener.THRESHOLD * 2));
// Check the notification count and the times sent with each
// notification.
Queue<Double> times = listener.notificationTimes;
assertTrue(times.size() >= 2);
assertEquals(orderedTimes.last(), times.poll(), epsilon);
assertEquals(orderedTimes.first(), times.poll(), epsilon);
// Remove the test listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.removeSelectionListener(listener);
}
});
return;
}
/**
* Checks that, when any of the time widgets are updated, the active play
* action is cancelled.
*/
@Test
public void checkPauseOnNewSelection() {
SWTBotButton playButton = getPlayPauseButton();
SWTBotText text = getTimeText();
String firstTime = text.getText();
// Add a new test listener.
final FakeListener listener = new FakeListener();
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.addSelectionListener(listener);
}
});
// The times sent should also alternate between the second and first
// timesteps, because each subsequent call undoes the previous one.
Iterator<Double> iter = orderedTimes.iterator();
double first = iter.next();
double second = iter.next();
// Pause by clicking the play button. No notification sent.
playButton.click();
playButton.click();
assertFalse(listener.wasNotified());
// Pause by clicking the time scale. 1 notification.
playButton.click();
getTimeScale().setValue(1);
assertTrue(listener.wasNotified());
assertEquals(second, listener.notificationTimes.poll());
// Pause by typing text. 1 notification.
playButton.click();
text.selectAll();
text.typeText(firstTime + SWT.CR + SWT.LF);
assertTrue(listener.wasNotified());
assertEquals(first, listener.notificationTimes.poll());
// Pause by clicking the next button. 1 notification.
playButton.click();
getNextButton().click();
assertTrue(listener.wasNotified());
assertEquals(second, listener.notificationTimes.poll());
// Pause by clicking the previous button. 1 notification.
playButton.click();
getPrevButton().click();
assertTrue(listener.wasNotified());
assertEquals(first, listener.notificationTimes.poll());
// The listener should not be notified again.
assertFalse(listener.wasNotified(5));
// Remove the test listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.removeSelectionListener(listener);
}
});
return;
}
/**
* Checks that listeners are updated when the spinner's associated text
* widget changes.
*/
@Test
public void checkSelectionListenersByText() {
/*
* IMPORTANT NOTE ABOUT THIS TEST!
*
* Simulating input into a Text widget with SWTBot is tricky.
* widget.setText(String) does not notify listeners, so you must use
* widget.selectAll() [highlights all the text] and
* widget.typeText(String) [replaces the text].
*
* However, this can be finicky and fail if you are touching the
* keyboard or the mouse, so try running this test again when you are
* not actively using your computer's input. :)
*/
// Get the first and last time.
Double firstTime = testTimes.get(0);
Double lastTime = testTimes.get(testTimes.size() - 1);
// Get the specific widget that will be used to set the time.
SWTBotText widget = getTimeText();
// Register the second fake listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.addSelectionListener(fakeListener2);
}
});
// They should both be notified when the widget is used to change the
// values.
widget.selectAll();
widget.typeText(lastTime.toString() + SWT.CR + SWT.LF);
assertTrue(fakeListener1.wasNotified());
assertTrue(fakeListener2.wasNotified());
// Unregister this listener.
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
timeComposite.removeSelectionListener(fakeListener2);
}
});
// It should not be notified when the widget changes, but the other
// should still be notified.
widget.selectAll();
widget.typeText(firstTime.toString() + SWT.CR + SWT.LF);
assertFalse(fakeListener2.wasNotified()); // Test this one first!
assertTrue(fakeListener1.wasNotified());
return;
}
/**
* Checks that the widget denies changes when the spinner's associated text
* widget is set to an invalid time.
*/
@Test
public void checkInvalidInputIntoText() {
// Get the text widget. We will try feeding it invalid times.
SWTBotText widget = getTimeText();
// Create a list of invalid times.
List<String> invalidTimes = new ArrayList<String>();
invalidTimes.add("");
invalidTimes.add("infinite improbability");
invalidTimes.add(" ");
// Get the initial time.
final AtomicReference<Double> time = new AtomicReference<Double>();
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
time.set(timeComposite.getTime());
}
});
final double initialTime = time.get();
for (String invalidTime : invalidTimes) {
// Try setting an invalid time string.
widget.setText(invalidTime);
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
time.set(timeComposite.getTime());
}
});
// Ensure that the time did not change.
assertEquals(initialTime, time.get(), epsilon);
}
return;
}
/**
* Checks that attempting to set or get fields on the widget from a non-UI
* thread throws an invalid thread access exception.
*/
@Test
public void checkInvalidThreadAccessExceptions() {
// Set up the helpful test failure message used if the exception is not
// thrown.
String missedExceptionFormat = "TimeSliderComposite failure: "
+ "Invalid thread exception not thrown for %s when accessed " + "from non-UI thread.";
// Check getTimeStep().
try {
timeComposite.getTimestep();
fail(String.format(missedExceptionFormat, "getTimestep()"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_THREAD_INVALID_ACCESS, e.code);
}
// Check getTime().
try {
timeComposite.getTime();
fail(String.format(missedExceptionFormat, "getTime()"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_THREAD_INVALID_ACCESS, e.code);
}
// Check setTimes(List<Double>).
try {
timeComposite.setTimes(testTimes);
fail(String.format(missedExceptionFormat, "setTimes(List<Double>)"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_THREAD_INVALID_ACCESS, e.code);
}
// Check addSelectionListener(SelectionListener).
try {
timeComposite.addSelectionListener(fakeListener1);
fail(String.format(missedExceptionFormat, "addSelectionListener(SelectionListener)"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_THREAD_INVALID_ACCESS, e.code);
}
// Check removeSelectionListener(SelectionListener).
try {
timeComposite.removeSelectionListener(fakeListener1);
fail(String.format(missedExceptionFormat, "removeSelectionListener(SelectionListener)"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_THREAD_INVALID_ACCESS, e.code);
}
return;
}
/**
* Checks that attempting to set or get fields on the widget throws a widget
* disposed exception if it is disposed.
*/
@Test
public void checkWidgetDisposedExceptions() {
// Set up the helpful test failure message used if the exception is not
// thrown.
String missedExceptionFormat = "TimeSliderComposite failure: "
+ "Widget disposed exception not thrown for %s when accessed " + "after widget is disposed.";
// Create a disposed time widget.
final AtomicReference<TimeSliderComposite> testCompositeRef;
testCompositeRef = new AtomicReference<TimeSliderComposite>();
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
TimeSliderComposite composite;
composite = new TimeSliderComposite(getShell(), SWT.NONE);
composite.dispose();
testCompositeRef.set(composite);
}
});
// Check getTimeStep().
try {
testCompositeRef.get().getTimestep();
fail(String.format(missedExceptionFormat, "getTimestep()"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_WIDGET_DISPOSED, e.code);
}
// Check getTime().
try {
testCompositeRef.get().getTime();
fail(String.format(missedExceptionFormat, "getTime()"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_WIDGET_DISPOSED, e.code);
}
// Check setTimes(List<Double>).
try {
testCompositeRef.get().setTimes(testTimes);
fail(String.format(missedExceptionFormat, "setTimes(List<Double>)"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_WIDGET_DISPOSED, e.code);
}
// Check addSelectionListener(SelectionListener).
try {
testCompositeRef.get().addSelectionListener(fakeListener1);
fail(String.format(missedExceptionFormat, "addSelectionListener(SelectionListener)"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_WIDGET_DISPOSED, e.code);
}
// Check removeSelectionListener(SelectionListener).
try {
testCompositeRef.get().removeSelectionListener(fakeListener1);
fail(String.format(missedExceptionFormat, "removeSelectionListener(SelectionListener)"));
} catch (SWTException e) {
assertEquals(SWT.ERROR_WIDGET_DISPOSED, e.code);
}
return;
}
/**
* Checks that setting the background for the main widget also updates its
* child widgets.
*/
@Test
public void checkSetBackground() {
final Display display = getDisplay();
final AtomicReference<Color> bg = new AtomicReference<Color>();
// Set the background for the widget.
display.syncExec(new Runnable() {
@Override
public void run() {
bg.set(display.getSystemColor(SWT.COLOR_DARK_GREEN));
timeComposite.setBackground(bg.get());
}
});
// Check the background for all of the child widgets.
assertEquals(bg.get(), getPrevButton().backgroundColor());
assertEquals(bg.get(), getPlayPauseButton().backgroundColor());
assertEquals(bg.get(), getNextButton().backgroundColor());
assertEquals(bg.get(), getTimeScale().backgroundColor());
return;
}
/**
* Checks that helpful tool tips are set on all of the child widgets.
*/
@Test
public void checkWidgetAppearance() {
// Get the widgets.
SWTBotScale scale = getTimeScale();
final SWTBotButton nextButton = getNextButton();
final SWTBotButton prevButton = getPrevButton();
final SWTBotButton playButton = getPlayPauseButton();
SWTBotText text = getTimeText();
// The buttons should not have text.
assertTrue(prevButton.getText().isEmpty());
assertTrue(playButton.getText().isEmpty());
assertTrue(nextButton.getText().isEmpty());
// Check that the buttons use images.
final List<Image> images = new ArrayList<Image>(3);
getDisplay().syncExec(new Runnable() {
@Override
public void run() {
images.add(prevButton.widget.getImage());
images.add(playButton.widget.getImage());
images.add(nextButton.widget.getImage());
}
});
assertNotNull("\"prev\" button is missing an image.", images.get(0));
assertNotNull("\"play\" button is missing an image.", images.get(1));
assertNotNull("\"next\" button is missing an image.", images.get(2));
// Check the tool tips.
assertEquals("Previous", prevButton.getToolTipText());
assertEquals("Play", playButton.getToolTipText());
assertEquals("Next", nextButton.getToolTipText());
assertEquals("Traverses the timesteps", scale.getToolTipText());
assertEquals("The current time", text.getToolTipText());
// Check the tool tip before and after the play button is toggled.
playButton.click();
assertEquals("Pause", playButton.getToolTipText());
playButton.click();
assertEquals("Play", playButton.getToolTipText());
return;
}
/**
* Gets the SWTBot-wrapped scale widget for the play/pause button.
*
* @return The wrapped play button.
*/
private SWTBotButton getPlayPauseButton() {
return getBot().button(1);
}
/**
* Gets the SWTBot-wrapped scale widget for the time steps.
*
* @return The wrapped scale widget.
*/
private SWTBotScale getTimeScale() {
return getBot().scale();
}
/**
* Gets the SWTBot-wrapped button widget that jumps to the next timestep.
*
* @return The wrapped next button.
*/
private SWTBotButton getNextButton() {
return getBot().button(2);
}
/**
* Gets the SWTBot-wrapped button widget that jumps to the previous
* timestep.
*
* @return The wrapped previous button.
*/
private SWTBotButton getPrevButton() {
return getBot().button(0);
}
/**
* Gets the SWTBot-wrapped text widget for the time steps.
*
* @return The wrapped text widget.
*/
private SWTBotText getTimeText() {
return getBot().text();
}
/**
* A fake {@link SelectionListener} that sets its {@link #wasNotified} flag
* to true if notified of a selection event. Instead of checking the flag
* itself, use the method {@link #wasNotified()}, which waits to make sure
* the listener has time to update.
*
* @author Jordan
*
*/
private class FakeListener extends SelectionAdapter {
/**
* This can be used to count how many notifications have been sent to
* this listener.
*/
private final AtomicInteger notificationCount = new AtomicInteger();
/**
* This can be used to determine what time was sent at each
* notification.
*/
private final Queue<Double> notificationTimes = new ConcurrentLinkedQueue<Double>();
/**
* This flag is set by {@link #widgetSelected(SelectionEvent)}.
*/
private final AtomicBoolean wasNotified = new AtomicBoolean();
/**
* The threshold of time (in milliseconds) to wait before returning.
*/
private static final long THRESHOLD = 3000;
/*
* Overrides a method from SelectionAdapter.
*/
@Override
public void widgetSelected(SelectionEvent e) {
notificationTimes.add((Double) e.data);
notificationCount.incrementAndGet();
wasNotified.set(true);
}
/**
* Determines whether the listener was notified of a selection event.
* This is safe to call from off the UI thread, and will wait up to
* {@link #THRESHOLD} milliseconds before returning the notified state.
* It will return sooner if the listener is notified sooner!
*
* @return True if the listener was notified within the threshold, false
* otherwise.
*/
private boolean wasNotified() {
// See if the listener was notified.
boolean notified = wasNotified.getAndSet(false);
// If not, keep trying for a few seconds or until it is notified.
long interval = 50;
for (long sleepTime = 0; sleepTime < THRESHOLD && !notified; sleepTime += interval) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
notified = wasNotified.getAndSet(false);
}
return notified;
}
/**
* Waits up to {@link #THRESHOLD} milliseconds before returning whether
* or not the notification count is greater than or equal to the desired
* count. This will return sooner if the notification count is satisfied
* sooner!
*
* @param count
* The number of notifications to wait on.
* @return True if the notification count is at least the specified
* count, false otherwise.
*/
private boolean wasNotified(int count) {
long interval = 50;
for (long sleepTime = 0; sleepTime < THRESHOLD && notificationCount.get() < count; sleepTime += interval) {
try {
Thread.sleep(interval);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
return notificationCount.get() >= count;
}
/**
* Waits up to {@link #THRESHOLD} milliseconds before returning whether
* or not the notification count is greater than or equal to the desired
* count. This will return sooner if the notification count is satisfied
* sooner!
*
* @param count
* The number of notifications to wait on.
* @param totalThreshold
* The total amount of time this request will wait.
* @return True if the notification count is at least the specified
* count, false otherwise.
*/
private boolean wasNotified(int count, long totalThreshold) {
long interval = 50;
for (long sleepTime = 0; sleepTime < totalThreshold
&& notificationCount.get() < count; sleepTime += interval) {
try {
Thread.sleep(interval);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
return notificationCount.get() >= count;
}
}
}
|
// -*- mode:Java; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
package org.apache.hadoop.fs.ceph;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
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.lang.IndexOutOfBoundsException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSInputStream;
class CephInputStream extends FSInputStream {
static {
System.loadLibrary("hadoopcephfs");
}
private int bufferSize;
//private Block[] blocks;
private boolean closed;
private long clientPointer;
private int fileHandle;
private long fileLength;
//private long pos = 0;
//private DataInputStream blockStream;
//private long blockEnd = -1;
private native int ceph_read(long client, int fh, byte[] buffer, int buffer_offset, int length);
private native long ceph_seek_from_start(long client, int fh, long pos);
private native long ceph_getpos(long client, int fh);
private native int ceph_close(long client, int fh);
private int ceph_read(byte[] buffer, int buffer_offset, int length)
{ return ceph_read(clientPointer, fileHandle, buffer, buffer_offset, length); }
private long ceph_seek_from_start(long pos) { return ceph_seek_from_start(clientPointer, fileHandle, pos); }
private long ceph_getpos() { return ceph_getpos(clientPointer, fileHandle); }
private int ceph_close() { return ceph_close(clientPointer, fileHandle); }
/*
public S3InputStream(Configuration conf, FileSystemStore store,
INode inode) {
this.store = store;
this.blocks = inode.getBlocks();
for (Block block : blocks) {
this.fileLength += block.getLength();
}
this.bufferSize = conf.getInt("io.file.buffer.size", 4096);
}
*/
public CephInputStream(Configuration conf, long clientp, int fh, long flength) {
// Whoever's calling the constructor is responsible for doing the actual ceph_open
// call and providing the file handle.
clientPointer = clientp;
fileLength = flength;
fileHandle = fh;
//System.out.println("CephInputStream constructor: initializing stream with fh "
// + fh + " and file length " + flength);
// TODO: Then what do we need from the config? The buffer size maybe?
// Anything? Bueller?
}
public synchronized long getPos() throws IOException {
return ceph_getpos();
}
@Override
public synchronized int available() throws IOException {
return (int) (fileLength - getPos());
}
public synchronized void seek(long targetPos) throws IOException {
//System.out.println("CephInputStream.seek: Seeking to position " + targetPos +
// " on fd " + fileHandle);
if (targetPos > fileLength) {
throw new IOException("CephInputStream.seek: failed seeking to position " + targetPos +
" on fd " + fileHandle + ": Cannot seek after EOF " + fileLength);
}
ceph_seek_from_start(targetPos);
}
//method stub obviously
public synchronized boolean seekToNewSource(long targetPos) {
return true;
}
// reads a byte
@Override
public synchronized int read() throws IOException {
//System.out.println("CephInputStream.read: Reading a single byte from fd " + fileHandle
// + " by calling general read function");
byte result[] = new byte[1];
if (getPos() >= fileLength) return -1;
if (-1 == read(result, 0, 1)) return -1;
return result[0];
}
@Override
public synchronized int read(byte buf[], int off, int len) throws IOException {
//System.out.println("CephInputStream.read: Reading " + len + " bytes from fd " + fileHandle);
if (closed) {
throw new IOException("CephInputStream.read: cannot read " + len +
" bytes from fd " + fileHandle + ": stream closed");
}
if (null == buf) {
throw new NullPointerException("Read buffer is null");
}
// check for proper index bounds
if((off < 0) || (len < 0) || (off + len > buf.length)) {
throw new IndexOutOfBoundsException("CephInputStream.read: Indices out of bounds for read: "
+ "read length is " + len + ", buffer offset is "
+ off +", and buffer size is " + buf.length);
}
// ensure we're not past the end of the file
if (getPos() >= fileLength)
{
System.out.println("CephInputStream.read: cannot read " + len +
" bytes from fd " + fileHandle + ": current position is " +
getPos() + " and file length is " + fileLength);
return -1;
}
// actually do the read
int result = ceph_read(buf, off, len);
if (result < 0)
System.out.println("CephInputStream.read: Reading " + len + " bytes from fd "
+ fileHandle + " failed.");
else {}
// System.out.println("CephInputStream.read: Reading " + len + " bytes from fd "
// + fileHandle + ": succeeded in reading " + result + " bytes");
return result;
}
@Override
public void close() throws IOException {
if (closed) {
throw new IOException("Stream closed");
}
int result = ceph_close();
if (result != 0) {
throw new IOException("Close failed!");
}
closed = true;
}
/**
* We don't support marks.
*/
@Override
public boolean markSupported() {
return false;
}
@Override
public void mark(int readLimit) {
// Do nothing
}
@Override
public void reset() throws IOException {
throw new IOException("Mark not supported");
}
}
|
package com.comcast.cdn.traffic_control.traffic_monitor.health;
import com.comcast.cdn.traffic_control.traffic_monitor.config.Cache;
import com.comcast.cdn.traffic_control.traffic_monitor.data.DataPoint;
import org.apache.log4j.Logger;
import org.apache.wicket.ajax.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
public class DeliveryServiceStateRegistry extends StateRegistry implements Serializable {
private static final Logger LOGGER = Logger.getLogger(DeliveryServiceStateRegistry.class);
// Recommended Singleton Pattern implementation
private DeliveryServiceStateRegistry() { }
public static DeliveryServiceStateRegistry getInstance() {
return DeliveryServiceStateRegistryHolder.REGISTRY;
}
private static class DeliveryServiceStateRegistryHolder {
private static final DeliveryServiceStateRegistry REGISTRY = new DeliveryServiceStateRegistry();
}
public void completeUpdateAll(final HealthDeterminer myHealthDeterminer, final JSONObject dsList, final long lenientTime) {
for(AbstractState state : CacheStateRegistry.getInstance().getAll()) {
if (state instanceof CacheState) {
CacheState cacheState = (CacheState) state;
if (!cacheState.getCache().hasDeliveryServices()) {
continue;
}
updateStates(cacheState, lenientTime);
}
}
final Collection<String> toRemove = new ArrayList<String>();
toRemove.addAll(states.keySet());
for(String dsId : JSONObject.getNames(dsList)) {
toRemove.remove(dsId);
try {
final DsState dss = (DsState) getOrCreate(dsId);
dss.completeRound(myHealthDeterminer.getDsControls(dss.getId()));
} catch(Exception e) {
LOGGER.warn(e,e);
}
}
for(String id : toRemove) {
states.remove(id);
}
}
private void updateStates(final CacheState cacheState, final long lenientTime) {
final Cache cache = cacheState.getCache();
for(String deliveryServiceId : cache.getDeliveryServiceIds()) {
try {
final List<String> fqdns = cache.getFqdns(deliveryServiceId);
final DsState deliveryServiceState = (DsState) getOrCreate(deliveryServiceId);
// Don't count the cache as reporting unless there were no errors and stats were read
boolean error = false;
boolean foundStats = false;
for(String fqdn : fqdns) {
final String propBase = "ats.plugin.remap_stats."+fqdn;
final DsStati stati = createStati(propBase, cacheState, lenientTime, deliveryServiceId);
deliveryServiceState.accumulate(stati, cache.getLocation(), cacheState);
if (stati != null) {
foundStats = true;
if (stati.error) {
error = true;
}
}
}
// Update cache counters
deliveryServiceState.addCacheConfigured();
if (cacheState.isAvailable()) {
deliveryServiceState.addCacheAvailable();
}
if (foundStats && !error) {
deliveryServiceState.addCacheReporting();
}
} catch(Exception e) {
LOGGER.warn(e,e);
}
}
}
public void startUpdateAll() {
synchronized(states) {
for(AbstractState ds :states.values()) {
ds.prepareStatisticsForUpdate();
}
}
}
@Override
protected AbstractState createState(final String deliveryServiceId) {
return new DsState(deliveryServiceId);
}
private DsStati createStati(final String propBase, final CacheState cacheState, final long leniency, final String dsId) {
DsStati dsStati;
synchronized (cacheState) {
final Deque<DataPoint> dataPoints = cacheState.getDataPoints(propBase + ".out_bytes");
if (dataPoints == null) {
return null;
}
long lastIndex = dataPoints.getLast().getIndex();
lastIndex = getLastGoodIndex(dataPoints, lastIndex);
if (lastIndex < 0) {
return null;
}
final long time = cacheState.getTime(lastIndex);
if (time < leniency) {
return null;
}
dsStati = new DsStati(propBase, cacheState, lastIndex, dsId);
final long prevIndex = getLastGoodIndex(dataPoints, lastIndex-1);
if (prevIndex >= 0) {
final DsStati priorDsStati = new DsStati(propBase, cacheState, prevIndex, dsId);
if (!dsStati.calculateKbps(priorDsStati)) {
if (LOGGER.isInfoEnabled()) {
printDps(dataPoints, propBase);
}
}
}
}
return dsStati;
}
private long getLastGoodIndex(final Deque<DataPoint> dataPoints, final long targetIndex) {
if (targetIndex < 0) {
return -1;
}
Iterator<DataPoint> dataPointIterator = dataPoints.descendingIterator();
while (dataPointIterator.hasNext()) {
DataPoint dataPoint = dataPointIterator.next();
if (dataPoint.getValue() == null) {
continue;
}
final long index = dataPoint.getIndex();
final long span = dataPoint.getSpan();
if (targetIndex <= (index-span)) {
continue;
}
if (targetIndex < index) {
return targetIndex;
}
return index;
}
return -1;
}
public boolean printDps(final Deque<DataPoint> dataPoints, final String id) {
LOGGER.warn(id + ":");
Iterator<DataPoint> dataPointIterator = dataPoints.descendingIterator();
while (dataPointIterator.hasNext()) {
DataPoint dataPoint = dataPointIterator.next();
LOGGER.warn(String.format("\tindex: %d, span: %d, value: %s", dataPoint.getIndex(), dataPoint.getSpan(), dataPoint.getValue()
));
}
return false;
}
}
|
package org.elasticsearch.xpack.ml.integration;
import org.apache.logging.log4j.LogManager;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig;
import org.elasticsearch.xpack.core.ml.job.config.AnalysisConfig;
import org.elasticsearch.xpack.core.ml.job.config.DataDescription;
import org.elasticsearch.xpack.core.ml.job.config.Detector;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import org.elasticsearch.xpack.core.ml.job.results.CategoryDefinition;
import org.elasticsearch.xpack.ml.MachineLearning;
import org.junit.After;
import org.junit.Before;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
/**
* A fast integration test for categorization
*/
public class CategorizationIT extends MlNativeAutodetectIntegTestCase {
private static final String DATA_INDEX = "log-data";
private long nowMillis;
@Before
public void setUpData() {
client().admin().indices().prepareCreate(DATA_INDEX)
.setMapping("time", "type=date,format=epoch_millis",
"msg", "type=text")
.get();
nowMillis = System.currentTimeMillis();
BulkRequestBuilder bulkRequestBuilder = client().prepareBulk();
IndexRequest indexRequest = new IndexRequest(DATA_INDEX);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(2).millis(),
"msg", "Node 1 started");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(DATA_INDEX);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(2).millis() + 1,
"msg", "Failed to shutdown [error org.aaaa.bbbb.Cccc line 54 caused " +
"by foo exception]");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(DATA_INDEX);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(1).millis(),
"msg", "Node 2 started");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(DATA_INDEX);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(1).millis() + 1,
"msg", "Failed to shutdown [error but this time completely different]");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(DATA_INDEX);
indexRequest.source("time", nowMillis, "msg", "Node 3 started");
bulkRequestBuilder.add(indexRequest);
BulkResponse bulkResponse = bulkRequestBuilder
.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL)
.get();
assertThat(bulkResponse.hasFailures(), is(false));
}
@After
public void tearDownData() {
cleanUp();
client().admin().indices().prepareDelete(DATA_INDEX).get();
refresh("*");
}
public void testBasicCategorization() throws Exception {
Job.Builder job = newJobBuilder("categorization", Collections.emptyList());
registerJob(job);
putJob(job);
openJob(job.getId());
String datafeedId = job.getId() + "-feed";
DatafeedConfig.Builder datafeedConfig = new DatafeedConfig.Builder(datafeedId, job.getId());
datafeedConfig.setIndices(Collections.singletonList(DATA_INDEX));
DatafeedConfig datafeed = datafeedConfig.build();
registerDatafeed(datafeed);
putDatafeed(datafeed);
startDatafeed(datafeedId, 0, nowMillis);
waitUntilJobIsClosed(job.getId());
List<CategoryDefinition> categories = getCategories(job.getId());
assertThat(categories.size(), equalTo(3));
CategoryDefinition category1 = categories.get(0);
assertThat(category1.getRegex(), equalTo(".*?Node.+?started.*"));
assertThat(category1.getExamples(),
equalTo(Arrays.asList("Node 1 started", "Node 2 started")));
CategoryDefinition category2 = categories.get(1);
assertThat(category2.getRegex(), equalTo(".*?Failed.+?to.+?shutdown.+?error.+?" +
"org\\.aaaa\\.bbbb\\.Cccc.+?line.+?caused.+?by.+?foo.+?exception.*"));
assertThat(category2.getExamples(), equalTo(Collections.singletonList(
"Failed to shutdown [error org.aaaa.bbbb.Cccc line 54 caused by foo exception]")));
CategoryDefinition category3 = categories.get(2);
assertThat(category3.getRegex(), equalTo(".*?Failed.+?to.+?shutdown.+?error.+?but.+?" +
"this.+?time.+?completely.+?different.*"));
assertThat(category3.getExamples(), equalTo(Collections.singletonList(
"Failed to shutdown [error but this time completely different]")));
openJob("categorization");
startDatafeed(datafeedId, 0, nowMillis + 1);
waitUntilJobIsClosed(job.getId());
categories = getCategories(job.getId());
assertThat(categories.size(), equalTo(3));
assertThat(categories.get(0).getExamples(),
equalTo(Arrays.asList("Node 1 started", "Node 2 started", "Node 3 started")));
}
public void testCategorizationWithFilters() throws Exception {
Job.Builder job = newJobBuilder("categorization-with-filters", Collections.singletonList("\\[.*\\]"));
registerJob(job);
putJob(job);
openJob(job.getId());
String datafeedId = job.getId() + "-feed";
DatafeedConfig.Builder datafeedConfig = new DatafeedConfig.Builder(datafeedId, job.getId());
datafeedConfig.setIndices(Collections.singletonList(DATA_INDEX));
DatafeedConfig datafeed = datafeedConfig.build();
registerDatafeed(datafeed);
putDatafeed(datafeed);
startDatafeed(datafeedId, 0, nowMillis);
waitUntilJobIsClosed(job.getId());
List<CategoryDefinition> categories = getCategories(job.getId());
assertThat(categories.size(), equalTo(2));
CategoryDefinition category1 = categories.get(0);
assertThat(category1.getRegex(), equalTo(".*?Node.+?started.*"));
assertThat(category1.getExamples(),
equalTo(Arrays.asList("Node 1 started", "Node 2 started")));
CategoryDefinition category2 = categories.get(1);
assertThat(category2.getRegex(), equalTo(".*?Failed.+?to.+?shutdown.*"));
assertThat(category2.getExamples(), equalTo(Arrays.asList(
"Failed to shutdown [error but this time completely different]",
"Failed to shutdown [error org.aaaa.bbbb.Cccc line 54 caused by foo exception]")));
}
public void testCategorizationPerformance() {
// To compare Java/C++ tokenization performance:
// 1. Change false to true in this assumption
// 2. Run the test several times
// 3. Change MachineLearning.CATEGORIZATION_TOKENIZATION_IN_JAVA to false
// 4. Run the test several more times
// 5. Check the timings that get logged
// 6. Revert the changes to this assumption and MachineLearning.CATEGORIZATION_TOKENIZATION_IN_JAVA
assumeTrue("This is time consuming to run on every build - it should be run manually when comparing Java/C++ tokenization",
false);
int testBatchSize = 1000;
int testNumBatches = 1000;
String[] possibleMessages = new String[] {
"<sol13m-9402.1.p2ps: Info: Tue Apr 06 19:00:16 2010> Source LOTS on 33080:817 has shut down.<END>",
"<lnl00m-8601.1.p2ps: Alert: Tue Apr 06 18:57:24 2010> P2PS failed to connect to the hrm server. "
+ "Reason: Failed to connect to hrm server - No ACK from SIPC<END>",
"<sol00m-8607.1.p2ps: Debug: Tue Apr 06 18:56:43 2010> Did not receive an image data for IDN_SELECTFEED:7630.T on 493. "
+ "Recalling item. <END>",
"<lnl13m-8602.1.p2ps.rrcpTransport.0.sinkSide.rrcp.transmissionBus: Warning: Tue Apr 06 18:36:32 2010> "
+ "RRCP STATUS MSG: RRCP_REBOOT: node 33191 has rebooted<END>",
"<sol00m-8608.1.p2ps: Info: Tue Apr 06 18:30:02 2010> Source PRISM_VOBr on 33069:757 has shut down.<END>",
"<lnl06m-9402.1.p2ps: Info: Thu Mar 25 18:30:01 2010> Service PRISM_VOB has shut down.<END>"
};
String jobId = "categorization-performance";
Job.Builder job = newJobBuilder(jobId, Collections.emptyList());
registerJob(job);
putJob(job);
openJob(job.getId());
long startTime = System.currentTimeMillis();
for (int batchNum = 0; batchNum < testNumBatches; ++batchNum) {
StringBuilder json = new StringBuilder(testBatchSize * 100);
for (int docNum = 0; docNum < testBatchSize; ++docNum) {
json.append(String.format(Locale.ROOT, "{\"time\":1000000,\"msg\":\"%s\"}\n",
possibleMessages[docNum % possibleMessages.length]));
}
postData(jobId, json.toString());
}
flushJob(jobId, false);
long duration = System.currentTimeMillis() - startTime;
LogManager.getLogger(CategorizationIT.class).info("Performance test with tokenization in " +
(MachineLearning.CATEGORIZATION_TOKENIZATION_IN_JAVA ? "Java" : "C++") + " took " + duration + "ms");
}
public void testNumMatchesAndCategoryPreference() throws Exception {
String index = "hadoop_logs";
client().admin().indices().prepareCreate(index)
.setMapping("time", "type=date,format=epoch_millis",
"msg", "type=text")
.get();
nowMillis = System.currentTimeMillis();
BulkRequestBuilder bulkRequestBuilder = client().prepareBulk();
IndexRequest indexRequest = new IndexRequest(index);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(8).millis(),
"msg", "2015-10-18 18:01:51,963 INFO [main] org.mortbay.log: jetty-6.1.26");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(index);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(7).millis(),
"msg",
"2015-10-18 18:01:52,728 INFO [main] org.mortbay.log: Started HttpServer2$SelectChannelConnectorWithSafeStartup@0.0.0.0:62267");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(index);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(6).millis(),
"msg", "2015-10-18 18:01:53,400 INFO [main] org.apache.hadoop.yarn.webapp.WebApps: Registered webapp guice modules");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(index);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(5).millis(),
"msg",
"2015-10-18 18:01:53,447 INFO [main] org.apache.hadoop.mapreduce.v2.app.rm.RMContainerRequestor: nodeBlacklistingEnabled:true");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(index);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(4).millis(),
"msg",
"2015-10-18 18:01:52,728 INFO [main] org.apache.hadoop.yarn.webapp.WebApps: Web app /mapreduce started at 62267");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(index);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(2).millis(),
"msg",
"2015-10-18 18:01:53,557 INFO [main] org.apache.hadoop.yarn.client.RMProxy: " +
"Connecting to ResourceManager at msra-sa-41/10.190.173.170:8030");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(index);
indexRequest.source("time", nowMillis - TimeValue.timeValueHours(1).millis(),
"msg",
"2015-10-18 18:01:53,713 INFO [main] org.apache.hadoop.mapreduce.v2.app.rm.RMContainerAllocator: " +
"maxContainerCapability: <memory:8192, vCores:32>");
bulkRequestBuilder.add(indexRequest);
indexRequest = new IndexRequest(index);
indexRequest.source("time", nowMillis,
"msg",
"2015-10-18 18:01:53,713 INFO [main] org.apache.hadoop.yarn.client.api.impl.ContainerManagementProtocolProxy: " +
"yarn.client.max-cached-nodemanagers-proxies : 0");
bulkRequestBuilder.add(indexRequest);
BulkResponse bulkResponse = bulkRequestBuilder
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.get();
assertThat(bulkResponse.hasFailures(), is(false));
Job.Builder job = newJobBuilder("categorization-with-preferred-categories", Collections.emptyList());
registerJob(job);
putJob(job);
openJob(job.getId());
String datafeedId = job.getId() + "-feed";
DatafeedConfig.Builder datafeedConfig = new DatafeedConfig.Builder(datafeedId, job.getId());
datafeedConfig.setIndices(Collections.singletonList(index));
DatafeedConfig datafeed = datafeedConfig.build();
registerDatafeed(datafeed);
putDatafeed(datafeed);
startDatafeed(datafeedId, 0, nowMillis + 1);
waitUntilJobIsClosed(job.getId());
List<CategoryDefinition> categories = getCategories(job.getId());
assertThat(categories, hasSize(7));
CategoryDefinition category1 = categories.get(0);
assertThat(category1.getNumMatches(), equalTo(2L));
long[] expectedPreferenceTo = new long[]{2L, 3L, 4L, 5L, 6L, 7L};
assertThat(category1.getPreferredToCategories(), equalTo(expectedPreferenceTo));
client().admin().indices().prepareDelete(index).get();
}
private static Job.Builder newJobBuilder(String id, List<String> categorizationFilters) {
Detector.Builder detector = new Detector.Builder();
detector.setFunction("count");
detector.setByFieldName("mlcategory");
AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(
Collections.singletonList(detector.build()));
analysisConfig.setBucketSpan(TimeValue.timeValueHours(1));
analysisConfig.setCategorizationFieldName("msg");
analysisConfig.setCategorizationFilters(categorizationFilters);
DataDescription.Builder dataDescription = new DataDescription.Builder();
dataDescription.setTimeField("time");
Job.Builder jobBuilder = new Job.Builder(id);
jobBuilder.setAnalysisConfig(analysisConfig);
jobBuilder.setDataDescription(dataDescription);
return jobBuilder;
}
}
|
package com.cognizant.devops.platformservice.rest.querycaching.service;
public interface QueryCachingConstants {
String METADATA = "metadata";
String STATEMENT = "statement";
String STATEMENTS = "statements";
String RESULT_CACHE = "resultCache";
String CACHING_TYPE = "cachingType";
String START_TIME = "startTime";
String END_TIME = "endTime";
String CACHE_TIME = "cacheTime";
String CACHE_VARIANCE = "cacheVariance";
String LOAD_CACHETIME_QUERY_FROM_RESOURCES = "/querycachingesquery/esQueryWithTime.json";
String LOAD_CACHEVARIANCE_QUERY_FROM_RESOURCES = "/querycachingesquery/esQueryWithVariance.json";
String QUERY_HASH = "queryHash";
String QUERY_HASHING = "__queryCache__";
String CACHED_STARTTIME = "__cachedStartTime__";
String CACHED_ENDTIME = "__cachedEndTime__";
String START_TIME_RANGE = "__startTime__";
String END_TIME_RANGE = "__endTime__";
String CURRENT_TIME = "__currentTime__";
String CACHED_PREVIOUS_TIME = "__cachePreviousTime__";
String HAS_EXPIRED = "hasExpired";
String CREATION_TIME = "creationTime";
}
|
package gov.hhs.fha.nhinc.orchestration;
import gov.hhs.fha.nhinc.admindistribution.entity.EntityAdminDistributionFactory;
import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType;
import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerCache;
import gov.hhs.fha.nhinc.docretrieve.entity.EntityDocRetrieveFactory;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
public class OrchestrationContextFactory {
private static OrchestrationContextFactory INSTANCE = new OrchestrationContextFactory();
private OrchestrationContextFactory() {
}
public static OrchestrationContextFactory getInstance() {
return INSTANCE;
}
public OrchestrationContextBuilder getBuilder(HomeCommunityType homeCommunityType, String serviceName) {
NhincConstants.GATEWAY_API_LEVEL apiLevel = ConnectionManagerCache.getApiVersionForNhinTarget(
homeCommunityType.getHomeCommunityId(), serviceName);
return getBuilder(apiLevel, serviceName);
}
private OrchestrationContextBuilder getBuilder(
NhincConstants.GATEWAY_API_LEVEL apiLevel, String serviceName) {
if (NhincConstants.DOC_RETRIEVE_SERVICE_NAME.equals(serviceName)) {
return EntityDocRetrieveFactory.getInstance().createOrchestrationContextBuilder(apiLevel);
} else if (NhincConstants.ADMIN_DIST_SERVICE_NAME.equals(serviceName)) {
return EntityAdminDistributionFactory.getInstance().createOrchestrationContextBuilder(apiLevel);
}
return null;
}
}
|
package org.eclipse.birt.report.designer.core.model;
import java.util.List;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.designer.util.MetricUtility;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.MasterPageHandle;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Insets;
/**
* Adapter class to adapt model handle. This adapter provides convenience
* methods to GUI requirement ReportDesignHandleAdapter responds to model
* ModuleHandle
*
*
*/
public class ReportDesignHandleAdapter extends DesignElementHandleAdapter
{
/**
* Constructor
*
* @param handle
* Module handle
*/
public ReportDesignHandleAdapter( ModuleHandle handle )
{
this( handle, null );
}
/**
* Constructor
*
* @param handle
* Module handle
* @param mark
* Help mark
*/
public ReportDesignHandleAdapter( ModuleHandle handle,
IModelAdapterHelper mark )
{
super( handle, mark );
}
/**
* Gets the Children iterator. This children relationship is determined by
* GUI requirement. This is not the model children relationship.
*
* @return Children iterator.
*/
public List getChildren( )
{
return getReportDesignHandle( ).getBody( ).getContents( );
}
/**
* Gets all the data source binding to report element.
*
* @return
* Data source list
*/
public List getDataSources( )
{
return getModuleHandle( ).getVisibleDataSources();
}
/**
* Gets data source handle binding to report element
*
* @param name
* The name of specified data source
* @return
* specified data souce's handle
*/
public DataSourceHandle getDataSourceHandle( String name )
{
return getModuleHandle( ).findDataSource( name );
}
/**
* Provides naming check logic of data source name.
*
* @param name
* Specfied data source name
* @return
* <code>true</code> if the data source exists, else false
*/
public boolean checkDataSourceName( String name )
{
return getModuleHandle( ).findDataSource( name ) != null;
}
/**
* Provides naming check logic of data set name.
*
* @param name
* Specified data set name
* @return
* <code>true</code> if the data set exists, else false
*/
public boolean checkDataSetName( String name )
{
return getModuleHandle( ).findDataSet( name ) != null;
}
/**
* Sets the ModuleHandle be adapted.
*
* @param handle
* the module handle
*/
public void setReportDesignHandle( ModuleHandle handle )
{
setElementHandle( handle );
}
/**
* Get master page handle
*
* @return the master page instace of Report Design.
*/
public MasterPageHandle getMasterPage( )
{
return getMasterPage( 0 );
}
/**
* Gets the master page instace of Report Design with specific position.
*
* @param pos
* The position
* @return handle of masterpage.
*/
public MasterPageHandle getMasterPage( int pos )
{
SlotHandle masterPages = getModuleHandle( ).getMasterPages( );
MasterPageHandle masterPage = (MasterPageHandle) masterPages.get( pos );
return masterPage;
}
/**
* Get the current master page size.
*
* @param handle
* The handle of master page.
* @return The current master page size.
*/
public Dimension getMasterPageSize( DesignElementHandle handle )
{
MasterPageHandle masterPage = (MasterPageHandle) handle;
Dimension size = null;
if ( masterPage == null
|| masterPage.getPageType( )
.equalsIgnoreCase( DesignChoiceConstants.PAGE_SIZE_US_LETTER ) )
{
size = new Dimension( MetricUtility.inchToPixel( 8.5, 11 ).x,
MetricUtility.inchToPixel( 8.5, 11 ).y );
}
else if ( masterPage == null
|| masterPage.getPageType( )
.equalsIgnoreCase( DesignChoiceConstants.PAGE_SIZE_US_LEDGER ) )
{
size = new Dimension( MetricUtility.inchToPixel( 11, 17 ).x,
MetricUtility.inchToPixel( 11, 17 ).y );
}
else if ( masterPage == null
|| masterPage.getPageType( )
.equalsIgnoreCase( DesignChoiceConstants.PAGE_SIZE_US_SUPER_B ) )
{
size = new Dimension( MetricUtility.inchToPixel( 11, 17 ).x,
MetricUtility.inchToPixel( 13, 19 ).y );
}
else if ( masterPage.getPageType( )
.equalsIgnoreCase( DesignChoiceConstants.PAGE_SIZE_US_LEGAL ) )
{
size = new Dimension( MetricUtility.inchToPixel( 8.5, 14 ).x,
MetricUtility.inchToPixel( 8.5, 14 ).y );
}
else if ( masterPage.getPageType( )
.equalsIgnoreCase( DesignChoiceConstants.PAGE_SIZE_A4 ) )
{
size = new Dimension( MetricUtility.inchToPixel( 8.3, 11.7 ).x,
MetricUtility.inchToPixel( 8.3, 11.7 ).y );
}
else if ( masterPage.getPageType( )
.equalsIgnoreCase( DesignChoiceConstants.PAGE_SIZE_A3 ) )
{
size = new Dimension( MetricUtility.inchToPixel( 11.7, 16.5 ).x,
MetricUtility.inchToPixel( 11.7, 16.5 ).y );
}
else if ( masterPage.getPageType( )
.equalsIgnoreCase( DesignChoiceConstants.PAGE_SIZE_A5 ) )
{
size = new Dimension( MetricUtility.inchToPixel( 5.8, 8.3 ).x,
MetricUtility.inchToPixel( 5.8, 8.3 ).y );
}
else if ( masterPage.getPageType( )
.equalsIgnoreCase( DesignChoiceConstants.PAGE_SIZE_CUSTOM ) )
{
int width = (int) DEUtil.convertoToPixel( masterPage.getWidth( ) );
int height = (int) DEUtil.convertoToPixel( masterPage.getHeight( ) );
size = new Dimension( width, height );
}
if ( masterPage != null && DesignChoiceConstants.PAGE_ORIENTATION_LANDSCAPE.equalsIgnoreCase( masterPage.getOrientation( ) ) )
{
int width = (int) DEUtil.convertoToPixel( masterPage.getWidth( ) );
int height = (int) DEUtil.convertoToPixel( masterPage.getHeight( ) );
size = new Dimension( width, height );
}
return size;
}
/**
* Get insets of master page.
*
* @param handle
* the handle of master page
* @return insets
*/
public Insets getMasterPageInsets( DesignElementHandle handle )
{
MasterPageHandle masterPage = (MasterPageHandle) handle;
return new Insets( (int) DEUtil.convertoToPixel( masterPage.getTopMargin( ) ),
(int) DEUtil.convertoToPixel( masterPage.getLeftMargin( ) ),
(int) DEUtil.convertoToPixel( masterPage.getBottomMargin( ) ),
(int) DEUtil.convertoToPixel( masterPage.getRightMargin( ) ) );
}
}
|
package org.eclipse.birt.report.designer.internal.ui.dialogs;
import org.eclipse.birt.report.designer.core.DesignerConstants;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.util.ColorManager;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.StyleHandle;
import org.eclipse.birt.report.model.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.elements.Style;
import org.eclipse.birt.report.model.metadata.Choice;
import org.eclipse.birt.report.model.metadata.MetaDataDictionary;
import org.eclipse.birt.report.model.metadata.PropertyValueException;
import org.eclipse.birt.report.model.util.DimensionUtil;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
/**
* Provides font preference page.
*/
public class FontPreferencePage extends BaseStylePreferencePage
{
/**
* the preference store( model ) for the preference page.
*/
private Object model;
/**
* field editors.
*/
private ColorFieldEditor color;
private EditableComboFieldEditor name;
private ComboBoxFieldEditor style;
private ComboBoxFieldEditor weight;
private ComboBoxMeasureFieldEditor size;
private DecorationFieldEditor docoration;
/**
* preview label for previewing sample text.
*/
private PreviewLabel sample;
/**
* Constructs a new instance of font preference page.
*
* @param model
* the preference store( model ) for the following field editors.
*/
public FontPreferencePage( Object model )
{
super( model );
setTitle( Messages.getString( "FontPreferencePage.displayname.Title" ) ); //$NON-NLS-1$
this.model = model;
}
/**
* Adjust the layout of the field editors so that they are properly aligned.
*/
protected void adjustGridLayout( )
{
super.adjustGridLayout( );
( (GridData) name.getComboBoxControl( getFieldEditorParent( ) )
.getLayoutData( ) ).widthHint = 170;
( (GridData) style.getComboBoxControl( getFieldEditorParent( ) )
.getLayoutData( ) ).widthHint = 170;
( (GridData) weight.getComboBoxControl( getFieldEditorParent( ) )
.getLayoutData( ) ).widthHint = 170;
}
/**
* Returns the model.
*
* @return
*/
public Object getModel( )
{
return model;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
*/
protected void createFieldEditors( )
{
super.createFieldEditors( );
name = new EditableComboFieldEditor( Style.FONT_FAMILY_PROP,
( (StyleHandle) model ).getPropertyHandle( Style.FONT_FAMILY_PROP )
.getDefn( )
.getDisplayName( ),
getFontChoiceArray( ),
getFieldEditorParent( ) );
color = new ColorFieldEditor( Style.COLOR_PROP,
( (StyleHandle) model ).getPropertyHandle( Style.COLOR_PROP )
.getDefn( )
.getDisplayName( ),
getFieldEditorParent( ) );
size = new ComboBoxMeasureFieldEditor( Style.FONT_SIZE_PROP,
( (StyleHandle) model ).getPropertyHandle( Style.FONT_SIZE_PROP )
.getDefn( )
.getDisplayName( ),
getChoiceArray( DesignChoiceConstants.CHOICE_FONT_SIZE ),
getChoiceArray( DesignChoiceConstants.CHOICE_UNITS ),
getFieldEditorParent( ) );
style = new ComboBoxFieldEditor( Style.FONT_STYLE_PROP,
( (StyleHandle) model ).getPropertyHandle( Style.FONT_STYLE_PROP )
.getDefn( )
.getDisplayName( ),
getChoiceArray( DesignChoiceConstants.CHOICE_FONT_STYLE ),
getFieldEditorParent( ) );
weight = new ComboBoxFieldEditor( Style.FONT_WEIGHT_PROP,
( (StyleHandle) model ).getPropertyHandle( Style.FONT_WEIGHT_PROP )
.getDefn( )
.getDisplayName( ),
getChoiceArray( DesignChoiceConstants.CHOICE_FONT_WEIGHT ),
getFieldEditorParent( ) );
docoration = new DecorationFieldEditor( Style.TEXT_UNDERLINE_PROP,
( (StyleHandle) model ).getPropertyHandle( Style.TEXT_UNDERLINE_PROP )
.getDefn( )
.getDisplayName( ),
Style.TEXT_OVERLINE_PROP,
( (StyleHandle) model ).getPropertyHandle( Style.TEXT_OVERLINE_PROP )
.getDefn( )
.getDisplayName( ),
Style.TEXT_LINE_THROUGH_PROP,
( (StyleHandle) model ).getPropertyHandle( Style.TEXT_LINE_THROUGH_PROP )
.getDefn( )
.getDisplayName( ),
Messages.getString( "FontPreferencePage.label.fontDecoration" ), //$NON-NLS-1$
getFieldEditorParent( ) );
addField( name );
addField( color );
addField( size );
addField( style );
addField( weight );
addField( docoration );
addField( new SeparatorFieldEditor( getFieldEditorParent( ), false ) );
Group group = new Group( getFieldEditorParent( ), SWT.SHADOW_OUT );
group.setText( Messages.getString( "FontPreferencePage.text.Preview" ) ); //$NON-NLS-1$
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.widthHint = 400;
gd.heightHint = 100;
gd.horizontalSpan = 4;
group.setLayoutData( gd );
group.setLayout( new GridLayout( ) );
sample = new PreviewLabel( group, SWT.NONE );
sample.setText( Messages.getString( "FontPreferencePage.text.PreviewContent" ) ); //$NON-NLS-1$
sample.setLayoutData( new GridData( GridData.FILL_BOTH ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.preference.FieldEditorPreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents( Composite parent )
{
Control ct = super.createContents( parent );
updatePreview( );
return ct;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.preference.FieldEditorPreferencePage#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange( PropertyChangeEvent event )
{
updatePreview( );
}
/**
* Updates sample text for preview according to the property change.
*
*/
private void updatePreview( )
{
if ( sample != null )
{
String fontFamily = name.getValueForName( name.getComboBoxControl( null )
.getText( ) );
if (fontFamily == null)
{
fontFamily = "Times New Roman"; //$NON-NLS-1$
}
String familyValue = (String) DesignerConstants.familyMap.get( fontFamily );
if ( familyValue == null )
{
familyValue = fontFamily;
}
//set default font size.
String fontSize = DesignChoiceConstants.FONT_SIZE_MEDIUM;
int sizeValue = Integer.valueOf( (String) DesignerConstants.fontMap.get( fontSize ) )
.intValue( );
if ( size.InComboNamesList( size.getComboBoxControl( getFieldEditorParent( ) )
.getText( ) ) )
{
fontSize = size.getBoxValueForName( size.getComboBoxControl( getFieldEditorParent( ) )
.getText( ) );
if ( DesignChoiceConstants.FONT_SIZE_LARGER.equals( fontSize ) )
{
fontSize = DesignChoiceConstants.FONT_SIZE_LARGE;
}
else if ( DesignChoiceConstants.FONT_SIZE_SMALLER.equals( fontSize ) )
{
fontSize = DesignChoiceConstants.FONT_SIZE_SMALL;
}
sizeValue = Integer.valueOf( (String) DesignerConstants.fontMap.get( fontSize ) )
.intValue( );
}
else
{
String text = size.getComboBoxControl( getFieldEditorParent( ) )
.getText( );
String pre = size.getMeasureValueForName( size.getMeasureControl( getFieldEditorParent( ) )
.getText( ) );
String target = DesignChoiceConstants.UNITS_PT;
if ( DimensionUtil.isAbsoluteUnit( pre ) )
{
if ( DEUtil.isValidNumber( text ) )
{
try
{
sizeValue = (int) ( DimensionUtil.convertTo( text,
pre,
target ) ).getMeasure( );
}
catch ( PropertyValueException e )
{
ExceptionHandler.handle( e );
}
}
}
else
{
// use default font size.
}
}
boolean italic = false;
String fontStyle = style.getValueForName( style.getComboBoxControl( getFieldEditorParent( ) )
.getText( ) );
if ( DesignChoiceConstants.FONT_STYLE_ITALIC.equals( fontStyle ) )
{
italic = true;
}
String fontWeight = weight.getValueForName( weight.getComboBoxControl( null )
.getText( ) );
boolean bold = false;
int fw = 400;
if ( DesignChoiceConstants.FONT_WEIGHT_NORMAL.equals( fontWeight ) )
{
}
else if ( DesignChoiceConstants.FONT_WEIGHT_BOLD.equals( fontWeight ) )
{
bold = true;
fw = 700;
}
else if ( DesignChoiceConstants.FONT_WEIGHT_BOLDER.equals( fontWeight ) )
{
bold = true;
fw = 1000;
}
else if ( DesignChoiceConstants.FONT_WEIGHT_LIGHTER.equals( fontWeight ) )
{
fw = 100;
}
else
{
try
{
fw = Integer.parseInt( fontWeight );
}
catch ( NumberFormatException e )
{
fw = 400;
}
if ( fw > 700 )
{
bold = true;
}
}
sample.setFontFamily( familyValue );
sample.setFontSize( sizeValue );
sample.setBold( bold );
sample.setItalic( italic );
sample.setFontWeight( fw );
// sample.setForeground( new Color( Display.getCurrent( ),
// color.getColorSelector( ).getColorValue( ) ) );
sample.setForeground( ColorManager.getColor( color.getColorSelector( )
.getRGB( ) ) );
sample.setUnderline( docoration.getUnderLinePropControl( null )
.getSelection( ) );
sample.setLinethrough( docoration.getLineThroughPropControl( null )
.getSelection( ) );
sample.setOverline( docoration.getOverLinePropControl( null )
.getSelection( ) );
sample.updateView( );
}
}
private String[][] getFontChoiceArray( )
{
String[][] fca = getChoiceArray( DesignChoiceConstants.CHOICE_FONT_FAMILY );
String[] sf = DEUtil.getSystemFontNames( );
String[][] rt = new String[fca.length + sf.length][2];
for ( int i = 0; i < rt.length; i++ )
{
if ( i < fca.length )
{
rt[i][0] = fca[i][0];
rt[i][1] = fca[i][1];
}
else
{
rt[i][0] = sf[i - fca.length];
rt[i][1] = sf[i - fca.length];
}
}
return rt;
}
/**
* Gets choice array of the given property name ( key ).
*
* @param key
* The given property name.
* @return String[][]: The choice array of the key, which contains he names
* (labels) and underlying values, will be arranged as: { {name1,
* value1}, {name2, value2}, ...}
*/
private String[][] getChoiceArray( String key )
{
Choice[] choices = MetaDataDictionary.getInstance( )
.getChoiceSet( key )
.getChoices( );
String[][] names = null;
if ( choices.length > 0 )
{
names = new String[choices.length][2];
for ( int i = 0; i < choices.length; i++ )
{
names[i][0] = choices[i].getDisplayName( );
names[i][1] = choices[i].getName( );
}
}
return names;
}
}
|
package org.eclipse.birt.report.designer.internal.ui.views.actions;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.Policy;
import org.eclipse.birt.report.designer.internal.ui.views.RenameInputDialog;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.CommandStack;
import org.eclipse.birt.report.model.api.ContentElementHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.EmbeddedImageHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.command.NameException;
import org.eclipse.birt.report.model.api.metadata.MetaDataConstants;
import org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.TreeItem;
/**
* This class represents the rename action
*/
public class RenameAction extends AbstractViewerAction
{
/**
* the default text
*/
public static final String TEXT = Messages.getString( "RenameAction.text" ); //$NON-NLS-1$
private TreeItem selectedItem;
private String originalName;
private static final String ERROR_TITLE = Messages.getString( "RenameInlineTool.DialogTitle.RenameFailed" ); //$NON-NLS-1$
private static final String TRANS_LABEL = Messages.getString( "RenameInlineTool.TransLabel.Rename" ); //$NON-NLS-1$
/**
* Create a new rename action under the specific viewer
*
* @param sourceViewer
* the source viewer
*
*/
public RenameAction( TreeViewer sourceViewer )
{
this( sourceViewer, TEXT );
}
/**
* Create a new rename action under the specific viewer with the given text
*
* @param sourceViewer
* the source viewer
* @param text
* the text of the action
*/
public RenameAction( TreeViewer sourceViewer, String text )
{
super( sourceViewer, text );
setAccelerator( SWT.F2 );
if ( isEnabled( ) )
{
selectedItem = getSelectedItems( )[0];
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IAction#isEnabled()
*/
public boolean isEnabled( )
{
if ( getSelectedObjects( ).size( ) != 1 )
{// multiple selection or no selection
return false;
}
Object obj = super.getSelectedObjects( ).getFirstElement( );
if ( obj instanceof EmbeddedImageHandle )
{
return true;
}
if ( obj instanceof ReportElementHandle )
{
if ( obj instanceof GroupHandle )
{
return !((GroupHandle)obj).getPropertyHandle( IGroupElementModel.GROUP_NAME_PROP ).isReadOnly( );
}
return ( (ReportElementHandle) obj ).getDefn( ).getNameOption( ) != MetaDataConstants.NO_NAME
&& ( (ReportElementHandle) obj ).canEdit( );
}
if ( obj instanceof ContentElementHandle )
{
return ( (ContentElementHandle) obj ).getDefn( ).getNameOption( ) != MetaDataConstants.NO_NAME
&& ( (ContentElementHandle) obj ).canEdit( );
}
// No report element selected
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run( )
{
if ( Policy.TRACING_ACTIONS )
{
System.out.println( "Rename action >> Runs with " + DEUtil.getDisplayLabel( getSelectedObjects( ).getFirstElement( ) ) ); //$NON-NLS-1$
}
doRename( );
}
private void doRename( )
{
if ( selectedItem.getData( ) instanceof DesignElementHandle
|| selectedItem.getData( ) instanceof EmbeddedImageHandle )
{
initOriginalName( );
RenameInputDialog inputDialog = new RenameInputDialog( selectedItem.getParent( )
.getShell( ),
Messages.getString( "RenameInputDialog.DialogTitle" ), //$NON-NLS-1$
Messages.getString( "RenameInputDialog.DialogMessage" ), //$NON-NLS-1$
originalName,
IHelpContextIds.RENAME_INPUT_DIALOG_ID );
inputDialog.create( );
if ( inputDialog.open( ) == Window.OK )
{
saveChanges( inputDialog.getResult( ).toString( ).trim( ) );
}
}
}
private void initOriginalName( )
{
if ( selectedItem.getData( ) instanceof DesignElementHandle )
{
originalName = ( (DesignElementHandle) selectedItem.getData( ) ).getName( );
}
if ( selectedItem.getData( ) instanceof EmbeddedImageHandle )
{
originalName = ( (EmbeddedImageHandle) selectedItem.getData( ) ).getName( );
}
if ( originalName == null )
{
originalName = ""; //$NON-NLS-1$
}
}
private void saveChanges( String newName )
{
if ( !newName.equals( originalName ) )
{
if ( !rename( selectedItem.getData( ), newName ) )
{
// failed to rename, do again
doRename( );
return;
}
}
}
/**
* Perform renaming
*
* @param handle
* the handle of the element to rename
* @param newName
* the newName to set
* @return Returns true if perform successfully,or false if failed
*/
private boolean rename( Object handle, String newName )
{
if ( newName.length( ) == 0 )
{
newName = null;
}
if (SessionHandleAdapter.getInstance( ).getReportDesignHandle( ) == null)
{
return false;
}
CommandStack stack = SessionHandleAdapter.getInstance( )
.getCommandStack( );
stack.startTrans( TRANS_LABEL + " " + DEUtil.getDisplayLabel( handle ) ); //$NON-NLS-1$
try
{
if ( handle instanceof DesignElementHandle )
{
( (DesignElementHandle) handle ).setName( newName );
}
if ( handle instanceof EmbeddedImageHandle )
{
( (EmbeddedImageHandle) handle ).setName( newName );
}
stack.commit( );
}
catch ( NameException e )
{
ExceptionHandler.handle( e, ERROR_TITLE, e.getLocalizedMessage( ) );
stack.rollback( );
return false;
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e, ERROR_TITLE, e.getLocalizedMessage( ) );
stack.rollback( );
// If set EmbeddedImage name error, then use former name;
return true;
}
return true;
}
}
|
package org.eclipse.birt.report.designer.internal.ui.views.actions;
import org.eclipse.birt.report.designer.internal.ui.views.RenameInlineTool;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.model.api.EmbeddedImageHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.metadata.MetaDataConstants;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
/**
* This class represents the rename action
*/
public class RenameAction extends AbstractViewerAction
{
/**
* the default text
*/
public static final String TEXT = Messages.getString( "RenameAction.text" ); //$NON-NLS-1$
private RenameInlineTool tool = null;
/**
* Create a new rename action under the specific viewer
*
* @param sourceViewer
* the source viewer
*
*/
public RenameAction( TreeViewer sourceViewer )
{
this( sourceViewer, TEXT );
}
/**
* Create a new rename action under the specific viewer with the given text
*
* @param sourceViewer
* the source viewer
* @param text
* the text of the action
*/
public RenameAction( TreeViewer sourceViewer, String text )
{
super( sourceViewer, text );
setAccelerator( SWT.F2 );
if ( isEnabled( ) )
{
tool = new RenameInlineTool( getSelectedItems( )[0] );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IAction#isEnabled()
*/
public boolean isEnabled( )
{
if ( getSelectedObjects( ).size( ) != 1 )
{//multiple selection or no selection
return false;
}
Object obj = super.getSelectedObjects( ).getFirstElement( );
if(obj instanceof EmbeddedImageHandle)
{
return true;
}
if ( obj instanceof ReportElementHandle )
{
if ( obj instanceof GroupHandle )
{
return true;
}
return ( (ReportElementHandle) obj ).getDefn( ).getNameOption( ) != MetaDataConstants.NO_NAME;
}
//No report element selected
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run( )
{
if ( tool != null )
{
tool.doRename( );
}
}
}
|
package org.openhab.binding.gardena.handler;
import java.util.Hashtable;
import java.util.concurrent.TimeUnit;
import org.eclipse.smarthome.config.discovery.DiscoveryService;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.Channel;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.RefreshType;
import org.openhab.binding.gardena.internal.GardenaSmart;
import org.openhab.binding.gardena.internal.GardenaSmartEventListener;
import org.openhab.binding.gardena.internal.GardenaSmartImpl;
import org.openhab.binding.gardena.internal.config.GardenaConfig;
import org.openhab.binding.gardena.internal.discovery.GardenaDeviceDiscoveryService;
import org.openhab.binding.gardena.internal.exception.GardenaException;
import org.openhab.binding.gardena.internal.model.Device;
import org.openhab.binding.gardena.internal.util.UidUtils;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link GardenaAccountHandler} is the handler for a Gardena Smart Home access and connects it to the framework.
*
* @author Gerhard Riegler - Initial contribution
*/
public class GardenaAccountHandler extends BaseBridgeHandler implements GardenaSmartEventListener {
private final Logger logger = LoggerFactory.getLogger(GardenaAccountHandler.class);
private static final long REINITIALIZE_DELAY_SECONDS = 10;
private GardenaDeviceDiscoveryService discoveryService;
private ServiceRegistration<?> discoveryServiceRegistration;
private GardenaSmart gardenaSmart = new GardenaSmartImpl();
private GardenaConfig gardenaConfig;
public GardenaAccountHandler(Bridge bridge) {
super(bridge);
}
@Override
public void initialize() {
logger.debug("Initializing Gardena account '{}'", getThing().getUID().getId());
gardenaConfig = getThing().getConfiguration().as(GardenaConfig.class);
logger.debug("{}", gardenaConfig);
initializeGardena();
}
/**
* Initializes the GardenaSmart account.
*/
private void initializeGardena() {
final GardenaAccountHandler instance = this;
scheduler.execute(new Runnable() {
@Override
public void run() {
try {
String id = getThing().getUID().getId();
gardenaSmart.init(id, gardenaConfig, instance, scheduler);
registerDeviceDiscoveryService();
discoveryService.startScan(null);
discoveryService.waitForScanFinishing();
updateStatus(ThingStatus.ONLINE);
} catch (GardenaException ex) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ex.getMessage());
disposeGardena();
scheduleReinitialize();
logger.debug("{}", ex.getMessage(), ex);
}
}
});
}
/**
* Schedules a reinitialization, if Gardea Smart Home account is not reachable at startup.
*/
private void scheduleReinitialize() {
scheduler.schedule(new Runnable() {
@Override
public void run() {
initializeGardena();
}
}, REINITIALIZE_DELAY_SECONDS, TimeUnit.SECONDS);
}
@Override
public void dispose() {
super.dispose();
disposeGardena();
}
/**
* Disposes the GardenaSmart account.
*/
private void disposeGardena() {
logger.debug("Disposing Gardena account '{}'", getThing().getUID().getId());
if (discoveryService != null) {
discoveryService.stopScan();
unregisterDeviceDiscoveryService();
}
gardenaSmart.dispose();
}
/**
* Registers the Gardena DeviceDiscoveryService.
*/
private void registerDeviceDiscoveryService() {
discoveryService = new GardenaDeviceDiscoveryService(this);
discoveryServiceRegistration = bundleContext.registerService(DiscoveryService.class.getName(), discoveryService,
new Hashtable<String, Object>());
discoveryService.activate();
}
/**
* Unregisters the Gardena DeviceDisoveryService.
*/
private void unregisterDeviceDiscoveryService() {
if (discoveryServiceRegistration != null) {
if (bundleContext != null) {
GardenaDeviceDiscoveryService service = (GardenaDeviceDiscoveryService) bundleContext
.getService(discoveryServiceRegistration.getReference());
service.deactivate();
}
discoveryServiceRegistration.unregister();
discoveryServiceRegistration = null;
discoveryService = null;
}
}
/**
* Returns the Gardena Smart Home implementation.
*/
public GardenaSmart getGardenaSmart() {
return gardenaSmart;
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (RefreshType.REFRESH == command) {
logger.debug("Refreshing Gardena account '{}'", getThing().getUID().getId());
disposeGardena();
initializeGardena();
}
}
@Override
public void onDeviceUpdated(Device device) {
for (ThingUID thingUID : UidUtils.getThingUIDs(device, getThing())) {
Thing gardenaThing = getThingByUID(thingUID);
try {
GardenaThingHandler gardenaThingHandler = (GardenaThingHandler) gardenaThing.getHandler();
gardenaThingHandler.updateProperties(device);
for (Channel channel : gardenaThing.getChannels()) {
gardenaThingHandler.updateChannel(channel.getUID());
}
gardenaThingHandler.updateSettings(device);
gardenaThingHandler.updateStatus(device);
} catch (GardenaException ex) {
logger.error("There is something wrong with your thing '{}', please check or recreate it: {}",
gardenaThing.getUID(), ex.getMessage());
logger.debug("Gardena exception caught on device update.", ex);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, ex.getMessage());
} catch (AccountHandlerNotAvailableException ignore) {
}
}
}
@Override
public void onNewDevice(Device device) {
if (discoveryService != null) {
discoveryService.deviceDiscovered(device);
}
onDeviceUpdated(device);
}
@Override
public void onDeviceDeleted(Device device) {
if (discoveryService != null) {
discoveryService.deviceRemoved(device);
}
}
@Override
public void onConnectionLost() {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Connection lost");
}
@Override
public void onConnectionResumed() {
updateStatus(ThingStatus.ONLINE);
}
}
|
package org.openhab.io.semantic.dogont.internal.util;
import org.openhab.io.semantic.dogont.internal.ontology.DogontSchema;
public class QueryResource {
public static final String Prefix = ""
+ "PREFIX rdfs: <" + SemanticConstants.NS_RDFS_SCHEMA + "> "
+ "PREFIX rdf: <" + SemanticConstants.NS_RDF_SYNTAX + "> "
+ "PREFIX dogont: <" + DogontSchema.NS + "> "
+ "PREFIX instance: <" + SemanticConstants.NS_INSTANCE + "> ";
/**
* Use String.format: Namespace, Property, Value
*/
public static final String SubjectByPropertyValueUncertainty = "PREFIX rdfs: <"
+ SemanticConstants.NS_RDFS_SCHEMA + "> "
+ "PREFIX : <%s> "
+ "SELECT * "
+ "WHERE {"
+ " ?subject : %s" + " ?value . " + "FILTER regex(?value, \"%s" + "\", \"i\") ."
+ " }";
/**
* Use String.format: namespace, property, value
*/
public static final String SubjectByPropertyValue = "PREFIX rdfs: <" + SemanticConstants.NS_RDFS_SCHEMA + "> "
+ "PREFIX : <%s>"
+ "SELECT * "
+ "WHERE {" + " ?subject : %s" + " \"%s\" . " + "}";
/**
* Use String.format phaseId
*/
public static final String SubjectByPhaseId = "PREFIX dogont: <" + DogontSchema.NS + "> "
+ "SELECT ?subject "
+ "WHERE {" + " ?statevalue dogont:phaseID \"<%s>\" ."
+ " ?state dogont:hasStateValue ?statevalue. "
+ " ?subject dogont:hasState ?state. " + "}";
/**
* Use String.format phaseId
*/
public static final String StateValueByPhaseId = "PREFIX dogont: <" + DogontSchema.NS + "> "
+ "SELECT ?statevalue " + "WHERE {" + " ?statevalue dogont:phaseID \"<%s>\" ." + "}";
/**
* Selects all BuildingThings which have an StateValue.<br>
* varNames: instance, state, value, realValue
*/
public static final String BuildingThingsContainingStateValue = ""
+ "PREFIX rdfs: <" + SemanticConstants.NS_RDFS_SCHEMA + "> "
+ "PREFIX rdf: <" + SemanticConstants.NS_RDF_SYNTAX + "> "
+ "PREFIX dogont: <" + DogontSchema.NS + "> "
+ "SELECT ?instance ?state ?value ?realValue "
+ "WHERE { "
+ "?class rdfs:subClassOf* dogont:BuildingThing. "
+ "?instance rdf:type ?class . "
+ "?instance dogont:hasState ?state. "
+ "?state dogont:hasStateValue ?value. "
+ "?value dogont:realStateValue ?realValue }";
/**
* Ask query. True if the given resource is a subClassOf* Functionality.<br>
* Use String.format local resource name
*/
public static final String ResourceIsSubClassOfFunctionality = ""
+ "PREFIX rdf: <" + SemanticConstants.NS_RDF_SYNTAX + "> "
+ "PREFIX rdfs: <" + SemanticConstants.NS_RDFS_SCHEMA + "> "
+ "PREFIX instance: <" + SemanticConstants.NS_INSTANCE + "> "
+ "PREFIX dogont: <" + DogontSchema.NS + "> "
+ "ASK "
+ "{ "
+ " instance:%s "
+ " rdf:type ?type. "
+ " ?type rdfs:subClassOf* dogont:Functionality "
+ "}";
/**
* Query for receiving the location name for a thing.
* Use String.format instance uri of the thing
*/
public static final String LocationNameOfThing = Prefix
+ "SELECT ?location ?realname "
+ "WHERE { "
+ " instance:%s dogont:isIn ?location . "
+ " ?location rdfs:label ?realname . "
+ "} ";
/**
* Query for receiving the location name for a state.
* Use String.format instance uri of the state.
*/
public static final String LocationNameOfFunctionality = Prefix
+ "SELECT ?location ?realname "
+ "WHERE { "
+ " ?thing dogont:hasFunctionality instance:%s . "
+ " ?thing dogont:isIn ?location . "
+ " ?location rdfs:label ?realname . "
+ "} ";
/**
* Query for receiving the location name for a state.
* Use String.format instance uri of the state.
*/
public static final String LocationNameOfState = Prefix
+ "SELECT ?location ?realname "
+ "WHERE { "
+ " ?thing dogont:hasState instance:%s ."
+ " ?thing dogont:isIn ?location . "
+ " ?location rdfs:label ?realname . "
+ "} ";
/**
* Gets all State items with their location name, and the type name for state and the thing
*/
public static final String AllSensors = Prefix
+ "SELECT ?instance ?shortName ?typeName ?location ?thingName ?unit ?symbol "
+ " WHERE { "
+ " ?class rdfs:subClassOf* dogont:State . "
+ " ?instance rdf:type ?class . "
+ " bind(strafter(str(?instance),str(instance:)) as ?shortName) . "
+ "bind(strafter(str(?class),str(dogont:)) as ?typeName) . "
+ "?thing dogont:hasState ?instance . "
+ "?thing rdf:type ?thingType . "
+ "bind(strafter(str(?thingType),str(dogont:)) as ?thingName) . "
+ "optional { "
+ "?thing dogont:isIn ?loc . "
+ "?loc rdfs:label ?location . "
+ "} "
+ " optional { "
+ " ?instance dogont:hasStateValue ?value . "
+ " ?value dogont:unitOfMeasure ?unit . "
+ " ?unit uomvocab:prefSymbol ?symbol . "
+ "} "
+"}";
}
|
package org.cagrid.dorian.service.wsrf;
import javax.xml.namespace.QName;
import org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OutboundSamlCanonicalizerInterceptor extends AbstractSamlCanonicalizerInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(OutboundSamlCanonicalizerInterceptor.class);
// It's stupid JAXB doesn't generate constants for these...
// TODO: could probably take these in as parameters
public static final QName AUTHENTICATE_USER_QNAME = new QName("http://cagrid.nci.nih.gov/Dorian",
"authenticateUser");
public OutboundSamlCanonicalizerInterceptor() {
super(Phase.PRE_STREAM);
addBefore(SoapPreProtocolOutInterceptor.class.getName());
}
@Override
protected boolean doesOutboundMessageApply(Message message) {
BindingOperationInfo operationInfo = message.getExchange().getBindingOperationInfo();
if (operationInfo != null && operationInfo.getName() != null) {
if (operationInfo.getName().equals(AUTHENTICATE_USER_QNAME)) {
LOG.debug("Matching operation:" + operationInfo.getName());
return true;
} else {
LOG.debug("Skipped operation:" + operationInfo.getName());
return false;
}
} else {
LOG.warn("Unable to determine whether to apply canonicalization as operation info was null. Ensure the Phase is POST_PROTOCOL, and this is running on the inbound path. Returning false.");
return false;
}
}
@Override
protected boolean doesInboundMessageApply(Message message) {
return false;
}
}
|
package com.jivesoftware.os.miru.service.partition;
import com.google.common.util.concurrent.AtomicDouble;
import com.jivesoftware.os.filer.io.FilerIO;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import com.jivesoftware.os.mlogger.core.ValueType;
import java.util.concurrent.atomic.AtomicLong;
/**
*
* @author jonathan.colt
*/
public class MiruMergeChits {
private static final MetricLogger log = MetricLoggerFactory.getLogger();
private final AtomicLong chits;
private final AtomicDouble movingAvgOfMillisPerIndexed = new AtomicDouble(0);
private final double mergeRateRatio;
public MiruMergeChits(long free, double mergeRateRatio) {
chits = new AtomicLong(free);
this.mergeRateRatio = mergeRateRatio;
}
public void take(int count) {
long chitsFree = chits.addAndGet(-count);
log.set(ValueType.COUNT, "chits>free", chitsFree);
}
public boolean merge(long indexed, long elapse) {
if (indexed <= 0) {
return false;
}
if (elapse < 0) {
elapse = 0;
}
double millisPerIndexed = (double) elapse / (double) indexed;
movingAvgOfMillisPerIndexed.set((movingAvgOfMillisPerIndexed.get() + millisPerIndexed) / 2);
double movingAvg = movingAvgOfMillisPerIndexed.get();
log.set(ValueType.VALUE, "chit>millisPerIndex", (long) movingAvg);
double scalar = 1;
if (movingAvg > 0) {
scalar += (millisPerIndexed / movingAvg) * (mergeRateRatio * 2); // * 2 magic inverse of div by 2 moving avg above.
}
long chitsFree = chits.get();
boolean merge = (indexed * scalar) > chitsFree;
if (merge) {
log.inc("chit>merged>power>" + FilerIO.chunkPower(indexed, 0));
}
return merge;
}
public void refund(long count) {
chits.addAndGet(count);
}
}
|
package de.unistuttgart.quadrama.io.dot;
import static org.apache.commons.io.IOUtils.closeQuietly;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.CASException;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.jcas.JCas;
import org.jgrapht.Graph;
import org.jgrapht.ext.DOTExporter;
import org.jgrapht.ext.VertexNameProvider;
import org.jgrapht.graph.DefaultWeightedEdge;
import de.tudarmstadt.ukp.dkpro.core.api.io.JCasFileWriter_ImplBase;
import de.unistuttgart.quadrama.api.Figure;
import de.unistuttgart.quadrama.graph.ext.GraphImporter;
public class DotExporter extends JCasFileWriter_ImplBase {
public static final String PARAM_VIEW_NAME = "View Name";
@ConfigurationParameter(name = PARAM_VIEW_NAME, mandatory = true)
String viewName = null;
@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
try {
Graph<Figure, DefaultWeightedEdge> graph =
GraphImporter.getGraph(jcas, viewName);
OutputStream docOS = null;
OutputStreamWriter writer = null;
try {
docOS = getOutputStream(jcas, ".dot");
writer = new OutputStreamWriter(docOS);
DOTExporter<Figure, DefaultWeightedEdge> exporter =
new DOTExporter<Figure, DefaultWeightedEdge>(
new VertexNameProvider<Figure>() {
public String getVertexName(Figure vertex) {
return String.valueOf(vertex.getId());
}
}, new VertexNameProvider<Figure>() {
public String getVertexName(Figure vertex) {
return vertex.getCoveredText();
}
}, null);
exporter.export(writer, graph);
} catch (Exception e) {
throw new AnalysisEngineProcessException(e);
} finally {
closeQuietly(writer);
closeQuietly(docOS);
}
} catch (CASException e1) {
throw new AnalysisEngineProcessException(e1);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
|
package org.slf4j;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import org.slf4j.helpers.SubstituteLoggerFactory;
import org.slf4j.helpers.Util;
import org.slf4j.impl.StaticLoggerBinder;
/**
* The <code>LoggerFactory</code> is a utility class producing Loggers for
* various logging APIs, most notably for log4j, logback and JDK 1.4 logging.
* Other implementations such as {@link org.slf4j.impl.NOPLogger NOPLogger} and
* {@link org.slf4j.impl.SimpleLogger SimpleLogger} are also supported.
*
* <p>
* <code>LoggerFactory</code> is essentially a wrapper around an
* {@link ILoggerFactory} instance bound with <code>LoggerFactory</code> at
* compile time.
*
* <p>
* Please note that all methods in <code>LoggerFactory</code> are static.
*
* @author Ceki Gülcü
* @author Robert Elliot
*/
public final class LoggerFactory {
static final String NO_STATICLOGGERBINDER_URL = "http://www.slf4j.org/codes.html#StaticLoggerBinder";
static final String NULL_LF_URL = "http://www.slf4j.org/codes.html#null_LF";
static final String VERSION_MISMATCH = "http://www.slf4j.org/codes.html#version_mismatch";
static final String SUBSTITUTE_LOGGER_URL = "http://www.slf4j.org/codes.html#substituteLogger";
static final String UNSUCCESSFUL_INIT_URL = "http://www.slf4j.org/codes.html#unsuccessfulInit";
static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory could not be successfully initialized. See also "
+ UNSUCCESSFUL_INIT_URL;
static final int UNINITIALIZED = 0;
static final int ONGOING_INITILIZATION = 1;
static final int FAILED_INITILIZATION = 2;
static final int SUCCESSFUL_INITILIZATION = 3;
static final int GET_SINGLETON_INEXISTENT = 1;
static final int GET_SINGLETON_EXISTS = 2;
static int INITIALIZATION_STATE = UNINITIALIZED;
static int GET_SINGLETON_METHOD = UNINITIALIZED;
static SubstituteLoggerFactory TEMP_FACTORY = new SubstituteLoggerFactory();
/**
* It is our responsibility to track version changes and manage the
* compatibility list.
*
* <p>
*/
static private final String[] API_COMPATIBILITY_LIST = new String[] {
"1.5.5", "1.5.6", "1.5.7" };
// private constructor prevents instantiation
private LoggerFactory() {
}
/**
* Force LoggerFactory to consider itself uninitialized.
*
* <p>
* This method is intended to be called by classes (in the same package) for
* testing purposes. This method is internal. It can be modified, renamed or
* removed at any time without notice.
*
* <p>
* You are strongly discouraged from calling this method in production code.
*/
static void reset() {
INITIALIZATION_STATE = UNINITIALIZED;
GET_SINGLETON_METHOD = UNINITIALIZED;
TEMP_FACTORY = new SubstituteLoggerFactory();
}
private final static void performInitialization() {
bind();
versionSanityCheck();
singleImplementationSanityCheck();
}
private final static void bind() {
try {
// the next line does the binding
getSingleton();
INITIALIZATION_STATE = SUCCESSFUL_INITILIZATION;
emitSubstitureLoggerWarning();
} catch (NoClassDefFoundError ncde) {
INITIALIZATION_STATE = FAILED_INITILIZATION;
String msg = ncde.getMessage();
if (msg != null && msg.indexOf("org/slf4j/impl/StaticLoggerBinder") != -1) {
Util
.reportFailure("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
Util.reportFailure("See " + NO_STATICLOGGERBINDER_URL
+ " for further details.");
}
throw ncde;
} catch (Exception e) {
INITIALIZATION_STATE = FAILED_INITILIZATION;
// we should never get here
Util.reportFailure("Failed to instantiate logger ["
+ getSingleton().getLoggerFactoryClassStr() + "]", e);
}
}
private final static void emitSubstitureLoggerWarning() {
List loggerNameList = TEMP_FACTORY.getLoggerNameList();
if (loggerNameList.size() == 0) {
return;
}
Util
.reportFailure("The following loggers will not work becasue they were created");
Util
.reportFailure("during the default configuration phase of the underlying logging system.");
Util.reportFailure("See also " + SUBSTITUTE_LOGGER_URL);
for (int i = 0; i < loggerNameList.size(); i++) {
String loggerName = (String) loggerNameList.get(i);
Util.reportFailure(loggerName);
}
}
private final static void versionSanityCheck() {
try {
String requested = StaticLoggerBinder.REQUESTED_API_VERSION;
boolean match = false;
for (int i = 0; i < API_COMPATIBILITY_LIST.length; i++) {
if (API_COMPATIBILITY_LIST[i].equals(requested)) {
match = true;
}
}
if (!match) {
Util.reportFailure("The requested version " + requested
+ " by your slf4j binding is not compatible with "
+ Arrays.toString(API_COMPATIBILITY_LIST));
Util.reportFailure("See " + VERSION_MISMATCH + " for further details.");
}
} catch (java.lang.NoSuchFieldError nsfe) {
// given our large user base and SLF4J's commitment to backward
// compatibility, we cannot cry here. Only for implementations
// which willingly declare a REQUESTED_API_VERSION field do we
// emit compatibility warnings.
} catch (Throwable e) {
// we should never reach here
Util.reportFailure(
"Unexpected problem occured during version sanity check", e);
}
}
// We need to use the name of the StaticLoggerBinder class, we can't reference
// the class itseld.
private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";
private static void singleImplementationSanityCheck() {
try {
Enumeration paths = LoggerFactory.class.getClassLoader().getResources(
STATIC_LOGGER_BINDER_PATH);
List implementationList = new ArrayList();
while (paths.hasMoreElements()) {
URL path = (URL) paths.nextElement();
implementationList.add(path);
}
if (implementationList.size() > 1) {
Util
.reportFailure("ClassPath contains more than one SLF4J implementation.");
for(int i = 0; i < implementationList.size(); i++) {
Util.reportFailure("Found binding under ["+implementationList.get(i)+"]");
}
Util.reportFailure("Will pick up one binding at random.");
}
} catch (IOException ioe) {
Util.reportFailure("Error getting resources from path", ioe);
}
}
private final static StaticLoggerBinder getSingleton() {
if (GET_SINGLETON_METHOD == GET_SINGLETON_INEXISTENT) {
return StaticLoggerBinder.SINGLETON;
}
if (GET_SINGLETON_METHOD == GET_SINGLETON_EXISTS) {
return StaticLoggerBinder.getSingleton();
}
try {
StaticLoggerBinder singleton = StaticLoggerBinder.getSingleton();
GET_SINGLETON_METHOD = GET_SINGLETON_EXISTS;
return singleton;
} catch (NoSuchMethodError nsme) {
GET_SINGLETON_METHOD = GET_SINGLETON_INEXISTENT;
return StaticLoggerBinder.SINGLETON;
}
}
/**
* Return a logger named according to the name parameter using the statically
* bound {@link ILoggerFactory} instance.
*
* @param name
* The name of the logger.
* @return logger
*/
public static Logger getLogger(String name) {
ILoggerFactory iLoggerFactory = getILoggerFactory();
return iLoggerFactory.getLogger(name);
}
/**
* Return a logger named corresponding to the class passed as parameter, using
* the statically bound {@link ILoggerFactory} instance.
*
* @param clazz
* the returned logger will be named after clazz
* @return logger
*/
public static Logger getLogger(Class clazz) {
return getLogger(clazz.getName());
}
/**
* Return the {@link ILoggerFactory} instance in use.
*
* <p>
* ILoggerFactory instance is bound with this class at compile time.
*
* @return the ILoggerFactory instance in use
*/
public static ILoggerFactory getILoggerFactory() {
if (INITIALIZATION_STATE == UNINITIALIZED) {
INITIALIZATION_STATE = ONGOING_INITILIZATION;
performInitialization();
}
switch (INITIALIZATION_STATE) {
case SUCCESSFUL_INITILIZATION:
return getSingleton().getLoggerFactory();
case FAILED_INITILIZATION:
throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
case ONGOING_INITILIZATION:
// support re-entrant behavior.
return TEMP_FACTORY;
}
throw new IllegalStateException("Unreachable code");
}
}
|
package org.eclipse.persistence.platform.database.oracle.plsql;
//javase imports
import static java.sql.Types.ARRAY;
//EclipseLink imports
import org.eclipse.persistence.internal.helper.ComplexDatabaseType;
import org.eclipse.persistence.internal.helper.DatabaseType;
public class PLSQLCollection extends ComplexDatabaseType implements Cloneable, OraclePLSQLType {
/**
* Defines the database type of the value contained in the collection type.
* <p>i.e. the OF type.
* <p>This could be a JDBC type, PLSQL type, or a PLSQL RECORD type.
*/
protected DatabaseType nestedType;
public PLSQLCollection() {
super();
}
@Override
public PLSQLCollection clone() {
PLSQLCollection clone = (PLSQLCollection)super.clone();
return clone;
}
public boolean isCollection() {
return true;
}
/**
* Return the database type of the value contained in the collection type.
*/
public DatabaseType getNestedType() {
return nestedType;
}
/**
* Set the database type of the value contained in the collection type.
* <p>i.e. the OF type.
* <p>This could be a JDBC type, PLSQL type, or a PLSQL RECORD type.
*/
public void setNestedType(DatabaseType nestedType) {
this.nestedType = nestedType;
}
public int getSqlCode() {
return ARRAY;
}
}
|
package org.innovateuk.ifs.project.core.transactional;
import org.innovateuk.ifs.BaseServiceUnitTest;
import org.innovateuk.ifs.activitylog.resource.ActivityType;
import org.innovateuk.ifs.activitylog.transactional.ActivityLogService;
import org.innovateuk.ifs.address.domain.Address;
import org.innovateuk.ifs.address.resource.OrganisationAddressType;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.repository.ApplicationRepository;
import org.innovateuk.ifs.application.resource.FundingDecision;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.publiccontent.resource.FundingType;
import org.innovateuk.ifs.finance.builder.ApplicationFinanceBuilder;
import org.innovateuk.ifs.finance.domain.ApplicationFinance;
import org.innovateuk.ifs.form.domain.Section;
import org.innovateuk.ifs.form.resource.SectionType;
import org.innovateuk.ifs.fundingdecision.domain.FundingDecisionStatus;
import org.innovateuk.ifs.invite.domain.ProjectUserInvite;
import org.innovateuk.ifs.invite.repository.ProjectUserInviteRepository;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.domain.OrganisationAddress;
import org.innovateuk.ifs.organisation.domain.OrganisationType;
import org.innovateuk.ifs.organisation.mapper.OrganisationMapper;
import org.innovateuk.ifs.organisation.repository.OrganisationRepository;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum;
import org.innovateuk.ifs.project.core.domain.PartnerOrganisation;
import org.innovateuk.ifs.project.core.domain.Project;
import org.innovateuk.ifs.project.core.domain.ProjectUser;
import org.innovateuk.ifs.project.core.mapper.ProjectMapper;
import org.innovateuk.ifs.project.core.repository.ProjectRepository;
import org.innovateuk.ifs.project.core.repository.ProjectUserRepository;
import org.innovateuk.ifs.project.core.workflow.configuration.ProjectWorkflowHandler;
import org.innovateuk.ifs.project.document.resource.DocumentStatus;
import org.innovateuk.ifs.project.documents.builder.ProjectDocumentBuilder;
import org.innovateuk.ifs.project.documents.domain.ProjectDocument;
import org.innovateuk.ifs.project.financechecks.domain.CostCategoryType;
import org.innovateuk.ifs.project.financechecks.transactional.FinanceChecksGenerator;
import org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration.EligibilityWorkflowHandler;
import org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration.PaymentMilestoneWorkflowHandler;
import org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration.ViabilityWorkflowHandler;
import org.innovateuk.ifs.project.grantofferletter.configuration.workflow.GrantOfferLetterWorkflowHandler;
import org.innovateuk.ifs.project.monitoring.domain.MonitoringOfficer;
import org.innovateuk.ifs.project.projectdetails.workflow.configuration.ProjectDetailsWorkflowHandler;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.project.spendprofile.configuration.workflow.SpendProfileWorkflowHandler;
import org.innovateuk.ifs.project.spendprofile.transactional.CostCategoryTypeStrategy;
import org.innovateuk.ifs.security.LoggedInUserSupplier;
import org.innovateuk.ifs.user.domain.ProcessRole;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.repository.UserRepository;
import org.innovateuk.ifs.user.resource.Role;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.springframework.dao.DataIntegrityViolationException;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.function.Predicate;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.Boolean.TRUE;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.innovateuk.ifs.LambdaMatcher.createLambdaMatcher;
import static org.innovateuk.ifs.LambdaMatcher.lambdaMatches;
import static org.innovateuk.ifs.address.builder.AddressBuilder.newAddress;
import static org.innovateuk.ifs.address.builder.AddressTypeBuilder.newAddressType;
import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication;
import static org.innovateuk.ifs.commons.error.CommonErrors.badRequestError;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition;
import static org.innovateuk.ifs.form.builder.SectionBuilder.newSection;
import static org.innovateuk.ifs.invite.builder.ProjectUserInviteBuilder.newProjectUserInvite;
import static org.innovateuk.ifs.organisation.builder.OrganisationAddressBuilder.newOrganisationAddress;
import static org.innovateuk.ifs.organisation.builder.OrganisationBuilder.newOrganisation;
import static org.innovateuk.ifs.organisation.builder.OrganisationResourceBuilder.newOrganisationResource;
import static org.innovateuk.ifs.organisation.builder.OrganisationTypeBuilder.newOrganisationType;
import static org.innovateuk.ifs.project.builder.ProjectResourceBuilder.newProjectResource;
import static org.innovateuk.ifs.project.core.builder.PartnerOrganisationBuilder.newPartnerOrganisation;
import static org.innovateuk.ifs.project.core.builder.ProjectBuilder.newProject;
import static org.innovateuk.ifs.project.core.builder.ProjectUserBuilder.newProjectUser;
import static org.innovateuk.ifs.project.core.domain.ProjectParticipantRole.*;
import static org.innovateuk.ifs.project.financecheck.builder.CostCategoryBuilder.newCostCategory;
import static org.innovateuk.ifs.project.financecheck.builder.CostCategoryGroupBuilder.newCostCategoryGroup;
import static org.innovateuk.ifs.project.financecheck.builder.CostCategoryTypeBuilder.newCostCategoryType;
import static org.innovateuk.ifs.user.builder.ProcessRoleBuilder.newProcessRole;
import static org.innovateuk.ifs.user.builder.UserBuilder.newUser;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleFilter;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
public class ProjectServiceImplTest extends BaseServiceUnitTest<ProjectService> {
@Mock
private CostCategoryTypeStrategy costCategoryTypeStrategyMock;
@Mock
private FinanceChecksGenerator financeChecksGeneratorMock;
@Mock
private ApplicationRepository applicationRepositoryMock;
@Mock
private OrganisationRepository organisationRepositoryMock;
@Mock
private LoggedInUserSupplier loggedInUserSupplierMock;
@Mock
private ProjectRepository projectRepositoryMock;
@Mock
private ProjectDetailsWorkflowHandler projectDetailsWorkflowHandlerMock;
@Mock
private ViabilityWorkflowHandler viabilityWorkflowHandlerMock;
@Mock
private EligibilityWorkflowHandler eligibilityWorkflowHandlerMock;
@Mock
private PaymentMilestoneWorkflowHandler paymentMilestoneWorkflowHandler;
@Mock
private GrantOfferLetterWorkflowHandler golWorkflowHandlerMock;
@Mock
private ProjectWorkflowHandler projectWorkflowHandlerMock;
@Mock
private ProjectMapper projectMapperMock;
@Mock
private UserRepository userRepositoryMock;
@Mock
private ProjectUserRepository projectUserRepositoryMock;
@Mock
private ProjectUserInviteRepository projectUserInviteRepositoryMock;
@Mock
private SpendProfileWorkflowHandler spendProfileWorkflowHandlerMock;
@Mock
private ActivityLogService activityLogService;
@Mock
private OrganisationMapper organisationMapperMock;
private long applicationId = 456;
private Competition competition;
private Application application;
private Organisation organisation;
private User user;
private User u;
private ProjectUser leadPartnerProjectUser;
private Organisation o;
private Project project;
@Before
public void setUp() {
organisation = newOrganisation().
withOrganisationType(OrganisationTypeEnum.BUSINESS).
build();
long userId = 7;
user = newUser().
withId(userId).
build();
ProcessRole leadApplicantProcessRole = newProcessRole().
withOrganisationId(organisation.getId()).
withRole(Role.LEADAPPLICANT).
withUser(user).
build();
leadPartnerProjectUser = newProjectUser().
withOrganisation(organisation).
withRole(PROJECT_PARTNER).
withUser(user).
build();
ApplicationFinance applicationFinance = ApplicationFinanceBuilder.newApplicationFinance()
.withApplication(application)
.withOrganisation(organisation)
.withWorkPostcode("UB7 8QF")
.build();
List<ApplicationFinance> applicationFinances = singletonList(applicationFinance);
Section section1 = newSection().withSectionType(SectionType.FINANCE).build();
Section section2 = newSection().withSectionType(SectionType.PAYMENT_MILESTONES).build();
competition = newCompetition()
.withSections(Arrays.asList(section1, section2))
.withFundingType(FundingType.PROCUREMENT)
.build();
application = newApplication().
withId(applicationId).
withCompetition(competition).
withProcessRoles(leadApplicantProcessRole).
withName("My Application").
withDurationInMonths(5L).
withStartDate(LocalDate.of(2017, 3, 2)).
withFundingDecision(FundingDecisionStatus.FUNDED).
withApplicationFinancesList(applicationFinances).
build();
OrganisationType businessOrganisationType = newOrganisationType().withOrganisationType(OrganisationTypeEnum.BUSINESS).build();
o = organisation;
o.setOrganisationType(businessOrganisationType);
List<PartnerOrganisation> partnerOrganisations = newPartnerOrganisation().
withOrganisation(o).
withLeadOrganisation(TRUE).
build(1);
u = newUser().
withEmailAddress("a@b.com").
withFirstName("A").
withLastName("B").
build();
List<ProjectUser> projectUsers = newProjectUser().
withRole(PROJECT_FINANCE_CONTACT).
withUser(u).
withOrganisation(o).
withInvite(newProjectUserInvite().
build()).
build(1);
project = newProject().
withProjectUsers(projectUsers).
withApplication(application).
withPartnerOrganisations(partnerOrganisations).
withDateSubmitted(ZonedDateTime.now()).
withSpendProfileSubmittedDate(ZonedDateTime.now()).
build();
ProjectDocument projectDocument = ProjectDocumentBuilder
.newProjectDocument()
.withProject(project)
.withStatus(DocumentStatus.APPROVED)
.build();
project.setProjectDocuments(singletonList(projectDocument));
when(applicationRepositoryMock.findById(applicationId)).thenReturn(Optional.of(application));
when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation));
when(loggedInUserSupplierMock.get()).thenReturn(newUser().build());
}
@Test
public void createProjectFromApplication() {
ProjectResource newProjectResource = newProjectResource().build();
PartnerOrganisation savedProjectPartnerOrganisation = newPartnerOrganisation().
withOrganisation(organisation).
withLeadOrganisation(true).
build();
Project savedProject = newProject().
withId(newProjectResource.getId()).
withApplication(application).
withProjectUsers(asList(leadPartnerProjectUser, newProjectUser().build())).
withPartnerOrganisations(singletonList(savedProjectPartnerOrganisation)).
build();
Project newProjectExpectations = createProjectExpectationsFromOriginalApplication();
when(projectRepositoryMock.save(newProjectExpectations)).thenReturn(savedProject);
CostCategoryType costCategoryTypeForOrganisation = newCostCategoryType().
withCostCategoryGroup(newCostCategoryGroup().
withCostCategories(newCostCategory().withName("Cat1", "Cat2").build(2)).
build()).
build();
when(costCategoryTypeStrategyMock.getOrCreateCostCategoryTypeForSpendProfile(savedProject.getId(),
organisation.getId())).thenReturn(serviceSuccess(costCategoryTypeForOrganisation));
when(financeChecksGeneratorMock.createMvpFinanceChecksFigures(savedProject, organisation, costCategoryTypeForOrganisation)).thenReturn(serviceSuccess());
when(financeChecksGeneratorMock.createFinanceChecksFigures(savedProject, organisation)).thenReturn(serviceSuccess(null));
when(projectDetailsWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true);
when(viabilityWorkflowHandlerMock.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true);
when(eligibilityWorkflowHandlerMock.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true);
when(paymentMilestoneWorkflowHandler.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true);
when(golWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true);
when(projectWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true);
when(spendProfileWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true);
when(projectMapperMock.mapToResource(savedProject)).thenReturn(newProjectResource);
ServiceResult<ProjectResource> project = service.createProjectFromApplication(applicationId);
assertTrue(project.isSuccess());
assertEquals(newProjectResource, project.getSuccess());
assertNotNull(competition.getProjectSetupStarted());
verify(costCategoryTypeStrategyMock).getOrCreateCostCategoryTypeForSpendProfile(savedProject.getId(), organisation.getId());
verify(financeChecksGeneratorMock).createMvpFinanceChecksFigures(savedProject, organisation, costCategoryTypeForOrganisation);
verify(financeChecksGeneratorMock).createFinanceChecksFigures(savedProject, organisation);
verify(projectDetailsWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser);
verify(viabilityWorkflowHandlerMock).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser);
verify(eligibilityWorkflowHandlerMock).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser);
verify(paymentMilestoneWorkflowHandler).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser);
verify(golWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser);
verify(projectWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser);
verify(projectMapperMock).mapToResource(savedProject);
verify(activityLogService).recordActivityByApplicationId(applicationId, ActivityType.APPLICATION_INTO_PROJECT_SETUP);
}
@Test
public void createProjectFromApplication_KTP() {
competition = newCompetition()
.withFundingType(FundingType.KTP)
.withSections(newSection().withSectionType(SectionType.FINANCE).build(1))
.build();
application.setCompetition(competition);
OrganisationAddress kbAddress = newOrganisationAddress()
.withAddressType(newAddressType().withId(OrganisationAddressType.KNOWLEDGE_BASE.getId()).build())
.withAddress(newAddress().withAddressLine1("address").build())
.build();
organisation.setOrganisationType(newOrganisationType().withOrganisationType(OrganisationTypeEnum.KNOWLEDGE_BASE).build());
organisation.setAddresses(newArrayList(kbAddress));
Organisation partner = newOrganisation().
withOrganisationType(OrganisationTypeEnum.BUSINESS).
build();
when(organisationRepositoryMock.findById(partner.getId())).thenReturn(Optional.of(partner));
ProcessRole partnerProcessRole = newProcessRole().
withOrganisationId(partner.getId()).
withRole(Role.COLLABORATOR).
withUser(newUser().build()).
build();
ProcessRole ktaRole = newProcessRole().
withRole(Role.KNOWLEDGE_TRANSFER_ADVISER).
withUser(newUser().build()).
build();
application.getProcessRoles().add(partnerProcessRole);
application.getProcessRoles().add(ktaRole);
when(projectRepositoryMock.save(any())).thenAnswer(inv -> inv.getArgument(0));
when(projectDetailsWorkflowHandlerMock.projectCreated(any(), any())).thenReturn(true);
when(viabilityWorkflowHandlerMock.projectCreated(any(), any())).thenReturn(true);
when(eligibilityWorkflowHandlerMock.projectCreated(any(), any())).thenReturn(true);
when(golWorkflowHandlerMock.projectCreated(any(), any())).thenReturn(true);
when(projectWorkflowHandlerMock.projectCreated(any(), any())).thenReturn(true);
when(paymentMilestoneWorkflowHandler.projectCreated(any(), any())).thenReturn(true);
when(spendProfileWorkflowHandlerMock.projectCreated(any(), any())).thenReturn(true);
when(projectMapperMock.mapToResource(project)).thenReturn(new ProjectResource());
CostCategoryType costCategoryTypeForOrganisation = newCostCategoryType().
withCostCategoryGroup(newCostCategoryGroup().
withCostCategories(newCostCategory().withName("Cat1", "Cat2").build(2)).
build()).
build();
when(costCategoryTypeStrategyMock.getOrCreateCostCategoryTypeForSpendProfile(any(),
any())).thenReturn(serviceSuccess(costCategoryTypeForOrganisation));
when(financeChecksGeneratorMock.createMvpFinanceChecksFigures(any(), any(), eq(costCategoryTypeForOrganisation))).thenReturn(serviceSuccess());
when(financeChecksGeneratorMock.createFinanceChecksFigures(any(), any())).thenReturn(serviceSuccess(null));
when(projectDetailsWorkflowHandlerMock.projectAddressAdded(any(), any())).thenReturn(true);
ServiceResult<ProjectResource> result = service.createProjectFromApplication(applicationId);
assertTrue(result.isSuccess());
verify(projectDetailsWorkflowHandlerMock).projectAddressAdded(any(), any());
Predicate<Project> matcher = p -> {
assertThat(p.getProjectUsers().size(), equalTo(5));
ProjectUser projectManager = p.getProjectUsers().stream().filter(pu -> pu.getRole() == PROJECT_MANAGER).findAny().get();
assertThat(projectManager.getUser().getId(), equalTo(leadPartnerProjectUser.getUser().getId()));
ProjectUser financeContact1 = p.getProjectUsers().stream().filter(pu -> pu.getRole() == PROJECT_FINANCE_CONTACT && pu.getOrganisation().getId().equals(organisation.getId())).findAny().get();
assertThat(financeContact1.getUser().getId(), equalTo(leadPartnerProjectUser.getUser().getId()));
ProjectUser financeContact2 = p.getProjectUsers().stream().filter(pu -> pu.getRole() == PROJECT_FINANCE_CONTACT && pu.getOrganisation().getId().equals(partner.getId())).findAny().get();
assertThat(financeContact2.getUser().getId(), equalTo(partnerProcessRole.getUser().getId()));
MonitoringOfficer monitoringOfficer = p.getProjectMonitoringOfficer().get();
assertThat(monitoringOfficer.getUser().getId(), equalTo(ktaRole.getUser().getId()));
Address address = p.getAddress();
assertThat(address, equalTo(kbAddress.getAddress()));
return true;
};
verify(projectMapperMock).mapToResource(argThat(lambdaMatches(matcher)));
}
@Test
public void createProjectFromApplication_alreadyExists() {
ProjectResource existingProjectResource = newProjectResource().build();
Project existingProject = newProject().withApplication(application).build();
when(projectRepositoryMock.findOneByApplicationId(applicationId)).thenReturn(existingProject);
when(projectMapperMock.mapToResource(existingProject)).thenReturn(existingProjectResource);
ServiceResult<ProjectResource> project = service.createProjectFromApplication(applicationId);
assertTrue(project.isSuccess());
assertEquals(existingProjectResource, project.getSuccess());
verify(projectRepositoryMock).findOneByApplicationId(applicationId);
verify(projectMapperMock).mapToResource(existingProject);
verify(costCategoryTypeStrategyMock, never()).getOrCreateCostCategoryTypeForSpendProfile(any(Long.class), any(Long.class));
verify(financeChecksGeneratorMock, never()).createMvpFinanceChecksFigures(any(Project.class), any(Organisation.class), any(CostCategoryType.class));
verify(financeChecksGeneratorMock, never()).createFinanceChecksFigures(any(Project.class), any(Organisation.class));
verify(projectDetailsWorkflowHandlerMock, never()).projectCreated(any(Project.class), any(ProjectUser.class));
verify(golWorkflowHandlerMock, never()).projectCreated(any(Project.class), any(ProjectUser.class));
verify(projectWorkflowHandlerMock, never()).projectCreated(any(Project.class), any(ProjectUser.class));
}
@Test
public void findByUserId_returnsOnlyDistinctProjects() {
Project project = newProject().build();
User user = newUser().build();
List<ProjectUser> projectUserRecords = newProjectUser()
.withProject(project)
.withRole(PROJECT_PARTNER, PROJECT_FINANCE_CONTACT)
.build(2);
ProjectResource projectResource = newProjectResource().build();
when(projectUserRepositoryMock.findByUserId(user.getId())).thenReturn(projectUserRecords);
when(projectMapperMock.mapToResource(project)).thenReturn(projectResource);
List<ProjectResource> result = service.findByUserId(user.getId()).getSuccess();
assertEquals(1L, result.size());
InOrder inOrder = inOrder(projectUserRepositoryMock, projectMapperMock);
inOrder.verify(projectUserRepositoryMock).findByUserId(user.getId());
inOrder.verify(projectMapperMock).mapToResource(project);
inOrder.verifyNoMoreInteractions();
}
@Test
public void addPartner_organisationNotOnProject(){
Organisation organisationNotOnProject = newOrganisation().build();
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project));
when(organisationRepositoryMock.findById(o.getId())).thenReturn(Optional.of(o));
when(organisationRepositoryMock.findById(organisationNotOnProject.getId())).thenReturn(Optional.of(organisationNotOnProject));
when(userRepositoryMock.findById(u.getId())).thenReturn(Optional.of(u));
// Method under test
ServiceResult<ProjectUser> shouldFail = service.addPartner(project.getId(), u.getId(), organisationNotOnProject.getId());
// Expectations
assertTrue(shouldFail.isFailure());
assertTrue(shouldFail.getFailure().is(badRequestError("project does not contain organisation")));
}
@Test
public void addPartner_partnerAlreadyExists(){
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project));
when(organisationRepositoryMock.findById(o.getId())).thenReturn(Optional.of(o));
when(userRepositoryMock.findById(u.getId())).thenReturn(Optional.of(u));
setLoggedInUser(newUserResource().withId(u.getId()).build());
// Method under test
ServiceResult<ProjectUser> shouldFail = service.addPartner(project.getId(), u.getId(), o.getId());
// Expectations
verifyZeroInteractions(projectUserRepositoryMock);
assertTrue(shouldFail.isSuccess());
}
@Test
public void existsOnApplication(){
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.ofNullable(project));
// Method under test
ServiceResult<Boolean> shouldSucceed = service.existsOnApplication(project.getId(), organisation.getId()); // Organisation on the application
// Expectations
assertTrue(shouldSucceed.isSuccess());
assertTrue(shouldSucceed.getSuccess());
}
@Test
public void doesNotExistsOnApplication(){
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.ofNullable(project));
// Method under test
ServiceResult<Boolean> shouldSucceed = service.existsOnApplication(project.getId(), newOrganisation().build().getId()); // Organisation on the application
// Expectations
assertTrue(shouldSucceed.isSuccess());
assertFalse(shouldSucceed.getSuccess());
}
@Test
public void addPartner(){
User newUser = newUser().build();
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.ofNullable(project));
when(organisationRepositoryMock.findById(o.getId())).thenReturn(Optional.ofNullable(o));
when(userRepositoryMock.findById(u.getId())).thenReturn(Optional.ofNullable(u));
when(userRepositoryMock.findById(newUser.getId())).thenReturn(Optional.ofNullable(u));
List<ProjectUserInvite> projectInvites = newProjectUserInvite().withUser(user).build(1);
projectInvites.get(0).open();
when(projectUserInviteRepositoryMock.findByProjectId(project.getId())).thenReturn(projectInvites);
// Method under test
ServiceResult<ProjectUser> shouldSucceed = service.addPartner(project.getId(), newUser.getId(), o.getId());
// Expectations
assertTrue(shouldSucceed.isSuccess());
}
@Test
public void createProjectsFromFundingDecisions() {
ProjectResource newProjectResource = newProjectResource().build();
PartnerOrganisation savedProjectPartnerOrganisation = newPartnerOrganisation().
withOrganisation(organisation).
withLeadOrganisation(true).
build();
Project savedProject = newProject().
withId(newProjectResource.getId()).
withApplication(application).
withProjectUsers(asList(leadPartnerProjectUser, newProjectUser().build())).
withPartnerOrganisations(singletonList(savedProjectPartnerOrganisation)).
build();
Project newProjectExpectations = createProjectExpectationsFromOriginalApplication();
when(projectRepositoryMock.save(newProjectExpectations)).thenReturn(savedProject);
CostCategoryType costCategoryTypeForOrganisation = newCostCategoryType().
withCostCategoryGroup(newCostCategoryGroup().
withCostCategories(newCostCategory().withName("Cat1", "Cat2").build(2)).
build()).
build();
when(costCategoryTypeStrategyMock.getOrCreateCostCategoryTypeForSpendProfile(savedProject.getId(),
organisation.getId())).thenReturn(serviceSuccess(costCategoryTypeForOrganisation));
when(financeChecksGeneratorMock.createMvpFinanceChecksFigures(savedProject, organisation, costCategoryTypeForOrganisation)).thenReturn(serviceSuccess());
when(financeChecksGeneratorMock.createFinanceChecksFigures(savedProject, organisation)).thenReturn(serviceSuccess(null));
when(projectDetailsWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true);
when(viabilityWorkflowHandlerMock.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true);
when(eligibilityWorkflowHandlerMock.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true);
when(paymentMilestoneWorkflowHandler.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true);
when(golWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true);
when(projectWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true);
when(spendProfileWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true);
when(projectMapperMock.mapToResource(savedProject)).thenReturn(newProjectResource);
Map<Long, FundingDecision> fundingDecisions = new HashMap<>();
fundingDecisions.put(applicationId, FundingDecision.FUNDED);
ServiceResult<Void> project = service.createProjectsFromFundingDecisions(fundingDecisions);
assertTrue(project.isSuccess());
assertNotNull(competition.getProjectSetupStarted());
verify(costCategoryTypeStrategyMock).getOrCreateCostCategoryTypeForSpendProfile(savedProject.getId(), organisation.getId());
verify(financeChecksGeneratorMock).createMvpFinanceChecksFigures(savedProject, organisation, costCategoryTypeForOrganisation);
verify(financeChecksGeneratorMock).createFinanceChecksFigures(savedProject, organisation);
verify(projectDetailsWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser);
verify(viabilityWorkflowHandlerMock).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser);
verify(eligibilityWorkflowHandlerMock).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser);
verify(paymentMilestoneWorkflowHandler).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser);
verify(golWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser);
verify(projectWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser);
verify(projectMapperMock).mapToResource(savedProject);
verify(activityLogService).recordActivityByApplicationId(applicationId, ActivityType.APPLICATION_INTO_PROJECT_SETUP);
}
@Test
public void createProjectsFromFundingDecisions_saveFails() throws Exception {
Project newProjectExpectations = createProjectExpectationsFromOriginalApplication();
when(projectRepositoryMock.save(newProjectExpectations)).thenThrow(new DataIntegrityViolationException("dummy constraint violation"));
Map<Long, FundingDecision> fundingDecisions = new HashMap<>();
fundingDecisions.put(applicationId, FundingDecision.FUNDED);
try {
service.createProjectsFromFundingDecisions(fundingDecisions);
assertThat("Service failed to throw expected exception.", false);
} catch (Exception e) {
assertEquals(e.getCause().getMessage(),"dummy constraint violation");
}
}
@Test
public void createProjectsFromFundingDecisions_noFinanceFails() throws Exception {
createProjectExpectationsFromOriginalApplication();
List<Section> oldSections = competition.getSections();
competition.setSections(emptyList());
Map<Long, FundingDecision> fundingDecisions = new HashMap<>();
fundingDecisions.put(applicationId, FundingDecision.FUNDED);
ServiceResult<Void> result = service.createProjectsFromFundingDecisions(fundingDecisions);
assertTrue(result.isFailure());
assertEquals(result.getFailure().getErrors().get(0).getErrorKey(), "CREATE_PROJECT_FROM_APPLICATION_FAILS");
competition.setSections(oldSections);
}
@Test
public void getLeadOrganisation() {
OrganisationResource expectedOrganisationResource = newOrganisationResource().build();
when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project));
when(organisationMapperMock.mapToResource(organisation)).thenReturn(expectedOrganisationResource);
OrganisationResource organisationResource = service.getLeadOrganisation(project.getId()).getSuccess();
assertEquals(expectedOrganisationResource, organisationResource);
InOrder inOrder = inOrder(projectRepositoryMock, organisationRepositoryMock, organisationMapperMock);
inOrder.verify(projectRepositoryMock).findById(project.getId());
inOrder.verify(organisationRepositoryMock).findById(project.getApplication().getLeadOrganisationId());
inOrder.verify(organisationMapperMock).mapToResource(organisation);
inOrder.verifyNoMoreInteractions();
}
private Project createProjectExpectationsFromOriginalApplication() {
assertFalse(application.getProcessRoles().isEmpty());
return createLambdaMatcher(project -> {
assertEquals(application.getName(), project.getName());
assertEquals(application.getDurationInMonths(), project.getDurationInMonths());
assertEquals(application.getStartDate(), project.getTargetStartDate());
assertFalse(project.getProjectUsers().isEmpty());
assertNull(project.getAddress());
List<ProcessRole> collaborativeRoles = simpleFilter(application.getProcessRoles(), ProcessRole::isLeadApplicantOrCollaborator);
assertEquals(collaborativeRoles.size(), project.getProjectUsers().size());
collaborativeRoles.forEach(processRole -> {
List<ProjectUser> matchingProjectUser = simpleFilter(project.getProjectUsers(), projectUser ->
projectUser.getOrganisation().getId().equals(processRole.getOrganisationId()) &&
projectUser.getUser().equals(processRole.getUser()));
assertEquals(1, matchingProjectUser.size());
assertEquals(Role.PARTNER.getName(), matchingProjectUser.get(0).getRole().getName());
assertEquals(project, matchingProjectUser.get(0).getProcess());
});
List<PartnerOrganisation> partnerOrganisations = project.getPartnerOrganisations();
assertEquals(1, partnerOrganisations.size());
PartnerOrganisation partnerOrganisation = partnerOrganisations.get(0);
assertEquals(project, partnerOrganisation.getProject());
assertEquals(organisation, partnerOrganisation.getOrganisation());
assertEquals("UB7 8QF", partnerOrganisation.getPostcode());
assertTrue(partnerOrganisation.isLeadOrganisation());
});
}
@Override
protected ProjectService supplyServiceUnderTest() {
return new ProjectServiceImpl();
}
}
|
package org.innovateuk.ifs.survey;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.commons.service.RootAnonymousUserRestTemplateAdaptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.innovateuk.ifs.survey.SurveyResourceBuilder.newSurveyResource;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.Silent.class)
public class SurveyRestServiceImplTest {
@InjectMocks
private SurveyRestServiceImpl surveyRestService;
@Mock
private RootAnonymousUserRestTemplateAdaptor rootAnonymousUserRestTemplateAdaptor;
@Test
public void save() {
String baseUrl = "base";
surveyRestService.setServiceUrl(baseUrl);
SurveyResource surveyResource = newSurveyResource().build();
RestResult<Void> expected = mock(RestResult.class);
when(rootAnonymousUserRestTemplateAdaptor.postWithRestResult(baseUrl + "/survey", surveyResource, Void.class)).thenReturn(expected);
RestResult<Void> result = surveyRestService.save(surveyResource);
assertEquals(result, expected);
}
}
|
package org.ovirt.engine.core.bll;
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 org.ovirt.engine.core.bll.command.utils.StorageDomainSpaceChecker;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.bll.validator.StorageDomainValidator;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.DiskImageDynamic;
import org.ovirt.engine.core.common.businessentities.ImageStatus;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.image_storage_domain_map;
import org.ovirt.engine.core.common.businessentities.image_vm_map;
import org.ovirt.engine.core.common.businessentities.image_vm_map_id;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.IrsBaseVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.backendcompat.Path;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
public final class ImagesHandler {
public static final Guid BlankImageTemplateId = new Guid("00000000-0000-0000-0000-000000000000");
public static final String DefaultDriveName = "1";
/**
* Adds a disk image (Adds image, disk and relevant entities)
*
* @param image
* DiskImage to add
* @param active
* true if the image should be added as active
* @param imageStorageDomainMap
* storage domain map entry to map between the image and its storage domain
*/
public static void addDiskImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap) {
try {
addImage(image, active, imageStorageDomainMap);
addDiskToVmIfNotExists(image.getDisk(), image.getvm_guid());
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
/**
* Gets a map of DiskImage IDs to DiskImage objects
*
* @param diskImages
* collection of DiskImage objects to create the map for
* @return map object is the collection is not null
*/
public static Map<Guid, DiskImage> getDiskImagesByIdMap(Collection<DiskImage> diskImages) {
Map<Guid, DiskImage> result = null;
if (diskImages != null) {
result = new HashMap<Guid, DiskImage>();
for (DiskImage diskImage : diskImages) {
result.put(diskImage.getId(), diskImage);
}
}
return result;
}
/**
* Adds a disk image (Adds image, disk, and relevant entities , but not VmDevice) This may be useful for Clone VMs,
* where besides adding images it is required to copy all vm devices (VmDeviceUtils.copyVmDevices) from the source
* VM
*
* @param image
* image to add
* @param active
* true if to add as active image
* @param imageStorageDomainMap
* entry of image storagte domain map
*/
public static void addDiskImageWithNoVmDevice(DiskImage image,
boolean active,
image_storage_domain_map imageStorageDomainMap) {
try {
addImage(image, active, imageStorageDomainMap);
addDisk(image.getDisk());
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
/**
* Adds a disk image (Adds image, disk, and relevant entities , but not VmDevice) This may be useful for Clone VMs,
* where besides adding images it is required to copy all vm devices (VmDeviceUtils.copyVmDevices) from the source
* VM
*
* @param image
* @param active
* @param imageStorageDomainMap
*/
public static void addDiskImageWithNoVmDevice(DiskImage image) {
addDiskImageWithNoVmDevice(image,
image.getactive(),
new image_storage_domain_map(image.getId(), image.getstorage_ids().get(0)));
}
/**
* Adds disk to a VM without creating a VmDevice entry
*
* @param disk
* disk to add
* @param vmId
* ID of the VM the disk will be associated with
*/
public static void addDisk(Disk disk) {
if (!DbFacade.getInstance().getDiskDao().exists(disk.getId())) {
DbFacade.getInstance().getDiskDao().save(disk);
}
}
/**
* Adds a disk image (Adds image with active flag according to the value in image, using the first storage domain in
* the storage id as entry to the storage domain map)
*
* @param image
* DiskImage to add
*/
public static void addDiskImage(DiskImage image) {
addDiskImage(image, image.getactive(), new image_storage_domain_map(image.getId(), image.getstorage_ids()
.get(0)));
}
/**
* Add image and related entities to DB (Adds image, disk image dynamic and image storage domain map)
*
* @param image
* the image to add
* @param active
* if true the image will be active
* @param imageStorageDomainMap
* entry of mapping between the storage domain and the image
*/
public static void addImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap) {
DbFacade.getInstance().getDiskImageDAO().save(image);
DbFacade.getInstance().getImageVmMapDAO().save(
new image_vm_map(active, image.getId(), image.getvm_guid()));
DiskImageDynamic diskDynamic = new DiskImageDynamic();
diskDynamic.setId(image.getId());
diskDynamic.setactual_size(image.getactual_size());
DbFacade.getInstance().getDiskImageDynamicDAO().save(diskDynamic);
if (imageStorageDomainMap != null) {
DbFacade.getInstance()
.getStorageDomainDAO()
.addImageStorageDomainMap(imageStorageDomainMap);
}
}
/**
* Add disk if it does not exist to a given vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the vm to add to if the disk does not exist for this VM
*/
public static void addDiskToVmIfNotExists(Disk disk, Guid vmId) {
if (!DbFacade.getInstance().getDiskDao().exists(disk.getId())) {
addDiskToVm(disk, vmId);
}
}
/**
* Adds disk to vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the VM to add to
*/
public static void addDiskToVm(Disk disk, Guid vmId) {
DbFacade.getInstance().getDiskDao().save(disk);
VmDeviceUtils.addManagedDevice(new VmDeviceId(disk.getId(), vmId),
VmDeviceType.DISK, VmDeviceType.DISK, "", true, false);
}
/**
* This function was developed especially for GUI needs. It returns a list of all the snapshots of current image of
* a specific VM. If there are two images mapped to same VM, it's assumed that this is a TryBackToImage case and the
* function returns a list of snapshots of inactive images. In this case the parent of the active image appears to
* be trybackfrom image
*
* @param imageId
* @param imageTemplateId
* @return
*/
public static ArrayList<DiskImage> getAllImageSnapshots(Guid imageId, Guid imageTemplateId) {
ArrayList<DiskImage> snapshots = new ArrayList<DiskImage>();
Guid curImage = imageId;
while (!imageTemplateId.equals(curImage) && !curImage.equals(Guid.Empty)) {
DiskImage curDiskImage = DbFacade.getInstance().getDiskImageDAO().getSnapshotById(curImage);
snapshots.add(curDiskImage);
curImage = curDiskImage.getParentId();
}
return snapshots;
}
public static String cdPathWindowsToLinux(String windowsPath, Guid storagePoolId) {
if (StringHelper.isNullOrEmpty(windowsPath)) {
return windowsPath; // empty string is used for 'eject'.
}
String fileName = Path.GetFileName(windowsPath);
String isoPrefix = (String) Backend.getInstance().getResourceManager()
.RunVdsCommand(VDSCommandType.IsoPrefix, new IrsBaseVDSCommandParameters(storagePoolId))
.getReturnValue();
return String.format("%1$s/%2$s", isoPrefix, fileName);
}
public static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId, Guid storageDomainId) {
return isImagesExists(images, storagePoolId, storageDomainId, new RefObject<ArrayList<DiskImage>>());
}
private static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId, Guid domainId,
RefObject<ArrayList<DiskImage>> irsImages) {
irsImages.argvalue = new ArrayList<DiskImage>();
boolean returnValue = true;
for (DiskImage image : images) {
Guid storageDomainId = !Guid.Empty.equals(domainId) ? domainId : image.getstorage_ids().get(0);
DiskImage fromIrs = isImageExist(storagePoolId, storageDomainId, image);
if (fromIrs == null) {
returnValue = false;
break;
} else {
irsImages.argvalue.add(fromIrs);
}
}
return returnValue;
}
private static DiskImage isImageExist(Guid storagePoolId,
Guid domainId,
DiskImage image) {
DiskImage fromIrs = null;
try {
Guid storageDomainId =
image.getstorage_ids() != null && !image.getstorage_ids().isEmpty() ? image.getstorage_ids()
.get(0) : domainId;
Guid imageGroupId = image.getimage_group_id() != null ? image.getimage_group_id().getValue()
: Guid.Empty;
fromIrs = (DiskImage) Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(
VDSCommandType.GetImageInfo,
new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId,
image.getId())).getReturnValue();
} catch (Exception e) {
}
return fromIrs;
}
public static boolean isVmInPreview(Guid vmId) {
return DbFacade.getInstance().getSnapshotDao().exists(vmId, SnapshotStatus.IN_PREVIEW);
}
public static boolean CheckImageConfiguration(storage_domain_static storageDomain,
DiskImageBase diskInfo, List<String> messages) {
boolean result = true;
if ((diskInfo.getvolume_type() == VolumeType.Preallocated && diskInfo.getvolume_format() == VolumeFormat.COW)
|| ((storageDomain.getstorage_type() == StorageType.FCP || storageDomain.getstorage_type() == StorageType.ISCSI) && (diskInfo
.getvolume_type() == VolumeType.Sparse && diskInfo.getvolume_format() == VolumeFormat.RAW))
|| (diskInfo.getvolume_format() == VolumeFormat.Unassigned || diskInfo.getvolume_type() == VolumeType.Unassigned)) {
// not supported
result = false;
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED.toString());
}
return result;
}
public static boolean CheckImagesConfiguration(Guid storageDomainId,
Collection<? extends DiskImageBase> disksConfigList,
List<String> messages) {
boolean result = true;
storage_domain_static storageDomain = DbFacade.getInstance().getStorageDomainStaticDAO().get(storageDomainId);
for (DiskImageBase diskInfo : disksConfigList) {
result = CheckImageConfiguration(storageDomain, diskInfo, messages);
if (!result)
break;
}
return result;
}
public static boolean PerformImagesChecks(VM vm,
List<String> messages,
Guid storagePoolId,
Guid storageDomainId,
boolean diskSpaceCheck,
boolean checkImagesLocked,
boolean checkImagesIllegal,
boolean checkImagesExist,
boolean checkVmInPreview,
boolean checkVmIsDown,
boolean checkStorageDomain,
boolean checkIsValid, List<DiskImage> diskImageList) {
boolean returnValue = true;
boolean isValid = checkIsValid
&& ((Boolean) Backend.getInstance().getResourceManager()
.RunVdsCommand(VDSCommandType.IsValid, new IrsBaseVDSCommandParameters(storagePoolId))
.getReturnValue()).booleanValue();
if (checkIsValid && !isValid) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_REPOSITORY_NOT_FOUND.toString());
}
}
if (returnValue && checkImagesLocked) {
if (vm.getstatus() == VMStatus.ImageLocked) {
returnValue = false;
} else if (diskImageList != null) {
for (DiskImage diskImage : diskImageList) {
if (diskImage.getimageStatus() == ImageStatus.LOCKED) {
returnValue = false;
break;
}
}
}
if (!returnValue && messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_LOCKED.toString());
}
} else if (returnValue && checkVmIsDown && vm.getstatus() != VMStatus.Down) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN.toString());
}
} else if (returnValue && isValid) {
List<DiskImage> images;
if (diskImageList == null) {
images = DbFacade.getInstance().getDiskImageDAO().getAllForVm(vm.getId());
} else {
images = diskImageList;
}
if (images.size() > 0) {
returnValue = returnValue &&
checkDiskImages(messages,
storagePoolId,
storageDomainId,
diskSpaceCheck,
checkImagesIllegal,
checkImagesExist,
checkVmInPreview,
checkStorageDomain,
vm,
images);
} else if (checkImagesExist) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_HAS_NO_DISKS.toString());
}
}
}
return returnValue;
}
private static boolean checkDiskImages(List<String> messages,
Guid storagePoolId,
Guid storageDomainId,
boolean diskSpaceCheck,
boolean checkImagesIllegal,
boolean checkImagesExist,
boolean checkVmInPreview,
boolean checkStorageDomain,
VM vm,
List<DiskImage> images) {
boolean returnValue = true;
ArrayList<DiskImage> irsImages = null;
if (checkImagesExist) {
RefObject<ArrayList<DiskImage>> tempRefObject =
new RefObject<ArrayList<DiskImage>>();
boolean isImagesExist = isImagesExists(images, storagePoolId, storageDomainId, tempRefObject);
irsImages = tempRefObject.argvalue;
if (!isImagesExist) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST.toString());
}
}
}
if (returnValue && checkImagesIllegal) {
returnValue = CheckImagesLegality(messages, images, vm, irsImages);
}
if (returnValue && checkVmInPreview && isVmInPreview(vm.getId())) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IN_PREVIEW.toString());
}
}
if (returnValue && (diskSpaceCheck || checkStorageDomain)) {
Set<Guid> domainsIds = new HashSet<Guid>();
if (!Guid.Empty.equals(storageDomainId)) {
domainsIds.add(storageDomainId);
} else {
for (DiskImage image : images) {
domainsIds.add(image.getstorage_ids().get(0));
}
}
for (Guid domainId : domainsIds) {
storage_domains domain = DbFacade.getInstance().getStorageDomainDAO().getForStoragePool(
domainId, storagePoolId);
if (checkStorageDomain) {
StorageDomainValidator storageDomainValidator =
new StorageDomainValidator(domain);
returnValue = storageDomainValidator.isDomainExistAndActive(messages);
}
if (diskSpaceCheck && returnValue && !StorageDomainSpaceChecker.isBelowThresholds(domain)) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW.toString());
}
break;
}
}
}
return returnValue;
}
private static boolean CheckImagesLegality(List<String> messages,
List<DiskImage> images, VM vm, List<DiskImage> irsImages) {
boolean returnValue = true;
if (vm.getstatus() == VMStatus.ImageIllegal) {
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_ILLEGAL.toString());
}
} else {
int i = 0;
for (DiskImage diskImage : images) {
if (diskImage != null) {
DiskImage image = irsImages.get(i++);
if (image.getimageStatus() != ImageStatus.OK) {
diskImage.setimageStatus(image.getimageStatus());
DbFacade.getInstance().getDiskImageDAO().update(diskImage);
returnValue = false;
if (messages != null) {
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_VM_IMAGE_IS_ILLEGAL.toString());
}
break;
}
}
}
}
return returnValue;
}
public static String calculateImageDescription(VM vm) {
String vmName = (vm == null) ? null : vm.getvm_name();
return calculateImageDescription(vmName);
}
public static String calculateImageDescription(String vmName) {
StringBuilder vmLabel = new StringBuilder("ActiveImage");
vmLabel = (vmName == null) ? vmLabel : vmLabel.append("_").append(vmName);
return String.format("_%1$s_%2$s", vmLabel, new java.util.Date());
}
public static void removeDiskImage(DiskImage diskImage) {
try {
removeDiskFromVm(diskImage.getvm_guid(), diskImage.getDisk().getId());
removeImage(diskImage);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
public static void removeImage(DiskImage diskImage) {
DbFacade.getInstance()
.getStorageDomainDAO()
.removeImageStorageDomainMap(new image_storage_domain_map(diskImage.getId(),
diskImage.getstorage_ids().get(0)));
DbFacade.getInstance().getDiskImageDynamicDAO().remove(diskImage.getId());
DbFacade.getInstance()
.getImageVmMapDAO()
.remove(new image_vm_map_id(diskImage.getId(), diskImage.getvm_guid()));
DbFacade.getInstance().getDiskImageDAO().remove(diskImage.getId());
}
public static void removeDiskFromVm(Guid vmGuid, Guid diskId) {
DbFacade.getInstance().getVmDeviceDAO().remove(new VmDeviceId(diskId, vmGuid));
DbFacade.getInstance().getDiskDao().remove(diskId);
}
protected static Log log = LogFactory.getLog(ImagesHandler.class);
}
|
package org.ovirt.engine.core.bll;
import java.io.File;
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 org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.storage.StorageHelperDirector;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.bll.validator.StorageDomainValidator;
import org.ovirt.engine.core.common.businessentities.BaseDisk;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.DiskImageDynamic;
import org.ovirt.engine.core.common.businessentities.DiskLunMapId;
import org.ovirt.engine.core.common.businessentities.ImageStatus;
import org.ovirt.engine.core.common.businessentities.LUNs;
import org.ovirt.engine.core.common.businessentities.LunDisk;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.image_storage_domain_map;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.utils.ListUtils;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.IrsBaseVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
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.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
public final class ImagesHandler {
public static final String DISK = "_Disk";
public static final String DefaultDriveName = "1";
private static final Log log = LogFactory.getLog(ImagesHandler.class);
/**
* The following method will find all images and storages where they located for provide template and will fill an
* diskInfoDestinationMap by imageId mapping on active storage id where image is located. The second map is
* mapping of founded storage ids to storage object
* @param template
* @param diskInfoDestinationMap
* @param destStorages
* @param notCheckSize - if we need to perform a size check for storage or not
*/
public static void fillImagesMapBasedOnTemplate(VmTemplate template,
Map<Guid, DiskImage> diskInfoDestinationMap,
Map<Guid, StorageDomain> destStorages, boolean notCheckSize) {
List<StorageDomain> domains =
DbFacade.getInstance()
.getStorageDomainDao()
.getAllForStoragePool(template.getStoragePoolId().getValue());
fillImagesMapBasedOnTemplate(template, domains, diskInfoDestinationMap, destStorages, notCheckSize);
}
public static void fillImagesMapBasedOnTemplate(VmTemplate template,
List<StorageDomain> domains,
Map<Guid, DiskImage> diskInfoDestinationMap,
Map<Guid, StorageDomain> destStorages, boolean notCheckSize) {
Map<Guid, StorageDomain> storageDomainsMap = new HashMap<Guid, StorageDomain>();
for (StorageDomain storageDomain : domains) {
StorageDomainValidator validator = new StorageDomainValidator(storageDomain);
if (validator.isDomainExistAndActive().isValid() && validator.domainIsValidDestination().isValid()
&& (notCheckSize || isStorageDomainWithinThresholds(storageDomain, null, false))) {
storageDomainsMap.put(storageDomain.getId(), storageDomain);
}
}
for (DiskImage image : template.getDiskMap().values()) {
for (Guid storageId : image.getStorageIds()) {
if (storageDomainsMap.containsKey(storageId)) {
ArrayList<Guid> storageIds = new ArrayList<Guid>();
storageIds.add(storageId);
image.setStorageIds(storageIds);
diskInfoDestinationMap.put(image.getId(), image);
break;
}
}
}
if (destStorages != null) {
for (DiskImage diskImage : diskInfoDestinationMap.values()) {
Guid storageDomainId = diskImage.getStorageIds().get(0);
destStorages.put(storageDomainId, storageDomainsMap.get(storageDomainId));
}
}
}
public static boolean setDiskAlias(BaseDisk disk, VM vm) {
return setDiskAlias(disk, vm, nullSafeGetCount(vm));
}
public static boolean setDiskAlias(BaseDisk disk, VM vm, int count) {
if (disk == null) {
log.error("Disk object is null");
return false;
}
String vmName = nullSafeGetVmName(vm);
disk.setDiskAlias(getSuggestedDiskAlias(disk, vmName, count));
return true;
}
private static String nullSafeGetVmName(VM vm) {
return vm == null ? "" : vm.getName();
}
private static int nullSafeGetCount(VM vm) {
return vm == null ? 1 : vm.getDiskMapCount() + 1;
}
/**
* Suggests an alias for a disk.
* If the disk does not already have an alias, one will be generated for it.
* The generated alias will be formed as prefix_DiskXXX, where XXX is an ordinal.
*
* @param disk
* - The disk that (possibly) requires a new alias
* @param diskPrefix
* - The prefix for the newly generated alias
* @param count
* - The ordinal of disk to create an alias for (first, second, etc.).
* @return The suggested alias
*/
public static String getSuggestedDiskAlias(BaseDisk disk, String diskPrefix, int count) {
String diskAlias;
if (disk == null) {
diskAlias = getDefaultDiskAlias(diskPrefix, DefaultDriveName);
log.warnFormat("Disk object is null, the suggested default disk alias to be used is {0}",
diskAlias);
} else {
String defaultAlias = getDefaultDiskAlias(diskPrefix, String.valueOf(count));
diskAlias = getDiskAliasWithDefault(disk, defaultAlias);
}
return diskAlias;
}
/**
* Returns an alias for the given disk. If the disk already has an alias, it is returned. If not,
* {@link #aliasIfNull} is returned.
*
* @param disk
* The disk
* @param aliasIfNull
* The alias to return if the disk does not have an alias
* @return The alias in question
*/
public static String getDiskAliasWithDefault(BaseDisk disk, String aliasIfNull) {
String diskAlias = disk.getDiskAlias();
if (StringUtils.isEmpty(diskAlias)) {
log.infoFormat("Disk alias retrieved from the client is null or empty, the suggested default disk alias to be used is {0}",
aliasIfNull);
return aliasIfNull;
}
return diskAlias;
}
public static String getDefaultDiskAlias(String prefix, String suffix) {
return prefix + DISK + suffix;
}
public static Map<Guid, List<DiskImage>> buildStorageToDiskMap(Collection<DiskImage> images,
Map<Guid, DiskImage> diskInfoDestinationMap) {
Map<Guid, List<DiskImage>> storageToDisksMap = new HashMap<Guid, List<DiskImage>>();
for (DiskImage disk : images) {
DiskImage diskImage = diskInfoDestinationMap.get(disk.getId());
Guid storageDomainId = diskImage.getStorageIds().get(0);
List<DiskImage> diskList = storageToDisksMap.get(storageDomainId);
if (diskList == null) {
diskList = new ArrayList<DiskImage>();
storageToDisksMap.put(storageDomainId, diskList);
}
diskList.add(disk);
}
return storageToDisksMap;
}
/**
* Adds a disk image (Adds image, disk and relevant entities)
*
* @param image
* DiskImage to add
* @param active
* true if the image should be added as active
* @param imageStorageDomainMap
* storage domain map entry to map between the image and its storage domain
*/
public static void addDiskImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap, Guid vmId) {
try {
addImage(image, active, imageStorageDomainMap);
addDiskToVmIfNotExists(image, vmId);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
/**
* Gets a map of DiskImage IDs to DiskImage objects
*
* @param diskImages
* collection of DiskImage objects to create the map for
* @return map object is the collection is not null
*/
public static Map<Guid, DiskImage> getDiskImagesByIdMap(Collection<DiskImage> diskImages) {
Map<Guid, DiskImage> result = null;
if (diskImages != null) {
result = new HashMap<Guid, DiskImage>();
for (DiskImage diskImage : diskImages) {
result.put(diskImage.getImageId(), diskImage);
}
}
return result;
}
/**
* Adds a disk image (Adds image, disk, and relevant entities , but not VmDevice) This may be useful for Clone VMs,
* where besides adding images it is required to copy all vm devices (VmDeviceUtils.copyVmDevices) from the source
* VM
*
* @param image
* image to add
* @param active
* true if to add as active image
* @param imageStorageDomainMap
* entry of image storagte domain map
*/
public static void addDiskImageWithNoVmDevice(DiskImage image,
boolean active,
image_storage_domain_map imageStorageDomainMap) {
try {
addImage(image, active, imageStorageDomainMap);
addDisk(image);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
/**
* Adds a disk image (Adds image, disk, and relevant entities , but not VmDevice) This may be useful for Clone VMs,
* where besides adding images it is required to copy all vm devices (VmDeviceUtils.copyVmDevices) from the source
* VM
*
* @param image
*/
public static void addDiskImageWithNoVmDevice(DiskImage image) {
addDiskImageWithNoVmDevice(image,
image.getActive(),
new image_storage_domain_map(image.getImageId(), image.getStorageIds().get(0)));
}
/**
* Adds disk to a VM without creating a VmDevice entry
*
* @param disk
* disk to add
*/
public static void addDisk(BaseDisk disk) {
if (!DbFacade.getInstance().getBaseDiskDao().exists(disk.getId())) {
DbFacade.getInstance().getBaseDiskDao().save(disk);
}
}
/**
* Adds a disk image (Adds image with active flag according to the value in image, using the first storage domain in
* the storage id as entry to the storage domain map)
*
* @param image
* DiskImage to add
*/
public static void addDiskImage(DiskImage image, Guid vmId) {
addDiskImage(image, image.getActive(), new image_storage_domain_map(image.getImageId(), image.getStorageIds()
.get(0)), vmId);
}
/**
* Add image and related entities to DB (Adds image, disk image dynamic and image storage domain map)
*
* @param image
* the image to add
* @param active
* if true the image will be active
* @param imageStorageDomainMap
* entry of mapping between the storage domain and the image
*/
public static void addImage(DiskImage image, boolean active, image_storage_domain_map imageStorageDomainMap) {
image.setActive(active);
DbFacade.getInstance().getImageDao().save(image.getImage());
DiskImageDynamic diskDynamic = new DiskImageDynamic();
diskDynamic.setId(image.getImageId());
diskDynamic.setactual_size(image.getActualSizeFromDiskImage());
DbFacade.getInstance().getDiskImageDynamicDao().save(diskDynamic);
if (imageStorageDomainMap != null) {
DbFacade.getInstance().getImageStorageDomainMapDao().save(imageStorageDomainMap);
}
}
/**
* Add disk if it does not exist to a given vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the vm to add to if the disk does not exist for this VM
*/
public static void addDiskToVmIfNotExists(BaseDisk disk, Guid vmId) {
if (!DbFacade.getInstance().getBaseDiskDao().exists(disk.getId())) {
addDiskToVm(disk, vmId);
}
}
/**
* Adds disk to vm
*
* @param disk
* the disk to add
* @param vmId
* the ID of the VM to add to
*/
public static void addDiskToVm(BaseDisk disk, Guid vmId) {
DbFacade.getInstance().getBaseDiskDao().save(disk);
VmDeviceUtils.addManagedDevice(new VmDeviceId(disk.getId(), vmId),
VmDeviceType.DISK,
VmDeviceType.DISK,
null,
true,
false);
}
/**
* This function was developed especially for GUI needs. It returns a list of all the snapshots of current image of
* a specific VM. If there are two images mapped to same VM, it's assumed that this is a TryBackToImage case and the
* function returns a list of snapshots of inactive images. In this case the parent of the active image appears to
* be trybackfrom image
*
* @param imageId
* @param imageTemplateId
* @return
*/
public static ArrayList<DiskImage> getAllImageSnapshots(Guid imageId, Guid imageTemplateId) {
ArrayList<DiskImage> snapshots = new ArrayList<DiskImage>();
Guid curImage = imageId;
while (!imageTemplateId.equals(curImage) && !curImage.equals(Guid.Empty)) {
DiskImage curDiskImage = DbFacade.getInstance().getDiskImageDao().getSnapshotById(curImage);
snapshots.add(curDiskImage);
curImage = curDiskImage.getParentId();
}
return snapshots;
}
public static String cdPathWindowsToLinux(String windowsPath, Guid storagePoolId) {
return cdPathWindowsToLinux(windowsPath, (String) Backend.getInstance()
.getResourceManager()
.RunVdsCommand(VDSCommandType.IsoPrefix, new IrsBaseVDSCommandParameters(storagePoolId))
.getReturnValue());
}
public static String cdPathWindowsToLinux(String windowsPath, String isoPrefix) {
if (StringUtils.isEmpty(windowsPath)) {
return windowsPath; // empty string is used for 'eject'.
}
String fileName = new File(windowsPath).getName();
return String.format("%1$s/%2$s", isoPrefix, fileName);
}
public static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId) {
return isImagesExists(images, storagePoolId, new ArrayList<DiskImage>());
}
private static boolean isImagesExists(Iterable<DiskImage> images, Guid storagePoolId, ArrayList<DiskImage> irsImages) {
boolean returnValue = true;
for (DiskImage image : images) {
DiskImage fromIrs = isImageExist(storagePoolId, image);
if (fromIrs == null) {
returnValue = false;
break;
}
irsImages.add(fromIrs);
}
return returnValue;
}
private static DiskImage isImageExist(Guid storagePoolId, DiskImage image) {
DiskImage fromIrs = null;
try {
Guid storageDomainId = image.getStorageIds().get(0);
Guid imageGroupId = image.getId() != null ? image.getId() : Guid.Empty;
fromIrs = (DiskImage) Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(
VDSCommandType.GetImageInfo,
new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId,
image.getImageId())).getReturnValue();
} catch (Exception e) {
log.debug("Unable to get image info from from storage.", e);
}
return fromIrs;
}
public static boolean CheckImageConfiguration(StorageDomainStatic storageDomain,
DiskImageBase diskInfo, List<String> messages) {
boolean result = true;
if ((diskInfo.getVolumeType() == VolumeType.Preallocated && diskInfo.getVolumeFormat() == VolumeFormat.COW)
|| (storageDomain.getStorageType().isBlockDomain() && diskInfo.getVolumeType() == VolumeType.Sparse && diskInfo.getVolumeFormat() == VolumeFormat.RAW)
|| diskInfo.getVolumeFormat() == VolumeFormat.Unassigned
|| diskInfo.getVolumeType() == VolumeType.Unassigned) {
// not supported
result = false;
messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED.toString());
}
return result;
}
public static boolean CheckImagesConfiguration(Guid storageDomainId,
Collection<? extends Disk> disksConfigList,
List<String> messages) {
boolean result = true;
StorageDomainStatic storageDomain = DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId);
for (Disk diskInfo : disksConfigList) {
if (DiskStorageType.IMAGE == diskInfo.getDiskStorageType()) {
result = CheckImageConfiguration(storageDomain, (DiskImage) diskInfo, messages);
}
if (!result)
break;
}
return result;
}
public static List<DiskImage> getPluggedImagesForVm(Guid vmId) {
return filterImageDisks(DbFacade.getInstance().getDiskDao().getAllForVm(vmId, true), true, false);
}
/**
* @return A unique {@link Set} of all the storage domain IDs relevant to all the given images
* @param images The images to get the storage domain IDs for
*/
public static Set<Guid> getAllStorageIdsForImageIds(Collection<DiskImage> images) {
Set<Guid> domainsIds = new HashSet<Guid>();
for (DiskImage image : images) {
domainsIds.addAll(image.getStorageIds());
}
return domainsIds;
}
/**
* Returns whether the storage domain is within the threshold
*
* @param storageDomain
* - The storage domain to be checked.
* @param messages
* - Add a message to the messages list.
* @param addCanDoMessage
* - Indicate whether to add a CDA message for failure
* @return <code>boolean</code> value which indicates if the storage domain has enough free space.
*/
private static boolean isStorageDomainWithinThresholds(StorageDomain storageDomain,
List<String> messages,
boolean addCanDoMessage) {
ValidationResult validationResult = new StorageDomainValidator(storageDomain).isDomainWithinThresholds();
if (addCanDoMessage) {
validate(validationResult, messages);
}
return validationResult.isValid();
}
private static boolean validate(ValidationResult validationResult, List<String> messages) {
if (!validationResult.isValid()) {
ListUtils.nullSafeAdd(messages, validationResult.getMessage().name());
if (validationResult.getVariableReplacements() != null) {
for (String variableReplacement : validationResult.getVariableReplacements()) {
messages.add(variableReplacement);
}
}
}
return validationResult.isValid();
}
public static void fillImagesBySnapshots(VM vm) {
for (Disk disk : vm.getDiskMap().values()) {
if (disk.getDiskStorageType() == DiskStorageType.IMAGE) {
DiskImage diskImage = (DiskImage) disk;
diskImage.getSnapshots().addAll(
ImagesHandler.getAllImageSnapshots(diskImage.getImageId(),
diskImage.getImageTemplateId()));
}
}
}
/**
* Filter image disks by attributes.
*
* @param listOfDisks
* - The list of disks to be filtered.
* @param allowOnlyNotShareableDisks
* - Indication whether to allow only disks that are not shareable
* @param allowOnlySnapableDisks
* - Indication whether to allow only disks which are allowed to be snapshoted.
* @return - List filtered of disk images.
*/
public static List<DiskImage> filterImageDisks(Collection<? extends Disk> listOfDisks,
boolean allowOnlyNotShareableDisks,
boolean allowOnlySnapableDisks) {
List<DiskImage> diskImages = new ArrayList<DiskImage>();
for (Disk disk : listOfDisks) {
if (disk.getDiskStorageType() == DiskStorageType.IMAGE &&
(!allowOnlyNotShareableDisks || !disk.isShareable()) &&
(!allowOnlySnapableDisks || disk.isAllowSnapshot())) {
diskImages.add((DiskImage) disk);
}
}
return diskImages;
}
public static List<LunDisk> filterDiskBasedOnLuns(Collection<Disk> listOfDisks) {
List<LunDisk> lunDisks = new ArrayList<LunDisk>();
for (Disk disk : listOfDisks) {
if (disk.getDiskStorageType() == DiskStorageType.LUN) {
lunDisks.add((LunDisk) disk);
}
}
return lunDisks;
}
public static void removeDiskImage(DiskImage diskImage, Guid vmId) {
try {
removeDiskFromVm(vmId, diskImage.getId());
removeImage(diskImage);
} catch (RuntimeException ex) {
log.error("Failed adding new disk image and related entities to db", ex);
throw new VdcBLLException(VdcBllErrors.DB, ex);
}
}
public static void removeLunDisk(LunDisk lunDisk) {
DbFacade.getInstance()
.getVmDeviceDao()
.remove(new VmDeviceId(lunDisk.getId(),
null));
LUNs lun = lunDisk.getLun();
DbFacade.getInstance()
.getDiskLunMapDao()
.remove(new DiskLunMapId(lunDisk.getId(), lun.getLUN_id()));
DbFacade.getInstance().getBaseDiskDao().remove(lunDisk.getId());
lun.setLunConnections(new ArrayList<StorageServerConnections>(DbFacade.getInstance()
.getStorageServerConnectionDao()
.getAllForLun(lun.getLUN_id())));
if (!lun.getLunConnections().isEmpty()) {
StorageHelperDirector.getInstance().getItem(
lun.getLunConnections().get(0).getstorage_type()).removeLun(lun);
} else {
// if there are no connections then the lun is fcp.
StorageHelperDirector.getInstance().getItem(StorageType.FCP).removeLun(lun);
}
}
public static void removeImage(DiskImage diskImage) {
DbFacade.getInstance()
.getImageStorageDomainMapDao()
.remove(diskImage.getImageId());
DbFacade.getInstance().getDiskImageDynamicDao().remove(diskImage.getImageId());
DbFacade.getInstance().getImageDao().remove(diskImage.getImageId());
}
public static void removeDiskFromVm(Guid vmGuid, Guid diskId) {
DbFacade.getInstance().getVmDeviceDao().remove(new VmDeviceId(diskId, vmGuid));
DbFacade.getInstance().getBaseDiskDao().remove(diskId);
}
public static void updateImageStatus(Guid imageId, ImageStatus imageStatus) {
DbFacade.getInstance().getImageDao().updateStatus(imageId, imageStatus);
}
}
|
package com.yunxian.recycleview.multiexpandable;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import com.yunxian.recycleview.multiexpandable.model.IExpandableItemModel;
import com.yunxian.recycleview.multiexpandable.provider.IMultiExpandableItemViewProvider;
import com.yunxian.recycleview.multiexpandable.utils.SimpleUtils;
import com.yunxian.recycleview.multiexpandable.viewholder.AbsMultiExpandableItemViewHolder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* RecycleView
*
* @author A Shuai
* @email ls1110924@gmail.com
* @date 17/5/19 3:41
*/
public class MultiExpandableRecycleViewAdapter extends RecyclerView.Adapter<AbsMultiExpandableItemViewHolder> implements AbsMultiExpandableItemViewHolder.OnBtnClickListener {
private static final String TAG = MultiExpandableRecycleViewAdapter.class.getSimpleName();
private final Context mContext;
private final RecyclerView mRecyclerView;
private final List<IExpandableItemModel> mTotalDataSet = new ArrayList<>();
private final List<IExpandableItemModel> mVisibleDataSet = new ArrayList<>();
private final List<String> mItemViewTypeIdMap = new ArrayList<>();
private final Map<String, IMultiExpandableItemViewProvider> mViewHolderProviders = new HashMap<>();
private final Map<String, Class<? extends IMultiExpandableItemViewProvider>> mViewHolderProviderClasses = new HashMap<>();
private final List<OnExpandableItemClickListener> mItemClickListener = new ArrayList<>();
public MultiExpandableRecycleViewAdapter(@NonNull Context context, @NonNull RecyclerView recyclerView) {
mContext = context;
mRecyclerView = recyclerView;
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
mRecyclerView.setAdapter(this);
}
public final void setData(@NonNull List<IExpandableItemModel> dataSet) {
mTotalDataSet.addAll(dataSet);
SimpleUtils.teaseExpandableTree(mTotalDataSet);
rebuildVisibleDataSet();
notifyDataSetChanged();
}
private void rebuildVisibleDataSet() {
mVisibleDataSet.addAll(SimpleUtils.buildVisibleExpandableNodeList(mTotalDataSet));
}
@Override
public AbsMultiExpandableItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
String itemViewType = mItemViewTypeIdMap.get(viewType);
if (TextUtils.isEmpty(itemViewType)) {
throw new IllegalStateException("Plz register itemView provider first!");
}
IMultiExpandableItemViewProvider viewProvider = getItemViewProvider(itemViewType);
AbsMultiExpandableItemViewHolder viewHolder = viewProvider.createViewHolder(mContext, parent);
viewHolder.addOnBtnClickListener(this);
return viewHolder;
}
@Override
public void onBindViewHolder(AbsMultiExpandableItemViewHolder holder, int position) {
holder.bindDataInternal(position, mVisibleDataSet.get(position));
}
@Override
public int getItemViewType(int position) {
String itemViewTypeStr = mVisibleDataSet.get(position).getItemViewType();
int index = mItemViewTypeIdMap.indexOf(itemViewTypeStr);
if (index >= 0) {
return index;
} else {
mItemViewTypeIdMap.add(itemViewTypeStr);
return mItemViewTypeIdMap.size() - 1;
}
}
@Override
public int getItemCount() {
return mVisibleDataSet.size();
}
/**
* ItemViewViewHolder
*
* @param itemViewType ItemView
* @param itemViewProviderClz ViewHolder
*/
public final void registerItemViewProvider(@NonNull String itemViewType, @NonNull Class<? extends IMultiExpandableItemViewProvider> itemViewProviderClz) {
if (mViewHolderProviderClasses.containsKey(itemViewType)) {
Class<? extends IMultiExpandableItemViewProvider> oldClz = mViewHolderProviderClasses.get(itemViewType);
if (oldClz == null) {
mViewHolderProviderClasses.put(itemViewType, itemViewProviderClz);
} else if (oldClz != itemViewProviderClz) {
throw new IllegalStateException("the same itemViewType has been register, the registered clz is " + oldClz.getSimpleName() + " and the new clz is " + itemViewProviderClz.getSimpleName());
}
} else {
mViewHolderProviderClasses.put(itemViewType, itemViewProviderClz);
}
}
/**
* ItemViewViewHolder
*
* @param itemViewType ItemView
*/
public final void unregisterItemViewProvider(@NonNull String itemViewType) {
mViewHolderProviderClasses.remove(itemViewType);
}
/**
* ItemViewViewProvider
*
* @param itemViewType ItemView
* @return ViewProvider
*/
@NonNull
private IMultiExpandableItemViewProvider getItemViewProvider(@NonNull String itemViewType) {
IMultiExpandableItemViewProvider itemViewProvider = mViewHolderProviders.get(itemViewType);
if (itemViewProvider == null) {
Class<? extends IMultiExpandableItemViewProvider> itemViewProviderClz = mViewHolderProviderClasses.get(itemViewType);
if (itemViewProviderClz == null) {
throw new IllegalStateException("plz register the corresponding item view provider of item view type " + itemViewType);
}
try {
itemViewProvider = itemViewProviderClz.newInstance();
} catch (Exception e) {
Log.d(TAG, "instantiation the provider fail, the provider class is " + itemViewProviderClz.getSimpleName(), e);
throw new IllegalStateException("instantiation the provider fail, the provider class is " + itemViewProviderClz.getSimpleName(), e);
}
mViewHolderProviders.put(itemViewType, itemViewProvider);
}
return itemViewProvider;
}
@Override
public boolean onExpandedBtnClick(@NonNull IExpandableItemModel dataModel) {
if (dataModel.isGroup()) {
if (dataModel.isExpanded()) {
dataModel.setExpanded(false);
List<IExpandableItemModel> childrenDataModel = new ArrayList<>();
for (int i = dataModel.getRecycleViewChildrenIndex() + 1, size = mVisibleDataSet.size(); i < size; i++) {
IExpandableItemModel childDataModel = mVisibleDataSet.get(i);
if (dataModel.getCoordinateInExpandableTree().isChild(childDataModel.getCoordinateInExpandableTree())) {
childDataModel.setRecycleViewChildrenIndex(-1);
childrenDataModel.add(childDataModel);
} else {
break;
}
}
mVisibleDataSet.removeAll(childrenDataModel);
SimpleUtils.teaseIndexOfVisibleNodeList(mVisibleDataSet);
notifyItemChanged(dataModel.getRecycleViewChildrenIndex());
notifyItemRangeRemoved(dataModel.getRecycleViewChildrenIndex() + 1, childrenDataModel.size());
} else {
dataModel.setExpanded(true);
List<? extends IExpandableItemModel> childrenDataModel = dataModel.getChildren();
if (childrenDataModel != null && childrenDataModel.size() > 0) {
mVisibleDataSet.addAll(dataModel.getRecycleViewChildrenIndex() + 1, childrenDataModel);
SimpleUtils.teaseIndexOfVisibleNodeList(mVisibleDataSet);
notifyItemChanged(dataModel.getRecycleViewChildrenIndex());
notifyItemRangeInserted(dataModel.getRecycleViewChildrenIndex() + 1, childrenDataModel.size());
} else {
Log.d(TAG, "the leaf dataModel has clicked by expanded btn");
}
}
} else {
Log.d(TAG, "the leaf dataModel has clicked by expanded btn");
}
return true;
}
@Override
public boolean onSelectedBtnClick(@NonNull IExpandableItemModel dataModel) {
for (OnExpandableItemClickListener listener : mItemClickListener) {
listener.onExpandableItemSelected(dataModel, dataModel.getCoordinateInExpandableTree().getCoordinates());
}
return true;
}
/**
*
*
* @param listener
*/
public final void addOnExpandableItemClickListener(OnExpandableItemClickListener listener) {
if (listener != null && !mItemClickListener.contains(listener)) {
mItemClickListener.add(listener);
}
}
/**
*
*
* @param listener
*/
public final void removeOnExpandableItemClickListener(OnExpandableItemClickListener listener) {
if (listener != null && mItemClickListener.contains(listener)) {
mItemClickListener.remove(listener);
}
}
/**
* RecyclerView
*/
public interface OnExpandableItemClickListener {
/**
*
*
* @param dataModel
* @param coordinate
*/
void onExpandableItemSelected(@NonNull IExpandableItemModel dataModel, @NonNull List<Integer> coordinate);
}
}
|
package org.ovirt.engine.core.bll;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.ovirt.engine.core.utils.MockConfigRule.mockConfig;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.ovirt.engine.core.bll.memory.MemoryUtils;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.ImageStatus;
import org.ovirt.engine.core.common.businessentities.LunDisk;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.utils.SizeConverter;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.MockConfigRule;
import org.ovirt.engine.core.utils.RandomUtils;
/** A test case for the {@link VmHandler} class. */
public class VmHandlerTest {
public static final long META_DATA_SIZE_IN_GB = 1;
public static final Integer LOW_SPACE_IN_GB = 3;
public static final Integer ENOUGH_SPACE_IN_GB = 4;
public static final Integer THRESHOLD_IN_GB = 4;
public static final Integer THRESHOLD_HIGH_GB = 10;
public static final int VM_SPACE_IN_MB = 2000;
@Rule
public MockConfigRule mcr = new MockConfigRule(
mockConfig(ConfigValues.FreeSpaceCriticalLowInGB, THRESHOLD_IN_GB));
@Before
public void setUp() {
VmHandler.init();
}
@Test
public void testUpdateFieldsNameInStatusUp() {
VmStatic src = new VmStatic();
src.setName(RandomUtils.instance().nextString(10));
src.setInterfaces(new ArrayList<VmNetworkInterface>(2));
VmStatic dest = new VmStatic();
dest.setName(RandomUtils.instance().nextString(10));
assertTrue("Update should be valid for different names",
VmHandler.isUpdateValid(src, dest));
}
@Test
public void filterDisksForVmDiskSnapshots() {
DiskImage snapshotDisk1 = createDiskImage(false);
DiskImage snapshotDisk2 = createDiskImage(false);
VM vm = new VM();
vm.setId(Guid.newGuid());
List<Disk> disks = new LinkedList<>();
disks.add(snapshotDisk1);
disks.add(snapshotDisk2);
populateVmWithDisks(disks, vm);
VmHandler.filterImageDisksForVM(vm, false, false, true);
assertTrue(vm.getDiskList().isEmpty());
assertTrue(vm.getManagedVmDeviceMap().isEmpty());
}
@Test
public void filterDisksForVmMixedDiskTypes() {
DiskImage snapshotDisk = createDiskImage(false);
DiskImage regularDisk = createDiskImage(true);
LunDisk lunDisk = createLunDisk();
VM vm = new VM();
vm.setId(Guid.newGuid());
populateVmWithDisks(Arrays.asList(snapshotDisk, regularDisk, lunDisk), vm);
VmHandler.filterImageDisksForVM(vm, false, false, true);
assertFalse(vm.getDiskList().contains(snapshotDisk));
assertTrue(vm.getDiskList().contains(regularDisk));
assertTrue(vm.getManagedVmDeviceMap().containsKey(regularDisk.getId()));
assertFalse(vm.getManagedVmDeviceMap().containsKey(lunDisk.getId()));
assertFalse(vm.getManagedVmDeviceMap().containsKey(snapshotDisk.getId()));
}
@Test
public void verifyDomainForMemory() {
Guid sdId = Guid.newGuid();
List<StorageDomain> storageDomains = createStorageDomains(sdId);
long vmSpaceInBytes = SizeConverter.convert(VM_SPACE_IN_MB, SizeConverter.SizeUnit.MB, SizeConverter.SizeUnit.BYTES).intValue();
List<DiskImage> disksList = MemoryUtils.createDiskDummies(vmSpaceInBytes, META_DATA_SIZE_IN_GB);
StorageDomain storageDomain = VmHandler.findStorageDomainForMemory(storageDomains, disksList);
assertThat(storageDomain, notNullValue());
if (storageDomain != null) {
Guid selectedId = storageDomain.getId();
assertThat(selectedId.equals(sdId), is(true));
}
mcr.mockConfigValue(ConfigValues.FreeSpaceCriticalLowInGB, THRESHOLD_HIGH_GB);
storageDomain = VmHandler.findStorageDomainForMemory(storageDomains, disksList);
assertThat(storageDomain, nullValue());
}
private static List<StorageDomain> createStorageDomains(Guid sdIdToBeSelected) {
StorageDomain sd1 = createStorageDomain(Guid.newGuid(), StorageType.NFS, LOW_SPACE_IN_GB);
StorageDomain sd2 = createStorageDomain(Guid.newGuid(), StorageType.NFS, LOW_SPACE_IN_GB);
StorageDomain sd3 = createStorageDomain(sdIdToBeSelected, StorageType.NFS, ENOUGH_SPACE_IN_GB);
List<StorageDomain> storageDomains = Arrays.asList(sd1, sd2, sd3);
return storageDomains;
}
private static StorageDomain createStorageDomain(Guid guid, StorageType storageType, Integer size) {
StorageDomain storageDomain = new StorageDomain();
storageDomain.setId(guid);
storageDomain.setStorageDomainType(StorageDomainType.Data);
storageDomain.setStorageType(storageType);
storageDomain.setStatus(StorageDomainStatus.Active);
storageDomain.setAvailableDiskSize(size);
return storageDomain;
}
private void populateVmWithDisks(List<Disk> disks, VM vm) {
VmHandler.updateDisksForVm(vm, disks);
for (Disk disk : disks) {
VmDevice device = new VmDevice(new VmDeviceId(disk.getId(), vm.getId()),
VmDeviceGeneralType.DISK,
VmDeviceType.DISK.getName(),
"",
0,
null,
true,
true,
false,
"",
null,
disk.getDiskStorageType() == Disk.DiskStorageType.IMAGE ? ((DiskImage)disk).getSnapshotId() : null);
vm.getManagedVmDeviceMap().put(disk.getId(), device);
}
}
private LunDisk createLunDisk() {
LunDisk lunDisk = new LunDisk();
lunDisk.setId(Guid.newGuid());
return lunDisk;
}
private static DiskImage createDiskImage(boolean active) {
DiskImage di = new DiskImage();
di.setActive(active);
di.setId(Guid.newGuid());
di.setImageId(Guid.newGuid());
di.setParentId(Guid.newGuid());
di.setImageStatus(ImageStatus.OK);
return di;
}
}
|
package org.nuxeo.opensocial.container.client.view;
import org.nuxeo.opensocial.container.client.GadgetService;
import org.nuxeo.opensocial.container.client.JsLibrary;
import org.nuxeo.opensocial.container.client.bean.GadgetBean;
import org.nuxeo.opensocial.container.client.bean.GadgetView;
import org.nuxeo.opensocial.container.client.bean.PreferencesBean;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Frame;
import com.gwtext.client.widgets.layout.FitLayout;
import com.gwtext.client.widgets.portal.Portlet;
/**
* @author Guillaume Cusnieux
*/
public class GadgetPortlet extends Portlet {
private static final String NONE_PROPERTY = "none";
private static final String PREFIX_PORTLET_ID = "portlet-";
static final String PREFIX_FRAME_ID = "gadget-";
public static final String CANVAS_VIEW = "canvas";
public static final String DEFAULT_VIEW = "default";
private GadgetBean gadget;
private GadgetTools tools;
private Frame frame;
private GadgetForm form;
private String view;
public GadgetPortlet(GadgetBean gadget, String view) {
super();
this.gadget = gadget;
this.view = view;
buildPortlet();
this.form = new GadgetForm(this);
this.tools.setGadgetForm(form);
this.setVisible(false);
}
public GadgetPortlet(GadgetBean bean) {
this(bean, DEFAULT_VIEW);
}
private void buildPortlet() {
this.setLayout(new FitLayout());
this.setTitle(this.gadget.getTitle());
if (!this.view.equals(DEFAULT_VIEW)) {
this.setDraggable(false);
this.setHideCollapseTool(true);
} else {
this.setDraggable(gadget.hasPermission("Everything"));
if (!(gadget.hasPermission("Everything") || gadget.hasPermission("SpaceContributeur")))
this.setHideCollapseTool(true);
}
this.setHeight(this.gadget.getHeight());
this.addListener(new PortletListener(this));
this.frame = buildFrame();
this.add(frame);
this.setId(getIdWithRefAndView(gadget.getRef(), view));
this.tools = new GadgetTools(this);
this.setTools(tools.getButtons());
GadgetService.setAuthToken(getIframeId(), this.gadget.getRef());
GadgetService.setRelayRpc(getIframeId(), this.gadget.getRef());
}
static enum DEFAULT_PREFS {
COLOR_header, COLOR_font, COLOR_border;
public static boolean isHeader(String name) {
return COLOR_header.name()
.equals(name);
}
public static boolean isFont(String name) {
return COLOR_font.name()
.equals(name);
}
public static boolean isBorder(String name) {
return COLOR_border.name()
.equals(name);
}
}
void renderDefaultPreferences() {
for (PreferencesBean p : this.gadget.getDefaultPrefs()) {
renderPreference(p.getName(), (p.getValue() != null) ? p.getValue()
: p.getDefaultValue());
}
}
public void renderPreference(String name, String value) {
if (DEFAULT_PREFS.isBorder(name)) {
if (!NONE_PROPERTY.equals(value))
changeBorderColor(this.getId(), value);
else
removeBorderColor(this.getId());
} else if (DEFAULT_PREFS.isFont(name)) {
if (!NONE_PROPERTY.equals(value))
changeTitleColor(this.getId(), value);
else
removeTitleColor(this.getId());
} else if (DEFAULT_PREFS.isHeader(name)) {
if (NONE_PROPERTY.equals(value))
removeHeaderColor(this.getId());
else
changeHeaderColor(this.getId(), value);
}
}
static String getIdWithRefAndView(String ref, String view) {
if (view == null)
view = DEFAULT_VIEW;
return PREFIX_PORTLET_ID + view + "-" + ref;
}
static String getIdWithIframeId(String iframeId) {
return iframeId.replace(PREFIX_FRAME_ID, PREFIX_PORTLET_ID);
}
private Frame buildFrame() {
reloadRenderUrl();
Frame f = new Frame(this.gadget.getRenderUrl());
f.setHeight("100%");
f.setWidth("100%");
Element elem = f.getElement();
elem.setId(getIframeId());
elem.setAttribute("name", getIframeId());
elem.setAttribute("overflow", "hidden");
return f;
}
@Override
public void setTitle(String title) {
if (title != null) {
super.setTitle(title);
this.gadget.setTitle(title);
if (this.form != null)
this.form.setTitle(title);
if (this.tools != null)
this.tools.setTitle(title);
}
}
public void setPortletTitle(String title) {
if (title != null) {
super.setTitle(title);
if (this.form != null)
this.form.setTitle(title);
}
}
public void reloadRenderUrl() {
String url = gadget.getRenderUrl();
if (url == null) {
return;
}
gadget.setRenderUrl(buildUrl(url, view));
}
private static native String buildUrl(String url, String view)
/*-{
var reg = new RegExp("view=[a-zA-Z]*&?");
return url.replace(reg,"view="+view+"&");
}-*/;
String getIframeId() {
return PREFIX_FRAME_ID + view + "-" + this.gadget.getRef();
}
public void doLayoutFrame() {
JsLibrary.updateIframe(getIframeId(), this.gadget.getRenderUrl());
}
public void updateGadgetPortlet() {
reloadRenderUrl();
this.setGadgetBean(gadget);
this.frame = buildFrame();
}
void setGadgetBean(GadgetBean bean) {
this.gadget = bean;
this.form.setGadget(bean);
}
public GadgetBean getGadgetBean() {
return gadget;
}
@Override
protected void afterRender() {
if (this.gadget.isCollapsed())
collapse(getIdWithRefAndView(gadget.getRef(), view),
"x-tmp-collapsed");
super.afterRender();
updateFrameHeightIfContentTypeIsUrl();
Timer t = new Timer() {
@Override
public void run() {
renderDefaultPreferences();
}
};
t.schedule(200);
}
private void updateFrameHeightIfContentTypeIsUrl() {
GadgetView v = this.gadget.getView(view);
if (v != null && "URL".equals(v.getContentType()
.toUpperCase())) {
this.setHeight(1000);
}
}
static native void collapse(String id, String className)
/*-{
var p = $wnd.jQuery("#"+id);
$wnd.jQuery(p).addClass("x-panel-collapsed "+ className);
$wnd.jQuery(p.children()[1]).hide();
}-*/;
static native void unCollapse(String id, String idFrame, String url)
/*-{
var p = $wnd.jQuery("#"+id);
$wnd.jQuery(p).removeClass("x-panel-collapsed");
var f = $wnd.jQuery(p).children()[1];
$wnd.jQuery(f).show();
if($wnd.jQuery(p).hasClass("x-tmp-collapsed")) {
$wnd.jQuery(p).removeClass("x-tmp-collapsed");
$wnd.document.getElementById(idFrame).src = "";
setTimeout(function(){
$wnd.document.getElementById(idFrame).src = url;
$wnd.jQuery($wnd.jQuery(p).children(".x-panel-body")).attr("style","overflow-x:auto;overflow-y:auto;");
},50);
}
}-*/;
public GadgetTools getTools() {
return tools;
}
public void unCollapseGadget() {
unCollapse(this.getId(), this.getIframeId(), this.gadget.getRenderUrl());
this.gadget.setCollapsed(false);
}
public void collapseGadget() {
collapse(this.getId(), "");
this.gadget.setCollapsed(true);
}
public String getView() {
return view;
}
public GadgetForm getGadgetForm() {
return form;
}
public void setView(String view) {
this.view = view;
}
private static native void removeHeaderColor(String id)
/*-{
$wnd.jQuery("#"+id).find("div.x-panel-tl").css("background","");
}-*/;
private static native void changeHeaderColor(String id, String color)
/*-{
$wnd.jQuery("#"+id).find("div.x-panel-tl").css("background-image","-webkit-gradient(linear,center top , #"+color+", #FFFFFF)");
$wnd.jQuery("#"+id).find("div.x-panel-tl").css("background-image","-moz-linear-gradient(center top , #"+color+", #FFFFFF)");
$wnd.jQuery("#"+id).find("div.x-panel-tl").css("background-color","#"+color);
}-*/;
static native void changeBorderColor(String id, String color)
/*-{
$wnd.jQuery("#"+id).find("div.x-panel-tl").css("border-bottom","1px solid #"+color);
$wnd.jQuery("#"+id).attr("style","border:1px solid #"+color);
}-*/;
static native void removeBorderColor(String id)
/*-{
$wnd.jQuery("#"+id).find("div.x-panel-tl").css("border-bottom","");
$wnd.jQuery("#"+id).attr("style","");
}-*/;
static native void removeBorder(String id)
/*-{
$wnd.jQuery("#"+id).find("div.x-panel-bwrap").css("border","0px");
}-*/;
static native void changeTitleColor(String id, String color)
/*-{
$wnd.jQuery("#"+id).find("span.x-panel-header-text").css("color","#"+color);
}-*/;
static native void removeTitleColor(String id)
/*-{
$wnd.jQuery("#"+id).find("span.x-panel-header-text").css("color","");
}-*/;
public void renderTitle() {
this.setTitle(this.gadget.getTitle());
}
public void removeStyle() {
_removeStyle(this.id);
};
private native static void _removeStyle(String id)
/*-{
$wnd.jQuery("#"+id).attr("style","");
}-*/;
}
|
package se.callistaenterprise.demo.api.controller;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import static com.google.zxing.BarcodeFormat.*;
import static com.google.zxing.EncodeHintType.CHARACTER_SET;
import static com.google.zxing.EncodeHintType.MARGIN;
import static com.google.zxing.client.j2se.MatrixToImageWriter.writeToStream;
import static org.springframework.http.MediaType.IMAGE_PNG_VALUE;
@Api(value = "Generates Barcodes and QR codes", tags = "DEMO",
description = "")
@RestController
@RequestMapping("/barcodes")
@Slf4j
public class BarcodeController {
@RequestMapping(method = RequestMethod.GET, produces = IMAGE_PNG_VALUE)
public void createBarcode(
@RequestParam(value = "format", defaultValue = "QR_CODE") String format,
@RequestParam(value = "content", defaultValue = "http://callistaenterprise.se/event/") String content,
@RequestParam(value = "margin", defaultValue = "0") int margin,
@RequestParam(value = "height", defaultValue = "300") int height,
@RequestParam(value = "width", defaultValue = "300") int width,
HttpServletResponse res) throws Exception {
log.info("RENDER barcode [height:{}, width:{}, margin:{}, content:{}, format:{}]", height, width, margin, content, format);
res.setContentType(IMAGE_PNG_VALUE);
disableCache(res);
writeToStream(renderBarcode(content, margin, height, width, format), "png", res.getOutputStream());
}
private BitMatrix renderBarcode(final String content, final int margin, final int height, final int width, String format) {
Map hints = new HashMap();
hints.put(MARGIN, margin);
hints.put(CHARACTER_SET, "UTF-8");
try {
switch (format) {
case "EAN-13":
return new MultiFormatWriter().encode(content, EAN_13, width, height, hints);
case "QR_CODE":
return new MultiFormatWriter().encode(content, QR_CODE, width, height, hints);
case "CODE_128":
return new MultiFormatWriter().encode(content, CODE_128, width, height, hints);
default:
return new MultiFormatWriter().encode(content, QR_CODE, width, height, hints);
}
} catch (Exception ex) {
throw new RuntimeException("Error rendering barcode for content " + content, ex);
}
}
private void disableCache(HttpServletResponse res) {
res.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.addHeader("Expires", "0");
res.addHeader("Pragma", "no-cache");
}
}
|
package org.nuxeo.ecm.core.search.api.client.querymodel.descriptor;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.nuxeo.common.xmap.annotation.XNode;
import org.nuxeo.common.xmap.annotation.XObject;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.schema.SchemaManager;
import org.nuxeo.ecm.core.schema.types.Field;
import org.nuxeo.ecm.core.schema.types.Schema;
import org.nuxeo.runtime.api.Framework;
@XObject(value = "field")
public class FieldDescriptor {
final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
@XNode("@name")
protected String name;
@XNode("@schema")
protected String schema;
private String fieldType;
public FieldDescriptor() {
}
public FieldDescriptor(String schema, String name) {
this.name = name;
this.schema = schema;
}
public String getName() {
return name;
}
public String getSchema() {
return schema;
}
public String getPlainStringValue(DocumentModel model) {
Object rawValue = model.getProperty(schema, name);
if (rawValue == null) {
return null;
}
String value = (String) rawValue;
if (value.equals("")) {
return null;
}
return value;
}
public Integer getIntValue(DocumentModel model) {
Object rawValue = model.getProperty(schema, name);
if (rawValue == null || "".equals(rawValue)) {
return null;
} else if (rawValue instanceof Integer) {
return (Integer) rawValue;
} else if (rawValue instanceof String) {
return Integer.parseInt((String) rawValue);
} else {
return Integer.parseInt(rawValue.toString());
}
}
public String getFieldType() throws ClientException {
try {
SchemaManager typeManager = Framework.getService(SchemaManager.class);
Schema schemaObj = typeManager.getSchema(schema);
if (schemaObj == null) {
throw new ClientException("failed to obtain schema: " + schema);
}
Field field = schemaObj.getField(name);
if (field == null) {
throw new ClientException("failed to obtain field: " + schema + ":" + name);
}
return field.getType().getName();
} catch (Exception e) {
throw new ClientException("failed to get field type for " + schema + ":" + name, e);
}
}
public String getStringValue(DocumentModel model) throws ClientException {
Object rawValue = model.getProperty(schema, name);
if (rawValue == null) {
return null;
}
String value;
if (rawValue instanceof GregorianCalendar) {
GregorianCalendar gc = (GregorianCalendar) rawValue;
value = "DATE '" + sf.format(gc.getTime()) + "'";
} else if (rawValue instanceof Date) {
Date date = (Date) rawValue;
value = "DATE '" + sf.format(date) + "'";
} else if (rawValue instanceof Integer || rawValue instanceof Long || rawValue instanceof Double) {
value = rawValue.toString(); // no quotes
} else if (rawValue instanceof Boolean) {
value = (Boolean) rawValue ? "1" : "0";
} else {
value = rawValue.toString().trim();
if (value.equals("")) {
return null;
}
if (fieldType == null) {
fieldType = getFieldType();
}
if ("long".equals(fieldType) || "integer".equals(fieldType) || "double".equals(fieldType)) {
return value;
} else {
// TODO switch back to SQLQueryParser for org.nuxeo.core 1.4
return QueryModelDescriptor.prepareStringLiteral(value);
}
}
return value;
}
@SuppressWarnings("unchecked")
public List<String> getListValue(DocumentModel model) {
Object rawValue = model.getProperty(schema, name);
if (rawValue == null) {
return null;
}
List<String> values = new ArrayList<String>();
if (rawValue instanceof ArrayList) {
rawValue = ((ArrayList<Object>) rawValue).toArray();
}
for (Object element : (Object[]) rawValue) {
// XXX: SQL escape values against SQL injection here! or refactor to
// use a PreparedStatement-like API at the Core level
if (element != null) {
String value = element.toString().trim();
if (!value.equals("")) {
values.add("'" + value + "'");
}
}
}
return values;
}
public Boolean getBooleanValue(DocumentModel model) {
Object rawValue = model.getProperty(schema, name);
if (rawValue == null) {
return null;
} else {
return (Boolean) rawValue;
}
}
}
|
package org.opendaylight.controller.config.it.base;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.maven;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.when;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.features;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
import com.google.common.base.Stopwatch;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.management.ObjectName;
import org.junit.Before;
import org.junit.Rule;
import org.junit.internal.AssumptionViolatedException;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.opendaylight.controller.config.api.ConfigRegistry;
import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.OptionUtils;
import org.ops4j.pax.exam.karaf.options.KarafDistributionOption;
import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
import org.ops4j.pax.exam.options.MavenArtifactUrlReference;
import org.ops4j.pax.exam.options.MavenUrlReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractConfigTestBase {
private static final String MAVEN_REPO_LOCAL = "maven.repo.local";
private static final String ORG_OPS4J_PAX_URL_MVN_LOCAL_REPOSITORY = "org.ops4j.pax.url.mvn.localRepository";
private static final String ETC_ORG_OPS4J_PAX_URL_MVN_CFG = "etc/org.ops4j.pax.url.mvn.cfg";
private static final String ETC_ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
private static final String PAX_EXAM_UNPACK_DIRECTORY = "target/exam";
private static final String KARAF_DEBUG_PORT = "5005";
private static final String KARAF_DEBUG_PROP = "karaf.debug";
private static final String KEEP_UNPACK_DIRECTORY_PROP = "karaf.keep.unpack";
private static final Logger LOG = LoggerFactory.getLogger(AbstractConfigTestBase.class);
public static final String ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
/*
* Default values for karaf distro type, groupId, and artifactId
*/
private static final String KARAF_DISTRO_TYPE = "zip";
private static final String KARAF_DISTRO_ARTIFACTID = "opendaylight-karaf-empty";
private static final String KARAF_DISTRO_GROUPID = "org.opendaylight.odlparent";
/*
* Property names to override defaults for karaf distro artifactId, groupId,
* version, and type
*/
private static final String KARAF_DISTRO_VERSION_PROP = "karaf.distro.version";
private static final String KARAF_DISTRO_TYPE_PROP = "karaf.distro.type";
private static final String KARAF_DISTRO_ARTIFACTID_PROP = "karaf.distro.artifactId";
private static final String KARAF_DISTRO_GROUPID_PROP = "karaf.distro.groupId";
/**
* Property file used to store the Karaf distribution version.
*/
private static final String PROPERTIES_FILENAME = "abstractconfigtestbase.properties";
/*
* Wait up to 10s for our configured module to come up
*/
private static final int MODULE_TIMEOUT_MILLIS = 60000;
/**
* This method need only be overridden if using the config system.
*
* @deprecated
*
* @return the config module name
*/
@Deprecated
public String getModuleName() {
return null;
}
/**
* This method need only be overridden if using the config system.
*
* @deprecated
*
* @return the config module instance name
*/
@Deprecated
public String getInstanceName() {
return null;
}
public abstract MavenUrlReference getFeatureRepo();
public abstract String getFeatureName();
public Option getLoggingOption() {
Option option = editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
"log4j2.logger.config-it-base.name",
AbstractConfigTestBase.class.getPackage().getName());
option = composite(option, editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
"log4j2.logger.config-it-base.level",
LogLevel.INFO.name()));
return option;
}
/**
* Override this method to provide more options to config.
*
* @return An array of additional config options
*/
protected Option[] getAdditionalOptions() {
return null;
}
/**
* Returns a Log4J logging configuration property name for the given class's package name of the form
* "log4j.logger.package_name".
*
* @deprecated The karaf logging provider is now Log4J2 so logging configurations must conform to the Log4J2 style.
* This method is kept for compilation backwards compatibility but will be removed in a future release.
*/
@Deprecated
public String logConfiguration(final Class<?> klazz) {
return "log4j.logger." + klazz.getPackage().getName();
}
public String getKarafDistro() {
String groupId = System.getProperty(KARAF_DISTRO_GROUPID_PROP, KARAF_DISTRO_GROUPID);
String artifactId = System.getProperty(KARAF_DISTRO_ARTIFACTID_PROP, KARAF_DISTRO_ARTIFACTID);
String version = System.getProperty(KARAF_DISTRO_VERSION_PROP);
String type = System.getProperty(KARAF_DISTRO_TYPE_PROP, KARAF_DISTRO_TYPE);
if (version == null) {
// We use a properties file to retrieve ${karaf.version}, instead of
// .versionAsInProject()
// This avoids forcing all users to depend on Karaf in their POMs
Properties abstractConfigTestBaseProps = new Properties();
try (InputStream abstractConfigTestBaseInputStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(PROPERTIES_FILENAME)) {
abstractConfigTestBaseProps.load(abstractConfigTestBaseInputStream);
} catch (final IOException e) {
LOG.error("Unable to load {} to determine the Karaf version", PROPERTIES_FILENAME, e);
}
version = abstractConfigTestBaseProps.getProperty(KARAF_DISTRO_VERSION_PROP);
}
MavenArtifactUrlReference karafUrl = maven().groupId(groupId).artifactId(artifactId).version(version)
.type(type);
return karafUrl.getURL();
}
protected Option mvnLocalRepoOption() {
String mvnRepoLocal = System.getProperty(MAVEN_REPO_LOCAL, "");
LOG.info("mvnLocalRepo \"{}\"", mvnRepoLocal);
return editConfigurationFilePut(ETC_ORG_OPS4J_PAX_URL_MVN_CFG, ORG_OPS4J_PAX_URL_MVN_LOCAL_REPOSITORY,
mvnRepoLocal);
}
@Configuration
public Option[] config() {
Option[] options = new Option[] {
when(Boolean.getBoolean(KARAF_DEBUG_PROP))
.useOptions(KarafDistributionOption.debugConfiguration(KARAF_DEBUG_PORT, true)),
karafDistributionConfiguration().frameworkUrl(getKarafDistro())
.unpackDirectory(new File(PAX_EXAM_UNPACK_DIRECTORY)).useDeployFolder(false),
when(Boolean.getBoolean(KEEP_UNPACK_DIRECTORY_PROP)).useOptions(keepRuntimeFolder()),
features(getFeatureRepo(), getFeatureName()),
mavenBundle("org.apache.aries.quiesce", "org.apache.aries.quiesce.api", "1.0.0"), getLoggingOption(),
mvnLocalRepoOption(),
editConfigurationFilePut(ETC_ORG_OPS4J_PAX_LOGGING_CFG, "log4j2.rootLogger.level", "INFO") };
return OptionUtils.combine(options, getAdditionalOptions());
}
@Before
@SuppressWarnings("IllegalCatch")
public void setup() throws Exception {
String moduleName = getModuleName();
String instanceName = getInstanceName();
if (moduleName == null || instanceName == null) {
return;
}
LOG.info("Module: {} Instance: {} attempting to configure.", moduleName, instanceName);
Stopwatch stopWatch = Stopwatch.createStarted();
ObjectName objectName = null;
for (int i = 0; i < MODULE_TIMEOUT_MILLIS; i++) {
try {
ConfigRegistry configRegistryClient = new ConfigRegistryJMXClient(
ManagementFactory.getPlatformMBeanServer());
objectName = configRegistryClient.lookupConfigBean(moduleName, instanceName);
LOG.info("Module: {} Instance: {} ObjectName: {}.", moduleName, instanceName, objectName);
break;
} catch (final Exception e) {
if (i < MODULE_TIMEOUT_MILLIS) {
Thread.sleep(1);
continue;
} else {
throw e;
}
}
}
if (objectName != null) {
LOG.info("Module: {} Instance: {} configured after {} ms", moduleName, instanceName,
stopWatch.elapsed(TimeUnit.MILLISECONDS));
} else {
throw new RuntimeException("NOT FOUND Module: " + moduleName + " Instance: " + instanceName
+ " configured after " + stopWatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
}
}
@Rule
public TestRule watcher = new TestWatcher() {
@Override
protected void starting(final Description description) {
LOG.info("TestWatcher: Starting test: {}", description.getDisplayName());
}
@Override
protected void finished(final Description description) {
LOG.info("TestWatcher: Finished test: {}", description.getDisplayName());
}
@Override
protected void succeeded(final Description description) {
LOG.info("TestWatcher: Test succeeded: {}", description.getDisplayName());
}
@Override
protected void failed(final Throwable ex, final Description description) {
LOG.info("TestWatcher: Test failed: {}", description.getDisplayName(), ex);
}
@Override
protected void skipped(final AssumptionViolatedException ex, final Description description) {
LOG.info("TestWatcher: Test skipped: {} ", description.getDisplayName(), ex);
}
};
}
|
package org.geomajas.plugin.printing.client.util;
import org.geomajas.annotation.Api;
/**
* Class which helps to provide consistent sizes and names for layout purposes.
* <p/>
* Implemented as static class to allow overwriting values at application start, thus allowing skinning.
*
* @author Joachim Van der Auwera
* @since 2.2.0
*/
@Api(allMethods = true)
public final class PrintingLayout {
// CHECKSTYLE VISIBILITY MODIFIER: OFF
/** Blank "waiting" image. */
public static String iconWaitBlank = "[ISOMORPHIC]/geomajas/plugin/printing/pleasewait-blank.gif";
/** Moving "waiting" image. */
public static String iconWaitMoving = "[ISOMORPHIC]/geomajas/plugin/printing/pleasewait.gif";
/** Wait image width. */
public static int iconWaitWidth = 214;
/** Wait image height. */
public static int iconWaitHeight = 15;
/** Width for the print preferences window. */
public static String printPreferencesWidth = "400";
/** Height for the print preferences window. */
public static String printPreferencesHeight = "400";
/** Width for the resolution selector in the print preferences window. */
public static String printPreferencesResolutionWidth = "250";
/** Height for the resolution selector in the print preferences window. */
public static String printPreferencesResolutionHeight = "30";
/** X margin for the default template. */
public static double templateMarginX = 20;
/** Y margin for the default template. */
public static double templateMarginY = 20;
/** Width of the north arrow in the template. */
public static double templateNorthArrowWidth = 10;
/** Font family for the legend in the template. */
public static String templateDefaultFontFamily = "Dialog";
/** Font style for the legend in the template. */
public static String templateDefaultFontStyle = "Italic";
/** Font size for the legend in the template. */
public static double templateDefaultFontSize = 14;
/** Background colour for the legend in the template. */
public static String templateDefaultBackgroundColor = "0xFFFFFF";
/** Border colour for the legend in the template. */
public static String templateDefaultBorderColor = "0x000000";
/** Font colour for the legend in the template. */
public static String templateDefaultColor = "0x000000";
/** Should the default template include a scale bar? */
public static boolean templateIncludeScaleBar = true;
/** Should the default template include a legend? */
public static boolean templateIncludeLegend = true;
/** Should the default template include a north arrow? */
public static boolean templateIncludeNorthArrow = true;
// CHECKSTYLE VISIBILITY MODIFIER: ON
private PrintingLayout() {
// do not allow instantiation.
}
}
|
package me.lucko.luckperms.bukkit.calculator;
import com.google.common.collect.ImmutableList;
import me.lucko.luckperms.bukkit.LPBukkitPlugin;
import me.lucko.luckperms.bukkit.context.BukkitContextManager;
import me.lucko.luckperms.common.cacheddata.CacheMetadata;
import me.lucko.luckperms.common.calculator.CalculatorFactory;
import me.lucko.luckperms.common.calculator.PermissionCalculator;
import me.lucko.luckperms.common.calculator.processor.MapProcessor;
import me.lucko.luckperms.common.calculator.processor.PermissionProcessor;
import me.lucko.luckperms.common.calculator.processor.RegexProcessor;
import me.lucko.luckperms.common.calculator.processor.WildcardProcessor;
import me.lucko.luckperms.common.config.ConfigKeys;
import net.luckperms.api.query.QueryOptions;
public class BukkitCalculatorFactory implements CalculatorFactory {
private final LPBukkitPlugin plugin;
public BukkitCalculatorFactory(LPBukkitPlugin plugin) {
this.plugin = plugin;
}
@Override
public PermissionCalculator build(QueryOptions queryOptions, CacheMetadata metadata) {
ImmutableList.Builder<PermissionProcessor> processors = ImmutableList.builder();
processors.add(new MapProcessor());
if (this.plugin.getConfiguration().get(ConfigKeys.APPLY_BUKKIT_CHILD_PERMISSIONS)) {
processors.add(new ChildProcessor(this.plugin));
}
if (this.plugin.getConfiguration().get(ConfigKeys.APPLYING_REGEX)) {
processors.add(new RegexProcessor());
}
if (this.plugin.getConfiguration().get(ConfigKeys.APPLYING_WILDCARDS)) {
processors.add(new WildcardProcessor());
}
boolean op = queryOptions.option(BukkitContextManager.OP_OPTION).orElse(false);
if (this.plugin.getConfiguration().get(ConfigKeys.APPLY_BUKKIT_DEFAULT_PERMISSIONS)) {
processors.add(new DefaultsProcessor(this.plugin, op));
}
if (op) {
processors.add(new OpProcessor());
}
return new PermissionCalculator(this.plugin, metadata, processors.build());
}
}
|
package org.python.pydev.editor.codecompletion;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.python.pydev.core.IModule;
import org.python.pydev.core.IPythonNature;
import org.python.pydev.core.REF;
import org.python.pydev.core.TestDependent;
import org.python.pydev.core.structure.CompletionRecursionException;
import org.python.pydev.editor.codecompletion.revisited.CodeCompletionTestsBase;
import org.python.pydev.editor.codecompletion.revisited.CompletionCache;
import org.python.pydev.editor.codecompletion.revisited.CompletionStateFactory;
import org.python.pydev.editor.codecompletion.revisited.modules.AbstractModule;
import org.python.pydev.editor.codecompletion.revisited.modules.CompiledModule;
import org.python.pydev.editor.codecompletion.revisited.visitors.Definition;
import org.python.pydev.editor.codecompletion.shell.AbstractShell;
import org.python.pydev.editor.codecompletion.shell.PythonShell;
import org.python.pydev.editor.codecompletion.shell.PythonShellTest;
import org.python.pydev.plugin.nature.PythonNature;
public class PythonCompletionWithBuiltinsTest extends CodeCompletionTestsBase{
protected boolean isInTestFindDefinition = false;
public static void main(String[] args) {
try {
PythonCompletionWithBuiltinsTest builtins = new PythonCompletionWithBuiltinsTest();
builtins.setUp();
builtins.testSortParamsCorrect();
builtins.tearDown();
junit.textui.TestRunner.run(PythonCompletionWithBuiltinsTest.class);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected PythonNature createNature() {
return new PythonNature(){
@Override
public boolean isJython() throws CoreException {
return false;
}
@Override
public boolean isPython() throws CoreException {
return true;
}
@Override
public int getGrammarVersion() {
return IPythonNature.LATEST_GRAMMAR_VERSION;
}
@Override
public String resolveModule(File file) {
if(isInTestFindDefinition){
return null;
}
return super.resolveModule(file);
}
};
}
private static PythonShell shell;
/*
* @see TestCase#setUp()
*/
public void setUp() throws Exception {
super.setUp();
ADD_MX_TO_FORCED_BUILTINS = false;
CompiledModule.COMPILED_MODULES_ENABLED = true;
this.restorePythonPath(TestDependent.GetCompletePythonLib(true)+"|"+
TestDependent.PYTHON_WXPYTHON_PACKAGES+"|"+
TestDependent.PYTHON_MX_PACKAGES+"|"+
TestDependent.PYTHON_NUMPY_PACKAGES, false);
codeCompletion = new PyCodeCompletion();
//we don't want to start it more than once
if(shell == null){
shell = PythonShellTest.startShell();
}
AbstractShell.putServerShell(nature, AbstractShell.COMPLETION_SHELL, shell);
}
/*
* @see TestCase#tearDown()
*/
public void tearDown() throws Exception {
CompiledModule.COMPILED_MODULES_ENABLED = false;
super.tearDown();
AbstractShell.putServerShell(nature, AbstractShell.COMPLETION_SHELL, null);
}
public void testRecursion() throws FileNotFoundException, CoreException, BadLocationException, CompletionRecursionException{
String file = TestDependent.TEST_PYSRC_LOC+"testrec3/rec.py";
String strDoc = "RuntimeError.";
File f = new File(file);
try{
nature.getAstManager().getCompletionsForToken(f, new Document(REF.getFileContents(f)),
CompletionStateFactory.getEmptyCompletionState("RuntimeError", nature, new CompletionCache()));
}catch(CompletionRecursionException e){
//that's ok... we're asking for it here...
}
requestCompl(f, strDoc, strDoc.length(), -1, new String[]{"__doc__", "__getitem__()", "__init__()", "__str__()"});
}
public void testCompleteImportBuiltin() throws BadLocationException, IOException, Exception{
String s;
s = "from datetime import datetime\n" +
"datetime.";
//for some reason, this is failing only when the module is specified...
File file = new File(TestDependent.TEST_PYDEV_PLUGIN_LOC+"tests/pysrc/simpledatetimeimport.py");
assertTrue(file.exists());
assertTrue(file.isFile());
requestCompl(file, s, s.length(), -1, new String[]{"today()", "now()", "utcnow()"});
s = "from datetime import datetime, date, MINYEAR,";
requestCompl(s, s.length(), -1, new String[] { "date", "datetime", "MINYEAR", "MAXYEAR", "timedelta" });
s = "from datetime.datetime import ";
requestCompl(s, s.length(), -1, new String[] { "today", "now", "utcnow" });
// Problem here is that we do not evaluate correctly if
// met( ddd,
// fff,
// ccc )
//so, for now the test just checks that we do not get in any sort of
//look...
s = "" +
"class bla(object):pass\n" +
"\n"+
"def newFunc(): \n"+
" callSomething( bla.__get#complete here... stack error \n"+
" keepGoing) \n";
//If we improve the parser to get the error above, uncomment line below to check it...
requestCompl(s, s.indexOf('#'), 1, new String[]{"__getattribute__()"});
//check for builtins..1
s = "" +
"\n" +
"";
requestCompl(s, s.length(), -1, new String[]{"RuntimeError"});
//check for builtins..2
s = "" +
"from testlib import *\n" +
"\n" +
"";
requestCompl(s, s.length(), -1, new String[]{"RuntimeError"});
//check for builtins..3 (builtins should not be available because it is an import request for completions)
requestCompl("from testlib.unittest import ", new String[]{"__file__", "__name__", "__init__", "__path__", "anothertest"
, "AnotherTest", "GUITest", "guitestcase", "main", "relative", "t", "TestCase", "testcase", "TestCaseAlias",
});
}
public void testBuiltinsInNamespace() throws BadLocationException, IOException, Exception{
String s = "__builtins__.";
requestCompl(s, s.length(), -1, new String[]{"RuntimeError"});
}
public void testBuiltinsInNamespace2() throws BadLocationException, IOException, Exception{
String s = "__builtins__.RuntimeError.";
requestCompl(s, s.length(), -1, new String[]{"__doc__", "__getitem__()", "__init__()", "__str__()"});
}
public void testPreferForcedBuiltin() throws BadLocationException, IOException, Exception{
if(TestDependent.HAS_MX_DATETIME){
String s = ""+
"from mx import DateTime\n"+
"DateTime.";
requestCompl(s, s.length(), -1, new String[]{"now()"});
}
}
public void testNumpy() throws BadLocationException, IOException, Exception{
if(TestDependent.HAS_NUMPY_INSTALLED){
String s = ""+
"from numpy import less\n"+
"less.";
requestCompl(new File(TestDependent.TEST_PYSRC_LOC+"extendable/not_existent.py"),
s, s.length(), -1, new String[]{"types", "ntypes", "nout", "nargs", "nin"});
}
}
public void testDeepNested6() throws CoreException, BadLocationException{
String s;
s = "" +
"from extendable.nested2 import hub\n"+
"hub.c1.f.";
requestCompl(s, s.length(), -1, new String[] { "curdir"});
}
public void testDeepNested10() throws CoreException, BadLocationException{
String s;
s = "" +
"from extendable.nested3 import hub2\n"+
"hub2.c.a.";
requestCompl(s, s.length(), -1, new String[] { "fun()"});
}
public void testRelativeOnSameProj() throws CoreException, BadLocationException{
String s;
s = "" +
"import prefersrc\n" +
"prefersrc.";
AbstractModule.MODULE_NAME_WHEN_FILE_IS_UNDEFINED = "foo";
try {
requestCompl(s, s.length(), -1, new String[] { "OkGotHere" }, nature2);
} finally {
AbstractModule.MODULE_NAME_WHEN_FILE_IS_UNDEFINED = "";
}
}
public void testDeepNested7() throws CoreException, BadLocationException{
String s;
s = "" +
"from extendable.nested2 import hub\n"+
"hub.c1.f.curdir.";
requestCompl(s, s.length(), -1, new String[] { "upper()"});
}
public void testDeepNested8() throws CoreException, BadLocationException{
String s;
s = "" +
"from extendable.nested2 import hub\n"+
"hub.C1.f.sep."; //changed: was altsep (may be None in linux).
requestCompl(s, s.length(), -1, new String[] { "upper()"});
}
public void testDeepNested9() throws CoreException, BadLocationException{
String s;
s = "" +
"from extendable.nested2 import hub\n"+
"hub.C1.f.inexistant.";
requestCompl(s, s.length(), -1, new String[] { });
}
public void testDictAssign() throws CoreException, BadLocationException{
String s;
s = "" +
"a = {}\n"+
"a.";
requestCompl(s, s.length(), -1, new String[] { "keys()" });
}
public void testPreferSrc() throws BadLocationException, IOException, Exception{
String s = ""+
"import prefersrc\n"+
"prefersrc.";
requestCompl(s, s.length(), -1, new String[]{"PreferSrc"});
}
public void testPreferCompiledOnBootstrap() throws BadLocationException, IOException, Exception{
String s = ""+
"from extendable.bootstrap_dll import umath\n"+
"umath.";
IModule module = nature.getAstManager().getModule("extendable.bootstrap_dll.umath", nature, true);
assertTrue("Expected CompiledModule. Found: "+module.getClass(), module instanceof CompiledModule);
//NOTE: The test can fail if numpy is not available (umath.pyd depends on numpy)
requestCompl(s, s.length(), -1, new String[]{"less"});
}
public void testPreferCompiledOnBootstrap2() throws BadLocationException, IOException, Exception{
String s = ""+
"from extendable.bootstrap_dll.umath import ";
IModule module = nature.getAstManager().getModule("extendable.bootstrap_dll.umath", nature, true);
assertTrue(module instanceof CompiledModule);
//NOTE: The test can fail if numpy is not available (umath.pyd depends on numpy)
requestCompl(s, s.length(), -1, new String[]{"less"});
}
public void testWxPython1() throws BadLocationException, IOException, Exception{
if(TestDependent.HAS_WXPYTHON_INSTALLED){ //we can only test what we have
String s = ""+
"from wxPython.wx import *\n"+
"import wx\n"+
"class HelloWorld(wx.App):\n"+
" def OnInit(self):\n"+
" frame = wx.Frame(None,-1,\"hello world\")\n"+
" frame.Show(True)\n"+
" self.SetTopWindow(frame)\n"+
" b=wx.Button(frame,-1,\"Button\")\n"+
" return True\n"+
"app = HelloWorld(0)\n"+
"app.MainLoop()\n"+
"app.";
requestCompl(s, s.length(), -1, new String[]{"MainLoop()"});
}
}
public void testCompleteImportBuiltinReference2() throws BadLocationException, IOException, Exception{
String s;
if(TestDependent.HAS_WXPYTHON_INSTALLED){ //we can only test what we have
s = "" +
"from wx import ";
requestCompl(s, s.length(), -1, new String[]{"glcanvas"});
}
}
public void testGlu() throws IOException, CoreException, BadLocationException {
if(TestDependent.HAS_GLU_INSTALLED){
final String s = "from OpenGL import ";
requestCompl(s, s.length(), -1, new String[]{"GLU", "GLUT"});
}
}
public void testGlu2() throws IOException, CoreException, BadLocationException {
if(TestDependent.HAS_GLU_INSTALLED){
final String s = "from OpenGL.GL import ";
requestCompl(s, s.length(), -1, new String[]{"glPushMatrix"});
}
}
public void testCompleteImportBuiltinReference() throws BadLocationException, IOException, Exception{
String s;
if(TestDependent.HAS_WXPYTHON_INSTALLED){ //we can only test what we have
s = "" +
"from wxPython.wx import wxButton\n"+
" \n"+
"wxButton.";
requestCompl(s, s.length(), -1, new String[]{"Close()"});
s = "" +
"import wxPython\n"+
" \n"+
"wxPython.";
requestCompl(s, s.length(), -1, new String[]{"wx"});
}
s = "" +
"import os\n"+
" \n"+
"os.";
File file = new File(TestDependent.TEST_PYDEV_PLUGIN_LOC+"tests/pysrc/simpleosimport.py");
assertTrue(file.exists());
assertTrue(file.isFile());
requestCompl(file, s, s.length(), -1, new String[]{"path"});
s = "" +
"import os\n"+
" \n"+
"os.";
requestCompl(s, s.length(), -1, new String[]{"path"});
if(TestDependent.HAS_QT_INSTALLED){ //we can only test what we have
//check for builtins with reference..3
s = "" +
"from qt import *\n"+
" \n"+
"q = QLabel() \n"+
"q.";
requestCompl(s, s.length(), -1, new String[]{"AlignAuto"});
}
//check for builtins with reference..3
s = "" +
"from testlib.unittest import anothertest\n"+
"anothertest.";
requestCompl(s, s.length(), 4, new String[]{"__file__", "__name__", "AnotherTest","t"});
}
public void testInstanceCompletion() throws Exception {
String s =
"class A:\n" +
" def __init__(self):\n" +
" self.list1 = []\n" +
"if __name__ == '__main__':\n" +
" a = A()\n" +
" a.list1.";
requestCompl(s, -1, new String[] {"pop()", "remove(value)"});
}
public void test__all__() throws Exception {
String s =
"from extendable.all_check import *\n" +
"";
//should keep the variables from the __builtins__ in this module
requestCompl(s, -1, new String[] {"ThisGoes", "RuntimeError"});
}
public void testSortParamsCorrect() throws Exception {
String s =
"[].sort" +
"";
//should keep the variables from the __builtins__ in this module
requestCompl(s, -1, new String[] {"sort(cmp=None, key=None, reverse=False)"});
}
public void testFindDefinition() throws Exception {
isInTestFindDefinition = true;
try {
CompiledModule mod = new CompiledModule("os", nature.getAstManager());
Definition[] findDefinition = mod.findDefinition(
CompletionStateFactory.getEmptyCompletionState("walk", nature, new CompletionCache()), -1, -1, nature);
assertEquals(1, findDefinition.length);
assertEquals("os", findDefinition[0].module.getName());
} finally {
isInTestFindDefinition = false;
}
}
}
|
package org.yakindu.sct.model.stext.validation;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.xtext.naming.QualifiedName;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.service.OperationCanceledManager;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.validation.INamesAreUniqueValidationHelper;
import org.eclipse.xtext.validation.NamesAreUniqueValidationHelper;
import org.eclipse.xtext.validation.ValidationMessageAcceptor;
import org.yakindu.sct.commons.EMFHelper;
import org.yakindu.sct.model.sgraph.SGraphPackage;
/**
* @author rbeckmann
*
*/
public class STextNamesAreUniqueValidationHelper extends NamesAreUniqueValidationHelper
implements INamesAreUniqueValidationHelper {
protected OperationCanceledManager operationCanceledManager = new OperationCanceledManager();
protected Map<QualifiedName, IEObjectDescription> nameMap;
protected Map<QualifiedName, IEObjectDescription> caseInsensitiveMap;
protected Map<String, IEObjectDescription> lastElementMap;
@Override
public void checkUniqueNames(Iterable<IEObjectDescription> descriptions, ValidationMessageAcceptor acceptor) {
checkUniqueNames(descriptions, null, acceptor);
}
/**
* <p>
* {@inheritDoc}
* </p>
* The cancel indicator will be queried everytime a description has been
* processed. It should provide a fast answer about its canceled state.
*/
@Override
public void checkUniqueNames(Iterable<IEObjectDescription> descriptions, CancelIndicator cancelIndicator,
ValidationMessageAcceptor acceptor) {
Iterator<IEObjectDescription> iter = descriptions.iterator();
this.nameMap = new HashMap<>();
this.caseInsensitiveMap = new HashMap<>();
this.lastElementMap = new HashMap<>();
if (!iter.hasNext())
return;
while (iter.hasNext()) {
IEObjectDescription description = iter.next();
checkDescriptionForDuplicatedName(description, acceptor);
operationCanceledManager.checkCanceled(cancelIndicator);
}
}
protected void checkDescriptionForDuplicatedName(IEObjectDescription description,
ValidationMessageAcceptor acceptor) {
if (!shouldValidateEClass(description.getEClass())) {
return;
}
QualifiedName qName = description.getName();
// check for exactly equal names
IEObjectDescription existing = nameMap.put(qName, description);
// check for names that only differ in case, like 'x' and 'X'
IEObjectDescription existingLowerCase = caseInsensitiveMap.put(qName.toLowerCase(), description);
// check for names where the qualifier is different but the name is the
// same, like 'region1.StateA' and 'region2.StateA'.
IEObjectDescription existingLastElement = lastElementMap.put(qName.getLastSegment(), description);
if (existing != null) {
validateEqualName(description, existing, acceptor);
} else if (existingLowerCase != null) {
validateCapitonym(description, existingLowerCase, acceptor);
}
if (existingLastElement != null) {
duplicateLastElement(description, existingLastElement, acceptor);
}
}
protected void validateEqualName(IEObjectDescription description, IEObjectDescription doublet,
ValidationMessageAcceptor acceptor) {
EClass common = checkForCommonSuperClass(doublet, description);
if (inSameResource(doublet, description) && common != null) {
createDuplicateNameError(description, common, acceptor);
createDuplicateNameError(doublet, common, acceptor);
}
}
protected void validateCapitonym(IEObjectDescription description, IEObjectDescription doublet,
ValidationMessageAcceptor acceptor) {
if (inSameResource(doublet, description) && doublet.getEClass().equals(description.getEClass())) {
createDuplicateNameWarning(description, description.getEClass(), acceptor);
createDuplicateNameWarning(doublet, description.getEClass(), acceptor);
}
}
protected void validateEqualSimpleName(IEObjectDescription description, IEObjectDescription doublet,
ValidationMessageAcceptor acceptor) {
}
protected void duplicateLastElement(IEObjectDescription description, IEObjectDescription put,
ValidationMessageAcceptor acceptor) {
}
protected boolean shouldValidateEClass(EClass eC) {
if (eC.isSuperTypeOf(SGraphPackage.Literals.STATECHART)) {
return false;
}
return true;
}
protected boolean inSameResource(IEObjectDescription one, IEObjectDescription two) {
return one.getEObjectOrProxy().eResource().equals(two.getEObjectOrProxy().eResource());
}
protected void createDuplicateNameWarning(IEObjectDescription description, EClass eClass,
ValidationMessageAcceptor acceptor) {
EObject object = description.getEObjectOrProxy();
EStructuralFeature feature = getNameFeature(object);
acceptor.acceptWarning(getDuplicateNameWarningMessage(description, eClass, feature), object, feature,
ValidationMessageAcceptor.INSIGNIFICANT_INDEX, getErrorCode());
}
protected String getDuplicateNameWarningMessage(IEObjectDescription description, EClass eClass,
EStructuralFeature feature) {
return getDuplicateNameErrorMessage(description, eClass, feature)
+ ". Names differ only in case, which can lead to compilation problems.";
}
protected EClass checkForCommonSuperClass(IEObjectDescription one, IEObjectDescription two) {
List<EClass> flatOne = EMFHelper.getAllSuperClasses(one.getEClass());
List<EClass> flatTwo = EMFHelper.getAllSuperClasses(two.getEClass());
for (EClass eC : flatOne) {
if (flatTwo.contains(eC))
return eC;
}
return null;
}
}
|
package gov.nih.nci.cabig.caaers.tools;
import static gov.nih.nci.cabig.caaers.tools.DataSourceSelfDiscoveringPropertiesFactoryBean.*;
import java.io.File;
import java.util.Properties;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* @author Rhett Sutphin
*/
public class DataSourceSelfDiscoveringPropertiesFactoryBeanTest extends TestCase {
private DataSourceSelfDiscoveringPropertiesFactoryBean factoryBean;
@Override
protected void setUp() throws Exception {
super.setUp();
File thisDir = new File(getClass().getResource("/").toURI());
System.setProperty("catalina.home", thisDir.getCanonicalPath());
factoryBean = new DataSourceSelfDiscoveringPropertiesFactoryBean();
factoryBean.setDatabaseConfigurationName("empty");
}
public void testDefaultPropertiesFoundAndBound() throws Exception {
factoryBean.setDatabaseConfigurationName(null);
assertDefaultLoadedProperties();
}
public void testEmptyConfNameUsesDefault() throws Exception {
factoryBean.setDatabaseConfigurationName(" \t");
assertDefaultLoadedProperties();
}
public void testDbConfigNameUsed() throws Exception {
factoryBean.setDatabaseConfigurationName("alternate");
assertLoadedProperties("jdbc:db:alternate", "java.lang.Long", "alt", "tla");
}
public void testDefaultDialectForPostgreSQLFromRDBMSProperty() throws Exception {
factoryBean.getDefaults().setProperty(RDBMS_PROPERTY_NAME, "PostgreSQL");
assertEquals(DEFAULT_POSTGRESQL_DIALECT,
getActualProperties().getProperty(HIBERNATE_DIALECT_PROPERTY_NAME));
}
public void testDefaultDialectForPostgreSQLFromDriver() throws Exception {
factoryBean.getDefaults().setProperty(DRIVER_PROPERTY_NAME, "org.postgresql.Driver");
assertEquals(DEFAULT_POSTGRESQL_DIALECT,
getActualProperties().getProperty(HIBERNATE_DIALECT_PROPERTY_NAME));
}
public void testExplicitHibernateDialectTrumps() throws Exception {
String expectedDialect = "org.hibernate.dialect.PostgreSQLDialect";
factoryBean.getDefaults().setProperty(RDBMS_PROPERTY_NAME, "PostgreSQL");
factoryBean.getDefaults().setProperty(HIBERNATE_DIALECT_PROPERTY_NAME, expectedDialect);
Assert.assertEquals(expectedDialect, getActualProperties().getProperty(HIBERNATE_DIALECT_PROPERTY_NAME));
}
private void assertLoadedProperties(
String expectedUrl, String expectedDriver, String expectedUser, String expectedPass
) throws Exception {
Properties actual = getActualProperties();
Assert.assertEquals("Wrong URL", expectedUrl, actual.getProperty(URL_PROPERTY_NAME));
Assert.assertEquals("Wrong driver", expectedDriver, actual.getProperty(DRIVER_PROPERTY_NAME));
Assert.assertEquals("Wrong user", expectedUser, actual.getProperty(USERNAME_PROPERTY_NAME));
Assert.assertEquals("Wrong password", expectedPass, actual.getProperty(PASSWORD_PROPERTY_NAME));
}
private void assertDefaultLoadedProperties() throws Exception {
// these values are in datasource.properties
assertLoadedProperties("jdbc:db:default", "java.lang.String", "default-user", "pass-default");
}
private Properties getActualProperties() throws Exception {
return (Properties) factoryBean.getObject();
}
public void testSelectQuartzDelegateClass() throws Exception{
Properties actual = factoryBean.getProperties();
String dbProperty = String.valueOf(actual.getProperty(DRIVER_PROPERTY_NAME)) + String.valueOf(actual.getProperty(RDBMS_PROPERTY_NAME)) ;
String quartzDelegateClass = actual.getProperty(QUARTZ_DELEGATE_PROPERTY_NAME);
assertNotNull("Quartz Delegate class empty", quartzDelegateClass);
if(dbProperty.toLowerCase().contains("oracle")){
assertEquals("Expected org.quartz.impl.jdbcjobstore.oracle.OracleDelegate",
"org.quartz.impl.jdbcjobstore.oracle.OracleDelegate" , quartzDelegateClass);
return;
}
if(dbProperty.toLowerCase().contains("postgres")){
assertEquals("Expected org.quartz.impl.jdbcjobstore.PostgreSQLDelegate",
"org.quartz.impl.jdbcjobstore.PostgreSQLDelegate" , quartzDelegateClass);
return;
}
if(dbProperty.toLowerCase().contains("hsql")){
assertEquals("Expected org.quartz.impl.jdbcjobstore.StdJDBCDelegate(Hibernate)",
"org.quartz.impl.jdbcjobstore.StdJDBCDelegate" , quartzDelegateClass);
return;
}
//assertTrue("datasource.properties has wrong configuation", false);
}
}
|
package com.joker.fourfun.di.component;
import com.joker.fourfun.di.PerFragment;
import com.joker.fourfun.di.module.FragmentModule;
import com.joker.fourfun.ui.fragment.PictureChildFragment;
import com.joker.fourfun.ui.fragment.PictureFragment;
import com.joker.fourfun.ui.fragment.ReadFragment;
import dagger.Component;
import me.yokeyword.fragmentation.SupportFragment;
@PerFragment
@Component(dependencies = AppComponent.class, modules = FragmentModule.class)
public interface FragmentComponent {
SupportFragment fragment();
void inject(ReadFragment fragment);
void inject(PictureFragment fragment);
void inject(PictureChildFragment fragment);
}
|
package com.github.TKnudsen.timeseries.operations.preprocessing.univariate.normalization;
import java.util.Arrays;
import java.util.List;
import com.github.TKnudsen.ComplexDataObject.model.processors.IDataProcessor;
import com.github.TKnudsen.ComplexDataObject.model.processors.complexDataObject.DataProcessingCategory;
import com.github.TKnudsen.ComplexDataObject.model.tools.MathFunctions;
import com.github.TKnudsen.timeseries.data.univariate.ITimeSeriesUnivariate;
import com.github.TKnudsen.timeseries.operations.preprocessing.univariate.ITimeSeriesUnivariatePreprocessor;
import com.github.TKnudsen.timeseries.operations.tools.TimeSeriesTools;
public class MinMaxNormalization implements ITimeSeriesUnivariatePreprocessor {
private boolean globalMinMax;
private double globalMin = Double.NaN;
private double globalMax = Double.NaN;
public MinMaxNormalization() {
this.globalMinMax = false;
}
public MinMaxNormalization(boolean globalMinMax) {
this.globalMinMax = globalMinMax;
}
public MinMaxNormalization(double globalMin, double globalMax) {
this.globalMinMax = true;
this.globalMin = globalMin;
this.globalMax = globalMax;
}
@Override
public void process(List<ITimeSeriesUnivariate> data) {
double globalMin = Double.POSITIVE_INFINITY;
double globalMax = Double.NEGATIVE_INFINITY;
if (!Double.isNaN(this.globalMin) && !Double.isNaN(this.globalMax)) {
globalMin = this.globalMin;
globalMax = this.globalMax;
} else if (globalMinMax)
for (ITimeSeriesUnivariate timeSeries : data) {
globalMin = Math.min(globalMin, TimeSeriesTools.getMinValue(timeSeries));
globalMax = Math.max(globalMax, TimeSeriesTools.getMaxValue(timeSeries));
}
for (ITimeSeriesUnivariate timeSeries : data) {
double min = TimeSeriesTools.getMinValue(timeSeries);
double max = TimeSeriesTools.getMaxValue(timeSeries);
for (int i = 0; i < timeSeries.size(); i++)
if (globalMinMax) // also true when this.globalmin/max are set
timeSeries.replaceValue(i, MathFunctions.linearScale(globalMin, globalMax, timeSeries.getValue(i)));
else
timeSeries.replaceValue(i, MathFunctions.linearScale(min, max, timeSeries.getValue(i)));
}
}
@Override
public DataProcessingCategory getPreprocessingCategory() {
return DataProcessingCategory.DATA_NORMALIZATION;
}
public boolean isGlobalMinMax() {
return globalMinMax;
}
public void setGlobalMinMax(boolean globalMinMax) {
this.globalMinMax = globalMinMax;
}
@Override
public List<IDataProcessor<ITimeSeriesUnivariate>> getAlternativeParameterizations(int count) {
return Arrays.asList(new MinMaxNormalization(!globalMinMax));
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof MinMaxNormalization))
return false;
MinMaxNormalization other = (MinMaxNormalization) o;
if (other.globalMinMax != globalMinMax)
return false;
if (other.globalMin != globalMin)
return false;
return other.globalMax == globalMax;
}
}
|
package com.persado.oss.quality.stevia.selenium.core.controllers.factories;
import com.opera.core.systems.OperaDriver;
import com.persado.oss.quality.stevia.selenium.core.SteviaContext;
import com.persado.oss.quality.stevia.selenium.core.WebController;
import com.persado.oss.quality.stevia.selenium.core.controllers.SteviaWebControllerFactory;
import com.persado.oss.quality.stevia.selenium.core.controllers.WebDriverWebController;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class WebDriverWebControllerFactoryImpl implements WebControllerFactory {
private static final Logger LOG = LoggerFactory.getLogger(WebDriverWebControllerFactoryImpl.class);
@Override
public WebController initialize(ApplicationContext context, WebController controller) {
WebDriverWebController wdController = (WebDriverWebController) controller;
WebDriver driver = null;
if (SteviaContext.getParam(SteviaWebControllerFactory.DEBUGGING).compareTo(SteviaWebControllerFactory.TRUE) == 0) { // debug=on
if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER) == null || SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("firefox") == 0
|| SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).isEmpty()) {
driver = setUpFirefoxDriver();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("chrome") == 0) {
driver = setUpChromeDriver();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("iexplorer") == 0) {
LOG.info("Debug enabled, using InternetExplorerDriver");
driver = new InternetExplorerDriver();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("safari") == 0) {
LOG.info("Debug enabled, using SafariDriver");
driver = new SafariDriver();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("opera") == 0) {
LOG.info("Debug enabled, using OperaDriver");
driver = new OperaDriver();
} else {
throw new IllegalArgumentException(SteviaWebControllerFactory.WRONG_BROWSER_PARAMETER);
}
} else { // debug=off
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
if (!StringUtils.isEmpty(System.getProperty("screenResolution"))) {
LOG.info("Set screen resolution to " + System.getProperty("screenResolution"));
desiredCapabilities.setCapability("screenResolution", System.getProperty("screenResolution"));
}
if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER) == null || SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("firefox") == 0
|| SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).isEmpty()) {
LOG.info("Debug OFF, using a RemoteWebDriver with Firefox capabilities");
desiredCapabilities = DesiredCapabilities.firefox();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("chrome") == 0) {
LOG.info("Debug OFF, using a RemoteWebDriver with Chrome capabilities");
desiredCapabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
if (SteviaContext.getParam("chromeExtensions") != null) {
List<String> extensionPaths = Arrays.asList(SteviaContext.getParam("chromeExtensions").split(","));
for (String path : extensionPaths) {
LOG.info("Use chrome with extension: " + path);
options.addExtensions(new File(path));
}
}
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("iexplorer") == 0) {
LOG.info("Debug OFF, using a RemoteWebDriver with Internet Explorer capabilities");
desiredCapabilities = DesiredCapabilities.internetExplorer();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("safari") == 0) {
LOG.info("Debug OFF, using a RemoteWebDriver with Safari capabilities");
desiredCapabilities = DesiredCapabilities.safari();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("opera") == 0) {
LOG.info("Debug OFF, using a RemoteWebDriver with Opera capabilities");
desiredCapabilities = DesiredCapabilities.opera();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("phantomjs") == 0) {
LOG.info("Debug OFF, using phantomjs driver");
desiredCapabilities = DesiredCapabilities.phantomjs();
} else {
throw new IllegalArgumentException(SteviaWebControllerFactory.WRONG_BROWSER_PARAMETER);
}
if (!StringUtils.isEmpty(SteviaContext.getParam("browserVersion"))) {
LOG.info("Version: " + SteviaContext.getParam("browserVersion"));
desiredCapabilities.setVersion(SteviaContext.getParam("browserVersion"));
}
if (!StringUtils.isEmpty(SteviaContext.getParam("platform"))) {
LOG.info("Operating System: " + SteviaContext.getParam("platform"));
desiredCapabilities.setPlatform(Platform.valueOf(SteviaContext.getParam("platform")));
}
if (!StringUtils.isEmpty(SteviaContext.getParam("recordVideo"))) {
String record_video = SteviaContext.getParam("recordVideo");
LOG.info("Set recording video to: " + SteviaContext.getParam("recordVideo"));
if (record_video.equalsIgnoreCase("True")) {
desiredCapabilities.setCapability("video", "True");
} else {
desiredCapabilities.setCapability("video", "False");
}
}
final DesiredCapabilities wdCapabilities = desiredCapabilities;
final String wdHost = SteviaContext.getParam(SteviaWebControllerFactory.RC_HOST) + ":" + SteviaContext.getParam(SteviaWebControllerFactory.RC_PORT);
CompletableFuture<WebDriver> wd = CompletableFuture.supplyAsync(() -> getRemoteWebDriver(wdHost, wdCapabilities));
try {
driver = wd.get(Integer.valueOf(SteviaContext.getParam("nodeTimeout")), TimeUnit.MINUTES);
} catch (InterruptedException | ExecutionException e) {
LOG.error(e.getMessage());
} catch (TimeoutException e) {
throw new RuntimeException("Timeout of " + Integer.valueOf(SteviaContext.getParam("nodeTimeout")) + " minutes reached waiting for a hub node to receive the request");
}
((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
}
if (SteviaContext.getParam(SteviaWebControllerFactory.TARGET_HOST_URL) != null) {
driver.get(SteviaContext.getParam(SteviaWebControllerFactory.TARGET_HOST_URL));
}
// driver.manage().window().maximize();
wdController.setDriver(driver);
if (SteviaContext.getParam(SteviaWebControllerFactory.ACTIONS_LOGGING).compareTo(SteviaWebControllerFactory.TRUE) == 0) {
wdController.enableActionsLogging();
}
return wdController;
}
@Override
public String getBeanName() {
return "webDriverController";
}
private WebDriver getRemoteWebDriver(String rcHost, DesiredCapabilities desiredCapabilities) {
WebDriver driver;
Augmenter augmenter = new Augmenter(); // adds screenshot capability to a default webdriver.
try {
driver = augmenter.augment(new RemoteWebDriver(new URL("http://" + rcHost + "/wd/hub"), desiredCapabilities));
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
return driver;
}
private WebDriver setUpFirefoxDriver() {
WebDriver driver;
String profileToUse = SteviaContext.getParam(SteviaWebControllerFactory.PROFILE);
if (profileToUse == null || profileToUse.isEmpty()) {
LOG.info("Debug enabled, using Firefox Driver");
driver = new FirefoxDriver();
} else {
LOG.info("Debug enabled, using a local Firefox profile {} with FirefoxDriver", profileToUse);
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile ffProfile = allProfiles.getProfile(profileToUse);
driver = new FirefoxDriver(ffProfile);
}
return driver;
}
private WebDriver setUpChromeDriver() {
WebDriver driver = null;
LOG.info("Debug enabled, using ChromeDriver");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
//Added support for headless chrome mode
if (SteviaContext.getParam("headlessChrome").equals("true")) {
options.addArguments("--headless");
}
if (SteviaContext.getParam("chromeExtensions") != null) {
List<String> extensionPaths = Arrays.asList(SteviaContext.getParam("chromeExtensions").split(","));
for (String path : extensionPaths) {
LOG.info("Use chrome with extension: " + path);
options.addExtensions(new File(path));
}
}
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
CompletableFuture<WebDriver> wd = CompletableFuture.supplyAsync(() -> getChromeDriver(capabilities));
try {
driver = wd.get(Integer.valueOf(SteviaContext.getParam("nodeTimeout")), TimeUnit.MINUTES);
} catch (InterruptedException | ExecutionException e) {
LOG.error(e.getMessage());
} catch (TimeoutException e) {
throw new RuntimeException("Timeout of " + Integer.valueOf(SteviaContext.getParam("nodeTimeout")) + " minutes reached waiting for a local chrome to come up");
}
return driver;
}
private WebDriver getChromeDriver(DesiredCapabilities desiredCapabilities) {
return new ChromeDriver(desiredCapabilities);
}
}
|
package com.persado.oss.quality.stevia.selenium.core.controllers.factories;
import com.persado.oss.quality.stevia.selenium.core.SteviaContext;
import com.persado.oss.quality.stevia.selenium.core.WebController;
import com.persado.oss.quality.stevia.selenium.core.controllers.SteviaWebControllerFactory;
import com.persado.oss.quality.stevia.selenium.core.controllers.WebDriverWebController;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.opera.OperaOptions;
import org.openqa.selenium.remote.AbstractDriverOptions;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class WebDriverWebControllerFactoryImpl implements WebControllerFactory {
DevTools devTools;
private static final Logger LOG = LoggerFactory.getLogger(WebDriverWebControllerFactoryImpl.class);
@Override
public WebController initialize(ApplicationContext context, WebController controller) {
Proxy proxy = null;
WebDriver driver;
if(SteviaContext.getParam(SteviaWebControllerFactory.PROXY) != null) {//security testing - ZAP
proxy = new Proxy();
proxy.setHttpProxy(SteviaContext.getParam(SteviaWebControllerFactory.PROXY));
proxy.setSslProxy(SteviaContext.getParam(SteviaWebControllerFactory.PROXY));
}
WebDriverWebController wdController = (WebDriverWebController) controller;
if (SteviaContext.getParam(SteviaWebControllerFactory.DEBUGGING).compareTo(SteviaWebControllerFactory.TRUE) == 0) { // debug=on
if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER) == null || SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("firefox") == 0
|| SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).isEmpty()) {
FirefoxOptions options = new FirefoxOptions();
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);//Default Normal
if(SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY) != null && !SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY).equals("normal"))
options.setCapability(CapabilityType.PAGE_LOAD_STRATEGY,SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY));
//security testing - ZAP
if(proxy != null){options.setCapability("proxy",proxy);}
LOG.info("Debug enabled, using Firefox and options : "+options);
driver = new FirefoxDriver(options);
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("chrome") == 0) {
ChromeOptions options = new ChromeOptions();
//Ignore certifications - insecure for zap
options.addArguments("--ignore-certificate-errors");
options.addArguments("start-maximized");
options.addArguments("test-type");
options.addArguments("--disable-backgrounding-occluded-windows");
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);//Default None
if(SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY) != null && !SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY).equals("normal"))
options.setCapability(CapabilityType.PAGE_LOAD_STRATEGY,SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY));
//security testing - ZAP
if(proxy != null){options.setCapability("proxy",proxy);}
LOG.info("Debug enabled, using ChromeDriver and options : "+options);
driver = new ChromeDriver(options);
mockingGeolocation((ChromeDriver) driver);
simulateDeviceDimension((ChromeDriver) driver);
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("iexplorer") == 0) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);//Default Normal
if(SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY) != null && !SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY).equals("normal"))
options.setCapability(CapabilityType.PAGE_LOAD_STRATEGY,SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY));
LOG.info("Debug enabled, using InternetExplorer and options : "+options);
driver = new InternetExplorerDriver(options);
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("safari") == 0) {
SafariOptions options = new SafariOptions();
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);//Default Normal
if(SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY) != null && !SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY).equals("normal"))
options.setCapability(CapabilityType.PAGE_LOAD_STRATEGY,SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY));
LOG.info("Debug enabled, using Safari and options : "+options);
driver = new SafariDriver(options);
} else {
throw new IllegalArgumentException(SteviaWebControllerFactory.WRONG_BROWSER_PARAMETER);
}
} else { // debug=off
AbstractDriverOptions browserOptions;
if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER) == null || SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("firefox") == 0
|| SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).isEmpty()) {
LOG.info("Debug OFF, using a RemoteWebDriver with Firefox options");
browserOptions = new FirefoxOptions();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("chrome") == 0) {
LOG.info("Debug OFF, using a RemoteWebDriver with Chrome options");
browserOptions = new ChromeOptions();
((ChromeOptions) browserOptions).addArguments("--ignore-certificate-errors");
((ChromeOptions) browserOptions).addArguments("start-maximized");
((ChromeOptions) browserOptions).addArguments("test-type");
((ChromeOptions) browserOptions).addArguments("test-type");
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("iexplorer") == 0) {
LOG.info("Debug OFF, using a RemoteWebDriver with Internet Explorer options");
browserOptions = new InternetExplorerOptions();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("safari") == 0) {
LOG.info("Debug OFF, using a RemoteWebDriver with Safari options");
browserOptions = new SafariOptions();
} else if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("opera") == 0) {
LOG.info("Debug OFF, using a RemoteWebDriver with Opera options");
browserOptions = new OperaOptions();
} else {
throw new IllegalArgumentException(SteviaWebControllerFactory.WRONG_BROWSER_PARAMETER);
}
browserOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);//Default Normal
if(SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY) != null && !SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY).equals("normal"))
browserOptions.setCapability(CapabilityType.PAGE_LOAD_STRATEGY,SteviaContext.getParam(SteviaWebControllerFactory.LOAD_STRATEGY));
if(proxy != null){browserOptions.setCapability("proxy",proxy);}
browserOptions.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
browserOptions.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS,true);
if(SteviaContext.getParam(SteviaWebControllerFactory.BROWSER_VERSION) != null){
browserOptions.setBrowserVersion(SteviaContext.getParam(SteviaWebControllerFactory.BROWSER_VERSION));
}
browserOptions.setCapability("enableVideo", true); //By default enabed Selenoid video
if(SteviaContext.getParam(SteviaWebControllerFactory.SELENOID_VIDEO) != null){
browserOptions.setCapability("enableVideo", Boolean.parseBoolean(SteviaContext.getParam(SteviaWebControllerFactory.SELENOID_VIDEO))); //Selenoid video
}
browserOptions.setCapability("enableVNC", true); //Selenoid
browserOptions.setCapability("labels", Map.<String, Object>of( //Selenoid manual session so that we can delete it
"manual", "true"
));
Augmenter augmenter = new Augmenter(); // adds screenshot capability to a default webdriver.
try {
driver = augmenter.augment(new RemoteWebDriver(new URL("http://" + SteviaContext.getParam(SteviaWebControllerFactory.RC_HOST) + ":" + SteviaContext.getParam(SteviaWebControllerFactory.RC_PORT)
+ "/wd/hub"), browserOptions));
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
LOG.info("Debug OFF, Remote Web Driver options are: "+browserOptions);
}
// if (SteviaContext.getParam(SteviaWebControllerFactory.BROWSER).compareTo("chrome") == 0) {
// mockingGeolocation((ChromeDriver) driver);
// simulateDeviceDimension((ChromeDriver) driver);
// if (SteviaContext.getParam(SteviaWebControllerFactory.TARGET_HOST_URL) != null) {
// driver.get(SteviaContext.getParam(SteviaWebControllerFactory.TARGET_HOST_URL));
// driver.manage().window().maximize();
wdController.setDriver(driver);
if (SteviaContext.getParam(SteviaWebControllerFactory.ACTIONS_LOGGING).compareTo(SteviaWebControllerFactory.TRUE) == 0) {
wdController.enableActionsLogging();
}
return wdController;
}
@Override
public String getBeanName() {
return "webDriverController";
}
/*
Use for Testing the location-based functionality of applications such as different offers, currencies, taxation rules,
freight charges and date/time format for various geolocations.
Optional keys -> need values if key is specified
*/
private void mockingGeolocation(ChromeDriver driver) {
if (SteviaContext.getParam(SteviaWebControllerFactory.LATITUDE) != null) {
Map location = new HashMap();
location.put("latitude",Double.parseDouble(SteviaContext.getParam(SteviaWebControllerFactory.LATITUDE)));
if (SteviaContext.getParam(SteviaWebControllerFactory.LONGITUDE) != null)
location.put("longitude",Double.parseDouble(SteviaContext.getParam(SteviaWebControllerFactory.LONGITUDE)));
if (SteviaContext.getParam(SteviaWebControllerFactory.ACCURACY) != null)
location.put("accuracy",Double.parseDouble(SteviaContext.getParam(SteviaWebControllerFactory.ACCURACY)));
DevTools devTools = driver.getDevTools();
devTools.createSession();
try {
driver.executeCdpCommand("Emulation.setGeolocationOverride", location);
LOG.info("MOCKING GEOLOCATION BY DEV TOOL: with params -> latitude: {},longitude: {},accuracy: {}", SteviaContext.getParam(SteviaWebControllerFactory.LATITUDE), SteviaContext.getParam(SteviaWebControllerFactory.LONGITUDE), SteviaContext.getParam(SteviaWebControllerFactory.ACCURACY));
}catch (InvalidArgumentException e){
LOG.error("SIMULATE DEVICE BY DEV TOOL NOT SET: Invalid parameters values for -> latitude: {},longitude: {},accuracy: {}", SteviaContext.getParam(SteviaWebControllerFactory.LATITUDE), SteviaContext.getParam(SteviaWebControllerFactory.LONGITUDE), SteviaContext.getParam(SteviaWebControllerFactory.ACCURACY));
}
}
}
/*
Overrides the values of device screen dimensions (window.screen.width, window.screen.height,
window.innerWidth, window.innerHeight, and "device-width"/"device-height"-related CSS media query results).
Mandatory keys - pass 0 to disable override
*/
private void simulateDeviceDimension(ChromeDriver driver){
if(SteviaContext.getParam(SteviaWebControllerFactory.WIDTH) != null) {
Map metrics = new HashMap();
metrics.put("width", Integer.parseInt(SteviaContext.getParam(SteviaWebControllerFactory.WIDTH)));
if(SteviaContext.getParam(SteviaWebControllerFactory.HEIGHT) != null)
metrics.put("height", Integer.parseInt(SteviaContext.getParam(SteviaWebControllerFactory.HEIGHT)));
if(SteviaContext.getParam(SteviaWebControllerFactory.DEVICE_TYPE) != null)
metrics.put("mobile", Boolean.parseBoolean(SteviaContext.getParam(SteviaWebControllerFactory.DEVICE_TYPE)));
if(SteviaContext.getParam(SteviaWebControllerFactory.DEVICE_SCALE_FACTOR) != null)
metrics.put("deviceScaleFactor", Integer.parseInt(SteviaContext.getParam(SteviaWebControllerFactory.DEVICE_SCALE_FACTOR)));
if (devTools == null) {
devTools = driver.getDevTools();
devTools.createSession();
}
try {
driver.executeCdpCommand("Emulation.setDeviceMetricsOverride", metrics);
LOG.info("SIMULATE DEVICE BY DEV TOOL: with params : {},{},{},{}", SteviaContext.getParam(SteviaWebControllerFactory.WIDTH), SteviaContext.getParam(SteviaWebControllerFactory.HEIGHT), SteviaContext.getParam(SteviaWebControllerFactory.DEVICE_TYPE),SteviaContext.getParam(SteviaWebControllerFactory.DEVICE_SCALE_FACTOR));
} catch (InvalidArgumentException e) {
LOG.error("SIMULATE DEVICE BY DEV TOOL NOT SET: Invalid parameters for simulate DEVICE, you need the mandatory ones: {},{},{},{}", "width", "height", "mobile", "deviceScaleFactor");
}
}
}
}
|
package org.apache.streams.twitter.provider;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Queues;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.typesafe.config.Config;
import org.apache.streams.config.StreamsConfigurator;
import org.apache.streams.core.StreamsDatum;
import org.apache.streams.core.StreamsProvider;
import org.apache.streams.core.StreamsResultSet;
import org.apache.streams.twitter.TwitterStreamConfiguration;
import org.apache.streams.util.ComponentUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.json.DataObjectFactory;
import java.io.Serializable;
import java.lang.Math;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TwitterTimelineProvider implements StreamsProvider, Serializable {
public final static String STREAMS_ID = "TwitterTimelineProvider";
private final static Logger LOGGER = LoggerFactory.getLogger(TwitterTimelineProvider.class);
private TwitterStreamConfiguration config;
private Class klass;
public TwitterStreamConfiguration getConfig() {
return config;
}
public void setConfig(TwitterStreamConfiguration config) {
this.config = config;
}
protected final Queue<StreamsDatum> providerQueue = Queues.synchronizedQueue(new ArrayBlockingQueue<StreamsDatum>(5000));
protected int idsCount;
protected Twitter client;
protected Iterator<Long> ids;
protected ListeningExecutorService executor;
protected DateTime start;
protected DateTime end;
Boolean jsonStoreEnabled;
Boolean includeEntitiesEnabled;
private static ExecutorService newFixedThreadPoolWithQueueSize(int nThreads, int queueSize) {
return new ThreadPoolExecutor(nThreads, nThreads,
5000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(queueSize, true), new ThreadPoolExecutor.CallerRunsPolicy());
}
public TwitterTimelineProvider() {
Config config = StreamsConfigurator.config.getConfig("twitter");
this.config = TwitterStreamConfigurator.detectConfiguration(config);
}
public TwitterTimelineProvider(TwitterStreamConfiguration config) {
this.config = config;
}
public TwitterTimelineProvider(Class klass) {
Config config = StreamsConfigurator.config.getConfig("twitter");
this.config = TwitterStreamConfigurator.detectConfiguration(config);
this.klass = klass;
}
public TwitterTimelineProvider(TwitterStreamConfiguration config, Class klass) {
this.config = config;
this.klass = klass;
}
public Queue<StreamsDatum> getProviderQueue() {
return this.providerQueue;
}
@Override
public void startStream() {
LOGGER.debug("{} startStream", STREAMS_ID);
throw new org.apache.commons.lang.NotImplementedException();
}
protected void captureTimeline(long currentId) {
Paging paging = new Paging(1, 200);
List<Status> statuses = null;
boolean KeepGoing = true;
boolean hadFailure = false;
do
{
int keepTrying = 0;
// keep trying to load, give it 5 attempts.
//while (keepTrying < 10)
while (keepTrying < 1)
{
try
{
statuses = client.getUserTimeline(currentId, paging);
for (Status tStat : statuses) {
String json = TwitterObjectFactory.getRawJSON(tStat);
ComponentUtils.offerUntilSuccess(new StreamsDatum(json), providerQueue);
}
paging.setPage(paging.getPage() + 1);
keepTrying = 10;
}
catch(TwitterException twitterException) {
keepTrying += TwitterErrorHandler.handleTwitterError(client, twitterException);
}
catch(Exception e) {
keepTrying += TwitterErrorHandler.handleTwitterError(client, e);
}
}
}
while (shouldContinuePulling(statuses));
}
private Map<Long, Long> userPullInfo;
protected boolean shouldContinuePulling(List<Status> statuses) {
return (statuses != null) && (statuses.size() > 0);
}
private void sleep()
{
Thread.yield();
try {
// wait one tenth of a millisecond
Thread.yield();
Thread.sleep(1);
Thread.yield();
}
catch(IllegalArgumentException e) {
// passing in static values, this will never happen
}
catch(InterruptedException e) {
// noOp, there must have been an issue sleeping
}
Thread.yield();
}
public StreamsResultSet readCurrent() {
LOGGER.debug("{} readCurrent", STREAMS_ID);
Preconditions.checkArgument(ids.hasNext());
StreamsResultSet current;
synchronized( TwitterTimelineProvider.class ) {
while( ids.hasNext() ) {
Long currentId = ids.next();
LOGGER.info("Provider Task Starting: {}", currentId);
captureTimeline(currentId);
}
}
LOGGER.info("Finished. Cleaning up...");
LOGGER.info("Providing {} docs", providerQueue.size());
StreamsResultSet result = new StreamsResultSet(providerQueue);
LOGGER.info("Exiting");
return result;
}
public StreamsResultSet readNew(BigInteger sequence) {
LOGGER.debug("{} readNew", STREAMS_ID);
throw new NotImplementedException();
}
public StreamsResultSet readRange(DateTime start, DateTime end) {
LOGGER.debug("{} readRange", STREAMS_ID);
throw new NotImplementedException();
}
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(10, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
@Override
public void prepare(Object o) {
executor = MoreExecutors.listeningDecorator(newFixedThreadPoolWithQueueSize(5, 20));
Preconditions.checkNotNull(providerQueue);
Preconditions.checkNotNull(this.klass);
Preconditions.checkNotNull(config.getOauth().getConsumerKey());
Preconditions.checkNotNull(config.getOauth().getConsumerSecret());
Preconditions.checkNotNull(config.getOauth().getAccessToken());
Preconditions.checkNotNull(config.getOauth().getAccessTokenSecret());
Preconditions.checkNotNull(config.getFollow());
idsCount = config.getFollow().size();
ids = config.getFollow().iterator();
jsonStoreEnabled = Optional.fromNullable(new Boolean(Boolean.parseBoolean(config.getJsonStoreEnabled()))).or(true);
includeEntitiesEnabled = Optional.fromNullable(new Boolean(Boolean.parseBoolean(config.getIncludeEntities()))).or(true);
client = getTwitterClient();
}
protected Twitter getTwitterClient()
{
String baseUrl = "https://api.twitter.com:443/1.1/";
ConfigurationBuilder builder = new ConfigurationBuilder()
.setOAuthConsumerKey(config.getOauth().getConsumerKey())
.setOAuthConsumerSecret(config.getOauth().getConsumerSecret())
.setOAuthAccessToken(config.getOauth().getAccessToken())
.setOAuthAccessTokenSecret(config.getOauth().getAccessTokenSecret())
.setIncludeEntitiesEnabled(includeEntitiesEnabled)
.setJSONStoreEnabled(jsonStoreEnabled)
.setAsyncNumThreads(3)
.setRestBaseURL(baseUrl)
.setIncludeMyRetweetEnabled(Boolean.TRUE)
.setPrettyDebugEnabled(Boolean.TRUE);
return new TwitterFactory(builder.build()).getInstance();
}
@Override
public void cleanUp() {
shutdownAndAwaitTermination(executor);
}
}
|
package org.eclipse.birt.report.tests.model.regression;
import org.eclipse.birt.report.model.api.ElementFactory;
import org.eclipse.birt.report.model.api.TableGroupHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.command.NameException;
import org.eclipse.birt.report.tests.model.BaseTestCase;
/**
* Regression description:
* </p>
* No exception for two group element with the same names
* </p>
* Test description:
* <p>
* Add two groups with the same name to the table, NameException should be thrown out
* </p>
*/
public class Regression_73182 extends BaseTestCase
{
private final static String INPUT = "Regression_73182.xml"; //$NON-NLS-1$
/**
* @throws Exception
*/
public void test_73182( ) throws Exception
{
openDesign( INPUT );
TableHandle table = (TableHandle) designHandle.findElement( "table" ); //$NON-NLS-1$
ElementFactory factory = designHandle.getElementFactory( );
TableGroupHandle group1 = factory.newTableGroup( );
group1.setName( "group1" ); //$NON-NLS-1$
TableGroupHandle group2 = factory.newTableGroup( );
table.getGroups( ).add( group1 );
table.getGroups( ).add( group2 );
try
{
group2.setName( "group1" ); //$NON-NLS-1$
table.getGroups( ).add( group2 );
fail( );
}
catch ( NameException e )
{
assertNotNull( e );
}
}
}
|
package network.thunder.core.communication.processor.implementations.gossip;
import network.thunder.core.communication.Message;
import network.thunder.core.communication.objects.messages.MessageExecutor;
import network.thunder.core.communication.objects.messages.impl.message.gossip.GossipGetMessage;
import network.thunder.core.communication.objects.messages.impl.message.gossip.GossipInvMessage;
import network.thunder.core.communication.objects.messages.impl.message.gossip.GossipSendMessage;
import network.thunder.core.communication.objects.messages.impl.message.gossip.objects.P2PDataObject;
import network.thunder.core.communication.objects.messages.impl.message.gossip.objects.PubkeyIPObject;
import network.thunder.core.communication.objects.messages.interfaces.factories.GossipMessageFactory;
import network.thunder.core.communication.objects.messages.interfaces.message.gossip.Gossip;
import network.thunder.core.communication.processor.interfaces.GossipProcessor;
import network.thunder.core.database.DBHandler;
import network.thunder.core.etc.Tools;
import network.thunder.core.mesh.Node;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GossipProcessorImpl extends GossipProcessor {
GossipMessageFactory messageFactory;
GossipSubject subject;
DBHandler dbHandler;
Node node;
MessageExecutor messageExecutor;
List<P2PDataObject> objectList = new ArrayList<>();
List<P2PDataObject> objectListTemp = new ArrayList<>();
boolean firstMessage = true;
int randomNumber;
public GossipProcessorImpl (GossipMessageFactory messageFactory, GossipSubject subject, DBHandler dbHandler, Node
node) {
this.messageFactory = messageFactory;
this.subject = subject;
this.dbHandler = dbHandler;
this.node = node;
}
@Override
public void onInboundMessage (Message message) {
if (message instanceof Gossip) {
consumeMessage(message);
} else {
messageExecutor.sendMessageDownwards(message);
}
}
@Override
public void onOutboundMessage (Message message) {
this.messageExecutor.sendMessageUpwards(message);
}
@Override
public void onLayerActive (MessageExecutor messageExecutor) {
this.messageExecutor = messageExecutor;
subject.registerObserver(this);
sendOwnIPAddress();
}
@Override
public void onLayerClose () {
subject.removeObserver(this);
}
@Override
public void update (List<P2PDataObject> newObjectList) {
for (P2PDataObject object : newObjectList) {
if (!objectList.contains(object)) {
objectList.add(object);
}
}
sendInvMessage();
}
private void consumeMessage (Message message) {
if (message instanceof GossipInvMessage) {
processGossipInvMessage(message);
} else if (message instanceof GossipSendMessage) {
processGossipSendMessage(message);
} else if (message instanceof GossipGetMessage) {
processGossipGetMessage(message);
} else {
throw new UnsupportedOperationException("Don't know this Gossip Message: " + message);
}
}
private void processGossipInvMessage (Message message) {
GossipInvMessage invMessage = (GossipInvMessage) message;
List<byte[]> objectsToGet = new ArrayList<>();
for (byte[] hash : invMessage.inventoryList) {
if (!subject.knowsObjectAlready(hash)) {
objectsToGet.add(hash);
}
}
if (objectsToGet.size() > 0) {
sendGossipGetMessage(objectsToGet);
}
}
private void processGossipSendMessage (Message message) {
GossipSendMessage sendMessage = (GossipSendMessage) message;
subject.newDataObjects(this, sendMessage.dataObjects);
if (firstMessage) {
node.port = sendMessage.pubkeyIPList.get(0).port;
firstMessage = false;
}
}
private void processGossipGetMessage (Message message) {
GossipGetMessage getMessage = (GossipGetMessage) message;
sendGossipSendMessage(getMessage.inventoryList);
}
private void sendInvMessage () {
if (objectList.size() > OBJECT_AMOUNT_TO_SEND) {
List<byte[]> hashList = translateP2PDataObjectListToHashList(objectList);
Message invMessage = messageFactory.getGossipInvMessage(hashList);
messageExecutor.sendMessageUpwards(invMessage);
swapLists();
}
}
private void sendOwnIPAddress () {
PubkeyIPObject pubkeyIPObject = new PubkeyIPObject();
pubkeyIPObject.pubkey = node.pubKeyServer.getPubKey();
pubkeyIPObject.port = node.portServer;
pubkeyIPObject.IP = node.hostServer;
pubkeyIPObject.timestamp = Tools.currentTimeFlooredToCurrentDay();
pubkeyIPObject.sign(node.pubKeyServer);
List<P2PDataObject> ipAddresses = new ArrayList<>();
ipAddresses.add(pubkeyIPObject);
Message gossipSendMessage = messageFactory.getGossipSendMessage(ipAddresses);
messageExecutor.sendMessageUpwards(gossipSendMessage);
}
private void sendGossipSendMessage (List<byte[]> objectsToSend) {
List<P2PDataObject> listToSend = buildObjectList(objectsToSend);
Message gossipSendMessage = messageFactory.getGossipSendMessage(listToSend);
messageExecutor.sendMessageUpwards(gossipSendMessage);
}
private void sendGossipGetMessage (List<byte[]> objectsToGet) {
Message gossipGetMessage = messageFactory.getGossipGetMessage(objectsToGet);
messageExecutor.sendMessageUpwards(gossipGetMessage);
}
private List<P2PDataObject> buildObjectList (List<byte[]> objectsToSend) {
List<P2PDataObject> listToSend = new ArrayList<>();
for (byte[] hash : objectsToSend) {
addP2PObjectToList(hash, listToSend);
}
return listToSend;
}
private void addP2PObjectToList (byte[] hash, List<P2PDataObject> objectListToAdd) {
for (P2PDataObject object : objectList) {
if (Arrays.equals(object.getHash(), hash)) {
objectListToAdd.add(object);
return;
}
}
for (P2PDataObject object : objectListTemp) {
if (Arrays.equals(object.getHash(), hash)) {
objectListToAdd.add(object);
return;
}
}
P2PDataObject object = dbHandler.getP2PDataObjectByHash(hash);
if (object != null) {
objectListToAdd.add(object);
return;
}
}
private void swapLists () {
objectListTemp.clear();
objectListTemp.addAll(objectList);
objectList.clear();
}
private List<byte[]> translateP2PDataObjectListToHashList (List<P2PDataObject> objectList) {
List<byte[]> hashList = new ArrayList<>();
for (P2PDataObject object : objectList) {
hashList.add(object.getHash());
}
return hashList;
}
}
|
package ncku.hpds.hadoop.fedhdfs;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsStatus;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.util.StringUtils;
import org.w3c.dom.Element;
public class DynamicHdfsClientRellocater {
public static void main(String[] args) throws Throwable {
// TODO Auto-generated method stub
String file = args[0];
//File XMfile = new File("etc/hadoop/fedhadoop-clusters.xml");
//TopcloudSelector top = new TopcloudSelector(XMfile, Alex);
TopcloudSelector top = new TopcloudSelector(file);
System.out.println("ANS :" + top.getTopCloud());
}
}
|
package org.xwiki.cache.util;
import javax.swing.event.EventListenerList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.cache.Cache;
import org.xwiki.cache.DisposableCacheValue;
import org.xwiki.cache.config.CacheConfiguration;
import org.xwiki.cache.event.CacheEntryEvent;
import org.xwiki.cache.event.CacheEntryListener;
/**
* Base class for {@link Cache} implementations. It provides events {@link DisposableCacheValue} management.
*
* @param <T>
* @version $Id$
*/
public abstract class AbstractCache<T> implements Cache<T>
{
/**
* The logger to use to log.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCache.class);
/**
* The configuration used to create the cache.
*/
protected CacheConfiguration configuration;
/**
* The list of listener to called when events appends on a cache entry.
*/
protected final EventListenerList cacheEntryListeners = new EventListenerList();
@Override
public void dispose()
{
for (CacheEntryListener<T> listener : this.cacheEntryListeners.getListeners(CacheEntryListener.class)) {
this.cacheEntryListeners.remove(CacheEntryListener.class, listener);
}
}
@Override
public void addCacheEntryListener(CacheEntryListener<T> listener)
{
this.cacheEntryListeners.add(CacheEntryListener.class, listener);
}
@Override
public void removeCacheEntryListener(CacheEntryListener<T> listener)
{
cacheEntryListeners.remove(CacheEntryListener.class, listener);
}
/**
* Helper method to send event when a new cache entry is inserted.
*
* @param event the event to send.
*/
protected void sendEntryAddedEvent(CacheEntryEvent<T> event)
{
for (org.xwiki.cache.event.CacheEntryListener<T> listener : this.cacheEntryListeners
.getListeners(org.xwiki.cache.event.CacheEntryListener.class)) {
listener.cacheEntryAdded(event);
}
}
/**
* Helper method to send event when an existing cache entry is removed.
*
* @param event the event to send.
*/
protected void sendEntryRemovedEvent(CacheEntryEvent<T> event)
{
for (org.xwiki.cache.event.CacheEntryListener<T> listener : this.cacheEntryListeners
.getListeners(org.xwiki.cache.event.CacheEntryListener.class)) {
listener.cacheEntryRemoved(event);
}
disposeCacheValue(event.getEntry().getValue());
}
/**
* Helper method to send event when a cache entry is modified.
*
* @param event the event to send.
*/
protected void sendEntryModifiedEvent(CacheEntryEvent<T> event)
{
for (org.xwiki.cache.event.CacheEntryListener<T> listener : this.cacheEntryListeners
.getListeners(org.xwiki.cache.event.CacheEntryListener.class)) {
listener.cacheEntryModified(event);
}
}
/**
* Dispose the value being removed from the cache.
*
* @param value the value to dispose
*/
protected void disposeCacheValue(T value)
{
if (value instanceof DisposableCacheValue) {
try {
((DisposableCacheValue) value).dispose();
} catch (Throwable e) {
LOGGER.warn("Error when trying to dispose a cache object of cache [{}]",
this.configuration.getConfigurationId(), e);
}
}
}
}
|
package com.marshalchen.ua.common.commonUtils.moduleUtils;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.marshalchen.ua.common.commonUtils.logUtils.Logs;
/**
* A webview which can open url by itself and can show some error message when receive error
*/
public class SampleWebViewClient extends WebViewClient {
String showErrorString = "<html><body><h1>" + "Network error" + "</h1></body></html>";
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
view.loadDataWithBaseURL("", showErrorString, "text/html", "utf-8", null);
}
public String getShowErrorString() {
return showErrorString;
}
public void setShowErrorString(String showErrorString) {
this.showErrorString = showErrorString;
}
}
|
package extracells.localization;
public enum Localization
{
US("en_US"), GERMAN("de_DE"), CHINESE("zn_CH"), RUSSIAN("ru_RU");
private final String locale;
Localization(String locale)
{
this.locale = locale;
}
public String filename()
{
return String.format("/assets/extracells/lang/%s.xml", locale);
}
public String locale()
{
return locale;
}
}
|
package gui.factories.turtlefactory;
import gui.componentdrawers.TurtleScreenDrawer;
import gui.mainclasses.workspace.Workspace;
import gui.turtlescreenwrap.CoordinateChanger;
import gui.turtlescreenwrap.TesselationMapper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Map;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import com.sun.javafx.geom.Point2D;
/**
* Represents a turtle node on the screen. Turtles nodes can be selected by the
* user by clicking on them and their position on the screen can be updated
* by incoming drawable objects (the result of user commands).
*
* @author Austin Kyker
*
*/
public class TurtleNode extends ImageView {
private static final String SELECTED_TURTLE_IMAGEPATH =
"./src/resources/guiResources/turtleImages/selected_turtle.png";
private static final String DESELECTED_TURTLE_IMAGEPATH =
"./src/resources/guiResources/turtleImages/deselected_turtle.png";
private static final double TURTLE_IMAGE_WIDTH_RATIO = 0.06;
private static final double TURTLE_IMAGE_WIDTH = TurtleScreenDrawer.GRID_WIDTH *
TURTLE_IMAGE_WIDTH_RATIO;
private static final double TURTLE_IMAGE_HEIGHT_RATIO = 0.06;
private static final double TURTLE_IMAGE_HEIGHT = TurtleScreenDrawer.GRID_HEIGHT *
TURTLE_IMAGE_HEIGHT_RATIO;
private boolean isSelected;
private Workspace myWorkspace;
private String myID;
public TurtleNode (Map<String, String> params, Workspace workspace)
throws FileNotFoundException {
isSelected = true;
myWorkspace = workspace;
myID = params.get(TurtleFactory.TURTLE_ID);
updateImage(SELECTED_TURTLE_IMAGEPATH);
updatePosition(params);
setOnMouseClicked(event -> selectTurtle());
}
/**
* Updates the position of a turtle based on the location parameters specified by the
* params map delivered in the drawable object.
*
* @param params
* @return
*/
public TurtleNode[] updatePosition (Map<String, String> params) {
double[] newLocation = parseStringToPoints(params.get(TurtleFactory.LOCATION));
Point2D dest = new Point2D((float) newLocation[0], (float) newLocation[1]);
dest = TesselationMapper.map(dest);
float x = CoordinateChanger.convX(dest.x);
float y = CoordinateChanger.convY(dest.y);
setLayoutX(x - getBoundsInParent().getWidth() / 2);
setLayoutY(y - getBoundsInParent().getHeight() / 2);
setRotate(Double.parseDouble(params.get(TurtleFactory.HEADING)));
setOpacity(Double.parseDouble(params.get(TurtleFactory.OPACITY)));
return new TurtleNode[] { this };
}
/**
* Converts the location string to a double array of points.
*
* @param point
* @return
*/
private double[] parseStringToPoints (String point) {
String[] splitPoint = point.split(" ");
return new double[] { Double.parseDouble(splitPoint[0]),
Double.parseDouble(splitPoint[1]) };
}
/**
* This method is called when a turtle is clicked. The image of the turtle changes
* to make the user aware that the turtle is selected and can be moved interactively
* using the arrow keys on the keyboard.
*/
private void selectTurtle () {
isSelected = !isSelected;
try {
if (isSelected) {
updateImage(SELECTED_TURTLE_IMAGEPATH);
}
else {
updateImage(DESELECTED_TURTLE_IMAGEPATH);
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myWorkspace.notifyOfTurtleSelectionChange();
}
/**
* Updates the image of the turtle to be the image located at the input
* imagePath
*
* @param imagePath
* @throws FileNotFoundException
*/
protected void updateImage (String imagePath) throws FileNotFoundException {
setImage(new Image(new FileInputStream(new File(imagePath)),
TURTLE_IMAGE_WIDTH, TURTLE_IMAGE_HEIGHT,
false, true));
}
public boolean isSelected () {
return isSelected;
}
public String getTurtleID () {
return myID;
}
}
|
package htsquirrel.database;
import static htsquirrel.FileManagement.*;
import htsquirrel.HTSquirrel;
import htsquirrel.game.Booking;
import htsquirrel.game.Cup;
import htsquirrel.game.Event;
import htsquirrel.game.Goal;
import htsquirrel.game.Injury;
import htsquirrel.game.Match;
import htsquirrel.game.MatchDetails;
import htsquirrel.game.Referee;
import htsquirrel.game.Team;
import htsquirrel.game.User;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
public class DatabaseManagement {
// create database connection
public static Connection createDatabaseConnection()
throws IOException,ClassNotFoundException, SQLException {
deleteDatabaseDir();
String dbUrl = "jdbc:h2:" + getDatabasePathShort();
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection(dbUrl);
return connection;
}
// convert sql code from file to string
public static String sqlToString(String sqlPath) throws IOException {
URL sqlUrl = new URL(HTSquirrel.getClassPath() + sqlPath);
InputStream inputStream = sqlUrl.openStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append(" ");
line = bufferedReader.readLine();
}
return stringBuilder.toString();
}
// check if table exists
public static boolean tableExists(Connection connection, String tableName)
throws SQLException {
boolean tableExists = false;
DatabaseMetaData dbMetaData = connection.getMetaData();
ResultSet resultSet = dbMetaData.getTables(null, null, null, null);
while (resultSet.next()) {
if (tableName.equals(resultSet.getString("TABLE_NAME"))) {
tableExists = true;
}
}
return tableExists;
}
// create missing tables
public static void checkTablesExist(Connection connection)
throws SQLException, IOException {
if (!(tableExists(connection, "TEAMS"))) {
createTeamsTable(connection);
}
if (!(tableExists(connection, "MATCHES"))) {
createMatchesTable(connection);
}
if (!(tableExists(connection, "MATCH_DETAILS"))) {
createMatchDetailsTable(connection);
}
if (!(tableExists(connection, "CUPS"))) {
createCupsTable(connection);
}
if (!(tableExists(connection, "REFEREES"))) {
createRefereesTable(connection);
}
if (!(tableExists(connection, "GOALS"))) {
createGoalsTable(connection);
}
if (!(tableExists(connection, "BOOKINGS"))) {
createBookingsTable(connection);
}
if (!(tableExists(connection, "INJURIES"))) {
createInjuriesTable(connection);
}
if (!(tableExists(connection, "EVENTS"))) {
createEventsTable(connection);
}
if (!(tableExists(connection, "TRANSFERS"))) {
createTransfersTable(connection);
}
}
// create teams table
private static void createTeamsTable(Connection connection)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_teams.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
// create matches table
private static void createMatchesTable(Connection connection)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_matches.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
// create match details table
private static void createMatchDetailsTable(Connection connection)
throws IOException, SQLException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_match_details.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
// create cups table
private static void createCupsTable(Connection connection)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_cups.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
// create referees table
private static void createRefereesTable(Connection connection)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_referees.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
//create goals table
private static void createGoalsTable(Connection connection)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_goals.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
// create bookings table
private static void createBookingsTable(Connection connection)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_bookings.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
// create injuries table
private static void createInjuriesTable(Connection connection)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_injuries.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
// create events table
private static void createEventsTable(Connection connection)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_events.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
// create transfers table
private static void createTransfersTable(Connection connection)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/create_table_transfers.sql");
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
// get team ids
public static ArrayList<Integer> getTeamIds(Connection connection,
int userId) throws SQLException, IOException {
ArrayList<Integer> teamIds = new ArrayList<>();
String sqlCode = "SELECT TEAM_ID FROM TEAMS " +
"WHERE USER_ID = " + userId;
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sqlCode);
while (resultSet.next()) {
teamIds.add(resultSet.getInt("TEAM_ID"));
}
statement.close();
return teamIds;
}
// get league id
public static int getLeagueId(Connection connection, Team team)
throws SQLException {
int leagueId = 1; // TODO check this - returns Sweden
String sqlCode = "SELECT LEAGUE_ID FROM TEAMS " +
"WHERE TEAM_ID = " + team.getTeamId();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sqlCode);
while (resultSet.next()) {
leagueId = resultSet.getInt("LEAGUE_ID");
}
statement.close();
return leagueId;
}
// get last season
public static int getLastSeason(Connection connection, Team team)
throws SQLException {
int lastSeason = 1;
String sqlCode = "SELECT MAX(SEASON) AS LAST_SEASON FROM MATCHES " +
"WHERE TEAM_ID = " + team.getTeamId();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sqlCode);
while (resultSet.next()) {
lastSeason = resultSet.getInt("LAST_SEASON");
}
if (lastSeason == 0) {
lastSeason = 1;
}
statement.close();
return lastSeason;
}
// get last match date
public static Timestamp getLastMatchDate(Connection connection, Team team)
throws SQLException {
Timestamp lastMatchDate = null;
String sqlCode = "SELECT MAX(MATCH_DATE) AS LAST_MATCH_DATE " +
"FROM MATCHES WHERE TEAM_ID = " + team.getTeamId();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sqlCode);
while (resultSet.next()) {
lastMatchDate = resultSet.getTimestamp("LAST_MATCH_DATE");
}
if (lastMatchDate == null) {
lastMatchDate = Timestamp.valueOf("1990-01-01 00:00:00.0");
}
statement.close();
return lastMatchDate;
}
// get missing matches
public static ArrayList<Match> getMissingMatches(Connection connection,
Team team) throws IOException, SQLException {
ArrayList<Match> matches = new ArrayList<>();
String sqlCode = sqlToString("htsquirrel/database/sql/select_missing_matches.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(team.getTeamId()));
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sqlCode);
while (resultSet.next()) {
long matchId = resultSet.getLong("MATCH_ID");
int teamId = resultSet.getInt("TEAM_ID");
String teamName = resultSet.getString("TEAM_NAME");
int opponentTeamId = resultSet.getInt("OPPONENT_TEAM_ID");
String opponentTeamName = resultSet.getString("OPPONENT_TEAM_NAME");
String venue = resultSet.getString("VENUE");
Timestamp matchDate = resultSet.getTimestamp("MATCH_DATE");
int season = resultSet.getInt("SEASON");
int matchType = resultSet.getInt("MATCH_TYPE");
int matchContextId = resultSet.getInt("MATCH_CONTEXT_ID");
int cupLevel = resultSet.getInt("CUP_LEVEL");
int cupLevelIndex = resultSet.getInt("CUP_LEVEL_INDEX");
int goalsFor = resultSet.getInt("GOALS_FOR");
int goalsAgainst = resultSet.getInt("GOALS_AGAINST");
Match match = new Match(matchId, teamId, teamName, opponentTeamId,
opponentTeamName, venue, matchDate, season, matchType,
matchContextId, cupLevel, cupLevelIndex, goalsFor,
goalsAgainst);
matches.add(match);
}
statement.close();
return matches;
}
public static void deleteFromTeams(Connection connection, User user)
throws SQLException, IOException {
String sqlCode = "DELETE FROM TEAMS WHERE USER_ID = " +
user.getUserId();
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void deleteFromCups(Connection connection, Team team)
throws SQLException, IOException {
String sqlCode = "DELETE FROM CUPS WHERE TEAM_ID = " +
team.getTeamId();
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void insertIntoTeams(Connection connection, User user,
Team team) throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/insert_into_teams.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_USER_ID\\b", String.valueOf(user.getUserId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_LOGIN_NAME\\b", user.getLoginName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_SUPPORTER_TIER\\b", user.getSupporterTier().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(team.getTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_NAME\\b", team.getTeamName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_SHORT_TEAM_NAME\\b", team.getShortTeamName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_FOUNDED_DATE\\b", String.valueOf(team.getFoundedDate()));
sqlCode = sqlCode.replaceAll("\\bVALUE_PRIMARY_CLUB\\b", String.valueOf(team.isPrimaryClub()));
sqlCode = sqlCode.replaceAll("\\bVALUE_ARENA_ID\\b", String.valueOf(team.getArenaId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_ARENA_NAME\\b", team.getArenaName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_LEAGUE_ID\\b", String.valueOf(team.getLeagueId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_LEAGUE_NAME\\b", team.getLeagueName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_REGION_ID\\b", String.valueOf(team.getRegionId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_REGION_NAME\\b", team.getRegionName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_COACH_ID\\b", String.valueOf(team.getCoachId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_LEAGUE_LEVEL_UNIT_ID\\b", String.valueOf(team.getLeagueLevelUnitId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_LEAGUE_LEVEL_UNIT_NAME\\b", team.getLeagueLevelUnitName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_LEAGUE_LEVEL\\b", String.valueOf(team.getLeagueLevel()));
sqlCode = sqlCode.replaceAll("\\bVALUE_FANCLUB_ID\\b", String.valueOf(team.getFanclubId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_FANCLUB_NAME\\b", team.getFanclubName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_FANCLUB_SIZE\\b", String.valueOf(team.getFanclubSize()));
sqlCode = sqlCode.replaceAll("\\bVALUE_LOGO_URI\\b", team.getLogoUri().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_DRESS_URI\\b", team.getDressUri().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_DRESS_ALTERNATE_URI\\b", team.getDressAlternateUri().replaceAll("'", "''"));
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void insertIntoMatches(Connection connection, Match match)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/insert_into_matches.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_ID\\b", String.valueOf(match.getMatchId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(match.getTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_NAME\\b", match.getTeamName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_TEAM_ID\\b", String.valueOf(match.getOpponentTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_TEAM_NAME\\b", match.getOpponentTeamName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_VENUE\\b", match.getVenue());
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_DATE\\b", String.valueOf(match.getMatchDate()));
sqlCode = sqlCode.replaceAll("\\bVALUE_SEASON\\b", String.valueOf(match.getSeason()));
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_TYPE\\b", String.valueOf(match.getMatchType()));
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_CONTEXT_ID\\b", String.valueOf(match.getMatchContextId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_CUP_LEVEL\\b", String.valueOf(match.getCupLevel()));
sqlCode = sqlCode.replaceAll("\\bVALUE_CUP_LEVEL_INDEX\\b", String.valueOf(match.getCupLevelIndex()));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOALS_FOR\\b", String.valueOf(match.getGoalsFor()));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOALS_AGAINST\\b", String.valueOf(match.getGoalsAgainst()));
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void insertIntoCups(Connection connection, Cup cup)
throws IOException, SQLException {
String sqlCode = sqlToString("htsquirrel/database/sql/insert_into_cups.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(cup.getTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_TYPE\\b", String.valueOf(cup.getMatchType()));
sqlCode = sqlCode.replaceAll("\\bVALUE_CUP_ID\\b", String.valueOf(cup.getCupId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_CUP_NAME\\b", cup.getCupName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_CUP_LEAGUE_LEVEL\\b", String.valueOf(cup.getCupLeagueLevel()));
sqlCode = sqlCode.replaceAll("\\bVALUE_CUP_LEVEL\\b", String.valueOf(cup.getCupLevel()));
sqlCode = sqlCode.replaceAll("\\bVALUE_CUP_LEVEL_INDEX\\b", String.valueOf(cup.getCupLevelIndex()));
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void insertIntoMatchDetails(Connection connection,
MatchDetails matchDetails) throws IOException, SQLException {
String sqlCode = sqlToString("htsquirrel/database/sql/insert_into_match_details.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_ID\\b", String.valueOf(matchDetails.getMatchId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(matchDetails.getTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_NAME\\b", matchDetails.getTeamName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_TEAM_ID\\b", String.valueOf(matchDetails.getOpponentTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_TEAM_NAME\\b", matchDetails.getOpponentTeamName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOALS_FOR\\b", String.valueOf(matchDetails.getGoalsFor()));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOALS_AGAINST\\b", String.valueOf(matchDetails.getGoalsAgainst()));
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_TYPE\\b", String.valueOf(matchDetails.getMatchType()));
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_CONTEXT_ID\\b", String.valueOf(matchDetails.getMatchContextId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_CUP_LEVEL\\b", String.valueOf(matchDetails.getCupLevel()));
sqlCode = sqlCode.replaceAll("\\bVALUE_CUP_LEVEL_INDEX\\b", String.valueOf(matchDetails.getCupLevelIndex()));
sqlCode = sqlCode.replaceAll("\\bVALUE_SEASON\\b", String.valueOf(matchDetails.getSeason()));
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_DATE\\b", String.valueOf(matchDetails.getMatchDate()));
sqlCode = sqlCode.replaceAll("\\bVALUE_FINISHED_DATE\\b", String.valueOf(matchDetails.getFinishedDate()));
sqlCode = sqlCode.replaceAll("\\bVALUE_VENUE\\b", matchDetails.getVenue());
sqlCode = sqlCode.replaceAll("\\bVALUE_ARENA_ID\\b", String.valueOf(matchDetails.getArenaId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_ARENA_NAME\\b", matchDetails.getArenaName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_SOLD_TOTAL\\b", String.valueOf(matchDetails.getSoldTotal()));
sqlCode = sqlCode.replaceAll("\\bVALUE_SOLD_TERRACES\\b", String.valueOf(matchDetails.getSoldTerraces()));
sqlCode = sqlCode.replaceAll("\\bVALUE_SOLD_BASIC\\b", String.valueOf(matchDetails.getSoldBasic()));
sqlCode = sqlCode.replaceAll("\\bVALUE_SOLD_ROOF\\b", String.valueOf(matchDetails.getSoldRoof()));
sqlCode = sqlCode.replaceAll("\\bVALUE_SOLD_VIP\\b", String.valueOf(matchDetails.getSoldVip()));
sqlCode = sqlCode.replaceAll("\\bVALUE_WEATHER_ID\\b", String.valueOf(matchDetails.getWeatherId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_DRESS_URI\\b", matchDetails.getDressUri().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_FORMATION\\b", matchDetails.getFormation().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_TACTIC_TYPE\\b", String.valueOf(matchDetails.getTacticType()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TACTIC_SKILL\\b", String.valueOf(matchDetails.getTacticSkill()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ATTITUDE\\b", String.valueOf(matchDetails.getTeamAttitude()));
sqlCode = sqlCode.replaceAll("\\bVALUE_RATING_M\\b", String.valueOf(matchDetails.getRatingM()));
sqlCode = sqlCode.replaceAll("\\bVALUE_RATING_RD\\b", String.valueOf(matchDetails.getRatingRD()));
sqlCode = sqlCode.replaceAll("\\bVALUE_RATING_CD\\b", String.valueOf(matchDetails.getRatingCD()));
sqlCode = sqlCode.replaceAll("\\bVALUE_RATING_LD\\b", String.valueOf(matchDetails.getRatingLD()));
sqlCode = sqlCode.replaceAll("\\bVALUE_RATING_RA\\b", String.valueOf(matchDetails.getRatingRA()));
sqlCode = sqlCode.replaceAll("\\bVALUE_RATING_CA\\b", String.valueOf(matchDetails.getRatingCA()));
sqlCode = sqlCode.replaceAll("\\bVALUE_RATING_LA\\b", String.valueOf(matchDetails.getRatingLA()));
sqlCode = sqlCode.replaceAll("\\bVALUE_RATING_ISPD\\b", String.valueOf(matchDetails.getRatingISPD()));
sqlCode = sqlCode.replaceAll("\\bVALUE_RATING_ISPA\\b", String.valueOf(matchDetails.getRatingISPA()));
sqlCode = sqlCode.replaceAll("\\bVALUE_POSSESSION_1\\b", String.valueOf(matchDetails.getPossession1()));
sqlCode = sqlCode.replaceAll("\\bVALUE_POSSESSION_2\\b", String.valueOf(matchDetails.getPossession2()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_DRESS_URI\\b", matchDetails.getOpponentDressUri().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_FORMATION\\b", matchDetails.getOpponentFormation().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_TACTIC_TYPE\\b", String.valueOf(matchDetails.getOpponentTacticType()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_TACTIC_SKILL\\b", String.valueOf(matchDetails.getOpponentTacticSkill()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_RATING_M\\b", String.valueOf(matchDetails.getOpponentRatingM()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_RATING_RD\\b", String.valueOf(matchDetails.getOpponentRatingRD()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_RATING_CD\\b", String.valueOf(matchDetails.getOpponentRatingCD()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_RATING_LD\\b", String.valueOf(matchDetails.getOpponentRatingLD()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_RATING_RA\\b", String.valueOf(matchDetails.getOpponentRatingRA()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_RATING_CA\\b", String.valueOf(matchDetails.getOpponentRatingCA()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_RATING_LA\\b", String.valueOf(matchDetails.getOpponentRatingLA()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_RATING_ISPD\\b", String.valueOf(matchDetails.getOpponentRatingISPD()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_RATING_ISPA\\b", String.valueOf(matchDetails.getOpponentRatingISPA()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_POSSESSION_1\\b", String.valueOf(matchDetails.getOpponentPossession1()));
sqlCode = sqlCode.replaceAll("\\bVALUE_OPPONENT_POSSESSION_2\\b", String.valueOf(matchDetails.getOpponentPossession2()));
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void insertIntoReferees(Connection connection,
Referee referee) throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/insert_into_referees.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_ID\\b", String.valueOf(referee.getMatchId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(referee.getTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_REFEREE_ROLE\\b", String.valueOf(referee.getRefereeRole()));
sqlCode = sqlCode.replaceAll("\\bVALUE_REFEREE_ID\\b", String.valueOf(referee.getRefereeId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_REFEREE_NAME\\b", referee.getRefereeName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_REFEREE_COUNTRY_ID\\b", String.valueOf(referee.getRefereeCountryId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_REFEREE_COUNTRY_NAME\\b", referee.getRefereeCountryName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_REFEREE_TEAM_ID\\b", String.valueOf(referee.getRefereeTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_REFEREE_TEAM_NAME\\b", referee.getRefereeTeamName().replaceAll("'", "''"));
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void insertIntoGoals(Connection connection, Goal goal)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/insert_into_goals.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_ID\\b", String.valueOf(goal.getMatchId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(goal.getTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOAL_INDEX\\b", String.valueOf(goal.getGoalIndex()));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOAL_PLAYER_ID\\b", String.valueOf(goal.getGoalPlayerId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOAL_PLAYER_NAME\\b", goal.getGoalPlayerName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOAL_TEAM_ID\\b", String.valueOf(goal.getGoalTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOAL_GOALS_FOR\\b", String.valueOf(goal.getGoalGoalsFor()));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOAL_GOALS_AGAINST\\b", String.valueOf(goal.getGoalGoalsAgainst()));
sqlCode = sqlCode.replaceAll("\\bVALUE_GOAL_MINUTE\\b", String.valueOf(goal.getGoalMinute()));
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void insertIntoBookings(Connection connection, Booking booking)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/insert_into_bookings.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_ID\\b", String.valueOf(booking.getMatchId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(booking.getTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_BOOKING_INDEX\\b", String.valueOf(booking.getBookingIndex()));
sqlCode = sqlCode.replaceAll("\\bVALUE_BOOKING_PLAYER_ID\\b", String.valueOf(booking.getBookingPlayerId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_BOOKING_PLAYER_NAME\\b", booking.getBookingPlayerName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_BOOKING_TEAM_ID\\b", String.valueOf(booking.getBookingTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_BOOKING_TYPE\\b", String.valueOf(booking.getBookingType()));
sqlCode = sqlCode.replaceAll("\\bVALUE_BOOKING_MINUTE\\b", String.valueOf(booking.getBookingMinute()));
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void insertIntoInjuries(Connection connection, Injury injury)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/insert_into_injuries.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_ID\\b", String.valueOf(injury.getMatchId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(injury.getTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_INJURY_INDEX\\b", String.valueOf(injury.getInjuryIndex()));
sqlCode = sqlCode.replaceAll("\\bVALUE_INJURY_PLAYER_ID\\b", String.valueOf(injury.getInjuryPlayerId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_INJURY_PLAYER_NAME\\b", injury.getInjuryPlayerName().replaceAll("'", "''"));
sqlCode = sqlCode.replaceAll("\\bVALUE_INJURY_TEAM_ID\\b", String.valueOf(injury.getInjuryTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_INJURY_TYPE\\b", String.valueOf(injury.getInjuryType()));
sqlCode = sqlCode.replaceAll("\\bVALUE_INJURY_MINUTE\\b", String.valueOf(injury.getInjuryMinute()));
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
public static void insertIntoEvents(Connection connection, Event event)
throws SQLException, IOException {
String sqlCode = sqlToString("htsquirrel/database/sql/insert_into_events.sql");
sqlCode = sqlCode.replaceAll("\\bVALUE_MATCH_ID\\b", String.valueOf(event.getMatchId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_TEAM_ID\\b", String.valueOf(event.getTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_EVENT_INDEX\\b", String.valueOf(event.getEventIndex()));
sqlCode = sqlCode.replaceAll("\\bVALUE_EVENT_MINUTE\\b", String.valueOf(event.getEventMinute()));
sqlCode = sqlCode.replaceAll("\\bVALUE_EVENT_TYPE\\b", String.valueOf(event.getEventType()));
sqlCode = sqlCode.replaceAll("\\bVALUE_EVENT_VARIATION\\b", String.valueOf(event.getEventVariation()));
sqlCode = sqlCode.replaceAll("\\bVALUE_EVENT_SUBJECT_TEAM_ID\\b", String.valueOf(event.getEventSubjectTeamId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_EVENT_SUBJECT_PLAYER_ID\\b", String.valueOf(event.getEventSubjectPlayerId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_EVENT_OBJECT_PLAYER_ID\\b", String.valueOf(event.getEventObjectPlayerId()));
sqlCode = sqlCode.replaceAll("\\bVALUE_EVENT_TEXT\\b", event.getEventText().replaceAll("'", "''"));
Statement statement = connection.createStatement();
statement.execute(sqlCode);
statement.close();
}
}
|
package io.xchris6041x.devin.gui;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
public class FrameListener implements Listener {
@EventHandler
public void onClick(InventoryClickEvent e) {
if(e.getInventory().getHolder() instanceof FrameHolder) {
FrameHolder holder = (FrameHolder) e.getInventory().getHolder();
if(e.getRawSlot() < holder.getFrame().getRows() * Container.MAX_WIDTH) {
e.setCancelled(true); // This will change when draggable controls are added.
holder.getFrame().onClick(holder, e);
}
else {
e.setCancelled(true);
}
}
}
}
|
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.dobj;
import java.util.AbstractSet;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;
import com.samskivert.util.ArrayUtil;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamable;
import static com.threerings.presents.Log.log;
/**
* The distributed set class provides a means by which an unordered set of objects can be
* maintained as a distributed object field. Entries can be added to and removed from the set,
* requests for which will generate events much like other distributed object fields.
*
* <p> Classes that wish to act as set entries must implement the {@link Entry} interface which
* extends {@link Streamable} and adds the requirement that the object provide a key which will be
* used to identify entry equality. Thus an entry is declared to be in a set of the object returned
* by that entry's {@link Entry#getKey} method is equal (using {@link Object#equals}) to the entry
* returned by the {@link Entry#getKey} method of some other entry in the set. Additionally, in the
* case of entry removal, only the key for the entry to be removed will be transmitted with the
* removal event to save network bandwidth. Lastly, the object returned by {@link Entry#getKey}
* must be a {@link Streamable} type.
*
* @param <E> the type of entry stored in this set.
*/
public class DSet<E extends DSet.Entry>
implements Iterable<E>, Streamable, Cloneable
{
/**
* Entries of the set must implement this interface.
*/
public static interface Entry extends Streamable
{
/**
* Each entry provide an associated key which is used to determine its uniqueness in the
* set. See the {@link DSet} class documentation for further information.
*/
Comparable<?> getKey ();
}
/**
* A quick and easy DSet.Entry that holds some sort of Comparable.
*
* Remember: this type must also be {@link Streamable}.
*/
public static class KeyWrapper<T extends Comparable<?>> implements DSet.Entry
{
public KeyWrapper (T key) {
_key = key;
}
public T getKey () {
return _key;
}
protected T _key;
}
/**
* Creates a new DSet of the appropriate generic type.
*/
public static <E extends DSet.Entry> DSet<E> newDSet ()
{
return new DSet<E>();
}
/**
* Creates a new DSet of the appropriate generic type.
*/
public static <E extends DSet.Entry> DSet<E> newDSet (Iterable<E> source)
{
return new DSet<E>(source);
}
/**
* Compares the first comparable to the second. This is useful to avoid type safety warnings
* when dealing with the keys of {@link DSet.Entry} values.
*/
public static int compare (Comparable<?> c1, Comparable<?> c2)
{
@SuppressWarnings("unchecked") Comparable<Object> cc1 = (Comparable<Object>)c1;
@SuppressWarnings("unchecked") Comparable<Object> cc2 = (Comparable<Object>)c2;
return cc1.compareTo(cc2);
}
/**
* Creates a distributed set and populates it with values from the supplied iterator. This
* should be done before the set is unleashed into the wild distributed object world because no
* associated entry added events will be generated. Additionally, this operation does not check
* for duplicates when adding entries, so one should be sure that the iterator contains only
* unique entries.
*
* @param source an iterator from which we will initially populate the set.
*/
public DSet (Iterable<E> source)
{
for (E e : source) {
add(e);
}
}
/**
* Creates a distributed set and populates it with values from the supplied iterator. This
* should be done before the set is unleashed into the wild distributed object world because no
* associated entry added events will be generated. Additionally, this operation does not check
* for duplicates when adding entries, so one should be sure that the iterator contains only
* unique entries.
*
* @param source an iterator from which we will initially populate the set.
*/
public DSet (Iterator<E> source)
{
while (source.hasNext()) {
add(source.next());
}
}
/**
* Creates a distributed set and populates it with values from the supplied array. This should
* be done before the set is unleashed into the wild distributed object world because no
* associated entry added events will be generated. Additionally, this operation does not check
* for duplicates when adding entries, so one should be sure that the iterator contains only
* unique entries.
*
* @param source an array from which we will initially populate the set.
*/
public DSet (E[] source)
{
for (E element : source) {
if (element != null) {
add(element);
}
}
}
/**
* Constructs an empty distributed set.
*/
public DSet ()
{
}
/**
* Returns the number of entries in this set.
*/
public int size ()
{
return _size;
}
/**
* Returns true if the set contains an entry whose <code>getKey()</code> method returns a key
* that <code>equals()</code> the key returned by <code>getKey()</code> of the supplied
* entry. Returns false otherwise.
*/
public boolean contains (E elem)
{
return containsKey(elem.getKey());
}
/**
* Returns true if an entry in the set has a key that <code>equals()</code> the supplied
* key. Returns false otherwise.
*/
public boolean containsKey (Comparable<?> key)
{
return get(key) != null;
}
/**
* Returns the entry that matches (<code>getKey().equals(key)</code>) the specified key or null
* if no entry could be found that matches the key.
*/
public E get (Comparable<?> key)
{
// determine where we'll be adding the new element
int eidx = ArrayUtil.binarySearch(
_entries, 0, _size, new KeyWrapper<Comparable<?>>(key), ENTRY_COMP);
return (eidx < 0) ? null : _entries[eidx];
}
/**
* Returns an iterator over the entries of this set. It does not support modification (nor
* iteration while modifications are being made to the set). It should not be kept around as it
* can quickly become out of date.
*
* @deprecated
*/
@Deprecated
public Iterator<E> entries ()
{
return iterator();
}
/**
* Returns an iterator over the entries of this set. It does not support modification (nor
* iteration while modifications are being made to the set). It should not be kept around as it
* can quickly become out of date.
*/
public Iterator<E> iterator ()
{
// the crazy sanity checks
if (_size < 0 || _size > _entries.length || (_size > 0 && _entries[_size-1] == null)) {
log.warning("DSet in a bad way", "size", _size, "entries", _entries, new Exception());
}
return new Iterator<E>() {
public boolean hasNext () {
checkComodification();
return (_index < _size);
}
public E next () {
checkComodification();
return _entries[_index++];
}
public void remove () {
throw new UnsupportedOperationException();
}
protected void checkComodification () {
if (_modCount != _expectedModCount) {
throw new ConcurrentModificationException();
}
if (_ssize != _size) {
log.warning("Size changed during iteration", "ssize", _ssize, "nsize", _size,
"entries", _entries, new Exception());
}
}
protected int _index = 0;
protected int _ssize = _size;
protected int _expectedModCount = _modCount;
};
}
/**
* Copies the elements of this distributed set into the supplied array. If the array is not
* large enough to hold all of the elements, as many as fit into the array will be copied. If
* the <code>array</code> argument is null, an object array of sufficient size to contain all
* of the elements of this set will be created and returned.
*/
public E[] toArray (E[] array)
{
if (array == null) {
@SuppressWarnings("unchecked") E[] copy = (E[])new Entry[size()];
array = copy;
}
System.arraycopy(_entries, 0, array, 0, array.length);
return array;
}
/**
* Creates an <b>immutable</b> view of this distributed set as a Java set.
*/
public Set<E> asSet ()
{
return new AbstractSet<E>() {
@Override public boolean add (E o) {
throw new UnsupportedOperationException();
}
@Override public boolean remove (Object o) {
throw new UnsupportedOperationException();
}
@Override public boolean contains (Object o) {
@SuppressWarnings("unchecked") E elem = (E)o;
return DSet.this.contains(elem);
}
@Override public Iterator<E> iterator () {
return DSet.this.iterator();
}
@Override public int size () {
return DSet.this.size();
}
};
}
/**
* @deprecated use {@link #toArray(Entry[])}.
*/
@Deprecated
public Object[] toArray (Object[] array)
{
@SuppressWarnings("unchecked") E[] casted = (E[])array;
return toArray(casted);
}
/**
* Adds the specified entry to the set. This should not be called directly, instead the
* associated <code>addTo{Set}()</code> method should be called on the distributed object that
* contains the set in question.
*
* @return true if the entry was added, false if it was already in the set.
*/
protected boolean add (E elem)
{
// determine where we'll be adding the new element
int eidx = ArrayUtil.binarySearch(_entries, 0, _size, elem, ENTRY_COMP);
// if the element is already in the set, bail now
if (eidx >= 0) {
log.warning("Refusing to add duplicate entry", "entry", elem, "set", this,
new Exception());
return false;
}
// convert the index into happy positive land
eidx = (eidx+1)*-1;
// expand our entries array if necessary
int elength = _entries.length;
if (_size >= elength) {
// sanity check
if (elength > 2048) {
log.warning("Requested to expand to questionably large size", "l", elength,
new Exception());
}
// create a new array and copy our data into it
@SuppressWarnings("unchecked") E[] elems = (E[])new Entry[elength*2];
System.arraycopy(_entries, 0, elems, 0, elength);
_entries = elems;
}
// if the entry doesn't go at the end, shift the elements down to accomodate it
if (eidx < _size) {
System.arraycopy(_entries, eidx, _entries, eidx+1, _size-eidx);
}
// stuff the entry into the array and note that we're bigger
_entries[eidx] = elem;
_size++;
_modCount++;
return true;
}
/**
* Removes the specified entry from the set. This should not be called directly, instead the
* associated <code>removeFrom{Set}()</code> method should be called on the distributed object
* that contains the set in question.
*
* @return true if the entry was removed, false if it was not in the set.
*/
protected boolean remove (E elem)
{
return (null != removeKey(elem.getKey()));
}
/**
* Removes from the set the entry whose key matches the supplied key. This should not be called
* directly, instead the associated <code>removeFrom{Set}()</code> method should be called on
* the distributed object that contains the set in question.
*
* @return the old matching entry if found and removed, null if not found.
*/
protected E removeKey (Comparable<?> key)
{
// don't fail, but generate a warning if we're passed a null key
if (key == null) {
log.warning("Requested to remove null key.", new Exception());
return null;
}
// look up this entry's position in our set
int eidx = ArrayUtil.binarySearch(
_entries, 0, _size, new KeyWrapper<Comparable<?>>(key), ENTRY_COMP);
// if we found it, remove it
if (eidx >= 0) {
// extract the old entry
E oldEntry = _entries[eidx];
_size
if ((_entries.length > INITIAL_CAPACITY) && (_size < _entries.length/8)) {
// if we're using less than 1/8 of our capacity, shrink by half
@SuppressWarnings("unchecked") E[] newEnts = (E[])new Entry[_entries.length/2];
System.arraycopy(_entries, 0, newEnts, 0, eidx);
System.arraycopy(_entries, eidx+1, newEnts, eidx, _size-eidx);
_entries = newEnts;
} else {
// shift entries past the removed one downwards
System.arraycopy(_entries, eidx+1, _entries, eidx, _size-eidx);
_entries[_size] = null;
}
_modCount++;
return oldEntry;
} else {
return null;
}
}
/**
* Updates the specified entry by locating an entry whose key matches the key of the supplied
* entry and overwriting it. This should not be called directly, instead the associated
* <code>update{Set}()</code> method should be called on the distributed object that contains
* the set in question.
*
* @return the old entry that was replaced, or null if it was not found (in which case nothing
* is updated).
*/
protected E update (E elem)
{
// look up this entry's position in our set
int eidx = ArrayUtil.binarySearch(_entries, 0, _size, elem, ENTRY_COMP);
// if we found it, update it
if (eidx >= 0) {
E oldEntry = _entries[eidx];
_entries[eidx] = elem;
_modCount++;
return oldEntry;
} else {
return null;
}
}
/**
* Generates a shallow copy of this object in a type safe manner.
*/
public DSet<E> typedClone ()
{
try {
@SuppressWarnings("unchecked") DSet<E> nset = (DSet<E>)super.clone();
@SuppressWarnings("unchecked") E[] copy = (E[])new Entry[_entries.length];
nset._entries = copy;
System.arraycopy(_entries, 0, nset._entries, 0, _entries.length);
nset._modCount = 0;
return nset;
} catch (CloneNotSupportedException cnse) {
throw new RuntimeException(cnse);
}
}
/**
* Generates a shallow copy of this object.
*/
@Override
public Object clone ()
{
return typedClone();
}
@Override
public String toString ()
{
StringBuilder buf = new StringBuilder("(");
String prefix = "";
for (E elem : _entries) {
if (elem != null) {
buf.append(prefix);
prefix = ", ";
buf.append(elem);
}
}
buf.append(")");
return buf.toString();
}
/** Custom writer method. @see Streamable. */
public void writeObject (ObjectOutputStream out)
throws IOException
{
out.writeInt(_size);
for (int ii = 0; ii < _size; ii++) {
out.writeObject(_entries[ii]);
}
}
/** Custom reader method. @see Streamable. */
public void readObject (ObjectInputStream in)
throws IOException, ClassNotFoundException
{
_size = in.readInt();
// ensure our capacity is a power of 2 (for consistency)
int capacity = INITIAL_CAPACITY;
while (capacity < _size) {
capacity <<= 1;
}
@SuppressWarnings("unchecked") E[] entries = (E[])new Entry[capacity];
_entries = entries;
for (int ii = 0; ii < _size; ii++) {
@SuppressWarnings("unchecked") E entry = (E)in.readObject();
_entries[ii] = entry;
}
}
/** The entries of the set (in a sparse array). */
@SuppressWarnings("unchecked") protected E[] _entries = (E[])new Entry[INITIAL_CAPACITY];
/** The number of entries in this set. */
protected int _size;
/** Used to check for concurrent modification. */
protected transient int _modCount;
/** The default capacity of a set instance. */
protected static final int INITIAL_CAPACITY = 2;
/** Used for lookups and to keep the set contents sorted on insertions. */
protected static Comparator<Entry> ENTRY_COMP = new Comparator<Entry>() {
public int compare (Entry e1, Entry e2) {
return DSet.compare(e1.getKey(), e2.getKey());
}
};
}
|
// $Id: DirectionUtil.java,v 1.4 2002/05/17 21:12:14 mdb Exp $
package com.threerings.util;
import java.awt.Point;
/**
* Direction related utility functions.
*/
public class DirectionUtil implements DirectionCodes
{
/**
* Returns an array of names corresponding to each direction constant.
*/
public static String[] getDirectionNames ()
{
return DIR_STRINGS;
}
/**
* Returns a string representation of the supplied direction code.
*/
public static String toString (int direction)
{
return ((direction >= SOUTHWEST) && (direction <= SOUTH)) ?
DIR_STRINGS[direction] : "INVALID";
}
/**
* Returns an abbreviated string representation of the supplied
* direction code.
*/
public static String toShortString (int direction)
{
return ((direction >= SOUTHWEST) && (direction <= SOUTH)) ?
SHORT_DIR_STRINGS[direction] : "?";
}
/**
* Returns a string representation of an array of direction codes. The
* directions are represented by the abbreviated names.
*/
public static String toString (int[] directions)
{
StringBuffer buf = new StringBuffer("{");
for (int i = 0; i < directions.length; i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(toShortString(directions[i]));
}
return buf.append("}").toString();
}
/**
* Returns the direction that point <code>b</code> lies in from point
* <code>a</code> as one of the {@link DirectionCodes} direction
* constants.
*/
public static int getDirection (Point a, Point b)
{
return getDirection(a.x, a.y, b.x, b.y);
}
/**
* Returns the direction that point <code>b</code> lies in from point
* <code>a</code> as one of the {@link DirectionCodes} direction
* constants.
*/
public static int getDirection (int ax, int ay, int bx, int by)
{
if (ax == bx && ay > by) {
return NORTH;
} else if (ax == bx && ay < by) {
return SOUTH;
} else if (ax < bx && ay > by) {
return NORTHEAST;
} else if (ax < bx && ay == by) {
return EAST;
} else if (ax < bx && ay < by) {
return SOUTHEAST;
} else if (ax > bx && ay < by) {
return SOUTHWEST;
} else if (ax > bx && ay == by) {
return WEST;
} else if (ax > bx && ay > by) {
return NORTHWEST;
} else {
return NONE;
}
}
/** Direction constant string names. */
protected static final String[] DIR_STRINGS = {
"SOUTHWEST", "WEST", "NORTHWEST", "NORTH",
"NORTHEAST", "EAST", "SOUTHEAST", "SOUTH"
};
/** Abbreviated direction constant string names. */
protected static final String[] SHORT_DIR_STRINGS = {
"SW", "W", "NW", "N", "NE", "E", "SE", "S"
};
}
|
// $Id: MessageBundle.java,v 1.11 2002/05/08 21:15:26 shaper Exp $
package com.threerings.util;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import com.samskivert.util.StringUtil;
/**
* A message bundle provides an easy mechanism by which to obtain
* translated message strings from a resource bundle. It uses the {@link
* MessageFormat} class to substitute arguments into the translation
* strings. Message bundles would generally be obtained via the {@link
* MessageManager}, but could be constructed individually if so desired.
*/
public class MessageBundle
{
/**
* Initializes the message bundle which will obtain localized messages
* from the supplied resource bundle. The path is provided purely for
* reporting purposes.
*/
public void init (String path, ResourceBundle bundle)
{
_path = path;
_bundle = bundle;
}
/**
* Obtains the translation for the specified message key. No arguments
* are substituted into the translated string. If a translation
* message does not exist for the specified key, an error is logged
* and the key itself is returned so that the caller need not worry
* about handling a null response.
*/
public String get (String key)
{
// if this string is tainted, we don't translate it, instead we
// simply remove the taint character and return it to the caller
if (key.startsWith(TAINT_CHAR)) {
return key.substring(1);
}
String msg = getResourceString(key);
return (msg != null) ? msg : key;
}
/**
* Get a String from the resource bundle, or null if there was an error.
*/
protected String getResourceString (String key)
{
try {
if (_bundle != null) {
return _bundle.getString(key);
}
} catch (MissingResourceException mre) {
Log.warning("Missing translation message " +
"[bundle=" + _path + ", key=" + key + "].");
}
return null;
}
/**
* Obtains the translation for the specified message key. The
* specified argument is substituted into the translated string.
*
* <p> See {@link MessageFormat} for more information on how the
* substitution is performed. If a translation message does not exist
* for the specified key, an error is logged and the key itself (plus
* the argument) is returned so that the caller need not worry about
* handling a null response.
*/
public String get (String key, Object arg1)
{
return get(key, new Object[] { arg1 });
}
/**
* Obtains the translation for the specified message key. The
* specified arguments are substituted into the translated string.
*
* <p> See {@link MessageFormat} for more information on how the
* substitution is performed. If a translation message does not exist
* for the specified key, an error is logged and the key itself (plus
* the arguments) is returned so that the caller need not worry about
* handling a null response.
*/
public String get (String key, Object arg1, Object arg2)
{
return get(key, new Object[] { arg1, arg2 });
}
/**
* Obtains the translation for the specified message key. The
* specified arguments are substituted into the translated string.
*
* <p> See {@link MessageFormat} for more information on how the
* substitution is performed. If a translation message does not exist
* for the specified key, an error is logged and the key itself (plus
* the arguments) is returned so that the caller need not worry about
* handling a null response.
*/
public String get (String key, Object arg1, Object arg2, Object arg3)
{
return get(key, new Object[] { arg1, arg2, arg3 });
}
/**
* Obtains the translation for the specified message key. The
* specified arguments are substituted into the translated string.
*
* <p> See {@link MessageFormat} for more information on how the
* substitution is performed. If a translation message does not exist
* for the specified key, an error is logged and the key itself (plus
* the arguments) is returned so that the caller need not worry about
* handling a null response.
*/
public String get (String key, Object[] args)
{
String msg = getResourceString(key);
return (msg != null) ? MessageFormat.format(msg, args)
: (key + StringUtil.toString(args));
}
/**
* Obtains the translation for the specified compound message key. A
* compound key contains the message key followed by a tab separated
* list of message arguments which will be subsituted into the
* translation string.
*
* <p> See {@link MessageFormat} for more information on how the
* substitution is performed. If a translation message does not exist
* for the specified key, an error is logged and the key itself (plus
* the arguments) is returned so that the caller need not worry about
* handling a null response.
*/
public String xlate (String compoundKey)
{
// to be more efficient about creating unnecessary objects, we
// do some checking before splitting
int tidx = compoundKey.indexOf('|');
if (tidx == -1) {
return get(compoundKey);
} else {
String key = compoundKey.substring(0, tidx);
String argstr = compoundKey.substring(tidx+1);
String[] args = StringUtil.split(argstr, "|");
// unescape and translate the arguments
for (int i = 0; i < args.length; i++) {
args[i] = xlate(unescape(args[i]));
}
return get(key, args);
}
}
/**
* Call this to "taint" any string that has been entered by an entity
* outside the application so that the translation code knows not to
* attempt to translate this string when doing recursive translations
* (see {@link #xlate}).
*/
public static String taint (String text)
{
return TAINT_CHAR + text;
}
/**
* Composes a message key with an array of arguments. The message can
* subsequently be translated in a single call using {@link #xlate}.
*/
public static String compose (String key, String[] args)
{
StringBuffer buf = new StringBuffer();
buf.append(key);
buf.append('|');
for (int i = 0; i < args.length; i++) {
if (i > 0) {
buf.append('|');
}
// escape the string while adding to the buffer
String arg = args[i];
int alength = arg.length();
for (int p = 0; p < alength; p++) {
char ch = arg.charAt(p);
if (ch == '|') {
buf.append("\\!");
} else if (ch == '\\') {
buf.append("\\\\");
} else {
buf.append(ch);
}
}
}
return buf.toString();
}
/**
* Unescapes characters that are escaped in a call to compose.
*/
protected static String unescape (String value)
{
int bsidx = value.indexOf('\\');
if (bsidx == -1) {
return value;
}
StringBuffer buf = new StringBuffer();
int vlength = value.length();
for (int i = 0; i < vlength; i++) {
char ch = value.charAt(i);
if (ch != '\\') {
buf.append(ch);
} else if (i < vlength-1) {
// look at the next character
ch = value.charAt(++i);
buf.append((ch == '!') ? '|' : ch);
} else {
buf.append(ch);
}
}
return buf.toString();
}
/**
* A convenience method for calling {@link #compose(String,String[])}
* with a single argument.
*/
public static String compose (String key, String arg)
{
return compose(key, new String[] { arg });
}
/**
* A convenience method for calling {@link #compose(String,String[])}
* with two arguments.
*/
public static String compose (String key, String arg1, String arg2)
{
return compose(key, new String[] { arg1, arg2 });
}
/**
* A convenience method for calling {@link #compose(String,String[])}
* with three arguments.
*/
public static String compose (
String key, String arg1, String arg2, String arg3)
{
return compose(key, new String[] { arg1, arg2, arg3 });
}
/**
* A convenience method for calling {@link #compose(String,String[])}
* with a single argument that will be automatically tainted (see
* {@link #taint}).
*/
public static String tcompose (String key, String arg)
{
return compose(key, new String[] { taint(arg) });
}
/**
* A convenience method for calling {@link #compose(String,String[])}
* with two arguments that will be automatically tainted (see {@link
* #taint}).
*/
public static String tcompose (String key, String arg1, String arg2)
{
return compose(key, new String[] { taint(arg1), taint(arg2) });
}
/**
* A convenience method for calling {@link #compose(String,String[])}
* with three arguments that will be automatically tainted (see {@link
* #taint}).
*/
public static String tcompose (
String key, String arg1, String arg2, String arg3)
{
return compose(key, new String[] {
taint(arg1), taint(arg2), taint(arg3) });
}
/**
* A convenience method for calling {@link #compose(String,String[])}
* with an array of arguments that will be automatically tainted (see
* {@link #taint}).
*/
public static String tcompose (String key, String[] args)
{
int acount = args.length;
String[] targs = new String[acount];
for (int ii = 0; ii < acount; ii++) {
targs[ii] = taint(args[ii]);
}
return compose(key, targs);
}
/** The path that identifies the resource bundle we are using to
* obtain our messages. */
protected String _path;
/** The resource bundle from which we obtain our messages. */
protected ResourceBundle _bundle;
/** Text prefixed by this character will be considered tainted when
* doing recursive translations and won't be translated. */
protected static final String TAINT_CHAR = "~";
// protected static final String TAINT_CHAR = '~';
}
|
package nanomsg.async.impl;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.Queue;
import java.util.Map;
import java.util.LinkedList;
import java.lang.Thread;
import com.sun.jna.Memory;
import com.sun.jna.Pointer;
import com.sun.jna.Native;
import com.sun.jna.ptr.PointerByReference;
import nanomsg.Socket;
import nanomsg.Nanomsg;
import nanomsg.async.IAsyncRunnable;
import nanomsg.async.IAsyncScheduler;
import nanomsg.async.AsyncOperation;
import nanomsg.async.impl.epoll.Epoll;
import nanomsg.exceptions.EAgainException;
import nanomsg.exceptions.IOException;
public class EPollScheduler implements Runnable, IAsyncScheduler {
/* Maps used for store references tu socket; */
private final Map<Integer, IAsyncRunnable> runnableMap = new ConcurrentHashMap<Integer, IAsyncRunnable>();
private final AtomicBoolean started = new AtomicBoolean(false);
private final int epollFd = Epoll.epoll_create1(Epoll.EPOLL_CLOEXEC);
private static EPollScheduler instance = null;
public synchronized static EPollScheduler getInstance() {
if(instance == null) {
instance = new EPollScheduler();
}
return instance;
}
public void register(final int fd, final int flags, final IAsyncRunnable runnable) {
// Register a file description in a runnables map
runnableMap.put(fd, runnable);
// Create new epoll event instance
final Epoll.EpollEvent.ByReference eevent = new Epoll.EpollEvent.ByReference(fd, flags);
// Register the file descriptor and epoll event into epoll inststance.
Epoll.epoll_ctl(epollFd, Epoll.EPOLL_CTL_ADD, fd, eevent);
// Temporal debug
System.out.println("registerOnce: fd:" + fd);
System.out.println("registerOnce: total:" + runnableMap.size());
}
public void registerRead(final Socket sock, final IAsyncRunnable runnable) {
register(sock.getRcvFd(), Epoll.EPOLLIN | Epoll.EPOLLONESHOT, runnable);
}
public void registerWrite(final Socket sock, final IAsyncRunnable runnable) {
register(sock.getSndFd(), Epoll.EPOLLOUT| Epoll.EPOLLONESHOT, runnable);
}
public void schedule(final Socket sock, final AsyncOperation op, final IAsyncRunnable handler) throws InterruptedException {
if (started.compareAndSet(false, true)) {
final Thread t = new Thread(this, "nanomsg-poll-scheduler");
t.setDaemon(true);
t.start();
}
if (epollFd < 0) {
throw new RuntimeException("Failed intialize epoll instance.");
}
if (op == AsyncOperation.READ) {
this.registerRead(sock, handler);
} else if (op == AsyncOperation.WRITE) {
this.registerWrite(sock, handler);
} else {
throw new RuntimeException("Operation not supported.");
}
}
private void processFd(final Epoll.EpollEvent.ByReference event) {
final int fd = event.data.fd;
if (runnableMap.containsKey(event.data.fd)) {
final IAsyncRunnable runnable = runnableMap.get(fd);
runnableMap.remove(event.data.fd);
try {
runnable.run();
} catch (IOException e) {
final int errno = e.getErrno();
if (errno == Nanomsg.constants.EAGAIN) {
System.out.println("EAGAIN error for fd=" + fd);
this.register(fd, event.events, runnable);
} else {
System.out.println("Error on runing the async runnable: " + errno);
}
}
}
}
public void run() {
System.out.println("Starting event loop.");
int readyCount;
int err;
final int MAX_EVENTS = 1024;
final int size_of_struct = new Epoll.EpollEvent().size();
final Memory ptr = new Memory(MAX_EVENTS * size_of_struct);
final Epoll.EpollEvent.ByReference event = new Epoll.EpollEvent.ByReference();
while (!Thread.interrupted()) {
readyCount = Epoll.epoll_wait(epollFd, ptr, MAX_EVENTS, 1000);
System.out.println("Epoll loop: found " + readyCount + " events.");
if (readyCount <= 0) {
continue;
}
for(int i = 0; i < readyCount; ++i) {
event.reuse(ptr, size_of_struct * i);
// System.out.println("Type EPOLLIN: " + (event.events & Epoll.EPOLLIN));
// System.out.println("Type EPOLLOUT: " + (event.events & Epoll.EPOLLOUT));
// System.out.println("Type EPOLLHUP: " + (event.events & Epoll.EPOLLHUP));
processFd(event);
}
if (runnableMap.size() == 0) {
System.out.println("Stoping event loop.");
started.compareAndSet(true, false);
break;
}
}
}
}
|
package net.sf.samtools.util;
import net.sf.samtools.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SequenceUtil {
/** Byte typed variables for all normal bases. */
public static final byte a='a', c='c', g='g', t='t', n='n', A='A', C='C', G='G', T='T', N='N';
/**
* Calculate the reverse complement of the specified sequence
* (Stolen from Reseq)
*
* @param sequenceData
* @return reverse complement
*/
public static String reverseComplement(final String sequenceData) {
final byte[] bases = net.sf.samtools.util.StringUtil.stringToBytes(sequenceData);
reverseComplement(bases);
return net.sf.samtools.util.StringUtil.bytesToString(bases);
}
/** Attempts to efficiently compare two bases stored as bytes for equality. */
public static boolean basesEqual(byte lhs, byte rhs) {
if (lhs == rhs) return true;
else {
if (lhs > 90) lhs -= 32;
if (rhs > 90) rhs -= 32;
}
return lhs == rhs;
}
/**
* returns true if the value of base represents a no call
*/
public static boolean isNoCall(final byte base) {
return base == 'N' || base == 'n' || base == '.';
}
/**
* Throws an exception if both parameters are not null sequenceListsEqual returns false
* @param s1 a list of sequence headers
* @param s2 a second list of sequence headers
*/
public static void assertSequenceListsEqual(final List<SAMSequenceRecord> s1, final List<SAMSequenceRecord> s2) {
if (s1 == null || s2 == null) return;
if (s1.size() != s2.size()) {
throw new SequenceListsDifferException("Sequence dictionaries are not the same size (" +
s1.size() + ", " + s2.size() + ")");
}
for (int i = 0; i < s1.size(); ++i) {
if (!s1.get(i).isSameSequence(s2.get(i))) {
String s1Attrs = "";
for (final java.util.Map.Entry<String, Object> entry : s1.get(i).getAttributes()) {
s1Attrs += "/" + entry.getKey() + "=" + entry.getValue();
}
String s2Attrs = "";
for (final java.util.Map.Entry<String, Object> entry : s2.get(i).getAttributes()) {
s2Attrs += "/" + entry.getKey() + "=" + entry.getValue();
}
throw new SequenceListsDifferException("Sequences at index " + i + " don't match: " +
s1.get(i).getSequenceIndex() + "/" + s1.get(i).getSequenceLength() + "/" + s1.get(i).getSequenceName() + s1Attrs +
" " + s2.get(i).getSequenceIndex() + "/" + s2.get(i).getSequenceLength() + "/" + s2.get(i).getSequenceName() + s2Attrs);
}
}
}
public static class SequenceListsDifferException extends SAMException {
public SequenceListsDifferException() {
}
public SequenceListsDifferException(final String s) {
super(s);
}
public SequenceListsDifferException(final String s, final Throwable throwable) {
super(s, throwable);
}
public SequenceListsDifferException(final Throwable throwable) {
super(throwable);
}
}
/**
* Throws an exception if both parameters are non-null and unequal.
*/
public static void assertSequenceDictionariesEqual(final SAMSequenceDictionary s1, final SAMSequenceDictionary s2) {
if (s1 == null || s2 == null) return;
assertSequenceListsEqual(s1.getSequences(), s2.getSequences());
}
/**
* Create a simple ungapped cigar string, which might have soft clipping at either end
* @param alignmentStart raw aligment start, which may result in read hanging off beginning or end of read
* @return cigar string that may have S operator at beginning or end, and has M operator for the rest of the read
*/
public static String makeCigarStringWithPossibleClipping(final int alignmentStart, final int readLength, final int referenceSequenceLength) {
int start = alignmentStart;
int leftSoftClip = 0;
if (start < 1) {
leftSoftClip = 1 - start;
start = 1;
}
int rightSoftClip = 0;
if (alignmentStart + readLength > referenceSequenceLength + 1) {
rightSoftClip = alignmentStart + readLength - referenceSequenceLength - 1;
}
// CIGAR is trivial because there are no indels or clipping in Gerald
final int matchLength = readLength - leftSoftClip - rightSoftClip;
if (matchLength < 1) {
throw new SAMException("Unexpected cigar string with no M op for read.");
}
return makeSoftClipCigar(leftSoftClip) + Integer.toString(matchLength) + "M" + makeSoftClipCigar(rightSoftClip);
}
/**
* Create a cigar string for a gapped alignment, which may have soft clipping at either end
* @param alignmentStart raw alignment start, which may result in read hanging off beginning or end of read
* @param readLength
* @param referenceSequenceLength
* @param indelPosition number of matching bases before indel. Must be > 0
* @param indelLength length of indel. Positive for insertion, negative for deletion.
* @return cigar string that may have S operator at beginning or end, has one or two M operators, and an I or a D.
*/
public static String makeCigarStringWithIndelPossibleClipping(final int alignmentStart,
final int readLength,
final int referenceSequenceLength,
final int indelPosition,
final int indelLength) {
int start = alignmentStart;
int leftSoftClip = 0;
if (start < 1) {
leftSoftClip = 1 - start;
start = 1;
}
int rightSoftClip = 0;
final int alignmentEnd = alignmentStart + readLength - indelLength;
if (alignmentEnd > referenceSequenceLength + 1) {
rightSoftClip = alignmentEnd - referenceSequenceLength - 1;
}
if (leftSoftClip >= indelPosition) {
throw new IllegalStateException("Soft clipping entire pre-indel match. leftSoftClip: " + leftSoftClip +
"; indelPosition: " + indelPosition);
}
// CIGAR is trivial because there are no indels or clipping in Gerald
final int firstMatchLength = indelPosition - leftSoftClip;
final int secondMatchLength = readLength - indelPosition - (indelLength > 0? indelLength: 0) - rightSoftClip;
if (secondMatchLength < 1) {
throw new SAMException("Unexpected cigar string with no M op for read.");
}
return makeSoftClipCigar(leftSoftClip) + Integer.toString(firstMatchLength) + "M" +
Math.abs(indelLength) + (indelLength > 0? "I": "D") +
Integer.toString(secondMatchLength) + "M" +
makeSoftClipCigar(rightSoftClip);
}
public static String makeSoftClipCigar(final int clipLength) {
if (clipLength == 0) {
return "";
}
return Integer.toString(clipLength) + "S";
}
/** Calculates the number of mismatches between the read and the reference sequence provided. */
public static int countMismatches(final SAMRecord read, final byte[] referenceBases) {
return countMismatches(read, referenceBases, 0, false);
}
/** Calculates the number of mismatches between the read and the reference sequence provided. */
public static int countMismatches(final SAMRecord read, final byte[] referenceBases, final int referenceOffset) {
return countMismatches(read, referenceBases, referenceOffset, false);
}
/**
* Calculates the number of mismatches between the read and the reference sequence provided.
*
* @param referenceBases Array of ASCII bytes that covers at least the the portion of the reference sequence
* to which read is aligned from getReferenceStart to getReferenceEnd.
* @param referenceOffset 0-based offset of the first element of referenceBases relative to the start
* of that reference sequence.
* @param bisulfiteSequence If this is true, it is assumed that the reads were bisulfite treated
* and C->T on the positive strand and G->A on the negative strand will not be counted
* as mismatches.
*/
public static int countMismatches(final SAMRecord read, final byte[] referenceBases, final int referenceOffset,
final boolean bisulfiteSequence) {
try {
int mismatches = 0;
final byte[] readBases = read.getReadBases();
for (final AlignmentBlock block : read.getAlignmentBlocks()) {
final int readBlockStart = block.getReadStart() - 1;
final int referenceBlockStart = block.getReferenceStart() - 1 - referenceOffset;
final int length = block.getLength();
for (int i=0; i<length; ++i) {
if (!bisulfiteSequence) {
if (!basesEqual(readBases[readBlockStart+i], referenceBases[referenceBlockStart+i])) {
++mismatches;
}
}
else {
if (!bisulfiteBasesEqual(read.getReadNegativeStrandFlag(), readBases[readBlockStart+i],
referenceBases[referenceBlockStart+i])) {
++mismatches;
}
}
}
}
return mismatches;
} catch (Exception e) {
throw new SAMException("Exception counting mismatches for read " + read, e);
}
}
/**
* Sadly, this is a duplicate of the method above, except that it takes char[] for referenceBases rather
* than byte[]. This is because GATK needs it this way.
*
* TODO: Remove this method when GATK map method is changed to take refseq as byte[].
*/
private static int countMismatches(final SAMRecord read, final char[] referenceBases, final int referenceOffset) {
int mismatches = 0;
final byte[] readBases = read.getReadBases();
for (final AlignmentBlock block : read.getAlignmentBlocks()) {
final int readBlockStart = block.getReadStart() - 1;
final int referenceBlockStart = block.getReferenceStart() - 1 - referenceOffset;
final int length = block.getLength();
for (int i=0; i<length; ++i) {
if (!basesEqual(readBases[readBlockStart+i], StringUtil.charToByte(referenceBases[referenceBlockStart+i]))) {
++mismatches;
}
}
}
return mismatches;
}
/**
* Calculates the sum of qualities for mismatched bases in the read.
* @param referenceBases Array of ASCII bytes in which the 0th position in the array corresponds
* to the first element of the reference sequence to which read is aligned.
*/
public static int sumQualitiesOfMismatches(final SAMRecord read, final byte[] referenceBases) {
return sumQualitiesOfMismatches(read, referenceBases, 0, false);
}
/**
* Calculates the sum of qualities for mismatched bases in the read.
* @param referenceBases Array of ASCII bytes that covers at least the the portion of the reference sequence
* to which read is aligned from getReferenceStart to getReferenceEnd.
* @param referenceOffset 0-based offset of the first element of referenceBases relative to the start
* of that reference sequence.
*/
public static int sumQualitiesOfMismatches(final SAMRecord read, final byte[] referenceBases,
final int referenceOffset) {
return sumQualitiesOfMismatches(read, referenceBases, referenceOffset, false);
}
/**
* Calculates the sum of qualities for mismatched bases in the read.
* @param referenceBases Array of ASCII bytes that covers at least the the portion of the reference sequence
* to which read is aligned from getReferenceStart to getReferenceEnd.
* @param referenceOffset 0-based offset of the first element of referenceBases relative to the start
* of that reference sequence.
* @param bisulfiteSequence If this is true, it is assumed that the reads were bisulfite treated
* and C->T on the positive strand and G->A on the negative strand will not be counted
* as mismatches.
*/
public static int sumQualitiesOfMismatches(final SAMRecord read, final byte[] referenceBases,
final int referenceOffset, final boolean bisulfiteSequence) {
int qualities = 0;
final byte[] readBases = read.getReadBases();
final byte[] readQualities = read.getBaseQualities();
if (read.getAlignmentStart() <= referenceOffset) {
throw new IllegalArgumentException("read.getAlignmentStart(" + read.getAlignmentStart() +
") <= referenceOffset(" + referenceOffset + ")");
}
for (final AlignmentBlock block : read.getAlignmentBlocks()) {
final int readBlockStart = block.getReadStart() - 1;
final int referenceBlockStart = block.getReferenceStart() - 1 - referenceOffset;
final int length = block.getLength();
for (int i=0; i<length; ++i) {
if (!bisulfiteSequence) {
if (!basesEqual(readBases[readBlockStart+i], referenceBases[referenceBlockStart+i])) {
qualities += readQualities[readBlockStart+i];
}
}
else {
if (!bisulfiteBasesEqual(read.getReadNegativeStrandFlag(), readBases[readBlockStart+i],
referenceBases[referenceBlockStart+i])) {
qualities += readQualities[readBlockStart+i];
}
}
}
}
return qualities;
}
/**
* Sadly, this is a duplicate of the method above, except that it takes char[] for referenceBases rather
* than byte[]. This is because GATK needs it this way.
*
* TODO: Remove this method when GATK map method is changed to take refseq as byte[].
*/
public static int sumQualitiesOfMismatches(final SAMRecord read, final char[] referenceBases,
final int referenceOffset) {
int qualities = 0;
final byte[] readBases = read.getReadBases();
final byte[] readQualities = read.getBaseQualities();
if (read.getAlignmentStart() <= referenceOffset) {
throw new IllegalArgumentException("read.getAlignmentStart(" + read.getAlignmentStart() +
") <= referenceOffset(" + referenceOffset + ")");
}
for (final AlignmentBlock block : read.getAlignmentBlocks()) {
final int readBlockStart = block.getReadStart() - 1;
final int referenceBlockStart = block.getReferenceStart() - 1 - referenceOffset;
final int length = block.getLength();
for (int i=0; i<length; ++i) {
if (!basesEqual(readBases[readBlockStart+i], StringUtil.charToByte(referenceBases[referenceBlockStart+i]))) {
qualities += readQualities[readBlockStart+i];
}
}
}
return qualities;
}
/**
* Calculates the for the predefined NM tag from the SAM spec. To the result of
* countMismatches() it adds 1 for each indel.
*/
public static int calculateSamNmTag(final SAMRecord read, final byte[] referenceBases) {
return calculateSamNmTag(read, referenceBases, 0, false);
}
/**
* Calculates the for the predefined NM tag from the SAM spec. To the result of
* countMismatches() it adds 1 for each indel.
* @param referenceOffset 0-based offset of the first element of referenceBases relative to the start
* of that reference sequence.
*/
public static int calculateSamNmTag(final SAMRecord read, final byte[] referenceBases,
final int referenceOffset) {
return calculateSamNmTag(read, referenceBases, referenceOffset, false);
}
/**
* Calculates the for the predefined NM tag from the SAM spec. To the result of
* countMismatches() it adds 1 for each indel.
* @param referenceOffset 0-based offset of the first element of referenceBases relative to the start
* of that reference sequence.
* @param bisulfiteSequence If this is true, it is assumed that the reads were bisulfite treated
* and C->T on the positive strand and G->A on the negative strand will not be counted
* as mismatches.
*/
public static int calculateSamNmTag(final SAMRecord read, final byte[] referenceBases,
final int referenceOffset, final boolean bisulfiteSequence) {
int samNm = countMismatches(read, referenceBases, referenceOffset, bisulfiteSequence);
for (final CigarElement el : read.getCigar().getCigarElements()) {
if (el.getOperator() == CigarOperator.INSERTION || el.getOperator() == CigarOperator.DELETION) {
samNm += el.getLength();
}
}
return samNm;
}
/**
* Sadly, this is a duplicate of the method above, except that it takes char[] for referenceBases rather
* than byte[]. This is because GATK needs it this way.
*
* TODO: Remove this method when GATK map method is changed to take refseq as byte[].
*/
public static int calculateSamNmTag(final SAMRecord read, final char[] referenceBases,
final int referenceOffset) {
int samNm = countMismatches(read, referenceBases, referenceOffset);
for (final CigarElement el : read.getCigar().getCigarElements()) {
if (el.getOperator() == CigarOperator.INSERTION || el.getOperator() == CigarOperator.DELETION) {
samNm += el.getLength();
}
}
return samNm;
}
/** Returns the complement of a single byte. */
public static byte complement(final byte b) {
switch (b) {
case a: return t;
case c: return g;
case g: return c;
case t: return a;
case A: return T;
case C: return G;
case G: return C;
case T: return A;
default: return b;
}
}
/** Reverses and complements the bases in place. */
public static void reverseComplement(final byte[] bases) {
final int lastIndex = bases.length - 1;
int i, j;
for (i=0, j=lastIndex; i<j; ++i, --j) {
final byte tmp = complement(bases[i]);
bases[i] = complement(bases[j]);
bases[j] = tmp;
}
if (bases.length % 2 == 1) {
bases[i] = complement(bases[i]);
}
}
/** Returns true if the bases are equal OR if the mismatch cannot be accounted for by
* bisfulite treatment. C->T on the positive strand and G->A on the negative strand
* do not count as mismatches */
public static boolean bisulfiteBasesEqual(boolean negativeStrand, byte read, byte reference) {
if (basesEqual(read, reference)) {
return true;
}
if (negativeStrand) {
if (basesEqual(reference, (byte)'G') && basesEqual(read, (byte)'A')) {
return true;
}
}
else {
if (basesEqual(reference, (byte)'C') && basesEqual(read, (byte)'T')) {
return true;
}
}
return false;
}
/*
* Regexp for MD string.
*
* \G = end of previous match.
* (?:[0-9]+) non-capturing (why non-capturing?) group of digits. For this number of bases read matches reference.
* - or -
* Single reference base for case in which reference differs from read.
* - or -
* ^one or more reference bases that are deleted in read.
*
*/
static final Pattern mdPat = Pattern.compile("\\G(?:([0-9]+)|([ACTGNactgn])|(\\^[ACTGNactgn]+))");
/**
* Produce reference bases from an aligned SAMRecord with MD string and Cigar.
* @param rec Must contain non-empty CIGAR and MD attribute.
* @param includeReferenceBasesForDeletions If true, include reference bases that are deleted in the read.
* This will make the returned array not line up with the read if there are deletions.
* @return References bases corresponding to the read. If there is an insertion in the read, reference contains
* '-'. If the read is soft-clipped, reference contains '0'. If there is a skipped region and
* includeReferenceBasesForDeletions==true, reference will have Ns for the skipped region.
*/
public static byte[] makeReferenceFromAlignment(final SAMRecord rec, boolean includeReferenceBasesForDeletions) {
final String md = rec.getStringAttribute(SAMTag.MD.name());
if (md == null) {
throw new SAMException("Cannot create reference from SAMRecord with no MD tag, read: " + rec.getReadName());
}
// Not sure how long output will be, but it will be no longer than this.
int maxOutputLength = 0;
final Cigar cigar = rec.getCigar();
if (cigar == null) {
throw new SAMException("Cannot create reference from SAMRecord with no CIGAR, read: " + rec.getReadName());
}
for (final CigarElement cigarElement : cigar.getCigarElements()) {
maxOutputLength += cigarElement.getLength();
}
final byte[] ret = new byte[maxOutputLength];
int outIndex = 0;
Matcher match = mdPat.matcher(md);
int curSeqPos = 0;
int savedBases = 0;
final byte[] seq = rec.getReadBases();
for (final CigarElement cigEl : cigar.getCigarElements())
{
int cigElLen = cigEl.getLength();
CigarOperator cigElOp = cigEl.getOperator();
if (cigElOp == CigarOperator.SKIPPED_REGION) {
// We've decided that MD tag will not contain bases for skipped regions, as they
// could be megabases long, so just put N in there if caller wants reference bases,
// otherwise ignore skipped regions.
if (includeReferenceBasesForDeletions) {
for (int i = 0; i < cigElLen; ++i) {
ret[outIndex++] = N;
}
}
}
// If it consumes reference bases, it's either a match or a deletion in the sequence
// read. Either way, we're going to need to parse through the MD.
else if (cigElOp.consumesReferenceBases()) {
// We have a match region, go through the MD
int basesMatched = 0;
// Do we have any saved matched bases?
while ((savedBases>0) && (basesMatched < cigElLen))
{
ret[outIndex++] = seq[curSeqPos++];
savedBases
basesMatched++;
}
while (basesMatched < cigElLen)
{
boolean matched = match.find();
if (matched)
{
String mg;
if ( ((mg = match.group(1)) !=null) && (mg.length() > 0) )
{
// It's a number , meaning a series of matches
int num = Integer.parseInt(mg);
for (int i = 0; i < num; i++)
{
if (basesMatched<cigElLen)
{
ret[outIndex++] = seq[curSeqPos++];
}
else
{
savedBases++;
}
basesMatched++;
}
}
else if ( ((mg = match.group(2)) !=null) && (mg.length() > 0) )
{
// It's a single nucleotide, meaning a mismatch
if (basesMatched<cigElLen)
{
ret[outIndex++] = StringUtil.charToByte(mg.charAt(0));
curSeqPos++;
}
else
{
throw new IllegalStateException("Should never happen.");
}
basesMatched++;
}
else if ( ((mg = match.group(3)) !=null) && (mg.length() > 0) )
{
// It's a deletion, starting with a caret
// don't include caret
if (includeReferenceBasesForDeletions) {
final byte[] deletedBases = StringUtil.stringToBytes(mg);
System.arraycopy(deletedBases, 1, ret, outIndex, deletedBases.length - 1);
outIndex += deletedBases.length - 1;
}
basesMatched += mg.length() - 1;
// Check just to make sure.
if (basesMatched != cigElLen)
{
throw new SAMException("Got a deletion in CIGAR (" + cigar + ", deletion " + cigElLen +
" length) with an unequal ref insertion in MD (" + md + ", md " + basesMatched + " length");
}
if (cigElOp != CigarOperator.DELETION)
{
throw new SAMException ("Got an insertion in MD ("+md+") without a corresponding deletion in cigar ("+cigar+")");
}
}
else
{
matched = false;
}
}
if (!matched)
{
throw new SAMException("Illegal MD pattern: " + md + " for read " + rec.getReadName() +
" with CIGAR " + rec.getCigarString());
}
}
}
else if (cigElOp.consumesReadBases())
{
// We have an insertion in read
for (int i = 0; i < cigElLen; i++)
{
char c = (cigElOp == CigarOperator.SOFT_CLIP) ? '0' : '-';
ret[outIndex++] = StringUtil.charToByte(c);
curSeqPos++;
}
}
else
{
// It's an op that consumes neither read nor reference bases. Do we just ignore??
}
}
if (outIndex < ret.length) {
byte[] shorter = new byte[outIndex];
System.arraycopy(ret, 0, shorter, 0, outIndex);
return shorter;
}
return ret;
}
}
|
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.GeneralPath;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import org.jdesktop.swingx.auth.LoginEvent;
import org.jdesktop.swingx.auth.LoginListener;
import org.jdesktop.swingx.auth.LoginService;
import org.jdesktop.swingx.auth.PasswordStore;
import org.jdesktop.swingx.auth.UserNameStore;
import org.jdesktop.swingx.util.WindowUtils;
/**
* A standard login dialog that provides a reasonable amount of flexibility
* while also providing ease of use and a professional look.
*
* @author rbair
*/
public class JXLoginDialog extends JDialog {
/**
* An optional banner at the top of the dialog
*/
private JXImagePanel banner;
/**
* Custom label allowing the developer to display some message to the user
*/
private JLabel label;
/**
* Shows a message such as "user name or password incorrect" or
* "could not contact server" or something like that if something
* goes wrong
*/
private JLabel messageLabel;
/**
* If something goes wrong, this link will be displayed so the user can
* click on it to be shown the exception, etc
*/
private JXHyperlink detailsLink;
/**
* The login panel containing the username & password fields, and handling
* the login procedures.
*/
private JXLoginPanel loginPanel;
private JXPanel contentPanel;
private JXPanel buttonPanel;
private JXPanel progressPanel;
/**
* Only true if the user cancels their login operation. This is reset to false
* after the login thread is cancelled and the proper message shown
*/
private boolean cancelled;
/** Creates a new instance of JXLoginDialog */
public JXLoginDialog() {
this(null, null, null);
}
public JXLoginDialog(LoginService service, PasswordStore ps, UserNameStore us) {
loginPanel = new JXLoginPanel(service, ps, us);
initComponents();
}
public JXLoginPanel getLoginPanel() {
return loginPanel;
}
private void initComponents() {
//initialize dialog itself
setModal(true);
setTitle("Login");//UIManager.getString(CLASS_NAME + ".loginString"));
loginPanel.getLoginService().addLoginListener(new Listener());
progressPanel = new ProgressPane();
//create the default banner
banner = new JXImagePanel();
banner.setImage(createLoginBanner());
//create the default label
label = new JLabel("Enter your user name and password");
label.setFont(label.getFont().deriveFont(Font.BOLD));
//create the message and hyperlink and hide them
messageLabel = new JLabel(" ");
messageLabel.setVisible(false);
detailsLink = new JXHyperlink();
detailsLink.setVisible(false);
//create the buttons
JButton okButton = new JButton("OK");//UIManager.getString(CLASS_NAME + ".okString"));
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cancelled = false;
loginPanel.startLogin();
}
});
okButton.setMnemonic('O');//UIManager.getInt(CLASS_NAME + ".okString.mnemonic"));
okButton.setPreferredSize(new Dimension(80, okButton.getPreferredSize().height));
JButton cancelButton = new JButton("Cancel");//UIManager.getString(CLASS_NAME + ".cancelString"));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
setVisible(false);
}
});
cancelButton.setMnemonic('C');//UIManager.getInt(CLASS_NAME + ".cancelString.mnemonic"));
cancelButton.setPreferredSize(new Dimension(80, okButton.getPreferredSize().height));
//layout the dialog
setLayout(new BorderLayout());
add(banner, BorderLayout.NORTH);
contentPanel = new JXPanel(new GridBagLayout());
contentPanel.add(label, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 7, 11), 0, 0));
contentPanel.add(loginPanel, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 36, 7, 11), 0, 0));
contentPanel.add(messageLabel, new GridBagConstraints(1, 2, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 36, 0, 11), 0, 0));
// contentPanel.add(detailsLink, )
add(contentPanel, BorderLayout.CENTER);
buttonPanel = new JXPanel(new GridBagLayout());
buttonPanel.add(okButton, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(17, 12, 11, 5), 0, 0));
buttonPanel.add(cancelButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(17, 0, 11, 11), 0, 0));
add(buttonPanel, BorderLayout.SOUTH);
// service.addLoginListener(this);
// panel.okButton.addActionListener(this);
// panel.cancelButton.addActionListener(this);
getRootPane().setDefaultButton(okButton);
pack();
setResizable(false);
setLocation(WindowUtils.getPointForCentering(this));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// progressIndicator = new JProgressBar();
// loginProgress = new JLabel(UIManager.getString(CLASS_NAME + ".loginIntructionString"));
// cancelLogin = new JButton(UIManager.getString(CLASS_NAME + ".cancelString"));
// cancelLogin.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent ev) {
// loginService.cancelAuthentication();
// progressIndicator.setIndeterminate(false);
// loginPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
// cancelLogin.setEnabled(false);
// cancelLogin.setEnabled(false);
}
// public void loginFailed(LoginEvent source) {
// finishedLogin(false);
// loginPanel.loginProgress.setText(UIManager.getString(CLASS_NAME + ".loginFailed"));
// public void loginSucceeded(LoginEvent source) {
// finishedLogin(true);
// dialog.dispose();
// public void loginStarted(LoginEvent source) {
// void finishedLogin(boolean result) {
// loginPanel.cancelLogin.setEnabled(false);
// loginPanel.progressIndicator.setIndeterminate(false);
// loginPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
// void cancelAuthentication() {
// service.cancelAuthentication();
// loginPanel.cancelLogin.setEnabled(false);
// loginPanel.progressIndicator.setIndeterminate(false);
// loginPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
// public void loginCanceled(LoginEvent source) {
// cancelled = true;
// public void actionPerformed(ActionEvent ae) {
// Object source = ae.getSource();
// if (source == loginPanel.okButton) {
// startLogin();
// } else if (source == loginPanel.cancelLogin) {
// cancelAuthentication();
// } else if (source == loginPanel.cancelButton) {
// dialog.dispose();
private BufferedImage createLoginBanner() {
int w = 400;
int h = 60;
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
//draw a big square
g2.setColor(UIManager.getColor("JXTitledPanel.title.darkBackground"));
g2.fillRect(0, 0, w, h);
//create the curve shape
GeneralPath curveShape = new GeneralPath(GeneralPath.WIND_NON_ZERO);
curveShape.moveTo(0, h * .6f);
curveShape.curveTo(w * .167f, h * 1.2f, w * .667f, h * -.5f, w, h * .75f);
curveShape.lineTo(w, h);
curveShape.lineTo(0, h);
curveShape.lineTo(0, h * .8f);
curveShape.closePath();
//draw into the buffer a gradient (bottom to top), and the text "Login"
GradientPaint gp = new GradientPaint(0, h, UIManager.getColor("JXTitledPanel.title.darkBackground"),
0, 0, UIManager.getColor("JXTitledPanel.title.lightBackground"));
g2.setPaint(gp);
g2.fill(curveShape);
Font font = new Font("Arial Bold", Font.PLAIN, 36);
g2.setFont(font);
g2.setColor(UIManager.getColor("JXTitledPanel.title.foreground"));
g2.drawString("Login", w * .05f, h * .75f);
return img;
}
/**
* Used as a glass pane when doing the login procedure
*/
private final class ProgressPane extends JXPanel {
public ProgressPane() {
setLayout(new BorderLayout(24, 24));
JXPanel contentPanel = new JXPanel(new GridBagLayout());
add(contentPanel, BorderLayout.CENTER);
JLabel label = new JLabel("Please wait, logging in....");
label.setFont(label.getFont().deriveFont(Font.BOLD));
JProgressBar pb = new JProgressBar();
pb.setIndeterminate(true);
JButton stopButton = new JButton("Stop login");
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
loginPanel.cancelLogin();
}
});
contentPanel.add(label, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 11, 11), 0, 0));
contentPanel.add(pb, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 11, 7), 0, 0));
contentPanel.add(stopButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 11, 11), 0, 0));
}
}
private final class Listener implements LoginListener {
public void loginSucceeded(LoginEvent source) {
setVisible(false);
}
public void loginStarted(LoginEvent source) {
//switch to login animation
buttonPanel.setVisible(false);
remove(contentPanel);
add(progressPanel, BorderLayout.CENTER);
}
public void loginFailed(LoginEvent source) {
//switch to input fields, show error
buttonPanel.setVisible(true);
remove(progressPanel);
add(contentPanel, BorderLayout.CENTER);
}
public void loginCanceled(LoginEvent source) {
//switch to input fields, show message
buttonPanel.setVisible(true);
remove(progressPanel);
add(contentPanel, BorderLayout.CENTER);
}
}
}
|
package com.jme3.app;
import com.jme3.system.AppSettings;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import javax.swing.*;
public final class SettingsDialog extends JDialog {
public static interface SelectionListener {
public void onSelection(int selection);
}
private static final Logger logger = Logger.getLogger(SettingsDialog.class.getName());
private static final long serialVersionUID = 1L;
public static final int NO_SELECTION = 0,
APPROVE_SELECTION = 1,
CANCEL_SELECTION = 2;
// Resource bundle for i18n.
ResourceBundle resourceBundle = ResourceBundle.getBundle("com.jme3.app/SettingsDialog");
// connection to properties file.
private final AppSettings source;
// Title Image
private URL imageFile = null;
// Array of supported display modes
private DisplayMode[] modes = null;
private static final DisplayMode[] windowDefaults = new DisplayMode[] {
new DisplayMode(1024, 768, 24, 60),
new DisplayMode(1280, 720, 24, 60),
new DisplayMode(1280, 1024, 24, 60),
};
private DisplayMode[] windowModes = null;
// UI components
private JCheckBox vsyncBox = null;
private JCheckBox fullscreenBox = null;
private JComboBox displayResCombo = null;
private JComboBox colorDepthCombo = null;
private JComboBox displayFreqCombo = null;
private JComboBox antialiasCombo = null;
private JLabel icon = null;
private int selection = 0;
private SelectionListener selectionListener = null;
private int minWidth = 0;
private int minHeight = 0;
/**
* Constructor for the <code>PropertiesDialog</code>. Creates a
* properties dialog initialized for the primary display.
*
* @param source
* the <code>AppSettings</code> object to use for working with
* the properties file.
* @param imageFile
* the image file to use as the title of the dialog;
* <code>null</code> will result in to image being displayed
* @throws NullPointerException
* if the source is <code>null</code>
*/
public SettingsDialog(AppSettings source, String imageFile, boolean loadSettings) {
this(source, getURL(imageFile), loadSettings);
}
/**
* Constructor for the <code>PropertiesDialog</code>. Creates a
* properties dialog initialized for the primary display.
*
* @param source
* the <code>GameSettings</code> object to use for working with
* the properties file.
* @param imageFile
* the image file to use as the title of the dialog;
* <code>null</code> will result in to image being displayed
* @param loadSettings
* @throws JmeException
* if the source is <code>null</code>
*/
public SettingsDialog(AppSettings source, URL imageFile, boolean loadSettings) {
if (source == null) {
throw new NullPointerException("Settings source cannot be null");
}
this.source = source;
this.imageFile = imageFile;
setModal(true);
setAlwaysOnTop(true);
setResizable(false);
AppSettings registrySettings = new AppSettings(true);
String appTitle;
if(source.getTitle()!=null){
appTitle = source.getTitle();
}else{
appTitle = registrySettings.getTitle();
}
minWidth = source.getMinWidth();
minHeight = source.getMinHeight();
try {
registrySettings.load(appTitle);
} catch (BackingStoreException ex) {
logger.log(Level.WARNING,
"Failed to load settings", ex);
}
if (loadSettings) {
source.copyFrom(registrySettings);
} else if(!registrySettings.isEmpty()) {
source.mergeFrom(registrySettings);
}
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
modes = device.getDisplayModes();
Arrays.sort(modes, new DisplayModeSorter());
DisplayMode[] merged = new DisplayMode[modes.length + windowDefaults.length];
int wdIndex = 0;
int dmIndex = 0;
int mergedIndex;
for (mergedIndex = 0;
mergedIndex<merged.length
&& (wdIndex < windowDefaults.length
|| dmIndex < modes.length);
mergedIndex++) {
if (dmIndex >= modes.length) {
merged[mergedIndex] = windowDefaults[wdIndex++];
} else if (wdIndex >= windowDefaults.length) {
merged[mergedIndex] = modes[dmIndex++];
} else if (modes[dmIndex].getWidth() < windowDefaults[wdIndex].getWidth()) {
merged[mergedIndex] = modes[dmIndex++];
} else if (modes[dmIndex].getWidth() == windowDefaults[wdIndex].getWidth()) {
if (modes[dmIndex].getHeight() < windowDefaults[wdIndex].getHeight()) {
merged[mergedIndex] = modes[dmIndex++];
} else if (modes[dmIndex].getHeight() == windowDefaults[wdIndex].getHeight()) {
merged[mergedIndex] = modes[dmIndex++];
wdIndex++;
} else {
merged[mergedIndex] = windowDefaults[wdIndex++];
}
} else {
merged[mergedIndex] = windowDefaults[wdIndex++];
}
}
if (merged.length == mergedIndex) {
windowModes = merged;
} else {
windowModes = Arrays.copyOfRange(merged, 0, mergedIndex);
}
createUI();
}
public void setSelectionListener(SelectionListener sl) {
this.selectionListener = sl;
}
public int getUserSelection() {
return selection;
}
private void setUserSelection(int selection) {
this.selection = selection;
selectionListener.onSelection(selection);
}
public int getMinWidth() {
return minWidth;
}
public void setMinWidth(int minWidth) {
this.minWidth = minWidth;
}
public int getMinHeight() {
return minHeight;
}
public void setMinHeight(int minHeight) {
this.minHeight = minHeight;
}
/**
* <code>setImage</code> sets the background image of the dialog.
*
* @param image
* <code>String</code> representing the image file.
*/
public void setImage(String image) {
try {
URL file = new URL("file:" + image);
setImage(file);
} catch (MalformedURLException e) {
logger.log(Level.WARNING, "Couldn’t read from file '" + image + "'", e);
}
}
/**
* <code>setImage</code> sets the background image of this dialog.
*
* @param image
* <code>URL</code> pointing to the image file.
*/
public void setImage(URL image) {
icon.setIcon(new ImageIcon(image));
pack(); // Resize to accomodate the new image
setLocationRelativeTo(null); // put in center
}
/**
* <code>showDialog</code> sets this dialog as visble, and brings it to
* the front.
*/
public void showDialog() {
setLocationRelativeTo(null);
setVisible(true);
toFront();
}
/**
* <code>init</code> creates the components to use the dialog.
*/
private void createUI() {
GridBagConstraints gbc;
JPanel mainPanel = new JPanel(new GridBagLayout());
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
logger.warning("Could not set native look and feel.");
}
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setUserSelection(CANCEL_SELECTION);
dispose();
}
});
if (source.getIcons() != null) {
safeSetIconImages( (List<BufferedImage>) Arrays.asList((BufferedImage[]) source.getIcons()) );
}
setTitle(MessageFormat.format(resourceBundle.getString("frame.title"), source.getTitle()));
// The buttons...
JButton ok = new JButton(resourceBundle.getString("button.ok"));
JButton cancel = new JButton(resourceBundle.getString("button.cancel"));
icon = new JLabel(imageFile != null ? new ImageIcon(imageFile) : null);
KeyListener aListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (verifyAndSaveCurrentSelection()) {
setUserSelection(APPROVE_SELECTION);
dispose();
}
}
else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
setUserSelection(CANCEL_SELECTION);
dispose();
}
}
};
displayResCombo = setUpResolutionChooser();
displayResCombo.addKeyListener(aListener);
colorDepthCombo = new JComboBox();
colorDepthCombo.addKeyListener(aListener);
displayFreqCombo = new JComboBox();
displayFreqCombo.addKeyListener(aListener);
antialiasCombo = new JComboBox();
antialiasCombo.addKeyListener(aListener);
fullscreenBox = new JCheckBox(resourceBundle.getString("checkbox.fullscreen"));
fullscreenBox.setSelected(source.isFullscreen());
fullscreenBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateResolutionChoices();
}
});
vsyncBox = new JCheckBox(resourceBundle.getString("checkbox.vsync"));
vsyncBox.setSelected(source.isVSync());
gbc = new GridBagConstraints();
gbc.weightx = 0.5;
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.EAST;
mainPanel.add(fullscreenBox, gbc);
gbc = new GridBagConstraints();
gbc.weightx = 0.5;
gbc.insets = new Insets(4, 16, 0, 4);
gbc.gridx = 2;
gbc.gridwidth = 2;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(vsyncBox, gbc);
gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.EAST;
gbc.weightx = 0.5;
mainPanel.add(new JLabel(resourceBundle.getString("label.resolutions")), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(displayResCombo, gbc);
gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 16, 4, 4);
gbc.gridx = 2;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.EAST;
mainPanel.add(new JLabel(resourceBundle.getString("label.colordepth")), gbc);
gbc = new GridBagConstraints();
gbc.weightx = 0.5;
gbc.gridx = 3;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(colorDepthCombo, gbc);
gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.weightx = 0.5;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.EAST;
mainPanel.add(new JLabel(resourceBundle.getString("label.refresh")), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(displayFreqCombo, gbc);
gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 16, 4, 4);
gbc.gridx = 2;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.EAST;
mainPanel.add(new JLabel(resourceBundle.getString("label.antialias")), gbc);
gbc = new GridBagConstraints();
gbc.weightx = 0.5;
gbc.gridx = 3;
gbc.gridy = 3;
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(antialiasCombo, gbc);
// Set the button action listeners. Cancel disposes without saving, OK
// saves.
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (verifyAndSaveCurrentSelection()) {
setUserSelection(APPROVE_SELECTION);
dispose();
}
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setUserSelection(CANCEL_SELECTION);
dispose();
}
});
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.gridy = 4;
gbc.anchor = GridBagConstraints.EAST;
mainPanel.add(ok, gbc);
gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 16, 4, 4);
gbc.gridx = 2;
gbc.gridwidth = 2;
gbc.gridy = 4;
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(cancel, gbc);
if (icon != null) {
gbc = new GridBagConstraints();
gbc.gridwidth = 4;
mainPanel.add(icon, gbc);
}
this.getContentPane().add(mainPanel);
pack();
mainPanel.getRootPane().setDefaultButton(ok);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Fill in the combos once the window has opened so that the insets can be read.
// The assumption is made that the settings window and the display window will have the
// same insets as that is used to resize the "full screen windowed" mode appropriately.
updateResolutionChoices();
if (source.getWidth() != 0 && source.getHeight() != 0) {
displayResCombo.setSelectedItem(source.getWidth() + " x "
+ source.getHeight());
} else {
displayResCombo.setSelectedIndex(displayResCombo.getItemCount()-1);
}
updateAntialiasChoices();
colorDepthCombo.setSelectedItem(source.getBitsPerPixel() + " bpp");
}
});
}
/* Access JDialog.setIconImages by reflection in case we're running on JRE < 1.6 */
private void safeSetIconImages(List<? extends Image> icons) {
try {
// Due to Java bug 6445278, we try to set icon on our shared owner frame first.
// Otherwise, our alt-tab icon will be the Java default under Windows.
Window owner = getOwner();
if (owner != null) {
Method setIconImages = owner.getClass().getMethod("setIconImages", List.class);
setIconImages.invoke(owner, icons);
return;
}
Method setIconImages = getClass().getMethod("setIconImages", List.class);
setIconImages.invoke(this, icons);
} catch (Exception e) {
logger.log(Level.WARNING, "Error setting icon images", e);
}
}
/**
* <code>verifyAndSaveCurrentSelection</code> first verifies that the
* display mode is valid for this system, and then saves the current
* selection as a properties.cfg file.
*
* @return if the selection is valid
*/
private boolean verifyAndSaveCurrentSelection() {
String display = (String) displayResCombo.getSelectedItem();
boolean fullscreen = fullscreenBox.isSelected();
boolean vsync = vsyncBox.isSelected();
int width = Integer.parseInt(display.substring(0, display.indexOf(" x ")));
display = display.substring(display.indexOf(" x ") + 3);
int height = Integer.parseInt(display);
String depthString = (String) colorDepthCombo.getSelectedItem();
int depth = -1;
if (depthString.equals("???")) {
depth = 0;
} else {
depth = Integer.parseInt(depthString.substring(0, depthString.indexOf(' ')));
}
String freqString = (String) displayFreqCombo.getSelectedItem();
int freq = -1;
if (fullscreen) {
if (freqString.equals("???")) {
freq = 0;
} else {
freq = Integer.parseInt(freqString.substring(0, freqString.indexOf(' ')));
}
}
String aaString = (String) antialiasCombo.getSelectedItem();
int multisample = -1;
if (aaString.equals(resourceBundle.getString("antialias.disabled"))) {
multisample = 0;
} else {
multisample = Integer.parseInt(aaString.substring(0, aaString.indexOf('x')));
}
// FIXME: Does not work in Linux
/*
* if (!fullscreen) { //query the current bit depth of the desktop int
* curDepth = GraphicsEnvironment.getLocalGraphicsEnvironment()
* .getDefaultScreenDevice().getDisplayMode().getBitDepth(); if (depth >
* curDepth) { showError(this,"Cannot choose a higher bit depth in
* windowed " + "mode than your current desktop bit depth"); return
* false; } }
*/
boolean valid = false;
// test valid display mode when going full screen
if (!fullscreen) {
valid = true;
} else {
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
valid = device.isFullScreenSupported();
}
if (valid) {
//use the GameSettings class to save it.
source.setWidth(width);
source.setHeight(height);
source.setBitsPerPixel(depth);
source.setFrequency(freq);
source.setFullscreen(fullscreen);
source.setVSync(vsync);
//source.setRenderer(renderer);
source.setSamples(multisample);
String appTitle = source.getTitle();
try {
source.save(appTitle);
} catch (BackingStoreException ex) {
logger.log(Level.WARNING,
"Failed to save setting changes", ex);
}
} else {
showError(
this,
resourceBundle.getString("error.unsupportedmode"));
}
return valid;
}
/**
* <code>setUpChooser</code> retrieves all available display modes and
* places them in a <code>JComboBox</code>. The resolution specified by
* GameSettings is used as the default value.
*
* @return the combo box of display modes.
*/
private JComboBox setUpResolutionChooser() {
JComboBox resolutionBox = new JComboBox();
resolutionBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateDisplayChoices();
}
});
return resolutionBox;
}
/**
* <code>updateDisplayChoices</code> updates the available color depth and
* display frequency options to match the currently selected resolution.
*/
private void updateDisplayChoices() {
if (!fullscreenBox.isSelected()) {
// don't run this function when changing windowed settings
return;
}
String resolution = (String) displayResCombo.getSelectedItem();
String colorDepth = (String) colorDepthCombo.getSelectedItem();
if (colorDepth == null) {
colorDepth = source.getBitsPerPixel() + " bpp";
}
String displayFreq = (String) displayFreqCombo.getSelectedItem();
if (displayFreq == null) {
displayFreq = source.getFrequency() + " Hz";
}
// grab available depths
String[] depths = getDepths(resolution, modes);
colorDepthCombo.setModel(new DefaultComboBoxModel(depths));
colorDepthCombo.setSelectedItem(colorDepth);
// grab available frequencies
String[] freqs = getFrequencies(resolution, modes);
displayFreqCombo.setModel(new DefaultComboBoxModel(freqs));
// Try to reset freq
displayFreqCombo.setSelectedItem(displayFreq);
}
/**
* <code>updateResolutionChoices</code> updates the available resolutions
* list to match the currently selected window mode (fullscreen or
* windowed). It then sets up a list of standard options (if windowed) or
* calls <code>updateDisplayChoices</code> (if fullscreen).
*/
private void updateResolutionChoices() {
if (!fullscreenBox.isSelected()) {
displayResCombo.setModel(new DefaultComboBoxModel(
getWindowedResolutions(windowModes)));
if (displayResCombo.getItemCount() > 0) {
displayResCombo.setSelectedIndex(displayResCombo.getItemCount()-1);
}
colorDepthCombo.setModel(new DefaultComboBoxModel(new String[]{
"24 bpp", "16 bpp"}));
displayFreqCombo.setModel(new DefaultComboBoxModel(
new String[]{resourceBundle.getString("refresh.na")}));
displayFreqCombo.setEnabled(false);
} else {
displayResCombo.setModel(new DefaultComboBoxModel(
getResolutions(modes, Integer.MAX_VALUE, Integer.MAX_VALUE)));
if (displayResCombo.getItemCount() > 0) {
displayResCombo.setSelectedIndex(displayResCombo.getItemCount()-1);
}
displayFreqCombo.setEnabled(true);
updateDisplayChoices();
}
}
private void updateAntialiasChoices() {
// maybe in the future will add support for determining this info
// through pbuffer
String[] choices = new String[]{resourceBundle.getString("antialias.disabled"), "2x", "4x", "6x", "8x", "16x"};
antialiasCombo.setModel(new DefaultComboBoxModel(choices));
antialiasCombo.setSelectedItem(choices[Math.min(source.getSamples()/2,5)]);
}
// Utility methods
/**
* Utility method for converting a String denoting a file into a URL.
*
* @return a URL pointing to the file or null
*/
private static URL getURL(String file) {
URL url = null;
try {
url = new URL("file:" + file);
} catch (MalformedURLException e) {
logger.log(Level.WARNING, "Invalid file name '" + file + "'", e);
}
return url;
}
private static void showError(java.awt.Component parent, String message) {
JOptionPane.showMessageDialog(parent, message, "Error",
JOptionPane.ERROR_MESSAGE);
}
/**
* Returns every unique resolution from an array of <code>DisplayMode</code>s
* where the resolution is greater than the configured minimums.
*/
private String[] getResolutions(DisplayMode[] modes, int heightLimit, int widthLimit) {
Insets insets = getInsets();
heightLimit -= insets.top + insets.bottom;
widthLimit -= insets.left + insets.right;
ArrayList<String> resolutions = new ArrayList<String>(modes.length);
for (int i = 0; i < modes.length; i++) {
int height = modes[i].getHeight();
int width = modes[i].getWidth();
if (width >= minWidth && height >= minHeight) {
if (height >= heightLimit) {
height = heightLimit;
}
if (width >= widthLimit) {
width = widthLimit;
}
String res = width + " x " + height;
if (!resolutions.contains(res)) {
resolutions.add(res);
}
}
}
String[] res = new String[resolutions.size()];
resolutions.toArray(res);
return res;
}
/**
* Returns every unique resolution from an array of <code>DisplayMode</code>s
* where the resolution is greater than the configured minimums and the height
* is less than the current screen resolution.
*/
private String[] getWindowedResolutions(DisplayMode[] modes) {
int maxHeight = 0;
int maxWidth = 0;
for (int i = 0; i < modes.length; i++) {
if (maxHeight < modes[i].getHeight()) {
maxHeight = modes[i].getHeight();
}
if (maxWidth < modes[i].getWidth()) {
maxWidth = modes[i].getWidth();
}
}
return getResolutions(modes, maxHeight, maxWidth);
}
/**
* Returns every possible bit depth for the given resolution.
*/
private static String[] getDepths(String resolution, DisplayMode[] modes) {
ArrayList<String> depths = new ArrayList<String>(4);
for (int i = 0; i < modes.length; i++) {
// Filter out all bit depths lower than 16 - Java incorrectly
// reports
// them as valid depths though the monitor does not support them
if (modes[i].getBitDepth() < 16 && modes[i].getBitDepth() > 0) {
continue;
}
String res = modes[i].getWidth() + " x " + modes[i].getHeight();
String depth = modes[i].getBitDepth() + " bpp";
if (res.equals(resolution) && !depths.contains(depth)) {
depths.add(depth);
}
}
if (depths.size() == 1 && depths.contains("-1 bpp")) {
// add some default depths, possible system is multi-depth supporting
depths.clear();
depths.add("24 bpp");
}
String[] res = new String[depths.size()];
depths.toArray(res);
return res;
}
/**
* Returns every possible refresh rate for the given resolution.
*/
private static String[] getFrequencies(String resolution,
DisplayMode[] modes) {
ArrayList<String> freqs = new ArrayList<String>(4);
for (int i = 0; i < modes.length; i++) {
String res = modes[i].getWidth() + " x " + modes[i].getHeight();
String freq;
if (modes[i].getRefreshRate() == DisplayMode.REFRESH_RATE_UNKNOWN) {
freq = "???";
} else {
freq = modes[i].getRefreshRate() + " Hz";
}
if (res.equals(resolution) && !freqs.contains(freq)) {
freqs.add(freq);
}
}
String[] res = new String[freqs.size()];
freqs.toArray(res);
return res;
}
/**
* Utility class for sorting <code>DisplayMode</code>s. Sorts by
* resolution, then bit depth, and then finally refresh rate.
*/
private class DisplayModeSorter implements Comparator<DisplayMode> {
/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(DisplayMode a, DisplayMode b) {
// Width
if (a.getWidth() != b.getWidth()) {
return (a.getWidth() > b.getWidth()) ? 1 : -1;
}
// Height
if (a.getHeight() != b.getHeight()) {
return (a.getHeight() > b.getHeight()) ? 1 : -1;
}
// Bit depth
if (a.getBitDepth() != b.getBitDepth()) {
return (a.getBitDepth() > b.getBitDepth()) ? 1 : -1;
}
// Refresh rate
if (a.getRefreshRate() != b.getRefreshRate()) {
return (a.getRefreshRate() > b.getRefreshRate()) ? 1 : -1;
}
// All fields are equal
return 0;
}
}
}
|
package bigdata;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import javax.xml.stream.XMLStreamException;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.QuoteMode;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
public class Main {
public static void main(String[] rawArgs) {
// force english output in cli help messages
Locale.setDefault(new Locale("en", "US"));
// for local debugging only
//System.setProperty("HADOOP_USER_NAME", "bigprak");
// init log4j to output to stderr
ConsoleAppender appender = new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "System.err");
appender.setThreshold(Level.WARN);
Logger.getRootLogger().addAppender(appender);
Namespace args = createArgsParser().parseArgsOrFail(rawArgs);
String command = args.getString("command");
try {
Configuration conf = new Configuration();
conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
FileSystem fs = FileSystem.get(new URI("hdfs://localhost"), conf);
if("dblp".equals(command) || "acm".equals(command)) {
CSVFormat format = createCsvFormat(args.getString("csv_format"));
InputStream inputStream = args.get("input_file");
Path hdfsPath = new Path(args.getString("output_folder"));
fs.mkdirs(hdfsPath);
if("dblp".equals(command)) {
FSDataOutputStream publicationStream = fs.create(new Path(hdfsPath, "dblp-publications.csv"));
FSDataOutputStream collectionStream = fs.create(new Path(hdfsPath, "dblp-collections.csv"));
Writer publicationWriter = new BufferedWriter(new OutputStreamWriter(publicationStream, StandardCharsets.UTF_8));
Writer collectionWriter = new BufferedWriter(new OutputStreamWriter(collectionStream, StandardCharsets.UTF_8));
try(CSVPrinter publicationCSVPrinter = new CSVPrinter(publicationWriter, format);
CSVPrinter collectionCSVPrinter = new CSVPrinter(collectionWriter, format)) {
System.out.print("Starting import ...");
long importedEntries = bigdata.dblp.Parser.parse(inputStream, publicationCSVPrinter, collectionCSVPrinter, new ProgressReporter());
System.out.format("%n... finished! Imported %,d entries.%n", importedEntries);
}
} else { // acm
FSDataOutputStream publicationStream = fs.create(new Path(hdfsPath, "acm-publications.csv"));
Writer publicationWriter = new BufferedWriter(new OutputStreamWriter(publicationStream, StandardCharsets.UTF_8));
try(CSVPrinter publicationCSVPrinter = new CSVPrinter(publicationWriter, format)) {
System.out.print("Starting import ...");
long importedEntries = bigdata.acm.Parser.parse(inputStream, publicationCSVPrinter, new ProgressReporter());
System.out.format("%n... finished! Imported %,d entries.%n", importedEntries);
}
}
} else if("csv".equals(command)) {
Path hdfsInput = new Path(args.getString("input_file"));
Path hdfsOutput = new Path(args.getString("output_file"));
long limit = args.getLong("limit");
FSDataInputStream inputStream = fs.open(hdfsInput);
FSDataOutputStream outputStream = fs.create(hdfsOutput);
CSVFormat inputFormat = null, outputFormat = null;
if(args.getBoolean("quoted_to_escaped")) {
inputFormat = createCsvFormat("quoted");
outputFormat = createCsvFormat("escaped");
} else if(args.getBoolean("escaped_to_quoted")) {
inputFormat = createCsvFormat("escaped");
outputFormat = createCsvFormat("quoted");
}
Reader inputReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
Writer outputWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
try(CSVParser parser = new CSVParser(inputReader, inputFormat);
CSVPrinter printer = new CSVPrinter(outputWriter, outputFormat)) {
long i = 0;
ProgressReporter progress = new ProgressReporter();
System.out.print("Starting conversion ...");
for(CSVRecord record : parser) {
printer.printRecord(record);
progress.report(i++);
if(limit > 0 && limit <= i) {
break;
}
}
System.out.format("%n... finished! Converted %,d lines.%n", i);
}
}
} catch(IOException | URISyntaxException e) {
System.err.println("Error writing to hdfs: " + e);
System.exit(2);
return;
} catch(XMLStreamException e) {
System.err.println("Error while parsing dblp.xml: " + e);
System.exit(3);
return;
}
System.exit(0);
}
protected static ArgumentParser createArgsParser() {
ArgumentParser parser = ArgumentParsers.newArgumentParser("pub-importer");
parser.version(Main.class.getPackage().getImplementationVersion());
parser.addArgument("-V", "--version").action(Arguments.version());
Subparsers subparsers = parser.addSubparsers()
.dest("command")
.title("subcommands")
.metavar("COMMAND");
Subparser dblpParser = subparsers.addParser("dblp");
dblpParser.help("import original dblp.xml into hdfs");
dblpParser.addArgument("input_file")
.help("input file, defaults to stdin")
.nargs("?")
.type(FileInputStream.class)
.setDefault(System.in);
dblpParser.addArgument("output_folder")
.help("destination folder in local hdfs");
dblpParser.addArgument("--csv-format")
.help("formatting of the csv files, use escaped for hive")
.required(true)
.choices("quoted", "escaped");
Subparser acmParser = subparsers.addParser("acm");
acmParser.help("import ACM.xml into hdfs");
acmParser.addArgument("input_file")
.help("input file, defaults to stdin")
.nargs("?")
.type(FileInputStream.class)
.setDefault(System.in);
acmParser.addArgument("output_folder")
.help("destination folder in local hdfs");
acmParser.addArgument("--csv-format")
.help("formatting of the csv files, use escaped for hive")
.required(true)
.choices("quoted", "escaped");
Subparser csvParser = subparsers.addParser("csv");
csvParser.help("convert csv files between differernt formats");
csvParser.addArgument("input_file")
.help("input file in local hdfs");
csvParser.addArgument("output_file")
.help("output file in local hdfs");
MutuallyExclusiveGroup conversionArguments = csvParser.addMutuallyExclusiveGroup();
conversionArguments.required(true);
conversionArguments.addArgument("--quoted-to-escaped")
.help("convert from quoted csv to escaped csv (hive)")
.action(Arguments.storeTrue());
conversionArguments.addArgument("--escaped-to-quoted")
.help("convert from escaped csv (hive) to quoted csv")
.action(Arguments.storeTrue());
csvParser.addArgument("--limit")
.metavar("N")
.help("only convert and copy the first N entries")
.type(Long.class)
.setDefault(new Long(0));
return parser;
}
public static CSVFormat createCsvFormat(String mode) {
if("quoted".equals(mode)) {
return CSVFormat.newFormat(',')
.withRecordSeparator('\n')
.withQuote('"')
.withQuoteMode(QuoteMode.MINIMAL)
.withNullString("");
} else if("escaped".equals(mode)) {
return CSVFormat.newFormat(',')
.withRecordSeparator('\n')
.withEscape('\\')
.withQuoteMode(QuoteMode.NONE)
.withNullString("");
} else {
throw new IllegalArgumentException("invalid csv mode: " + mode);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.